{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import SimLocalAdvance.\n\nRequire Import ITreeLang.\nRequire Import ITreeLib.\n\nSet Implicit Arguments.\n\n\nVariant split_release: forall R (i1: MemE.t R) (i2: MemE.t R), Prop :=\n| split_release_store\n l v:\n split_release (MemE.write l v Ordering.acqrel) (MemE.write l v Ordering.strong_relaxed)\n| split_release_update\n l rmw or\n (OR: Ordering.le or Ordering.strong_relaxed):\n split_release (MemE.update l rmw or Ordering.acqrel) (MemE.update l rmw or Ordering.strong_relaxed)\n.\n\nVariant sim_released: forall R\n (st_src:(Language.state (lang R))) (lc_src:Local.t) (gl1_src:Global.t)\n (st_tgt:(Language.state (lang R))) (lc_tgt:Local.t) (gl1_tgt:Global.t), Prop :=\n| sim_released_intro\n R\n (i_src i_tgt: MemE.t R)\n lc1_src gl1_src\n lc1_tgt gl1_tgt\n (SPLIT: split_release i_src i_tgt)\n (LOCAL: sim_local lc1_src lc1_tgt)\n (RELEASED: forall l, View.le (TView.cur (Local.tview lc1_tgt)) ((TView.rel (Local.tview lc1_tgt)) l))\n (GLOBAL: sim_global gl1_src gl1_tgt)\n (LC_WF_SRC: Local.wf lc1_src gl1_src)\n (LC_WF_TGT: Local.wf lc1_tgt gl1_tgt)\n (GL_WF_SRC: Global.wf gl1_src)\n (GL_WF_TGT: Global.wf gl1_tgt):\n sim_released\n (Vis i_src (fun r => Ret r)) lc1_src gl1_src\n (Vis i_tgt (fun r => Ret r)) lc1_tgt gl1_tgt\n.\n\nLemma sim_released_mon\n R\n st_src lc_src gl1_src\n st_tgt lc_tgt gl1_tgt\n gl2_src\n gl2_tgt\n (SIM1: sim_released st_src lc_src gl1_src\n st_tgt lc_tgt gl1_tgt)\n (GLOBAL: sim_global gl2_src gl2_tgt)\n (LC_WF_SRC: Local.wf lc_src gl2_src)\n (LC_WF_TGT: Local.wf lc_tgt gl2_tgt)\n (GL_WF_SRC: Global.wf gl2_src)\n (GL_WF_TGT: Global.wf gl2_tgt):\n @sim_released R\n st_src lc_src gl2_src\n st_tgt lc_tgt gl2_tgt.\nProof.\n destruct SIM1. econs; eauto.\nQed.\n\nLemma sim_released_step\n R\n st1_src lc1_src gl1_src\n st1_tgt lc1_tgt gl1_tgt\n (SIM: @sim_released R\n st1_src lc1_src gl1_src\n st1_tgt lc1_tgt gl1_tgt):\n _sim_thread_step (lang R) (lang R)\n ((@sim_thread (lang R) (lang R) (sim_terminal eq)) \\6/ @sim_released R)\n st1_src lc1_src gl1_src\n st1_tgt lc1_tgt gl1_tgt.\nProof.\n destruct SIM. ii.\n inv STEP_TGT; [|inv LOCAL0; destruct SPLIT; ss; dependent destruction STATE].\n - (* internal *)\n right.\n exploit Local.internal_step_future; eauto. i. des.\n exploit sim_local_internal; try exact LOCAL; eauto. i. des.\n exploit Local.internal_step_future; eauto. i. des.\n esplits; try exact GL2; eauto.\n + inv LOCAL0; ss.\n + right. econs; eauto.\n inv LOCAL0; inv LOCAL1; ss.\n - (* update-load *)\n right.\n exploit sim_local_read; try exact LOCAL1; eauto; try refl. i. des.\n esplits.\n + ss.\n + refl.\n + econs 2. econs 2; [|econs 2]; eauto. econs; eauto.\n + ss.\n + ss.\n + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.\n - (* write *)\n right.\n hexploit sim_local_write_released; try exact LOCAL1; eauto; try refl.\n { by rewrite <- View.join_l. }\n i. des.\n esplits.\n + ss.\n + refl.\n + econs 2. econs 2; [|econs 3]; eauto. econs. refl.\n + ss.\n + ss.\n + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.\n - (* update *)\n right.\n exploit sim_local_update_released; try exact LOCAL1; try exact LOCAL2; eauto; try refl. i. des.\n esplits.\n + ss.\n + refl.\n + econs 2. econs 2; [|econs 4]; eauto. econs; eauto.\n + ss.\n + ss.\n + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.\n - (* racy read *)\n right.\n exploit sim_local_racy_read; try exact LOCAL1; eauto; try refl. i. des.\n esplits.\n + ss.\n + refl.\n + econs 2. econs 2; [|econs 8]; eauto. econs; eauto.\n + ss.\n + ss.\n + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.\n - (* racy write *)\n left.\n exploit sim_local_racy_write_released; try exact LOCAL1; eauto. i. des.\n econs; try refl.\n + econs 2; [|econs 9]; eauto. econs; eauto.\n + ss.\n - (* racy update *)\n left.\n exploit sim_local_racy_update_released; try exact LOCAL1; eauto. i. des.\n econs; try refl.\n + econs 2; [|econs 10]; eauto. econs; eauto.\n + ss.\nQed.\n\nLemma sim_released_sim_thread R:\n @sim_released R <6= @sim_thread (lang R) (lang R) (sim_terminal eq).\nProof.\n pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n - inv TERMINAL_TGT. inv PR; ss.\n - right. esplits; eauto.\n inv PR. eapply sim_local_promises_bot; eauto.\n - exploit sim_released_mon; eauto. i.\n exploit sim_released_step; eauto. i. des; eauto.\n + right. esplits; eauto.\n left. eapply paco9_mon; eauto. ss.\n + right. esplits; eauto.\nQed.\n\nLemma split_release_sim_itree R\n (i_src i_tgt: MemE.t R)\n (SPLIT: split_release i_src i_tgt):\n sim_itree eq\n (ITree.trigger i_src)\n (ITree.trigger (MemE.fence Ordering.plain Ordering.acqrel);; ITree.trigger i_tgt).\nProof.\n replace (ITree.trigger i_src) with (Vis i_src (fun r => Ret r)).\n 2: { unfold ITree.trigger. grind. }\n replace (ITree.trigger (MemE.fence Ordering.plain Ordering.acqrel);; ITree.trigger i_tgt) with\n (Vis (MemE.fence Ordering.plain Ordering.acqrel) (fun _ => Vis i_tgt (fun r => Ret r))).\n 2: { unfold ITree.trigger. grind. repeat f_equal. extensionality u. grind. }\n pcofix CIH. ii. subst. pfold. ii. splits; ii.\n { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }\n { right. esplits; eauto.\n eapply sim_local_promises_bot; eauto.\n }\n right.\n inv STEP_TGT; ss.\n - (* internal *)\n exploit sim_local_internal; eauto. i. des.\n esplits; try apply GL2; eauto; ss.\n inv LOCAL0; ss.\n - (* fence *)\n inv LOCAL0; dependent destruction STATE.\n exploit Local.fence_step_future; eauto. i. des.\n esplits.\n + ss.\n + refl.\n + econs 1.\n + ss.\n + exploit Local.fence_step_non_sc; eauto. i. subst. ss.\n + left. eapply paco9_mon; [apply sim_released_sim_thread|]; ss.\n inv LOCAL1. econs; eauto.\n * inv LOCAL. econs; ss. etrans; eauto.\n * s. i. repeat condtac; ss. refl.\n * inv GLOBAL. econs; ss. \nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/SplitRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.14989693334869492}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of PM: PThread *)\n(* *)\n(* Provide the initialization and primtives of thread *)\n(* *)\n(* Ronghui Gu *)\n(* Yu Guo *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the PThread layer, \nwhich will introduce the primtives of thread*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjFlatMem.\nRequire Export ObjContainer.\nRequire Export ObjVMM.\nRequire Export ObjLMM.\nRequire Export ObjShareMem.\nRequire Export ObjThread.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n Local Open Scope Z_scope.\n\n Context `{real_params: RealParams}.\n\n (** **Definition of the invariants at MPTNew layer*)\n (** [0th page map] is reserved for the kernel thread*)\n Record high_level_invariant (abd: RData) :=\n mkInvariant {\n valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;\n valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);\n valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);\n valid_kern: ipt abd = false -> pg abd = true;\n valid_iptt: ipt abd = true -> ikern abd = true; \n valid_iptf: ikern abd = false -> ipt abd = false; \n valid_ihost: ihost abd = false -> pg abd = true /\\ ikern abd = true;\n valid_container: Container_valid (AC abd);\n valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);\n init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;\n valid_PMap: pg abd = true -> \n (forall i, 0<= i < num_proc ->\n PMap_valid (ZMap.get i (ptpool abd)));\n (* 0th page map is reserved for the kernel thread*) \n valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;\n valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));\n valid_PT: pg abd = true -> 0<= PT abd < num_proc;\n valid_dirty: dirty_ppage (pperm abd) (HP abd);\n\n valid_idpde: pg abd = true -> IDPDE_init (idpde abd);\n valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);\n\n valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;\n\n valid_TCB: pg abd = true -> AbTCBStrong_range (abtcb abd);\n valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);\n valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);\n valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);\n valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd);\n valid_curid: 0 <= cid abd < num_proc;\n correct_curid: pg abd = true -> CurIDValid (cid abd) (AC abd) (abtcb abd);\n single_curid: pg abd = true -> SingleRun (cid abd) (abtcb abd)\n\n }.\n\n (** ** Definition of the abstract state ops *)\n Global Instance pthread_data_ops : CompatDataOps RData :=\n {\n empty_data := init_adt;\n high_level_invariant := high_level_invariant;\n low_level_invariant := low_level_invariant;\n kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n observe := ObservationImpl.observe\n }.\n\n (** ** Proofs that the initial abstract_data should satisfy the invariants*) \n Section Property_Abstract_Data.\n\n Lemma empty_data_high_level_invariant:\n high_level_invariant init_adt.\n Proof.\n constructor; simpl; intros; auto; try inv H.\n - apply empty_container_valid.\n - eapply Lconsistent_ppage_init.\n - eapply dirty_ppage_init.\n - eapply consistent_pmap_init.\n - eapply consistent_pmap_domain_init.\n - eapply consistent_lat_domain_init.\n - repeat rewrite ZMap.gi; intuition.\n Qed.\n\n (** ** Definition of the abstract state *)\n Global Instance pthread_data_prf : CompatData RData.\n Proof.\n constructor.\n - apply low_level_invariant_incr.\n - apply empty_data_low_level_invariant.\n - apply empty_data_high_level_invariant.\n Qed.\n\n End Property_Abstract_Data.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** * Proofs that the primitives satisfies the invariants at this layer *)\n Section INV.\n\n Section ALLOC.\n \n Lemma alloc_high_level_inv:\n forall d d' i n,\n alloc_spec i d = Some (d', n) ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros. functional inversion H; subst; eauto. \n inv H0. constructor; simpl; eauto.\n - intros; eapply LAT_kern_norm; eauto. eapply _x.\n - intros; eapply LAT_usr_norm; eauto.\n - eapply alloc_container_valid'; eauto.\n - eapply Lconsistent_ppage_norm_alloc; eauto.\n - intros; congruence.\n - eapply dirty_ppage_gso_alloc; eauto.\n - eapply consistent_pmap_gso_at_false; eauto. apply _x.\n - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.\n - eapply consistent_lat_domain_gss_nil; eauto.\n - zmap_solve.\n - intros; apply NotInQ_gso_true; auto.\n - intros; apply CurIDValid_gss_ac; auto.\n Qed.\n \n Lemma alloc_low_level_inv:\n forall d d' n i n',\n alloc_spec i d = Some (d', n) ->\n low_level_invariant n' d ->\n low_level_invariant n' d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n inv H0. constructor; eauto.\n Qed.\n\n Lemma alloc_kernel_mode:\n forall d d' i n,\n alloc_spec i d = Some (d', n) ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n Qed.\n\n Global Instance alloc_inv: PreservesInvariants alloc_spec.\n Proof.\n preserves_invariants_simpl'.\n - eapply alloc_low_level_inv; eassumption.\n - eapply alloc_high_level_inv; eassumption.\n - eapply alloc_kernel_mode; eassumption.\n Qed.\n\n End ALLOC.\n\n Global Instance pfree_inv: PreservesInvariants pfree_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n - intros; eapply LAT_kern_norm; eauto. \n - intros; eapply LAT_usr_norm; eauto.\n - eapply Lconsistent_ppage_norm_undef; eauto.\n - eapply dirty_ppage_gso_undef; eauto.\n - eapply consistent_pmap_gso_pperm_alloc; eauto.\n - eapply consistent_pmap_domain_gso_at_0; eauto.\n - eapply consistent_lat_domain_gss_nil; eauto.\n Qed.\n\n Global Instance trapin_inv: PrimInvariants trapin_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance trapout_inv: PrimInvariants trapout_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance hostin_inv: PrimInvariants hostin_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance hostout_inv: PrimInvariants hostout_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance ptin_inv: PrimInvariants ptin_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance ptout_inv: PrimInvariants ptout_spec.\n Proof.\n PrimInvariants_simpl H H0.\n Qed.\n\n Global Instance fstore_inv: PreservesInvariants fstore_spec.\n Proof.\n split; intros; inv_generic_sem H; inv H0; functional inversion H2.\n - functional inversion H. split; trivial. \n - functional inversion H.\n split; subst; simpl; \n try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial. \n - functional inversion H0.\n split; simpl; try assumption.\n Qed.\n\n Global Instance setPT_inv: PreservesInvariants setPT_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n Qed.\n\n Section PTINSERT.\n \n Section PTINSERT_PTE.\n\n Lemma ptInsertPTE_high_level_inv:\n forall d d' n vadr padr p,\n ptInsertPTE0_spec n vadr padr p d = Some d' ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n inv H0; constructor_gso_simpl_tac; intros.\n - eapply LAT_kern_norm; eauto. \n - eapply LAT_usr_norm; eauto.\n - eapply Lconsistent_ppage_norm; eassumption.\n - eapply PMap_valid_gso_valid; eauto.\n - functional inversion H2. functional inversion H1. \n eapply PMap_kern_gso; eauto.\n - functional inversion H2. functional inversion H0.\n eapply consistent_pmap_ptp_same; try eassumption.\n eapply consistent_pmap_gso_pperm_alloc'; eassumption.\n - functional inversion H2.\n eapply consistent_pmap_domain_append; eauto.\n destruct (ZMap.get pti pdt); try contradiction;\n red; intros (v0 & p0 & He); contra_inv. \n - eapply consistent_lat_domain_gss_append; eauto.\n subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;\n red; intros (v0 & p0 & He); contra_inv. \n Qed.\n\n Lemma ptInsertPTE_low_level_inv:\n forall d d' n vadr padr p n',\n ptInsertPTE0_spec n vadr padr p d = Some d' ->\n low_level_invariant n' d ->\n low_level_invariant n' d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n inv H0. constructor; eauto.\n Qed.\n\n Lemma ptInsertPTE_kernel_mode:\n forall d d' n vadr padr p,\n ptInsertPTE0_spec n vadr padr p d = Some d' ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n Qed.\n\n End PTINSERT_PTE.\n\n Section PTALLOCPDE.\n\n Lemma ptAllocPDE_high_level_inv:\n forall d d' n vadr v,\n ptAllocPDE0_spec n vadr d = Some (d', v) ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros. functional inversion H; subst; eauto. \n inv H0; constructor_gso_simpl_tac; intros.\n - eapply LAT_kern_norm; eauto. eapply _x.\n - eapply LAT_usr_norm; eauto.\n - eapply alloc_container_valid'; eauto.\n - apply Lconsistent_ppage_norm_hide; try assumption.\n - congruence.\n - eapply PMap_valid_gso_pde_unp; eauto.\n eapply real_init_PTE_defined.\n - functional inversion H3. \n eapply PMap_kern_gso; eauto.\n - eapply dirty_ppage_gss; eauto.\n - eapply consistent_pmap_ptp_gss; eauto; apply _x.\n - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.\n eapply consistent_pmap_domain_ptp_unp; eauto.\n apply real_init_PTE_unp.\n - apply consistent_lat_domain_gss_nil; eauto.\n apply consistent_lat_domain_gso_p; eauto.\n - zmap_solve.\n - apply NotInQ_gso_true; auto.\n - apply CurIDValid_gss_ac; auto.\n Qed.\n\n Lemma ptAllocPDE_low_level_inv:\n forall d d' n vadr v n',\n ptAllocPDE0_spec n vadr d = Some (d', v) ->\n low_level_invariant n' d ->\n low_level_invariant n' d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n inv H0. constructor; eauto.\n Qed.\n\n Lemma ptAllocPDE_kernel_mode:\n forall d d' n vadr v,\n ptAllocPDE0_spec n vadr d = Some (d', v) ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n Qed.\n\n End PTALLOCPDE.\n\n Lemma ptInsert_high_level_inv:\n forall d d' n vadr padr p v,\n ptInsert0_spec n vadr padr p d = Some (d', v) ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros. functional inversion H; subst; eauto. \n - eapply ptInsertPTE_high_level_inv; eassumption.\n - eapply ptAllocPDE_high_level_inv; eassumption.\n - eapply ptInsertPTE_high_level_inv; try eassumption.\n eapply ptAllocPDE_high_level_inv; eassumption.\n Qed.\n\n Lemma ptInsert_low_level_inv:\n forall d d' n vadr padr p n' v,\n ptInsert0_spec n vadr padr p d = Some (d', v) ->\n low_level_invariant n' d ->\n low_level_invariant n' d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n - eapply ptInsertPTE_low_level_inv; eassumption.\n - eapply ptAllocPDE_low_level_inv; eassumption.\n - eapply ptInsertPTE_low_level_inv; try eassumption.\n eapply ptAllocPDE_low_level_inv; eassumption.\n Qed.\n\n Lemma ptInsert_kernel_mode:\n forall d d' n vadr padr p v,\n ptInsert0_spec n vadr padr p d = Some (d', v) ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n - eapply ptInsertPTE_kernel_mode; eassumption.\n - eapply ptAllocPDE_kernel_mode; eassumption.\n - eapply ptInsertPTE_kernel_mode; try eassumption.\n eapply ptAllocPDE_kernel_mode; eassumption.\n Qed.\n\n End PTINSERT.\n\n Section PTRESV.\n\n Lemma ptResv_high_level_inv:\n forall d d' n vadr p v,\n ptResv_spec n vadr p d = Some (d', v) ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros. functional inversion H; subst; eauto. \n eapply ptInsert_high_level_inv; try eassumption.\n eapply alloc_high_level_inv; eassumption.\n Qed.\n\n Lemma ptResv_low_level_inv:\n forall d d' n vadr p n' v,\n ptResv_spec n vadr p d = Some (d', v) ->\n low_level_invariant n' d ->\n low_level_invariant n' d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n eapply ptInsert_low_level_inv; try eassumption.\n eapply alloc_low_level_inv; eassumption.\n Qed.\n\n Lemma ptResv_kernel_mode:\n forall d d' n vadr p v,\n ptResv_spec n vadr p d = Some (d', v) ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros. functional inversion H; subst; eauto.\n eapply ptInsert_kernel_mode; try eassumption.\n eapply alloc_kernel_mode; eassumption.\n Qed.\n\n Global Instance ptResv_inv: PreservesInvariants ptResv_spec.\n Proof.\n preserves_invariants_simpl'.\n - eapply ptResv_low_level_inv; eassumption.\n - eapply ptResv_high_level_inv; eassumption.\n - eapply ptResv_kernel_mode; eassumption.\n Qed.\n\n End PTRESV.\n\n Section OFFER_SHARE.\n\n Section PTRESV2.\n\n Lemma ptResv2_high_level_inv:\n forall d d' n vadr p n' vadr' p' v,\n ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n high_level_invariant d ->\n high_level_invariant d'.\n Proof.\n intros; functional inversion H; subst; eauto;\n eapply ptInsert_high_level_inv; try eassumption.\n - eapply alloc_high_level_inv; eassumption.\n - eapply ptInsert_high_level_inv; try eassumption.\n eapply alloc_high_level_inv; eassumption.\n Qed.\n\n Lemma ptResv2_low_level_inv:\n forall d d' n vadr p n' vadr' p' l v,\n ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n low_level_invariant l d ->\n low_level_invariant l d'.\n Proof.\n intros; functional inversion H; subst; eauto;\n eapply ptInsert_low_level_inv; try eassumption.\n - eapply alloc_low_level_inv; eassumption.\n - eapply ptInsert_low_level_inv; try eassumption.\n eapply alloc_low_level_inv; eassumption.\n Qed.\n\n Lemma ptResv2_kernel_mode:\n forall d d' n vadr p n' vadr' p' v,\n ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n kernel_mode d ->\n kernel_mode d'.\n Proof.\n intros; functional inversion H; subst; eauto;\n eapply ptInsert_kernel_mode; try eassumption.\n - eapply alloc_kernel_mode; eassumption.\n - eapply ptInsert_kernel_mode; try eassumption.\n eapply alloc_kernel_mode; eassumption.\n Qed.\n\n End PTRESV2.\n\n Global Instance offer_shared_mem_inv: \n PreservesInvariants offer_shared_mem_spec.\n Proof.\n preserves_invariants_simpl';\n functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).\n - exploit ptResv2_low_level_inv; eauto.\n intros HP; inv HP. constructor; trivial.\n - exploit ptResv2_low_level_inv; eauto.\n intros HP; inv HP. constructor; trivial.\n - exploit ptResv2_high_level_inv; eauto.\n intros HP; inv HP. constructor; trivial.\n - exploit ptResv2_high_level_inv; eauto.\n intros HP; inv HP. constructor; trivial.\n - exploit ptResv2_kernel_mode; eauto.\n - exploit ptResv2_kernel_mode; eauto.\n Qed.\n\n End OFFER_SHARE.\n\n Global Instance shared_mem_status_inv: \n PreservesInvariants shared_mem_status_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n Qed.\n\n Global Instance sched_init_inv: PreservesInvariants sched_init_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant.\n - apply real_nps_range.\n - apply real_lat_kern_valid.\n - apply real_lat_usr_valid.\n - apply real_container_valid.\n - rewrite init_pperm0; try assumption.\n apply Lreal_pperm_valid. \n - eapply real_pt_PMap_valid; eauto.\n - apply real_pt_PMap_kern.\n - omega.\n - assumption.\n - apply real_idpde_init.\n - apply real_pt_consistent_pmap. \n - apply real_pt_consistent_pmap_domain. \n - apply Lreal_at_consistent_lat_domain.\n - apply real_abtcb_strong_range'; eauto.\n - apply real_abq_range; auto.\n - eapply real_abtcb_pb_notInQ'; eauto.\n - eapply real_abtcb_abq_QCount'; eauto.\n - eapply real_abq_tcb_inQ; eauto.\n - omega.\n - eapply real_abtcb_AC_CurIDValid; eauto. \n - eapply real_abtcb_SingleRun; eauto. \n Qed.\n\n Global Instance thread_wakeup_inv: PreservesInvariants thread_wakeup_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n - eapply AbTCBStrong_range_gss_READY; eauto. \n - eapply AbQCorrect_range_gss_wakeup; eauto.\n - eapply NotInQ_InQ_gss_wakeup; eauto.\n - eapply QCount_gss_wakeup; eauto.\n - eapply InQ_gss_wakeup; eauto.\n - eapply CurIDValid_gso_tcb; eauto.\n eapply last_neq_cid; eauto. omega.\n - eapply SingleRun_gso_state_READY; eauto.\n Qed.\n\n Global Instance thread_spawn_inv: DNewInvariants thread_spawn_spec.\n Proof.\n constructor; intros; inv H0;\n unfold thread_spawn_spec in *;\n subdestruct; inv H; simpl; auto.\n\n - (* low level invariant *)\n constructor; trivial; intros; simpl in *.\n eapply kctxt_inject_neutral_gss_flatinj'; eauto.\n eapply kctxt_inject_neutral_gss_flatinj; eauto.\n\n - (* high_level_invariant *)\n constructor; simpl; eauto 2; try congruence; intros.\n + exploit split_container_valid; eauto.\n eapply container_split_some; eauto.\n auto.\n + unfold update_cusage, update_cchildren; zmap_solve.\n + eapply AbTCBStrong_range_gss_READY; eauto. \n + eapply AbQCorrect_range_gss_enqueue; eauto.\n + unfold update_cusage, update_cchildren; apply NotInQ_gso_ac_true; eauto.\n zmap_simpl; repeat apply NotInQ_gso_true; auto.\n + eapply QCount_gss_spawn; eauto. \n eapply AbTCBStrong_range_impl; eauto.\n split; [|split; [|eauto]].\n assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.\n apply cvalid_unused_next_child; auto.\n + eapply InQ_gss_spawn; eauto.\n eapply AbTCBStrong_range_impl; eauto.\n split; [|split; [|eauto]].\n assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.\n apply cvalid_unused_next_child; auto.\n + unfold update_cusage, update_cchildren; apply CurIDValid_gso_neq_true; auto.\n zmap_simpl; repeat apply CurIDValid_gss_ac; auto.\n assert (Hneq:= cvalid_child_id_neq _ valid_container0 _ Hdestruct3); zmap_simpl.\n apply cvalid_unused_next_child; auto.\n + eapply SingleRun_gso_state_READY; eauto.\n Qed.\n \n Local Opaque remove.\n\n\n Global Instance thread_yield_inv: ThreadScheduleInvariants thread_yield_spec.\n Proof.\n constructor; intros; functional inversion H. \n - inv H1. constructor; trivial. \n eapply kctxt_inject_neutral_gss_mem; eauto.\n - inv H0. subst.\n assert (HOS: 0<= num_chan <= num_chan) by omega.\n exploit last_range_AbQ; eauto. intros Hrange.\n constructor; auto; simpl in *; intros; try congruence.\n + eapply AbTCBStrong_range_gss_RUN; eauto. \n eapply AbTCBStrong_range_gss_READY; eauto. \n + eapply AbQCorrect_range_gss_remove'; eauto.\n eapply list_range_enqueue; eauto.\n eapply AbQCorrect_range_impl; eauto.\n + eapply NotInQ_gso_neg; eauto.\n eapply NotInQ_gso_ac; eauto. \n eapply correct_curid0; eauto.\n + eapply QCount_gss_yield; eauto.\n + eapply InQ_gss_yield; eauto.\n + eapply CurIDValid_gss_last; eauto. \n + eapply SingleRun_gss_gso_cid; eauto. congruence.\n Qed.\n\n Global Instance thread_sleep_inv: ThreadTransferInvariants thread_sleep_spec.\n Proof.\n constructor; intros; functional inversion H. \n - inv H1. constructor; trivial. \n eapply kctxt_inject_neutral_gss_mem; eauto.\n - inv H0. subst.\n assert (HOS: 0<= num_chan <= num_chan) by omega.\n assert (HNeq: 64 <> n') by omega.\n exploit last_range_AbQ; eauto. intros Hrange.\n assert (HOS': 0 <= n' <= num_proc) by omega.\n assert (Hcid: ZMap.get (cid d) (abtcb d) = AbTCBValid RUN (-1)) \n by (eapply correct_curid0; eauto).\n constructor; auto; simpl in *; intros; try congruence.\n + eapply AbTCBStrong_range_gss_RUN; eauto. \n eapply AbTCBStrong_range_gss_SLEEP; eauto. \n + eapply AbQCorrect_range_gss_remove; eauto.\n * eapply AbQCorrect_range_gss_enqueue; eauto.\n * rewrite ZMap.gso; eauto. \n + eapply NotInQ_gso_neg; eauto.\n eapply NotInQ_gso_ac; eauto. \n eapply correct_curid0; eauto.\n + eapply QCount_gss_remove; eauto.\n * eapply QCount_gss_enqueue; eauto.\n * rewrite ZMap.gso; eauto. \n + eapply InQ_gss_remove; eauto.\n * eapply InQ_gss_enqueue; eauto.\n * eapply QCount_gss_enqueue; eauto.\n * rewrite ZMap.gso; eauto. \n * apply last_correct; eauto.\n + eapply CurIDValid_gss_last; eauto. \n + eapply SingleRun_gss_gso_cid; eauto. congruence.\n Qed.\n\n Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; \n try eapply dirty_ppage_gss_copy; eauto.\n Qed.\n\n Global Instance device_output_inv: PreservesInvariants device_output_spec.\n Proof. \n preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.\n Qed.\n \n End INV.\n\n Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).\n\n Definition exec_storeex {F V} := exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).\n\n Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).\n Proof.\n split; inversion 1; intros. \n - functional inversion H0. split; trivial.\n - functional inversion H1. \n split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.\n Qed.\n\n Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n Proof.\n split; inversion 1; intros; constructor; auto.\n Qed.\n\n (** * Layer Definition *)\n Definition pthread_fresh : compatlayer (cdata RData) :=\n thread_yield ↦ primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)\n ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem thread_sleep_spec.\n\n Definition pthread_passthrough : compatlayer (cdata RData) :=\n fload ↦ gensem fload_spec\n ⊕ fstore ↦ gensem fstore_spec\n ⊕ flatmem_copy ↦ gensem flatmem_copy_spec\n ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n ⊕ device_output ↦ gensem device_output_spec\n ⊕ pfree ↦ gensem pfree_spec\n ⊕ set_pt ↦ gensem setPT_spec\n ⊕ pt_read ↦ gensem ptRead_spec\n ⊕ pt_resv ↦ gensem ptResv_spec\n ⊕ shared_mem_status ↦ gensem shared_mem_status_spec\n ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec\n ⊕ get_state ↦ gensem get_state0_spec\n ⊕ get_curid ↦ gensem get_curid_spec\n ⊕ thread_spawn ↦ dnew_compatsem thread_spawn_spec\n ⊕ thread_wakeup ↦ gensem thread_wakeup_spec\n ⊕ sched_init ↦ gensem sched_init_spec\n\n ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n ⊕ container_get_quota ↦ gensem container_get_quota_spec\n ⊕ container_get_usage ↦ gensem container_get_usage_spec\n ⊕ container_can_consume ↦ gensem container_can_consume_spec\n ⊕ container_alloc ↦ gensem alloc_spec\n ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n Definition pthread : compatlayer (cdata RData) := pthread_fresh ⊕ pthread_passthrough.\n\n (*Definition semantics := LAsm.Lsemantics pthread.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.14965269597926625}} {"text": "Require Import Wellfounded CoqlibC Maps AST Linking.\nRequire Import Integers ValuesC Memory Events Smallstep Globalenvs.\nRequire Import Switch Registers Cminor Op CminorSelC RTLC.\nRequire Import RTLgen RTLgenspec.\nRequire Import sflib.\n(** newly added **)\nRequire Export RTLgenproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem.\nRequire SimMemExt.\nRequire SoundTop.\n\nSet Implicit Arguments.\n\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariable prog: CminorSel.program.\nVariable tprog: RTL.program.\nLet md_src: Mod.t := (CminorSelC.module prog).\nLet md_tgt: Mod.t := (RTLC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\n\nHypothesis TRANSL: match_prog prog tprog.\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat * nat) (st_src0: CminorSel.state) (st_tgt0: RTL.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: RTLgenproof.match_states st_src0 st_tgt0)\n (MCOMPATSRC: (CminorSelC.get_mem st_src0) = sm0.(SimMem.src))\n (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt))\n (MEASRUE: idx = measure_state st_src0).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun cu f tf => transl_fundef f = Errors.OK tf) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nLet SEGESRC: senv_genv_compat skenv_link ge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.\nLet SEGETGT: senv_genv_compat skenv_link tge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.\n\nInductive match_states_at: Cminor.state -> CminorSel.state -> SimMem.t -> SimMem.t -> Prop :=\n| match_states_at_intro\n fptr sg vs k m st_tgt sm_at sm_arg\n (ATEXT: Genv.find_funct ge fptr = None):\n match_states_at (Cminor.Callstate fptr sg vs k m) st_tgt sm_at sm_arg.\n\nTheorem sim_modsem: ModSemPair.sim msp.\nProof.\n eapply match_states_sim with (match_states := match_states) (match_states_at := top4);\n eauto; ii; ss.\n - eapply wf_lex_ord; eauto; apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation; eauto.\n - (* init bsim *)\n destruct sm_arg; ss. clarify.\n inv INITTGT. inv SIMARGS; ss. clarify.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n eexists. eexists (SimMemExt.mk _ _). esplits; eauto.\n + econs; eauto; ss.\n * inv TYP. rpapply match_callstate; eauto.\n { econs; eauto. }\n { eapply lessdef_list_typify_list; try apply VALS; eauto. rewrite <- LEN.\n symmetry. eapply lessdef_list_length; eauto. }\n folder. inv SAFESRC. inv TYP.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. folder.\n inv FPTR; ss.\n rr in H0. des. ss. unfold Errors.bind in *. des_ifs.\n unfold fundef in *. clarify.\n assert(SGEQ: CminorSel.fn_sig fd0 = fn_sig fd).\n { destruct fd0; ss. unfold transl_function in *. ss. unfold bind in *. des_ifs. }\n f_equal; try congruence.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss. inv FPTR; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. unfold bind in *. folder. des_ifs.\n inv TYP. rr in H0. des. ss. unfold Errors.bind in *. des_ifs.\n assert(SGEQ: (CminorSel.fn_sig fd) = f.(fn_sig)).\n { destruct fd; ss. unfold transl_function in *. ss. unfold bind in *. des_ifs. }\n esplits; eauto. econs; eauto.\n + ss. rewrite <- SGEQ. ss.\n + econs; eauto with congruence.\n erewrite <- lessdef_list_length; eauto. etrans; eauto with congruence.\n + erewrite <- lessdef_list_length; eauto. etrans; eauto with congruence.\n - (* call wf *)\n inv MATCH; ss. destruct sm0; ss. clarify. u in CALLSRC. des. inv CALLSRC. inv MATCHST; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n inv CALLSRC. inv MATCHST; ss; cycle 1.\n folder. esplits; eauto.\n + econs; eauto.\n * folder. des. r in TRANSL. r in TRANSL.\n exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.\n { apply SIMSKENV. }\n intro GE. apply (fsim_external_funct_id GE); ss.\n folder. inv FPTR; ss.\n * des. esplits; eauto. eapply SimSymb.simskenv_func_fsim; eauto; ss. unfold Sk.get_csig in *. des_ifs.\n + econs; ss; eauto.\n * instantiate (1:= SimMemExt.mk _ _). ss.\n * ss.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; eauto.\n + econs; eauto.\n + econs; ss; eauto. econs; eauto.\n eapply lessdef_typify; ss.\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss.\n inv MS. destruct sm0; ss. clarify.\n eexists (SimMemExt.mk _ _). esplits; ss; eauto. econs; eauto.\n - left; i. esplits; eauto.\n { apply CminorSelC.modsem_receptive; et. }\n inv MATCH. ii. hexploit (@transl_step_correct prog skenv_link skenv_link); eauto.\n { inv SIMSKENV. ss. }\n { apply make_match_genvs; eauto. apply SIMSKENV. }\n i; des_safe. folder. des.\n + esplits; eauto.\n * left. eapply ModSemProps.spread_dplus; et. apply modsem_determinate; et.\n * instantiate (1:= (SimMemExt.mk _ _)). ss.\n + clarify. esplits; eauto.\n * right. esplits; eauto. { instantiate (1:= R2). eapply ModSemProps.spread_dstar; eauto. eapply modsem_determinate; eauto. }\n * instantiate (1:= (SimMemExt.mk _ _)). ss.\nUnshelve.\n all: ss. apply msp.\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariable prog: CminorSel.program.\nVariable tprog: RTL.program.\nHypothesis TRANSL: match_prog prog tprog.\n\nDefinition mp: ModPair.t := SimSymbId.mk_mp (CminorSelC.module prog) (RTLC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. eapply Sk.match_program_eq; eauto.\n ii. destruct f1; ss.\n + clarify. right. unfold bind in MATCH. inv MATCH. des. unfold Errors.bind, transl_function in *. ss. des_ifs. esplits; eauto.\n + clarify. left. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/RTLgenproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1495015128861036}} {"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import AsmC.\nRequire SimMemInjInvC.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import AsmregsC.\nRequire Import MatchSimModSem.\nRequire Import StoreArguments StoreArgumentsProps.\nRequire Import AsmStepInj IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import AsmExtra IdSimExtra IdSimAsmExtra IdSimInvExtra.\n\nRequire Import MatchSimModSemExcl2.\nRequire Import Conventions1C.\n\nRequire Import mktac.\n\n\nSet Implicit Arguments.\n\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\n\n\nSection INJINV.\n\nVariable P: SimMemInjInv.memblk_invariant.\n\nLocal Instance SimMemP: SimMem.class := SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P.\nLocal Instance SimSymbP: SimSymb.class SimMemP := SimMemInjInvC.SimSymbIdInv P.\nLocal Existing Instance SoundTop.Top.\n\nLemma asm_inj_inv_id\n (asm: Asm.program)\n (WF: Sk.wf (module asm))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimMemInjInvC.mk bot1 _ _).\n econs; ss; i.\n { econs; ss; i; clarify. }\n eapply MatchSimModSemExcl2.match_states_sim with\n (match_states :=\n @match_states\n SimMemInjInv.top_inv P\n skenv_link_tgt\n (SkEnv.revive (SkEnv.project skenv_link_src (Sk.of_program fn_sig asm)) asm)\n (SkEnv.revive (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig asm)) asm))\n (match_states_at := top4)\n (sidx := unit); ss; eauto; ii.\n - apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation.\n\n - (** ******************* initial **********************************)\n destruct sm_arg as [sm_arg mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n exploit SimSymbIdInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n inv SIMARGS.\n { ss. clarify.\n inv INITTGT; clarify. ss. inv TYP. cinv STORE.\n\n exploit store_arguments_parallel; eauto.\n { eapply typify_has_type_list; eauto. }\n { exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto. i. des.\n inv WFTGT. rpapply WFPARAM; eauto; ss. }\n { eapply inject_list_typify_list; try eassumption.\n erewrite inject_list_length; eauto. } i. des.\n hexploit (assign_junk_blocks_parallel n); eauto. i. des.\n eexists (AsmC.mkstate (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd))) # PC <- fptr_src)\n # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA)))\n # RSP <- (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero)\n (Asm.State _ _)).\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm_arg sm0); eauto.\n { etrans; eauto. }\n { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.\n - eapply Mem.unchanged_on_implies with (P:=top2); ss. etrans.\n + eapply store_arguments_unchanged_on; eauto.\n + rewrite <- MTGT. rewrite MTGT0.\n eapply JunkBlock.assign_junk_blocks_unchanged_on. } intros MWFINV1.\n\n eexists (SimMemInjInv.mk sm0 _ _). esplits; eauto.\n { econs; ss; eauto.\n - inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto. i.\n setoid_rewrite FINDF in H. clarify.\n - assert (JUNK: JunkBlock.is_junk_value m0 (JunkBlock.assign_junk_blocks m0 n) (rs RA)).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; ss. }\n split.\n + unfold Pregmap.set, src_junk_val. des_ifs.\n + unfold Pregmap.set, src_junk_val. des_ifs; ss; des; eauto.\n - unfold Pregmap.set. des_ifs. unfold src_junk_val, JunkBlock.is_junk_value in *.\n des_ifs. ii. clarify. apply n1.\n assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm1) - Mem.nextblock (SimMemInj.tgt sm1)) (Mem.nextblock (SimMemInj.src sm1))).\n { eapply Plt_Ple_trans; eauto.\n inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.\n rewrite NBSRC.\n etrans; eauto. etrans; eauto. eapply Mem.unchanged_on_nextblock; eauto. }\n exfalso. eapply Plt_lemma; eauto.\n - econs; eauto. erewrite inject_list_length; eauto.\n - inv ARGTGT. econs; ss; eauto.\n econs; try eassumption; eauto.\n eapply extcall_arguments_same; eauto. i.\n unfold Pregmap.set, to_mregset, to_pregset, to_preg.\n erewrite to_preg_to_mreg. des_ifs; clarify; ss.\n + unfold preg_of in *; des_ifs.\n + unfold preg_of in *; des_ifs.\n + unfold preg_of in *; des_ifs.\n + unfold set_regset_junk. des_ifs; clarify; eauto.\n exfalso. eapply Loc.notin_not_in in n3. eauto.\n - i. unfold Pregmap.set in *. des_ifs; eauto.\n { exploit PTRFREE.\n - ii. eapply src_junk_val_junk in H; eauto.\n - i. des; clarify. } left.\n unfold to_pregset, set_regset_junk, to_mregset in *. des_ifs; ss.\n + exploit PTRFREE.\n * ii. eapply src_junk_val_junk in H; eauto.\n * i. erewrite to_mreg_some_to_preg in *; eauto. des; ss.\n clarify. esplits; eauto.\n + esplits; eauto. erewrite loc_notin_not_in in n3. tauto. }\n\n { econs; ss; eauto. etrans; eauto. }\n\n { assert (AGREE0:\n AsmStepInj.agree\n (SimMemInj.inj sm0)\n (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd)))\n # PC <- fptr_src) # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA))) # RSP <-\n (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero) rs).\n { ii. unfold Pregmap.set, to_mregset, to_pregset, to_preg.\n inv MLE0. des_ifs; ss; eauto.\n - eapply val_inject_incr; eauto. rewrite INJ.\n unfold update_meminj. rewrite H1. econs; des_ifs. ss.\n - rewrite MINJ. eapply src_junk_val_inj; eauto. inv MWF0. eauto.\n - inv MLE. eapply val_inject_incr; eauto.\n - unfold set_regset_junk. des_ifs.\n + erewrite to_mreg_preg_of; eauto. rewrite MINJ.\n eapply src_junk_val_inj; eauto. inv MWF0. eauto.\n + eapply val_inject_incr; eauto. rewrite INJ in *.\n specialize (AGREE m). unfold to_mregset in *.\n erewrite to_mreg_preg_of in *; eauto. }\n econs; eauto.\n - rewrite <- MTGT. auto.\n\n - instantiate (1:=fd). inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto. i.\n setoid_rewrite FINDF in H. clarify.\n - econs.\n + econs; eauto.\n * unfold Pregmap.set. des_ifs.\n * unfold Pregmap.set. des_ifs. unfold src_junk_val. des_ifs.\n * unfold Pregmap.set. des_ifs. unfold src_junk_val.\n assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs RA)).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify. }\n clear - RADEF JUNK.\n unfold JunkBlock.is_junk_value, Mem.valid_block in *. des_ifs; des; eauto.\n + econs; ss. ii. congruence.\n + { unfold to_pregset, set_regset, Pregmap.set. ii.\n rewrite to_preg_to_mreg in *. des_ifs.\n + apply f_equal with (f:=to_mreg) in e.\n rewrite to_preg_to_mreg in e. ss.\n + apply f_equal with (f:=to_mreg) in e.\n rewrite to_preg_to_mreg in e. ss.\n + unfold set_regset_junk in *. des_ifs.\n * assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs (to_preg r))).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify.\n erewrite to_preg_to_mreg in MR. clarify.\n eapply Loc.notin_not_in; eauto. }\n unfold src_junk_val in *. des_ifs_safe.\n unfold JunkBlock.is_junk_value in *.\n unfold to_mregset in *. rewrite Heq in *.\n unfold Mem.valid_block in *. exfalso. des. des_ifs.\n * erewrite loc_notin_not_in in n3. apply NNPP in n3.\n apply loc_args_callee_save_disjoint in n3. exfalso. eauto. }\n + ss.\n - unfold Genv.find_funct, Genv.find_funct_ptr, Genv.find_def. des_ifs.\n eapply Genv.genv_defs_range in Heq0. exfalso. eapply RANOTFPTR; eauto.\n - unfold Pregmap.set. des_ifs. ii. clarify. rewrite MINJ. rewrite INJ.\n unfold junk_inj, update_meminj. des_ifs; eauto. }\n }\n { ss. inv INITTGT; clarify. ss.\n hexploit (assign_junk_blocks_parallel n); eauto. i. des.\n\n eexists (AsmC.mkstate\n (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))\n (Asm.State\n (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))\n (SimMemInj.src sm1))).\n esplits; eauto.\n - econs 2; ss; eauto.\n + inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto.\n * eapply RS.\n * i. setoid_rewrite FINDF in H. clarify.\n + unfold Pregmap.set. des_ifs. unfold src_junk_val.\n des_ifs; split; ss; eauto; des; clarify.\n + unfold src_junk_val. des_ifs. i. clarify. ii. apply n0.\n assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm_arg) - Mem.nextblock (SimMemInj.tgt sm_arg)) (Mem.nextblock (SimMemInj.src sm_arg))).\n { eapply Plt_Ple_trans; eauto.\n inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.\n rewrite NBSRC. etrans; eauto. }\n exfalso. eapply Plt_lemma; eauto.\n + rewrite MSRC. eapply src_junk_val_junk; eauto.\n - instantiate (1:=SimMemInjInv.mk sm1 _ _). econs; ss.\n - cinv MWF. econs; eauto; simpl.\n + eapply AsmStepInj.agree_step; eauto.\n * eapply agree_incr; try apply RS; eauto.\n rewrite MINJ. eapply junk_inj_incr; eauto.\n * rewrite MINJ. eapply src_junk_val_inj; eauto.\n + eapply AsmStepInj.agree_step; eauto.\n * eapply agree_incr; try apply RS; eauto.\n rewrite MINJ. eapply junk_inj_incr; eauto.\n * rewrite MINJ. eapply src_junk_val_inj; eauto.\n + hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm_arg sm1); eauto.\n eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n { ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto. }\n { eapply Mem.unchanged_on_implies with (P:=top2); ss. rewrite MTGT.\n eapply JunkBlock.assign_junk_blocks_unchanged_on. }\n + rewrite Pregmap.gso; clarify.\n inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto.\n * eapply RS.\n * i. setoid_rewrite FINDF in H. clarify. eauto.\n + econs 2; eauto.\n * unfold src_junk_val. econs; eauto; rewrite Pregmap.gss.\n { des_ifs. }\n { des_ifs; clarify; ss; des; clarify. }\n * econs; eauto; rewrite Pregmap.gss.\n + rewrite Pregmap.gss. unfold Genv.find_funct, Genv.find_funct_ptr. des_ifs.\n eapply Genv.genv_defs_range in Heq. exfalso. eapply RANOTFPTR; eauto.\n + i. des. clarify. }\n\n - (** ******************* safe **********************************)\n exploit SimSymbIdInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH. des.\n inv SAFESRC.\n { inv TYP. inv SIMARGS; clarify. ss.\n eapply asm_initial_frame_succeed; eauto.\n + apply inject_list_length in VALS.\n transitivity (Datatypes.length vs_src); eauto.\n + exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto.\n i. des. inv WFSRC. eapply WFPARAM in H; eauto.\n + exploit match_globals_find_funct; eauto. }\n { inv SIMARGS; clarify. ss.\n eapply asm_initial_frame_succeed_asmstyle; eauto.\n exploit match_globals_find_funct; eauto. eapply RS. }\n\n - inv MATCH. ss.\n\n - (** ******************* at external **********************************)\n inv SIMSKENV. inv CALLSRC.\n { inv MATCH.\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n des; ss; clarify. des_ifs.\n set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.\n assert (delta = 0).\n { psimpl. inv SIMSKELINK. ss. inv INJECT. exploit IMAGE; eauto. rewrite <- H0 in *.\n - left. ss. clear - SIG. unfold Genv.find_funct_ptr in *.\n des_ifs. eapply Genv.genv_defs_range; eauto.\n - i. des. eauto. }\n clarify. psimpl. ss.\n exploit extcall_arguments_inject; eauto.\n { inv MWF. eauto. }\n i. des. cinv (AGREE Asm.RSP); rewrite RSP in *; clarify.\n\n exploit SimMemInjC.Mem_free_parallel'; eauto. i. des.\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm0 sm1); eauto.\n { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.\n - eapply Mem.free_unchanged_on; eauto. ii.\n exploit INVRANGETGT; eauto. i. des. exploit H6; eauto.\n eapply Mem.perm_cur. eapply Mem.perm_implies.\n + eapply Mem.free_range_perm; eauto.\n instantiate (1:=Ptrofs.unsigned ofs + delta). lia.\n + econs. } intros MWFINV0.\n\n eexists (Args.mk (Vptr b2 _) _ _). eexists (SimMemInjInv.mk sm1 _ _).\n esplits; eauto; ss; i.\n + econs; auto.\n * eauto.\n * exploit SimSymbIdInv_find_None; try eassumption.\n { ii. rewrite H in *. ss. }\n { unfold Genv.find_funct. des_ifs. }\n * esplits; eauto. inv SIMSKELINK. inv INJECT. inv SIMSKENV. ss.\n rewrite <- H0 in *. inv INJPC. exploit IMAGE; eauto.\n { left. eapply Genv.genv_defs_range; eauto. ss.\n unfold Genv.find_funct_ptr in *. clear EXTERNAL. des_ifs; eauto. }\n { i. des. clarify. }\n * clear - AGREE TPTR RADEF. splits.\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n * eauto.\n * eauto.\n * destruct (zlt 0 (size_arguments sg)).\n { inv MWF. exploit Mem.mi_representable; eauto.\n - right.\n instantiate (1:=Ptrofs.add ofs (Ptrofs.repr (4 * size_arguments sg))).\n eapply Mem.perm_cur.\n eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].\n rewrite unsigned_add.\n + clear - ARGSRANGE l. lia.\n + clear- ARGSRANGE. set (size_arguments_above sg).\n set (Ptrofs.unsigned_range_2 ofs). lia.\n - repeat rewrite unsigned_add. i. des.\n + lia.\n + exploit Mem.mi_representable; eauto. left. eapply Mem.perm_cur.\n eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].\n clear - ARGSRANGE l. lia.\n + clear - ARGSRANGE.\n set (size_arguments_above sg).\n set (Ptrofs.unsigned_range_2 ofs). lia. }\n { set (Ptrofs.unsigned_range_2 (Ptrofs.add ofs (Ptrofs.repr delta))). lia. }\n * inv MWF. i. erewrite Mem.address_inject; eauto; cycle 1.\n { eapply Mem.free_range_perm; eauto.\n set (size_chunk_pos chunk). lia. }\n eapply Z.divide_add_r; eauto.\n inv PUBLIC. inv mi_inj. exploit mi_align; eauto.\n eapply Mem.free_range_perm in FREE.\n intros ofs0 RANGE. exploit FREE; eauto.\n -- instantiate (1:=ofs0). instantiate (1:=Ptrofs.unsigned ofs) in RANGE. nia.\n -- i. eapply Mem.perm_cur_max. eapply Mem.perm_implies; eauto. econs.\n * eauto.\n + inv MLE. econs; s; eauto. rewrite H0. rewrite H1. eauto.\n }\n { ss. inv MATCH.\n des; ss; clarify. des_ifs.\n set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.\n assert (delta = 0).\n { psimpl. inv SIMSKELINK. ss. inv INJECT. exploit IMAGE; eauto. rewrite <- H0 in *.\n - left. ss. clear - SIG. unfold Genv.find_funct_ptr in *.\n des_ifs. eapply Genv.genv_defs_range; eauto.\n - i. des. eauto. } clarify. psimpl. ss.\n exists (Args.Asmstyle rs_tgt (SimMemInj.tgt sm0.(SimMemInjInv.minj))). esplits; eauto.\n - econs 2; eauto.\n + exploit SimSymbIdInv_find_None; try eassumption.\n { ii. rewrite H in *. ss. }\n { unfold Genv.find_funct. des_ifs. }\n + esplits; eauto. inv SIMSKELINK. inv INJECT. inv SIMSKENV. ss.\n rewrite <- H0 in *. inv INJPC. exploit IMAGE; eauto.\n { left. eapply Genv.genv_defs_range; eauto. ss.\n unfold Genv.find_funct_ptr in *. clear EXTERNAL. des_ifs; eauto. }\n { i. des. clarify. rewrite <- H1 in *. auto. }\n + clear - AGREE TPTR RADEF. splits.\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n - econs 2; eauto.\n - refl. }\n\n - (** ******************* after external **********************************)\n exploit SimSymbIdInv_match_globals.\n { inv SIMSKENV. ss. eauto. } instantiate (1:=asm). intros GEMATCH.\n inv MATCH. inv AFTERSRC.\n { inv SIMRET; clarify. inv HISTORY; clarify.\n inv CALLSRC; clarify; cycle 1.\n { ss. des. clarify. }\n inv CALLTGT; clarify; cycle 1.\n { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify.\n rewrite RSRSP in *. des. ss. des_ifs. clarify.\n cinv (AGREE Asm.RSP); rewrite RSRSP in *; ss; clarify; rewrite RSP0 in *; clarify.\n\n assert (SKD: skd1 = skd).\n { inv SIMSKENV. inv SIMSKELINK. ss. inv INJECT.\n cinv (AGREE PC); rewrite <- H1 in *; clarify. eauto.\n exploit IMAGE; eauto.\n - left. rewrite <- H0 in *. ss. clear - SIG0. unfold Genv.find_funct_ptr in *.\n des_ifs. eapply Genv.genv_defs_range; eauto.\n - i. des. clarify. inv SIMSKENVLINK. inv SIMSKENV. clarify.\n rewrite <- H0 in *. ss. des_ifs. } clarify.\n\n hexploit (@Mem_unfree_parallel P sm0 sm_arg sm_ret); eauto.\n\n i. des. esplits; eauto. i.\n esplits; ss; eauto.\n\n + econs; ss; eauto.\n + dup MLE2. rename MLE4 into MINVLE2.\n destruct MLE2 as [MLE2 MINVEQSRC2 MINVEQTGT2].\n econs; try refl; eauto.\n * clarify. inv MLE2. ii.\n unfold set_pair, Pregmap.set, loc_external_result, map_rpair.\n des_ifs; ss; eauto.\n { rewrite MINJ. eauto. }\n { unfold regset_after_external. des_ifs; ss; eauto. }\n { rewrite MINJ. eapply Val.loword_inject. eauto. }\n { rewrite MINJ. eapply Val.hiword_inject. eauto. }\n { unfold regset_after_external. des_ifs; ss; eauto. }\n * inv MLE2. eapply agree_incr; eauto.\n * inv MLE2. i. exploit RSPDELTA; eauto. i. des. esplits; eauto.\n }\n { inv SIMRET; clarify. inv HISTORY; clarify.\n inv CALLSRC; clarify.\n { ss. des. clarify. }\n inv CALLTGT; clarify.\n { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify. ss.\n exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n eexists. eexists (AsmC.mkstate _ (Asm.State _ _)). esplits; eauto.\n - etrans; eauto.\n - clear - MLE0. inv MLE0. inv MLE. ss. econs; ss; eauto. eapply SimMemInj.frozen_refl.\n - i. esplits; eauto.\n + econs 2; eauto.\n + exploit SimMemInjInvC.unlift_wf; try apply MLE0; eauto. i. inv MLE2.\n cinv MLE3. ss.\n econs; try apply H; auto; eauto.\n * eapply AsmStepInj.agree_step; eauto.\n * eapply AsmStepInj.agree_incr; eauto.\n * i. exploit RSPDELTA; eauto. i. des. eauto. }\n\n - (** ******************* final **********************************)\n\n exploit SimSymbIdInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n inv MATCH. inv FINALSRC.\n {\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.\n exploit SimMemInjC.Mem_free_parallel'; eauto.\n { instantiate (3:=Ptrofs.zero). zsimpl. psimpl. eauto. }\n i. des.\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm0 sm1); eauto.\n { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.\n - eapply Mem.free_unchanged_on; eauto.\n ii. exploit INVRANGETGT; eauto. i. des. exploit H3; eauto.\n eapply Mem.perm_cur. eapply Mem.perm_implies.\n + eapply Mem.free_range_perm; eauto.\n instantiate (1:=delta). lia.\n + econs. } intros MWFINV0.\n\n assert (delta = 0).\n { rewrite FINDF in *. clarify. exploit RSPDELTA; eauto. i. des. clarify. }\n clarify. ss. zsimpl.\n\n esplits; ss; eauto.\n + cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.\n econs; ss; ii; eauto.\n * des. esplits; eauto.\n eapply match_globals_find_funct; eauto.\n * inv WFINITRS; clarify. clear - EXTERNAL AGREE SIMSKENVLINK SIMSKENV WFINITSRC RSRA.\n unfold external_state, Genv.find_funct, Genv.find_funct_ptr in *.\n cinv (AGREE PC); eauto.\n { rewrite <- H0 in *. des_ifs_safe.\n inv SIMSKENV. ss. inv SIMSKELINK. ss. inv SIMSKENV.\n inv INJECT. exploit IMAGE; eauto.\n - right. eapply Genv.genv_defs_range in Heq0. ss.\n - i. des. clarify. rewrite Heq0 in *. clarify. }\n { exfalso. rewrite <- H1 in *. inv WFINITSRC. eauto. }\n * inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.\n unfold Val.has_type in TPTR. des_ifs.\n -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n -- ss. clear RANOTFPTR. des_ifs.\n cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n * specialize (CALLEESAVE _ H).\n specialize (AGREEINIT (to_preg mr0)).\n specialize (AGREE (to_preg mr0)). inv WFINITRS; clarify.\n clear - CALLEESAVE AGREEINIT AGREE WFINITSRC WFINITTGT H UNDEF.\n inv WFINITSRC.\n eapply lessdef_commute; eauto.\n * cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify.\n cinv (AGREE RSP); rewrite RSRSP in *; clarify.\n + econs; ss. eapply val_inject_incr; cycle 1; eauto.\n inv MLE. eauto.\n + econs; ss; eauto.\n }\n { exists sm0. exists (Retv.Asmstyle rs_tgt sm0.(SimMemInjInv.minj).(SimMemInj.tgt)).\n esplits; ss; eauto.\n + econs 2; ss; ii; eauto.\n * des. esplits; eauto.\n eapply match_globals_find_funct; eauto.\n * des.\n inv WFINITRS; clarify. clear - EXTERNAL AGREE SIMSKENVLINK SIMSKENV WFINITSRC RSRA.\n unfold external_state, Genv.find_funct, Genv.find_funct_ptr in *.\n cinv (AGREE PC); eauto.\n { rewrite <- H0 in *. des_ifs_safe.\n inv SIMSKENV. ss. inv SIMSKELINK. ss. inv SIMSKENV.\n inv INJECT. exploit IMAGE; eauto.\n - right. eapply Genv.genv_defs_range in Heq0. ss.\n - i. des. clarify. rewrite Heq0 in *. clarify. }\n { exfalso. rewrite <- H1 in *. inv WFINITSRC. eauto. }\n * des. des_ifs. clarify.\n inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.\n unfold Val.has_type in TPTR. des_ifs.\n -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n -- ss. clear RANOTFPTR. des_ifs.\n cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n + econs 2; ss.\n + refl. }\n\n - (** ******************* step **********************************)\n left; i.\n esplits; ss; i.\n + apply AsmC.modsem_receptive.\n + exists O.\n { inv STEPSRC. destruct st_src0, st_src1. inv MATCH. ss.\n inv SIMSKENV. destruct st0. ss. clarify.\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n\n exploit asm_step_preserve_injection; eauto.\n { exploit SimSymbIdInv_match_globals; eauto.\n intros MATCH. inv MATCH. econs; ss; i; eauto.\n exploit DEFLE; eauto. i. des. clarify. esplits; eauto. }\n { eapply symbols_inject_weak_imply.\n exploit SimMemInjInvC.skenv_inject_symbols_inject; eauto. }\n { cinv MWF. eauto. }\n\n i. des.\n eexists (AsmC.mkstate init_rs_tgt (Asm.State _ _)).\n\n exploit SimMemInjC.parallel_gen; eauto.\n { ii. eapply asm_step_max_perm; eauto. }\n { ii. eapply asm_step_max_perm; eauto. }\n i. des.\n hexploit SimMemInjInv.le_inj_wf_wf; eauto.\n { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.\n - eapply Mem.unchanged_on_implies; eauto.\n i. exploit INVRANGETGT; eauto. i. des. eauto. } intros MWFINV0.\n eexists (SimMemInjInv.mk _ _ _).\n\n esplits; eauto.\n - left. econs; cycle 1.\n + apply star_refl.\n + symmetry. apply E0_right.\n + econs.\n * apply AsmC.modsem_determinate.\n * econs; ss; eauto.\n - econs; ss; eauto.\n - econs; ss; eauto.\n + eapply agree_incr; eauto.\n + i. exploit RSPDELTA; eauto. i. des. esplits; eauto.\n }\nUnshelve. all: apply 0.\nQed.\n\nEnd INJINV.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/demo/mutrec/IdSimAsmIdInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.1494959873909939}} {"text": "(******************************************************************************)\n(** * Sc-per-loc *)\n(******************************************************************************)\n\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\n\nRequire Import Events.\nRequire Import Execution.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\n\nSection ECO.\nVariable G : execution.\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'rmw'\" := G.(rmw).\n\nNotation \"'fr'\" := G.(fr).\nNotation \"'coe'\" := G.(coe).\nNotation \"'coi'\" := G.(coi).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'fre'\" := G.(fre).\nNotation \"'fri'\" := G.(fri).\n\nNotation \"'lab'\" := G.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\n\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\n\nNotation \"'Pln'\" := (is_only_pln lab).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (is_sc lab).\n\nImplicit Type WF : Wf G.\nImplicit Type COMP : complete G.\nImplicit Type ATOM : rmw_atomicity G.\n\n(******************************************************************************)\n(** ** extended coherence order *)\n(******************************************************************************)\n\nDefinition eco := rf ∪ co ⨾ rf^? ∪ fr ⨾ rf^?.\n\nDefinition sc_per_loc := irreflexive (sb ⨾ eco).\n\nImplicit Type SC_PER_LOC : sc_per_loc.\n\n(******************************************************************************)\n(** ** Basic Properties *)\n(******************************************************************************)\n\nLemma co_in_eco: co ⊆ eco.\nProof using. unfold eco; basic_solver 6. Qed.\n\nLemma rf_in_eco: rf ⊆ eco.\nProof using. unfold eco; basic_solver 6. Qed.\n\nLemma fr_in_eco: fr ⊆ eco.\nProof using. unfold eco; basic_solver 6. Qed.\n\nLemma co_rf_in_eco: co ;; rf ⊆ eco.\nProof using. unfold eco; basic_solver 6. Qed.\n\nLemma fr_rf_in_eco: fr ;; rf ⊆ eco.\nProof using. unfold eco; basic_solver 6. Qed.\n\nLemma rfe_in_eco : rfe ⊆ eco.\nProof using. rewrite rfe_in_rf. apply rf_in_eco. Qed.\n\nLemma coe_in_eco : coe ⊆ eco.\nProof using. rewrite coe_in_co. apply co_in_eco. Qed.\n\nLemma fre_in_eco : fre ⊆ eco.\nProof using. rewrite fre_in_fr. apply fr_in_eco. Qed.\n\nLemma loceq_eco WF : funeq loc eco.\nProof using. destruct WF; desf. eauto 10 with hahn. Qed.\n\nLemma wf_ecoE WF : eco ≡ ⦗E⦘ ⨾ eco ⨾ ⦗E⦘.\nProof using.\nsplit; [|basic_solver].\nunfold eco.\nrewrite (wf_rfE WF) at 1 2 3.\nrewrite (wf_coE WF) at 1.\nrewrite (wf_frE WF) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_ecoD WF : eco ≡ ⦗RW⦘ ⨾ eco ⨾ ⦗RW⦘.\nProof using.\nsplit; [|basic_solver].\nunfold eco.\nrewrite wf_rfD at 1 2 3; try done.\nrewrite wf_coD at 1; try done.\nrewrite wf_frD at 1; try done.\ntype_solver 42.\nQed.\n\nLemma eco_alt WF: eco ≡ (co ∪ fr) ∪ (co ∪ fr)^? ⨾ rf.\nProof using.\n unfold eco, Execution.fr; basic_solver 42.\nQed.\n\nLemma eco_alt2 WF: eco ≡ rf ∪ (rf⁻¹)^? ⨾ co ⨾ rf^?.\nProof using.\n unfold eco, Execution.fr; basic_solver 42.\nQed.\n\nLemma eco_trans WF: transitive eco.\nProof using.\nunfold eco.\napply transitiveI.\ngeneralize (rf_rf WF) (rf_fr WF) (co_co WF) (rf_co WF) (co_fr WF) (fr_fr WF) (fr_co WF).\nunfolder; ins; desf; try basic_solver 1.\nall: try (exfalso; basic_solver).\nall: basic_solver 42.\nQed.\n\nLemma eco_irr WF: irreflexive eco.\nProof using.\nunfold eco.\ngeneralize (co_irr WF) (rf_irr WF) (fr_irr WF).\ngeneralize (rf_fr WF) (rf_co WF).\nbasic_solver 5.\nQed.\n\nLemma eco_alt3 WF: eco ≡ (rf ∪ co ∪ fr)⁺.\nProof using.\nsplit; eauto 8 using rf_in_eco, co_in_eco, fr_in_eco, eco_trans with hahn.\nunfold eco; rewrite !crE; relsf. \nunionL; eauto 6 using inclusion_step2_ct with hahn.\nQed.\n\nLemma eco_f WF : eco ⨾ ⦗F⦘ ⊆ ∅₂.\nProof using.\nrewrite (wf_ecoD WF); type_solver.\nQed.\n\nLemma eco_almost_total WF COMP x y \n (ACTx: E x) (ACTy: E y)\n (RWx: RW x) (RWy: RW y) (LOC: loc x = loc y)\n (NEQ: x <> y): \n eco x y \\/ eco y x \\/ exists z, rf z x /\\ rf z y.\nProof using.\ngeneralize (dom_to_doma (wf_rfE WF)); intro rfE1; unfolder in rfE1.\ngeneralize (dom_to_domb (wf_rfE WF)); intro rfE2; unfolder in rfE2.\ngeneralize (dom_to_doma (wf_rfD WF)); intro rfD1; unfolder in rfD1.\ngeneralize (dom_to_domb (wf_rfD WF)); intro rfD2; unfolder in rfD2.\ngeneralize (loceq_rf WF); intro rfL; unfolder in rfL.\nassert (exists l, loc x = l).\nby destruct x; eauto.\nunfolder in RWx. \nunfolder in RWy.\nins; desf.\n- assert (exists wx, rf wx x) by (apply COMP; basic_solver).\n assert (exists wy, rf wy y) by (apply COMP; basic_solver).\n desf.\n destruct (classic (wx=wy)); try subst; eauto.\n assert (co wx wy \\/ co wy wx); cycle 1.\n by unfold eco, Execution.fr; basic_solver 42.\n eapply WF; unfolder; splits; eauto.\n by apply (loceq_rf WF) in H; apply (loceq_rf WF) in H0; congruence.\n- assert (exists wy, rf wy y) by (apply COMP; basic_solver).\n desf.\n destruct (classic (wy=x)); [subst; unfold eco; basic_solver 5|].\n assert (co wy x \\/ co x wy); cycle 1.\n by unfold eco, Execution.fr; basic_solver 42.\n eapply WF; unfolder; splits; eauto.\n by apply (loceq_rf WF) in H; congruence.\n- assert (exists wx, rf wx x).\n by apply COMP; basic_solver.\n desf.\n destruct (classic (wx=y)); [subst; unfold eco; basic_solver 5|].\n assert (co wx y \\/ co y wx); cycle 1.\n by unfold eco, Execution.fr; basic_solver 42.\n eapply WF; unfolder; splits; eauto.\n by apply (loceq_rf WF) in H; congruence.\n- assert (co x y \\/ co y x); [eapply WF|unfold eco]; basic_solver 10.\nQed.\n\n\nLemma transp_rf_rf_eco_in_eco WF : rf⁻¹ ⨾ rf ⨾ eco ⊆ eco.\nProof using.\nunfold eco, Execution.fr; relsf.\nrewrite rf_rf; auto.\nseq_rewrite rf_co; auto.\nrewrite !seqA.\nsin_rewrite rf_transp_rf; basic_solver 10.\nQed.\n\nLemma eco_transp_rf_rf_in_eco WF : eco ⨾ rf⁻¹ ⨾ rf ⊆ eco.\nProof using.\nunfold eco, Execution.fr; relsf.\nrewrite !seqA, !crE; relsf.\narewrite_false (co ⨾ rf⁻¹).\nby rewrite (wf_coD WF), (wf_rfD WF); type_solver.\nsin_rewrite !rf_transp_rf; auto.\nbasic_solver 8.\nQed.\n\n(******************************************************************************)\n(** ** implications of SC_PER_LOC *)\n(******************************************************************************)\n\nLemma no_co_to_init WF SC_PER_LOC : co ⊆ co ⨾ ⦗fun x => ~ is_init x⦘.\nProof using.\nrewrite wf_coE at 1; try done.\nunfolder; ins; splits; auto; desf; intro.\neapply SC_PER_LOC; exists x; splits; [|eby apply co_in_eco].\nunfold Execution.sb; unfolder; splits; try done.\ncut (~ is_init x).\nby destruct x, y; ins.\nintro.\nassert (x=y).\neby apply (loceq_co WF) in H0; eapply init_same_loc.\neby subst; eapply (co_irr WF).\nQed.\n\nLemma no_fr_to_init WF SC_PER_LOC : fr ⊆ fr ⨾ ⦗fun x => ~ is_init x⦘.\nProof using.\nunfold Execution.fr.\nrewrite no_co_to_init at 1; try done.\nbasic_solver.\nQed.\n\nLemma co_from_init WF SC_PER_LOC : \n ⦗fun x => is_init x⦘ ⨾ (same_loc \\ (fun x y => x = y)) ⨾ ⦗E ∩₁ W⦘ ⊆ co.\nProof using.\nunfolder; ins; desf.\ngeneralize (init_w WF H); intro Wx.\ngeneralize (is_w_loc lab x Wx).\nunfold Events.same_loc in *; ins; desf.\neapply tot_ex.\n- eapply WF.\n- basic_solver.\n- unfolder; splits; try edone.\n destruct x; [|unfold is_init in *; desf].\n eapply (wf_init WF); exists y; splits; eauto.\n unfold Events.loc in *.\n rewrite (wf_init_lab WF) in *.\n congruence.\n- intro A.\n hahn_rewrite (no_co_to_init WF SC_PER_LOC) in A.\n unfolder in *; desf.\n- intro; eauto.\nQed.\n\nLemma atomicity_alt WF SC_PER_LOC ATOM : rmw ∩ (fr ⨾ co) ⊆ ∅₂.\nProof using.\nrewrite rmw_from_non_init, no_fr_to_init; eauto.\nunfolder; red in ATOM; red in SC_PER_LOC; ins; desf.\ndestruct (classic (sb x z));\ndestruct (classic (sb z y)); eauto 8.\n- by eapply wf_rmwi; eauto.\n- eapply sb_semi_total_l with (y:=y) in H4; eauto.\n desf.\n eapply SC_PER_LOC.\n by eexists; splits; [eauto| apply co_in_eco].\n eby intro; subst; eapply (co_irr WF).\n eby apply rmw_in_sb.\n- eapply sb_semi_total_r with (x:=y) (y:=x) in H5; eauto.\n desf.\n eapply SC_PER_LOC.\n by eexists; splits; [eauto| apply fr_in_eco].\n eby intro; subst; eapply fr_irr.\n eby apply rmw_in_sb.\n- by eapply ATOM; unfolder; splits; eauto.\nQed.\n\nLemma BasicRMW WF SC_PER_LOC: irreflexive (co^? ⨾ rf ⨾ rmw).\nProof using.\nrewrite rmw_in_sb; try done.\nunfold sc_per_loc, eco in *; unfolder in *; basic_solver 10.\nQed.\n\nLemma w_r_loc_w_in_co WF r \n (rE: r ≡ ⦗E⦘ ⨾ r ⨾ ⦗E⦘) (IRR: irreflexive r)\n (A: irreflexive (r ⨾ eco)): \n ⦗W⦘ ⨾ r ∩ same_loc ⨾ ⦗W⦘ ⊆ co.\nProof using.\nrewrite rE.\nunfolder; ins; desf.\neapply tot_ex.\n- eapply WF.\n- unfolder; splits; try edone.\n- unfolder; splits; try edone.\n- intro; eapply A; unfold eco; basic_solver 12.\n- intro; subst; eapply IRR; eauto.\nQed.\n\nLemma w_r_loc_r_in_co_rf WF r\n (rE: r ≡ ⦗E⦘ ⨾ r ⨾ ⦗E⦘) \n (A: irreflexive (r ⨾ eco)) COMP : \n ⦗W⦘ ⨾ r ∩ same_loc ⨾ ⦗R⦘ ⊆ co^? ⨾ rf.\nProof using.\nrewrite rE.\ncut (⦗W⦘ ⨾ ⦗E⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ R⦘ ⊆ co^? ⨾ rf).\nby basic_solver 12.\nred in COMP; rewrite COMP.\nrewrite (dom_l (wf_rfD WF)) at 1.\nrewrite (dom_l (wf_rfE WF)) at 1.\nrewrite (loceq_same_loc (loceq_rf WF)) at 1.\nunfolder; ins; desf; eexists; splits; [|edone].\ndestruct (classic (x=z)); [eauto|].\nright; eapply tot_ex.\n- eapply WF.\n- splits; try edone.\n- splits; try edone.\n- intro; eapply A.\nunfold eco, Execution.fr; basic_solver 22.\n- congruence. \nQed.\n\nLemma r_r_loc_w_in_fr WF r\n (rE: r ≡ ⦗E⦘ ⨾ r ⨾ ⦗E⦘) \n (A: irreflexive (r ⨾ eco)) COMP : \n ⦗R⦘ ⨾ r ∩ same_loc ⨾ ⦗W⦘ ⊆ fr.\nProof using.\nrewrite rE.\ncut (⦗E ∩₁ R⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ W⦘ ⊆ fr).\nby basic_solver 12.\nred in COMP; rewrite COMP.\nrewrite (dom_l (wf_rfD WF)) at 1.\nrewrite (dom_l (wf_rfE WF)) at 1.\nrewrite (loceq_same_loc (loceq_rf WF)) at 1.\nunfolder; ins; desf; eexists; splits; [edone|].\n(* destruct (classic (x=z)); [eauto|]. *)\neapply tot_ex.\n- eapply WF.\n- splits; try edone.\n- unfolder; splits; [done | done | unfolder in *; congruence].\n- intro; eapply A.\nunfold eco; basic_solver 22.\n- intro; subst. \neapply A.\nunfold eco; basic_solver 22.\nQed.\n\nLemma r_r_loc_r_in_fr_rf WF r\n (rE: r ≡ ⦗E⦘ ⨾ r ⨾ ⦗E⦘) \n (A: irreflexive (r ⨾ eco)) COMP : \n ⦗R⦘ ⨾ r ∩ same_loc ⨾ ⦗R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf.\nProof using.\nrewrite rE.\ncut (⦗E ∩₁ R⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf).\nby basic_solver 12.\nred in COMP; rewrite COMP.\nrewrite (dom_l (wf_rfD WF)) at 1 2.\nrewrite (dom_l (wf_rfE WF)) at 1 2.\nrewrite (loceq_same_loc (loceq_rf WF)) at 1 2.\nunfolder; ins; desf.\ndestruct (classic (z0=z)).\nby right; eexists; subst; eauto.\nleft.\nunfold Execution.fr; unfolder.\neexists; splits; [|edone].\neexists; splits; [edone|].\neapply tot_ex.\n- eapply WF.\n- splits; try edone.\n- unfolder; splits; [done | done | unfolder in *; congruence].\n- intro; eapply A.\nunfold eco, Execution.fr; basic_solver 22.\n- intro; subst; eauto. \nQed.\n\nLemma w_sb_loc_w_in_coi WF SC_PER_LOC:\n ⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ coi.\nProof using.\narewrite (⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ (⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘) ∩ sb).\nbasic_solver.\nrewrite (w_r_loc_w_in_co WF (@wf_sbE G) (@sb_irr G) SC_PER_LOC).\nby ie_unfolder.\nQed.\n\nLemma w_sb_loc_r_in_co_rf WF SC_PER_LOC COMP:\n ⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗R⦘ ⊆ co^? ⨾ rf.\nProof using.\napply (w_r_loc_r_in_co_rf WF (@wf_sbE G) SC_PER_LOC COMP).\nQed.\n\nLemma r_sb_loc_w_in_fri WF SC_PER_LOC COMP:\n ⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ fri.\nProof using.\narewrite (⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ (⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘) ∩ sb).\nbasic_solver.\nrewrite (r_r_loc_w_in_fr WF (@wf_sbE G) SC_PER_LOC COMP).\nby ie_unfolder.\nQed.\n\nLemma r_sb_loc_r_in_fr_rf WF SC_PER_LOC COMP:\n ⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf.\nProof using.\napply (r_r_loc_r_in_fr_rf WF (@wf_sbE G) SC_PER_LOC COMP).\nQed.\n\nLemma rmw_in_fri WF SC_PER_LOC COMP : rmw ⊆ fri.\nProof using.\nrewrite (wf_rmwD WF), (rmw_in_sb_loc WF).\nrewrite (r_sb_loc_w_in_fri WF SC_PER_LOC COMP).\nie_unfolder; basic_solver.\nQed.\n\nLemma rmw_in_fr WF SC_PER_LOC COMP : rmw ⊆ fr.\nProof using.\n rewrite rmw_in_fri; auto. apply fri_in_fr.\nQed.\n\nLemma rf_rmw_in_co_helper WF SC_PER_LOC: rf ⨾ rmw ⊆ co ∪ co^{-1}.\nProof using.\nrewrite (dom_l WF.(wf_rfE)).\nrewrite (dom_r WF.(wf_rmwE)).\nrewrite (dom_l WF.(wf_rfD)).\nrewrite (dom_r WF.(wf_rmwD)).\nunfolder; ins; desf.\neapply WF.(wf_co_total); [basic_solver| |].\n{ unfolder; ins; desf; splits; eauto.\n apply WF.(wf_rfl) in H0.\n apply WF.(wf_rmwl) in H1.\n unfold Events.same_loc in *; congruence. }\nintro; subst.\neapply SC_PER_LOC.\nexists y; splits; eauto.\neapply WF.(rmw_in_sb); edone.\neapply rf_in_eco; edone.\nQed.\n\nLemma rf_rmw_in_co WF SC_PER_LOC : rf ⨾ rmw ⊆ co.\nProof using.\narewrite (rf ⨾ rmw ⊆ (rf ⨾ rmw) ∩ (rf ;; rmw)).\nrewrite rf_rmw_in_co_helper at 1; eauto.\nrewrite inter_union_l; unionL; [basic_solver|].\ntransitivity (fun _ _ : actid => False); [|basic_solver].\nunfolder; ins; desf.\neapply SC_PER_LOC.\nexists y; splits; eauto.\neapply WF.(rmw_in_sb); edone.\neapply co_rf_in_eco; basic_solver.\nQed.\n\nLemma rf_rmw_ct_in_co WF SC_PER_LOC : (rf ⨾ rmw)⁺ ⊆ co.\nProof using. by rewrite rf_rmw_in_co, (ct_of_trans (co_trans WF)). Qed.\n\nLemma rf_rmw_rt_in_co WF SC_PER_LOC : (rf ⨾ rmw)* ⊆ co^?.\nProof using. by rewrite rf_rmw_in_co, (rt_of_trans (co_trans WF)). Qed.\n\nLemma rf_rmw_in_coimm WF SC_PER_LOC ATOM: rf ⨾ rmw ⊆ immediate co.\nProof using.\nins; split; [by apply rf_rmw_in_co|].\nins; unfolder in *; desf.\neapply atomicity_alt; try done.\nunfold Execution.fr; basic_solver 10.\nQed.\n\n(******************************************************************************)\n(** ** properties of external/internal relations *)\n(******************************************************************************)\n\nLemma coe_coi WF SC_PER_LOC: coe ⨾ coi ⊆ coe.\nProof using.\ncut ((co \\ sb) ⨾ co ∩ sb ⊆ co ⨾ co \\ sb).\nby rewrite (co_co WF).\napply re_ri; try done; try by apply no_co_to_init.\nby apply co_irr.\nrotate 1.\nby rewrite co_in_eco.\nQed.\n\nLemma fre_coi WF SC_PER_LOC : fre ⨾ coi ⊆ fre.\nProof using.\ncut ((fr \\ sb) ⨾ co ∩ sb ⊆ fr ⨾ co \\ sb).\nby rewrite (fr_co WF).\napply re_ri; try done; try by apply no_fr_to_init.\nby apply fr_irr.\nrotate 1.\nby rewrite fr_in_eco.\nQed.\n\nLemma coi_coe WF SC_PER_LOC: \n ⦗fun x => ~ is_init x⦘ ⨾ coi ⨾ coe ⊆ coe.\nProof using.\ncut (⦗fun x => ~ is_init x⦘ ⨾ (co ∩ sb) ⨾ (co \\ sb) ⊆ co ⨾ co \\ sb).\nby rewrite (co_co WF).\napply ri_re; try done; try by apply no_co_to_init.\nby apply co_irr.\nrotate 1.\nby rewrite co_in_eco.\nQed.\n\nLemma rfe_fri WF SC_PER_LOC : rfe ;; fri ⊆ coe.\nProof using.\n cut ((rf \\ sb) ⨾ fr ∩ sb ⊆ rf ⨾ fr \\ sb).\n { by rewrite (rf_fr WF). }\n apply re_ri; try done; try by apply no_rf_to_init.\n { by apply rf_irr. }\n rotate 1. by rewrite rf_in_eco.\nQed.\n\nLemma eco_refl : \n eco^? ⊆ ((co ∪ fre)^? ⨾ rf^?) ∪ fri ⨾ rfi^? ∪ fri ⨾ rfe.\nProof using.\nunfold eco.\nrewrite !(@fri_union_fre G).\nrewrite !(@rfi_union_rfe G).\nbasic_solver 12.\nQed.\n\nLemma eco_alt4 WF : eco ⊆ ⦗RW⦘ ⨾ sb ∪ rfe ∪ co ⨾ rf^? ∪ fre ⨾ rf^? ∪ fri ⨾ rfe.\nProof using.\nunfold eco.\nrewrite (dom_l (wf_rfD WF)) at 1.\nrewrite (dom_l (wf_frD WF)) at 1.\nrewrite !(@fri_union_fre G); relsf.\nunionL.\n- rewrite !(@rfi_union_rfe G).\n arewrite (rfi ⊆ sb) at 1.\n basic_solver 12.\n- basic_solver 12.\n- rewrite !(@rfi_union_rfe G).\n case_refl (rfi ∪ rfe).\n arewrite (fri ⊆ sb); basic_solver 12.\n relsf; unionL; [|basic_solver 12].\n arewrite (fri ⊆ sb); arewrite (rfi ⊆ sb).\n generalize (@sb_trans G).\n basic_solver 12.\n- basic_solver 12.\nQed.\n\nLemma thread_rfe_sb WF SC_PER_LOC : (rfe^{-1} ⨾ sb) ∩ same_tid ⊆ ∅₂.\nProof using.\nie_unfolder; unfolder; unfold same_tid; ins; desf.\nhahn_rewrite (@wf_sbE G) in H1; unfolder in H1; desf.\nhahn_rewrite (wf_rfE WF) in H; unfolder in H; desf.\nhahn_rewrite (no_rf_to_init WF) in H5; unfolder in H5; desf.\napply (@same_thread G) in H0; try done.\ndesf.\n- destruct H0; [subst; auto|].\neapply sb_semi_total_r in H0; try edone.\n2: by intro; subst; eapply (rf_irr WF); edone.\ndesf; eapply SC_PER_LOC; unfold eco; basic_solver 12.\n- eapply H2; eapply (@sb_trans G); edone. \nQed.\n\nLemma co_sb_loc WF SC_PER_LOC : ⦗W⦘ ⨾ co^? ⨾ (sb ∩ same_loc)^? ⨾ ⦗W⦘ ⊆ co^?.\nProof using.\n case_refl (sb ∩ same_loc); [basic_solver|].\n rewrite (dom_r (wf_coD WF)).\n arewrite (⦗W⦘ ⨾ (co ⨾ ⦗W⦘)^? ⊆ co^? ⨾ ⦗W⦘) by basic_solver.\n rewrite (w_sb_loc_w_in_coi WF SC_PER_LOC), (dom_r (wf_coiD WF)).\n generalize (co_trans WF); ie_unfolder; basic_solver 12.\nQed.\n\nEnd ECO.\n", "meta": {"author": "fresheed", "repo": "omm-imm", "sha": "59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2", "save_path": "github-repos/coq/fresheed-omm-imm", "path": "github-repos/coq/fresheed-omm-imm/omm-imm-59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2/src/basic/Execution_eco.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.14940585351294156}} {"text": "Require Import CertiGraph.unionfind.env_unionfind.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\nRequire Import CertiGraph.msl_application.GList.\nRequire Import CertiGraph.msl_application.GList_UnionFind.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.unionfind.spatial_graph_glist.\n\nLocal Coercion UFGraph_LGraph: UFGraph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation vertices_at sh P g:= (@vertices_at _ _ _ _ _ mpred (@SGP pSGG_VST nat unit (sSGG_VST sh)) (SGA_VST sh) P g).\nNotation whole_graph sh g := (vertices_at sh (vvalid g) g).\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ x g).\nNotation UFGraph := (@UFGraph pSGG_VST).\nNotation uf_under_bound g := (uf_under_bound id g).\n#[local] Existing Instances maGraph finGraph liGraph RGF.\n\nDefinition vlabel_in_bound (g: UFGraph) := forall x, vvalid g x -> Z.of_nat (vlabel g x) <= Int.max_unsigned.\n\nLemma rank_unchanged_in_bound: forall (g g': UFGraph), uf_equiv g g' -> rank_unchanged g g' -> vlabel_in_bound g -> vlabel_in_bound g'.\nProof. unfold uf_equiv, rank_unchanged, vlabel_in_bound. intros. destruct H as [? _]. pose proof H2. rewrite <- H in H2. rewrite <- H0; auto. Qed.\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n WITH sh: wshare, n:Z\n PRE [tint]\n PROP (0 <= n <= Int.max_signed)\n PARAMS (Vint (Int.repr n))\n GLOBALS ()\n SEP ()\n POST [ tptr tvoid ]\n EX v: addr,\n PROP ()\n LOCAL (temp ret_temp (pointer_val_val v))\n SEP (data_at sh node_type (Vint (Int.repr 0), pointer_val_val null)\n (pointer_val_val v)).\n\nDefinition find_spec :=\n DECLARE _find\n WITH sh: wshare, g: UFGraph, x: pointer_val\n PRE [tptr (Tstruct _Node noattr)]\n PROP (vvalid g x ; uf_under_bound g)\n PARAMS (pointer_val_val x)\n GLOBALS ()\n SEP (whole_graph sh g)\n POST [ tptr (Tstruct _Node noattr) ]\n EX g': UFGraph, EX rt : pointer_val,\n PROP (uf_equiv g g'; uf_root g' x rt ; uf_under_bound g' ; rank_unchanged g g')\n LOCAL (temp ret_temp (pointer_val_val rt))\n SEP (whole_graph sh g').\n\nDefinition unionS_spec :=\n DECLARE _unionS\n WITH sh: wshare, g: UFGraph, x: pointer_val, y: pointer_val\n PRE [tptr (Tstruct _Node noattr), tptr (Tstruct _Node noattr)]\n PROP (vvalid g x; vvalid g y ; uf_under_bound g ; vlabel_in_bound g)\n PARAMS (pointer_val_val x; pointer_val_val y)\n GLOBALS ()\n SEP (whole_graph sh g)\n POST [ Tvoid ]\n EX g': UFGraph,\n PROP (uf_union g x y g' ; uf_under_bound g')\n LOCAL()\n SEP (whole_graph sh g').\n\nDefinition makeSet_spec :=\n DECLARE _makeSet\n WITH sh: wshare, g: UFGraph\n PRE []\n PROP (uf_under_bound g)\n PARAMS ()\n GLOBALS ()\n SEP (whole_graph sh g)\n POST [tptr (Tstruct _Node noattr)]\n EX g': UFGraph, EX rt: pointer_val,\n PROP (~ vvalid g rt ; vvalid g' rt ; is_partial_graph g g' ; uf_under_bound g')\n LOCAL (temp ret_temp (pointer_val_val rt))\n SEP (whole_graph sh g').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mallocN_spec; makeSet_spec; find_spec; unionS_spec]).\n\nLemma body_makeSet: semax_body Vprog Gprog f_makeSet makeSet_spec.\nProof.\n start_function.\n forward_call (sh, if Archi.ptr64 then 16 else 8).\n - cbv [Archi.ptr64]. rep_lia.\n - Intros x.\n assert_PROP (x <> null) as x_not_null by (entailer !; destruct H1 as [? _]; apply H1).\n assert_PROP (~ vvalid g x) by (entailer; apply (@vertices_at_sepcon_unique_1x _ _ _ _ SGBA_VST _ _ (SGA_VST sh) (SGAvs_VST sh) g x (vvalid g) (O, null))).\n forward. forward. forward.\n Exists (make_set_Graph O tt tt x g x_not_null H0) x. entailer !.\n + split; [|split]; simpl; [right | apply is_partial_make_set_pregraph | apply uf_under_bound_make_set_graph]; auto.\n + assert (Coqlib.Prop_join (vvalid g) (eq x) (vvalid (make_set_Graph 0%nat tt tt x g x_not_null H0))). {\n simpl; hnf; split; intros; [unfold graph_gen.addValidFunc | subst a]; intuition.\n } assert (vgamma (make_set_Graph O tt tt x g x_not_null H0) x = (O, x)). {\n unfold vgamma, UnionFindGraph.vgamma. simpl. f_equal.\n - destruct (SGBA_VE x x); [| hnf in c; unfold Equivalence.equiv in c; exfalso]; auto.\n - unfold graph_gen.updateEdgeFunc. destruct (EquivDec.equiv_dec (x, tt) (x, tt)). 2: compute in c; exfalso; auto. destruct (SGBA_VE null null); auto.\n hnf in c. unfold Equivalence.equiv in c. exfalso; auto.\n } rewrite <- (vertices_at_sepcon_1x (make_set_Graph 0%nat tt tt x g x_not_null H0) x (vvalid g) _ (O, x)); auto. apply sepcon_derives. 1: apply derives_refl.\n assert (vertices_at sh (vvalid g) g = vertices_at sh (vvalid g) (make_set_Graph O tt tt x g x_not_null H0)). {\n apply vertices_at_vertices_identical. simpl. hnf. intros. destruct a as [y ?]. unfold Morphisms_ext.app_sig. simpl.\n unfold UnionFindGraph.vgamma. simpl. unfold graph_gen.updateEdgeFunc. f_equal.\n - destruct (SGBA_VE y x); [hnf in e; subst y; exfalso |]; auto.\n - destruct (EquivDec.equiv_dec (x, tt) (y, tt)); auto. hnf in e. inversion e. subst y. exfalso; auto.\n } rewrite <- H6. apply derives_refl.\nQed.\n\nLemma false_Cne_eq: forall x y, typed_false tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n - destruct (Ptrofs.eq i i0) eqn:? .\n + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst; auto.\n + simpl in H. inversion H.\n - simpl in H. inversion H.\nQed.\n\nLemma true_Cne_neq: forall x y, typed_true tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n - destruct (Ptrofs.eq i i0) eqn:? .\n + simpl in H. inversion H.\n + subst b0. pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro; apply H0. inversion H1. reflexivity.\n - intro. inversion H0. auto.\nQed.\n\nLemma graph_local_facts: forall sh x (g: UFGraph), vvalid g x -> whole_graph sh g |-- valid_pointer (pointer_val_val x).\nProof.\n intros. eapply derives_trans; [apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (vgamma g x)); auto |].\n simpl vertex_at at 1. unfold binode. entailer!.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n start_function.\n remember (vgamma g x) as rpa eqn:?H. destruct rpa as [r pa].\n (* p = x -> parent; *)\n localize [data_at sh node_type (vgamma2cdata (vgamma g x)) (pointer_val_val x)]. rewrite <- H1. simpl vgamma2cdata.\n forward. 1: entailer!; destruct pa; simpl; auto.\n unlocalize [whole_graph sh g].\n 1: rewrite <- H1; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (r, pa)); auto.\n assert (H_PARENT_Valid: vvalid g pa) by (eapply valid_parent; eauto).\n (* if (p != x) { *)\n forward_if\n (EX g': UFGraph, EX rt : pointer_val,\n PROP (uf_equiv g g' /\\ uf_root g' x rt /\\ uf_under_bound g' /\\ rank_unchanged g g')\n LOCAL (temp _p (pointer_val_val rt); temp _x (pointer_val_val x))\n SEP (whole_graph sh g')).\n - apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n - (* p0 = find(p); *)\n forward_call (sh, g, pa). Intros vret. destruct vret as [g' root]. simpl fst in *. simpl snd in *.\n Opaque pointer_val_val. forward. Transparent pointer_val_val.\n assert (pa <> x). {\n intro; subst; apply H2; trivial.\n }\n assert (weak_valid g' root) by (right; destruct H4; apply reachable_foot_valid in H4; auto).\n assert (vvalid g' x) by (destruct H3 as [? _]; rewrite <- H3; apply H).\n assert (~ reachable g' root x) by (apply (uf_equiv_not_reachable g g' x r pa root); auto).\n assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' x root H8 H9 H10)) (Graph_gen_redirect_parent g' x root H8 H9 H10) =\n vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' x root H8 H9 H10)). {\n apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n remember (vgamma g' x) as rpa eqn:?H. destruct rpa as [r' pa']. symmetry in H12.\n localize [data_at sh node_type (Vint (Int.repr (Z.of_nat r')), pointer_val_val pa') (pointer_val_val x)].\n forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g' x root H8 H9 H10)].\n + rewrite H11. apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto. destruct H4.\n apply reachable_foot_valid in H4. intro. subst root. apply (valid_not_null g' null H4). simpl. auto.\n + Exists (Graph_gen_redirect_parent g' x root H8 H9 H10) root. rewrite H11. entailer!.\n assert (uf_root g' x root). {\n rewrite <- (uf_equiv_root_the_same g g' x root); auto.\n apply (uf_root_edge _ (liGraph g) _ pa); [| apply (vgamma_not_dst g x r pa) | rewrite (uf_equiv_root_the_same g g')]; auto.\n } split; [|split].\n * apply (graph_gen_redirect_parent_equiv g g' x r pa); auto.\n * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto. apply reachable_refl; auto.\n * apply uf_under_bound_redirect_parent; auto.\n - forward. Exists g x. entailer!.\n rename H2 into Htemp.\n assert (H2: pa = x). {\n destruct pa; destruct x; inversion Htemp; trivial.\n }\n subst pa. split.\n + apply (uf_equiv_refl _ (liGraph g)).\n + apply uf_root_vgamma with (n := r); auto.\n - Intros g' rt. forward. Exists g' rt. entailer!.\nQed. (* Original: 56.251 secs; VST 2.*: 2.084 secs*)\n\n(* Print Assumptions body_find. *)\n\nLemma true_Ceq_eq: forall x y, typed_true tint (force_val (sem_cmp_pp Ceq (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n - destruct (Ptrofs.eq i i0) eqn:? .\n + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst. reflexivity.\n + simpl in H. inversion H.\n - simpl in H. inversion H.\nQed.\n\nLemma false_Ceq_neq: forall x y, typed_false tint (force_val (sem_cmp_pp Ceq (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n - destruct (Ptrofs.eq i i0) eqn:? .\n + simpl in H. inversion H.\n + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro. apply H0. inversion H1. reflexivity.\n - intro. apply n. inversion H0; reflexivity.\nQed.\n\nLemma body_unionS: semax_body Vprog Gprog f_unionS unionS_spec.\nProof.\n start_function.\n forward_call (sh, g, x). Intros vret. destruct vret as [g1 x_root]. simpl fst in *. simpl snd in *. apply rank_unchanged_in_bound in H6; auto.\n assert (vvalid g1 y) by (destruct H3 as [? _]; rewrite <- H3; apply H0).\n forward_call (sh, g1, y). Intros vret. destruct vret as [g2 y_root]. simpl fst in *. simpl snd in *. apply rank_unchanged_in_bound in H11; auto.\n assert (H_VALID_XROOT: vvalid g2 x_root) by (destruct H8 as [? _]; rewrite <- H8; destruct H4; apply reachable_foot_valid in H4; apply H4).\n assert (H_VALID_YROOT: vvalid g2 y_root) by (destruct H9; apply reachable_foot_valid in H9; apply H9).\n assert (H_XROOT_NOT_NULL: x_root <> null) by (intro; subst x_root; apply (valid_not_null g2 null H_VALID_XROOT); simpl; auto).\n assert (H_YROOT_NOT_NULL: y_root <> null) by (intro; subst y_root; apply (valid_not_null g2 null H_VALID_YROOT); simpl; auto).\n forward_if_tac\n (PROP (x_root <> y_root)\n LOCAL (temp _yRoot (pointer_val_val y_root); temp _xRoot (pointer_val_val x_root);\n temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n SEP (vertices_at sh (vvalid g2) g2)).\n - apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n - forward.\n rename H12 into Htemp.\n assert (H12: x_root = y_root). {\n destruct x_root; destruct y_root; inversion Htemp; trivial.\n }\n Exists g2. subst y_root. entailer!. apply (the_same_root_union g g1 g2 x y x_root); auto.\n - forward.\n rename H12 into Htemp.\n assert (x_root <> y_root). {\n intro; subst; apply Htemp; trivial.\n }\n entailer!.\n - Intros. (* xRank = xRoot -> rank; *)\n remember (vgamma g2 x_root) as rpa eqn:?H. destruct rpa as [rankXRoot paXRoot]. symmetry in H13.\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n rewrite H13. simpl vgamma2cdata. forward.\n unlocalize [whole_graph sh g2].\n 1: rewrite H13; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g2 (vvalid g2) x_root (rankXRoot, paXRoot)); auto.\n (* yRank = yRoot -> rank; *)\n remember (vgamma g2 y_root) as rpa eqn:?H. destruct rpa as [rankYRoot paYRoot]. symmetry in H14.\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n rewrite H14. simpl vgamma2cdata. forward.\n unlocalize [whole_graph sh g2].\n 1: rewrite H14; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g2 (vvalid g2) y_root (rankYRoot, paYRoot)); auto.\n rename H_VALID_XROOT into H15. clear H1 H2 H5 H6.\n assert (Int.unsigned (Int.repr (Z.of_nat rankXRoot)) = Z.of_nat (vlabel g2 x_root)). {\n simpl vgamma in H13. inversion H13. apply Int.unsigned_repr. split; [apply Zle_0_nat | specialize (H11 x_root H15); auto].\n } assert (Int.unsigned (Int.repr (Z.of_nat rankYRoot)) = Z.of_nat (vlabel g2 y_root)). {\n simpl vgamma in H14. inversion H14. apply Int.unsigned_repr. split; [apply Zle_0_nat | specialize (H11 y_root H_VALID_YROOT); auto].\n } clear H11.\n forward_if\n (EX g': UFGraph,\n PROP (uf_union g x y g' /\\ uf_under_bound g')\n LOCAL (temp _xRank (Vint (Int.repr (Z.of_nat rankXRoot))); temp _yRank (Vint (Int.repr (Z.of_nat rankYRoot)));\n temp _xRoot (pointer_val_val x_root); temp _yRoot (pointer_val_val y_root);\n temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n SEP (whole_graph sh g')).\n + assert (weak_valid g2 y_root) by (right; auto).\n assert (~ reachable g2 y_root x_root) by (intro; destruct H9; specialize (H16 _ H11); auto).\n assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)) (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11) =\n vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)). {\n apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n (* xRoot -> parent = yRoot; *)\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n rewrite H13. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)].\n 1: rewrite H13; simpl vgamma2cdata; rewrite H16; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n Exists (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11). entailer !. split.\n * apply (diff_root_union_1 g g1 g2 x y x_root y_root); auto.\n * rewrite H1 in *. rewrite H2 in *. rewrite <- Nat2Z.inj_lt in H5. destruct H9. apply uf_under_bound_redirect_parent_lt; auto.\n + assert (weak_valid g2 x_root) by (right; auto). rename H_VALID_YROOT into H11.\n assert (~ reachable g2 x_root y_root) by (intro; rewrite (uf_equiv_root_the_same g1 g2) in H4; auto; destruct H4; specialize (H17 _ H16); auto).\n assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)) (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16) =\n vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)). {\n apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n forward_if\n (EX g': UFGraph,\n PROP (uf_union g x y g' /\\ uf_under_bound g')\n LOCAL (temp _xRank (Vint (Int.repr (Z.of_nat rankXRoot))); temp _yRank (Vint (Int.repr (Z.of_nat rankYRoot)));\n temp _xRoot (pointer_val_val x_root); temp _yRoot (pointer_val_val y_root);\n temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n SEP (whole_graph sh g')).\n * (* yRoot -> parent = xRoot; *)\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n rewrite H14. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)].\n 1: rewrite H14; simpl vgamma2cdata; rewrite H17; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n Exists (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16). entailer!. split.\n -- apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto.\n -- rewrite H1 in *. rewrite H2 in *. rewrite <- Nat2Z.inj_lt in H18. apply uf_under_bound_redirect_parent_lt; auto.\n rewrite (uf_equiv_root_the_same g1 g2) in H4; auto. destruct H4. auto.\n * (* yRoot -> parent = xRoot; *)\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n rewrite H14. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)].\n 1: rewrite H14; simpl vgamma2cdata; rewrite H17; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n set (g3 := Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16).\n assert (uf_union g x y g3) by (subst g3; simpl; apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto).\n (* xRoot -> rank = xRank + 1; *)\n localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n rewrite H13. simpl vgamma2cdata. forward.\n rewrite add_repr. replace (Z.of_nat rankXRoot + 1) with (Z.of_nat (rankXRoot + 1)). 2: rewrite Nat2Z.inj_add; simpl; auto.\n unlocalize [whole_graph sh (Graph_vgen g3 x_root (rankXRoot + 1)%nat)].\n -- assert (vertices_at sh (vvalid (Graph_vgen g3 x_root (rankXRoot + 1)%nat)) (Graph_vgen g3 x_root (rankXRoot + 1)%nat) =\n vertices_at sh (vvalid g3) (Graph_vgen g3 x_root (rankXRoot + 1)%nat)). {\n apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition.\n } rewrite H20. clear H20. rewrite H13. simpl vgamma2cdata. apply (@graph_vgen_ramify _ (sSGG_VST sh)).\n ++ subst g3. simpl. destruct H8 as [? _]. rewrite <- H8. destruct H4; apply reachable_foot_valid in H4; apply H4.\n ++ subst g3. remember (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16) as g3.\n apply (graph_gen_redirect_parent_vgamma _ _ _ rankXRoot paXRoot) in Heqg3; auto. intros. inversion H20; auto.\n -- Exists (Graph_vgen g3 x_root (rankXRoot + 1)%nat). entailer!. rewrite H1 in *; rewrite H2 in *.\n assert (Z.of_nat (vlabel g2 x_root) = Z.of_nat (vlabel g2 y_root)) by (clear -H5 H18; intuition). apply Nat2Z.inj in H24.\n simpl in H13. inversion H13. apply uf_under_bound_redirect_parent_eq; auto. rewrite (uf_equiv_root_the_same g1 g2) in H4; auto. destruct H4. auto.\n + Intros g'. Exists g'. entailer!.\nQed. (* Original: 192.772 secs; VST 2.*: 4.786 secs *)\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/unionfind/verif_unionfind_rank.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.14940585351294156}} {"text": "(*! Language | Semantics of typed Kôika programs with compact logs !*)\nRequire Export Koika.Common Koika.Environments Koika.CompactLogs Koika.Syntax Koika.TypedSyntax.\n\nSection Interp.\n Context {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t: Type}.\n Context {reg_t_eq_dec: EqDec reg_t}.\n\n Context {R: reg_t -> type}.\n Context {Sigma: ext_fn_t -> ExternalSignature}.\n\n Context {REnv: Env reg_t}.\n\n Notation Log := (Log R REnv).\n\n Notation rule := (rule pos_t var_t fn_name_t R Sigma).\n Notation action := (action pos_t var_t fn_name_t R Sigma).\n Notation scheduler := (scheduler pos_t rule_name_t).\n\n Definition tcontext (sig: tsig var_t) :=\n context (fun k_tau => type_denote (snd k_tau)) sig.\n\n Definition acontext (sig argspec: tsig var_t) :=\n context (fun k_tau => action sig (snd k_tau)) argspec.\n\n Section Action.\n Context (r: REnv.(env_t) R).\n Context (sigma: forall f, Sig_denote (Sigma f)).\n\n Section Args.\n Context (interp_action:\n forall {sig: tsig var_t} {tau}\n (Gamma: tcontext sig)\n (sched_log: Log) (action_log: Log)\n (a: action sig tau),\n option (Log * type_denote tau * (tcontext sig))).\n\n Fixpoint interp_args'\n {sig: tsig var_t}\n (Gamma: tcontext sig)\n (sched_log: Log)\n (action_log: Log)\n {argspec: tsig var_t}\n (args: acontext sig argspec)\n : option (Log * tcontext argspec * (tcontext sig)) :=\n match args with\n | CtxEmpty => Some (action_log, CtxEmpty, Gamma)\n | @CtxCons _ _ argspec k_tau arg args =>\n let/opt3 action_log, ctx, Gamma := interp_args' Gamma sched_log action_log args in\n let/opt3 action_log, v, Gamma := interp_action _ _ Gamma sched_log action_log arg in\n Some (action_log, CtxCons k_tau v ctx, Gamma)\n end.\n End Args.\n\n Fixpoint interp_action\n {sig: tsig var_t}\n {tau}\n (Gamma: tcontext sig)\n (sched_log: Log)\n (action_log: Log)\n (a: action sig tau)\n {struct a}\n : option (Log * tau * (tcontext sig)) :=\n match a in TypedSyntax.action _ _ _ _ _ ts tau return (tcontext ts -> option (Log * tau * (tcontext ts))) with\n | Fail tau => fun _ =>\n None\n | Var m => fun Gamma =>\n Some (action_log, cassoc m Gamma, Gamma)\n | Const cst => fun Gamma =>\n Some (action_log, cst, Gamma)\n | Seq r1 r2 => fun Gamma =>\n let/opt3 action_log, _, Gamma := interp_action Gamma sched_log action_log r1 in\n interp_action Gamma sched_log action_log r2\n | @Assign _ _ _ _ _ _ _ _ k tau m ex => fun Gamma =>\n let/opt3 action_log, v, Gamma := interp_action Gamma sched_log action_log ex in\n Some (action_log, Ob, creplace m v Gamma)\n | @Bind _ _ _ _ _ _ _ sig tau tau' var ex body => fun (Gamma : tcontext sig) =>\n let/opt3 action_log1, v, Gamma := interp_action Gamma sched_log action_log ex in\n let/opt3 action_log2, v, Gamma := interp_action (CtxCons (var, tau) v Gamma) sched_log action_log1 body in\n Some (action_log2, v, ctl Gamma)\n | If cond tbranch fbranch => fun Gamma =>\n let/opt3 action_log, cond, Gamma := interp_action Gamma sched_log action_log cond in\n if Bits.single cond then\n interp_action Gamma sched_log action_log tbranch\n else\n interp_action Gamma sched_log action_log fbranch\n | Read P0 idx => fun Gamma =>\n if may_read0 sched_log idx then\n Some (Environments.update\n REnv action_log idx\n (fun rl => {| lread0 := true; lread1 := rl.(lread1);\n lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),\n REnv.(getenv) r idx,\n Gamma)\n else None\n | Read P1 idx => fun Gamma =>\n if may_read1 sched_log idx then\n Some (Environments.update\n REnv action_log idx\n (fun rl => {| lread0 := rl.(lread1); lread1 := true;\n lwrite0 := rl.(lwrite0); lwrite1 := rl.(lwrite1) |}),\n match (REnv.(getenv) action_log idx).(lwrite0), (REnv.(getenv) sched_log idx).(lwrite0) with\n | Some v, _ => v\n | _, Some v => v\n | _, _ => REnv.(getenv) r idx\n end,\n Gamma)\n else None\n | Write P0 idx val => fun Gamma =>\n let/opt3 action_log, val, Gamma_new := interp_action Gamma sched_log action_log val in\n if may_write0 sched_log action_log idx then\n Some (Environments.update\n REnv action_log idx\n (fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);\n lwrite0 := Some val; lwrite1 := rl.(lwrite1) |}),\n Bits.nil, Gamma_new)\n else None\n | Write P1 idx val => fun Gamma =>\n let/opt3 action_log, val, Gamma_new := interp_action Gamma sched_log action_log val in\n if may_write1 sched_log action_log idx then\n Some (Environments.update\n REnv action_log idx\n (fun rl => {| lread0 := rl.(lread1); lread1 := rl.(lread1);\n lwrite0 := rl.(lwrite0); lwrite1 := Some val |}),\n Bits.nil, Gamma_new)\n else None\n | Unop fn arg1 => fun Gamma =>\n let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n Some (action_log, (PrimSpecs.sigma1 fn) arg1, Gamma)\n | Binop fn arg1 arg2 => fun Gamma =>\n let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n let/opt3 action_log, arg2, Gamma := interp_action Gamma sched_log action_log arg2 in\n Some (action_log, (PrimSpecs.sigma2 fn) arg1 arg2, Gamma)\n | ExternalCall fn arg1 => fun Gamma =>\n let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n Some (action_log, sigma fn arg1, Gamma)\n | InternalCall name args body => fun Gamma =>\n let/opt3 action_log, results, Gamma := interp_args' (@interp_action) Gamma sched_log action_log args in\n let/opt3 action_log, v, _ := interp_action results sched_log action_log body in\n Some (action_log, v, Gamma)\n | APos _ a => fun Gamma =>\n interp_action Gamma sched_log action_log a\n end Gamma.\n\n Definition interp_rule (sched_log: Log) (rl: rule) : option Log :=\n match interp_action CtxEmpty sched_log log_empty rl with\n | Some (l, _, _) => Some l\n | None => None\n end.\n End Action.\n\n Section Scheduler.\n Context (r: REnv.(env_t) R).\n Context (sigma: forall f, Sig_denote (Sigma f)).\n Context (rules: rule_name_t -> rule).\n\n Fixpoint interp_scheduler'\n (sched_log: Log)\n (s: scheduler)\n {struct s} :=\n let interp_try rl s1 s2 :=\n match interp_rule r sigma sched_log (rules rl) with\n | Some l => interp_scheduler' (log_app l sched_log) s1\n | None => interp_scheduler' sched_log s2\n end in\n match s with\n | Done => sched_log\n | Cons r s => interp_try r s s\n | Try r s1 s2 => interp_try r s1 s2\n | SPos _ s => interp_scheduler' sched_log s\n end.\n\n Definition interp_scheduler (s: scheduler) :=\n interp_scheduler' log_empty s.\n End Scheduler.\n\n Definition interp_cycle (sigma: forall f, Sig_denote (Sigma f)) (rules: rule_name_t -> rule)\n (s: scheduler) (r: REnv.(env_t) R) :=\n commit_update r (interp_scheduler r sigma rules s).\nEnd Interp.\n\nNotation interp_args r sigma Gamma sched_log action_log args :=\n (interp_args' (@interp_action _ _ _ _ _ _ _ _ r sigma) Gamma sched_log action_log args).\n", "meta": {"author": "mit-plv", "repo": "koika", "sha": "c758c7b0092186f76ed858f4137366cc62f7a04a", "save_path": "github-repos/coq/mit-plv-koika", "path": "github-repos/coq/mit-plv-koika/koika-c758c7b0092186f76ed858f4137366cc62f7a04a/coq/CompactSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.14889974403968265}} {"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\nRequire Import iCompatibility.\n\nRequire Import FulfillStep.\nRequire Import ReorderStep.\nRequire Import ReorderRelFenceCommon.\n\nRequire Import ITreeLang.\nRequire Import Program.\n\nSet Implicit Arguments.\n\n\nInductive reorder_release_fenceF: forall R (i2:MemE.t R), Prop :=\n| reorder_release_fenceF_load\n l2 o2:\n reorder_release_fenceF (MemE.read l2 o2)\n| reorder_release_fenceF_store\n l2 v2 o2\n (ORD21: Ordering.le o2 Ordering.plain \\/ Ordering.le Ordering.acqrel o2)\n (ORD22: Ordering.le Ordering.plain o2):\n reorder_release_fenceF (MemE.write l2 v2 o2)\n| reorder_release_fenceF_update\n l2 rmw2 or2 ow2\n (ORDW2: Ordering.le ow2 Ordering.plain \\/ Ordering.le Ordering.acqrel ow2):\n reorder_release_fenceF (MemE.update l2 rmw2 or2 ow2)\n| reorder_release_fenceF_fence:\n reorder_release_fenceF (MemE.fence Ordering.acqrel Ordering.plain)\n.\n\nInductive sim_release_fenceF: forall R\n (st_src:itree MemE.t (unit * R)%type) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n (st_tgt:itree MemE.t (unit * R)%type) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_relese_fenceF_intro\n R (v: R) pview\n lc1_src sc1_src mem1_src\n lc1_tgt sc1_tgt mem1_tgt\n (LOCALF: sim_local pview lc1_src (local_relfenced lc1_tgt)):\n sim_release_fenceF\n (Ret (tt, v)) lc1_src sc1_src mem1_src\n (Vis (MemE.fence Ordering.plain Ordering.acqrel) (fun r => Ret (r, v))) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_release_fenceF_step\n R\n st1_src lc1_src sc0_src mem0_src\n st1_tgt lc1_tgt sc0_tgt mem0_tgt\n (SIM: sim_release_fenceF st1_src lc1_src sc0_src mem0_src\n st1_tgt lc1_tgt sc0_tgt mem0_tgt):\n forall sc1_src sc1_tgt\n mem1_src mem1_tgt\n (SC: TimeMap.le sc1_src sc1_tgt)\n (MEMORY: sim_memory mem1_src mem1_tgt)\n (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n (MEM_FUTURE_SRC: Memory.future_weak mem0_src mem1_src)\n (MEM_FUTURE_TGT: Memory.future_weak mem0_tgt mem1_tgt)\n (WF_SRC: Local.wf lc1_src mem1_src)\n (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n (MEM_SRC: Memory.closed mem1_src)\n (MEM_TGT: Memory.closed mem1_tgt),\n _sim_thread_step (lang (unit * R)%type) (lang (unit * R)%type)\n ((@sim_thread (lang (unit * R)%type) (lang (unit * R)%type) (sim_terminal eq)) \\8/ @sim_release_fenceF R)\n st1_src lc1_src sc1_src mem1_src\n st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n destruct SIM; ii. right.\n inv STEP_TGT; [inv STEP|dependent destruction STEP; inv LOCAL; ss; dependent destruction STATE]; ss.\n - (* promise *)\n exploit sim_local_promise_relfenced; eauto. i. des.\n esplits.\n + ss.\n + eauto.\n + econs 2. econs 1. econs; eauto.\n + auto.\n + auto.\n + auto.\n + right. econs 1; eauto.\n - (* fence *)\n exploit sim_local_fence_tgt_relfenced; try exact SC; eauto. i. des.\n esplits.\n + ss.\n + eauto.\n + econs 1.\n + auto.\n + auto.\n + auto.\n + left. eapply paco11_mon; [apply sim_itree_ret|]; ss.\nQed.\n\nLemma sim_release_fenceF_sim_thread R:\n @sim_release_fenceF R <8= (@sim_thread (lang (unit * R)%type) (lang (unit * R)%type) (sim_terminal eq)).\nProof.\n pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n - right. inv TERMINAL_TGT. inv PR; ss.\n - right. inv PR.\n esplits; eauto.\n eapply sim_local_memory_bot; eauto.\n - exploit sim_release_fenceF_step; try apply PR; try apply SC; eauto. i. des; eauto.\n + right. esplits; eauto.\n left. eapply paco11_mon; eauto. ss.\n + right. esplits; eauto.\nQed.\n\nLemma reorder_release_fenceF_sim_itree R\n (i1: MemE.t R) (REORDER: reorder_release_fenceF i1):\n sim_itree eq\n (Vis (MemE.fence Ordering.plain Ordering.acqrel) (fun r0 => Vis i1 (fun r => Ret (r0, r))))\n (Vis i1 (fun r => Vis (MemE.fence Ordering.plain Ordering.acqrel) (fun r0 => Ret (r0, r)))).\nProof.\n pcofix CIH. ii. subst. pfold. ii. splits; ii.\n { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }\n { right. esplits; eauto.\n inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n }\n inv STEP_TGT.\n { (* promise *)\n right.\n inv STEP.\n exploit sim_local_promise_bot; eauto. i. des.\n esplits; try apply SC; eauto; ss.\n econs 2. econs 1; eauto. econs; eauto.\n }\n exploit sim_local_intro_relfenced; eauto. i. des.\n exploit sim_local_nonsynch_src; try exact SC_SRC; eauto using local_relfenced_wf. i. des.\n instantiate (3:=lang (unit * R)) in STEP_SRC.\n instantiate (2:=Vis (MemE.fence Ordering.plain Ordering.acqrel)\n (fun r0 => Vis i1 (fun r => Ret (r0, r)))) in STEP_SRC.\n exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n exploit sim_local_fence_src_relfenced; eauto. i. des.\n exploit Local.fence_step_future; eauto. i. des.\n inv STEP. inv LOCAL1; ss; dependent destruction STATE; inv REORDER.\n - (* load *)\n right.\n exploit sim_local_read_relfenced; eauto; try refl. i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs. econs.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* update-load *)\n right.\n guardH ORDW2.\n exploit sim_local_read_relfenced; eauto; try refl. i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs; eauto.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* write *)\n right.\n guardH ORD21.\n hexploit sim_local_write_relfenced; try exact SC;\n try match goal with\n | [|- is_true (Ordering.le _ _)] => refl\n end; eauto; (try by econs). i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 3]; eauto. econs. econs.\n replace sc2_src with sc1_src; eauto. apply TimeMap.antisym; ss.\n + auto.\n + auto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* update *)\n right.\n guardH ORDW2.\n exploit Local.read_step_future; eauto. i. des.\n exploit sim_local_read_relfenced; eauto; try refl. i. des.\n exploit Local.read_step_future; eauto. i. des.\n hexploit sim_local_write_relfenced; try exact SC;\n try match goal with\n | [|- is_true (Ordering.le _ _)] => refl\n end; eauto; (try by econs). i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 4]; eauto.\n * econs; eauto.\n * replace sc2_src with sc1_src; eauto. apply TimeMap.antisym; ss.\n + auto.\n + auto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* fence *)\n right.\n exploit sim_local_fence_relfenced; try exact SC; eauto; try refl. i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 5]; eauto.\n * econs. econs.\n * replace sc2_src with sc1_src; eauto. apply TimeMap.antisym; ss.\n + auto.\n + auto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* na write *)\n inv LOCAL3. destruct ord; ss.\n - (* racy read *)\n right.\n exploit sim_local_racy_read_relfenced; eauto; try refl. i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 9]; eauto. econs. econs.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* racy update-load *)\n right.\n guardH ORDW2.\n exploit sim_local_racy_read_relfenced; eauto; try refl. i. des.\n esplits.\n + ss.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs 2. econs; [|econs 9]; eauto. econs; eauto.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco11_mon; [apply sim_release_fenceF_sim_thread|]; ss.\n econs. eauto.\n - (* racy write *)\n left.\n guardH ORD21.\n exploit sim_local_racy_write_relfenced;\n try match goal with\n | [|- is_true (Ordering.le _ _)] => refl\n end; eauto. i. des.\n unfold Thread.steps_failure. esplits.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs; [|econs 10]; eauto. econs. econs.\n + ss.\n - (* racy update *)\n left.\n guardH ORDW2.\n exploit sim_local_racy_update_relfenced;\n try match goal with\n | [|- is_true (Ordering.le _ _)] => refl\n end; eauto. i. des.\n unfold Thread.steps_failure. esplits.\n + etrans; [eauto|]. econs 2; [|refl]. econs.\n * econs. econs 2. econs; [|econs 5]; eauto. econs. econs.\n * ss.\n + econs 2. econs; [|econs 11]; eauto. econs; eauto.\n + ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/transformation/iReorderRelFence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.14889974089336905}} {"text": "(******************************************************************************)\n(** * Compilation correctness from the S_IMM memory model to the ARMv8.3 model *)\n(******************************************************************************)\n\nFrom hahn Require Import Hahn.\nRequire Import AuxRel2.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import Arm.\nRequire Import imm_bob.\nRequire Import imm_s_ppo.\nRequire Import imm_s_rfppo.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import imm_ppo.\nRequire Import imm_hb.\nRequire Import imm.\nRequire Import immToARMhelper.\nRequire Import imm_s_hb_hb.\nRequire Import ImmFair.\nRequire Import FairExecution.\n\nSet Implicit Arguments.\n\nSection immToARM.\n\nVariable G : execution.\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'data'\" := (data G).\nNotation \"'addr'\" := (addr G).\nNotation \"'ctrl'\" := (ctrl G).\nNotation \"'deps'\" := (deps G).\nNotation \"'rmw_dep'\" := (rmw_dep G).\n\nNotation \"'fre'\" := (fre G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'coe'\" := (coe G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'fri'\" := (fri G).\nNotation \"'coi'\" := (coi G).\nNotation \"'fr'\" := (fr G).\nNotation \"'eco'\" := (eco G).\n\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\n\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\nNotation \"'detour'\" := (detour G).\nNotation \"'bob'\" := (bob G).\n\n(* imm_s *)\nNotation \"'s_sw'\" := (imm_s_hb.sw G).\nNotation \"'s_release'\" := (imm_s_hb.release G).\nNotation \"'s_rs'\" := (imm_s_hb.rs G).\nNotation \"'s_hb'\" := (imm_s_hb.hb G).\nNotation \"'s_ppo'\" := (imm_s_ppo.ppo G).\nNotation \"'s_psc_f'\" := (imm_s.psc_f G).\nNotation \"'s_psc_base'\" := (imm_s.psc_base G).\nNotation \"'s_ar_int'\" := (imm_s_ppo.ar_int G).\n\n(* imm *)\nNotation \"'sw'\" := (imm_hb.sw G).\nNotation \"'release'\" := (imm_hb.release G).\nNotation \"'rs'\" := (imm_hb.rs G).\nNotation \"'hb'\" := (imm_hb.hb G).\nNotation \"'ppo'\" := (imm_ppo.ppo G).\nNotation \"'psc'\" := (imm.psc G).\nNotation \"'psc_f'\" := (imm.psc_f G).\nNotation \"'psc_base'\" := (imm.psc_base G).\nNotation \"'ar_int'\" := (imm_ppo.ar_int G).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (fun a => is_true (is_rlx lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Acqrel'\" := (fun a => is_true (is_acqrel lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\n(* arm *)\nNotation \"'obs'\" := (obs G).\nNotation \"'obs''\" := (obs' G).\nNotation \"'aob'\" := (aob G).\nNotation \"'boba'\" := (Arm.bob G).\nNotation \"'boba''\" := (bob' G).\nNotation \"'dob'\" := (dob G).\n\nNotation \"'L'\" := (W ∩₁ (fun a => is_true (is_rel lab a))).\nNotation \"'Q'\" := (R ∩₁ (fun a => is_true (is_acq lab a))).\nNotation \"'A'\" := (R ∩₁ (fun a => is_true (is_sc lab a))).\n\nNotation \"'F^ld'\" := (F ∩₁ (fun a => is_true (is_acq lab a))).\nNotation \"'F^sy'\" := (F ∩₁ (fun a => is_true (is_rel lab a))).\n\nHypothesis RMW_DEPS : rmw ⊆ ctrl ∪ data.\nHypothesis W_EX_ACQ_SB : ⦗W_ex_acq⦘ ⨾ sb ⊆ sb ⨾ ⦗F^ld⦘ ⨾ sb^?.\nHypothesis DEPS_RMW_SB : rmw_dep ⨾ sb ⊆ ctrl.\nHypothesis REX_IN_RMW_CTRL : ⦗R_ex⦘ ⨾ sb ⊆ ctrl.\n\nHypothesis CON: ArmConsistent G.\n\nLemma WF : Wf G.\nProof using CON. apply CON. Qed.\nLemma COMP : complete G.\nProof using CON. apply CON. Qed.\nLemma SC_PER_LOC : sc_per_loc G.\nProof using CON. apply CON. Qed.\n\nLemma RMW_COI : rmw ⨾ coi ⊆ obs' ∪ dob ∪ aob ∪ boba.\nProof using CON.\n cdes CON. rewrite rmw_in_fri; auto.\n rewrite fri_coi; auto. rewrite fri_in_fr. \n unfold Arm.obs'. eauto with hahn.\nQed.\n\nLemma R_ex_fail_sb_in_ctrl : ⦗R_ex \\₁ dom_rel rmw⦘ ⨾ sb ⊆ ctrl.\nProof using REX_IN_RMW_CTRL.\n rewrite <- REX_IN_RMW_CTRL.\n basic_solver.\nQed.\n\nLemma s_ppo_in_dob : s_ppo ⊆ dob⁺.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n unfold imm_s_ppo.ppo.\n rewrite REX_IN_RMW_CTRL.\n arewrite (data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi ∪ rmw ∪ rmw_dep ⨾ sb^? ∪ ctrl ⊆\n data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi ∪ rmw_dep ⨾ sb^?).\n { rewrite RMW_DEPS. unionL; eauto with hahn. }\n rewrite path_union, !seq_union_l, !seq_union_r. unionL.\n { apply ppo_in_dob_helper; auto. }\n assert ((data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi)* ⊆ sb^?) as AA.\n { rewrite (data_in_sb WF), (ctrl_in_sb WF), (addr_in_sb WF).\n arewrite (rfi ⊆ sb).\n generalize (@sb_trans G). ins. relsf. }\n rewrite AA at 2.\n rewrite ct_begin, !seqA.\n rewrite AA at 2.\n arewrite (sb^? ⨾ (sb^? ⨾ rmw_dep ⨾ sb^?)* ⨾ sb^? ⊆ sb^?).\n { rewrite (rmw_dep_in_sb WF). generalize (@sb_trans G). ins. relsf. }\n arewrite (rmw_dep ⨾ sb^? ⨾ ⦗W⦘ ⊆ rmw_dep ⨾ sb ⨾ ⦗W⦘).\n { rewrite (dom_r (wf_rmw_depD WF)) at 1. rewrite R_ex_in_R. type_solver. }\n sin_rewrite DEPS_RMW_SB.\n arewrite (ctrl ⊆ data ∪ ctrl ∪ addr ⨾ sb^? ∪ rfi) at 2.\n seq_rewrite <- ct_end.\n apply ppo_in_dob_helper; auto.\nQed.\n\nLemma s_ppo_in_ord : s_ppo ⊆ (obs⁺ ∩ sb ∪ dob ∪ aob ∪ boba' ∪ sb ⨾ ⦗F^ld⦘)⁺.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n rewrite s_ppo_in_dob. apply clos_trans_mori. eauto with hahn. \nQed.\n\nLemma s_ar_int_in_ord : ⦗R⦘ ⨾ s_ar_int⁺ ⨾ ⦗W⦘ ⊆ (obs ∪ dob ∪ aob ∪ boba')⁺.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n unfold imm_s_ppo.ar_int.\n transitivity (⦗R⦘ ⨾ ((obs⁺∩ sb) ∪ dob ∪ aob ∪ boba' ∪ sb ⨾ ⦗F^ld⦘)⁺ ⨾ ⦗W⦘).\n 2: { rewrite path_union.\n relsf; unionL.\n { arewrite_id ⦗R⦘; arewrite_id ⦗W⦘.\n rels.\n arewrite (obs⁺ ∩ sb ⊆ obs⁺).\n apply inclusion_t_t2.\n apply_unionL_once.\n apply_unionL_once.\n apply_unionL_once.\n { apply inclusion_t_t. basic_solver. }\n all: rewrite <- ct_step; basic_solver. }\n rewrite (dob_in_sb WF) at 1 2.\n rewrite (aob_in_sb WF) at 1 2.\n rewrite (bob'_in_sb WF) at 1 2.\n arewrite (obs⁺ ∩ sb ⊆ sb).\n rewrite ct_begin.\n arewrite_id ⦗F^ld⦘ at 2.\n generalize (@sb_trans G); ins; relsf.\n arewrite (⦗F^ld⦘ ⨾ sb^? ⨾ ⦗W⦘ ⊆ ⦗F^ld⦘ ⨾ sb) by type_solver.\n unfold Arm.bob', Arm.bob.\n rewrite <- ct_step. basic_solver 21. }\n arewrite (detour ⊆ detour ∩ sb).\n rewrite W_ex_acq_sb_in_boba1; auto.\n rewrite bob_in_boba; auto.\n rewrite detour_in_obs; auto.\n hahn_frame.\n apply inclusion_t_t2.\n apply_unionL_once.\n 2: { rewrite <- ct_step. unfold Arm.aob. basic_solver 12. }\n apply_unionL_once.\n 2: { apply inclusion_t_t; basic_solver 12. }\n apply_unionL_once.\n 2: by unfolder; ins; econs; eauto.\n apply_unionL_once.\n { rewrite <- ct_step; rewrite <- ct_step; unfold Arm.obs; ie_unfolder; basic_solver 12. }\n apply s_ppo_in_ord.\nQed.\n\nLemma C_EXT_helper: imm_s.acyc_ext G (⦗F∩₁Sc⦘ ⨾ s_hb ⨾ eco ⨾ s_hb ⨾ ⦗F∩₁Sc⦘).\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n apply (s_acyc_ext_psc_helper WF).\n rewrite s_ar_int_in_ord.\n arewrite (rfe ⊆ (obs ∪ dob ∪ aob ∪ boba')⁺ ).\n { unfold Arm.obs; rewrite <- ct_step; basic_solver 12. }\n arewrite (imm_s.psc G ⊆ imm.psc G).\n { unfold imm_s.psc, imm.psc. by rewrite s_hb_in_hb. }\n rewrite psc_in_ord; auto.\n relsf; red; relsf.\n apply (external_alt_bob' WF CON).\nQed.\n\nLemma C_SC : acyclic (imm_s.psc_f G ∪ imm_s.psc_base G).\nProof using CON RMW_DEPS W_EX_ACQ_SB.\n unfold imm_s.psc_f, imm_s.psc_base, imm_s.scb.\n rewrite s_hb_in_hb. \n apply immToARMhelper.C_SC; auto.\nQed.\n\nLemma IMM_s_coherence :\n imm_s_hb.coherence G.\nProof using CON.\n red.\n rewrite crE, seq_union_r, seq_id_r.\n rewrite s_hb_in_hb. \n apply irreflexive_union. split.\n 2: { apply COH; auto. } \n rewrite hb_in_ord; auto. \n apply irreflexive_union. split.\n { by apply (@sb_irr G). }\n apply (external_alt_bob' WF CON).\nQed.\n\nLemma IMM_s_psc_consistent (FINDOM : set_finite E) :\n exists sc, imm_psc_consistent G sc.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n edestruct (imm_s.s_acyc_ext_helper WF FINDOM C_EXT_helper) as [sc HH]. desc.\n exists sc. red. splits; eauto.\n 2: by apply C_SC.\n red. splits; eauto; try apply CON.\n now apply IMM_s_coherence.\nQed.\n\nLemma no_ar_int_to_init:\n s_ar_int ≡ s_ar_int ⨾ ⦗set_compl is_init⦘.\nProof using CON.\n split; [| basic_solver]. apply domb_helper.\n rewrite imm_s_ppo.ar_int_in_sb; [| by apply WF].\n erewrite no_sb_to_init. basic_solver.\nQed.\n\nLemma IMM_s_fsupp\n (FSUPP : fsupp (⦗set_compl is_init⦘ ⨾ (obs ∪ dob ∪ aob ∪ boba')⁺))\n (NOSC : E ∩₁ F ∩₁ Sc ⊆₁ ∅) : \n imm_s_fair G ∅₂.\nProof using W_EX_ACQ_SB RMW_DEPS REX_IN_RMW_CTRL DEPS_RMW_SB CON.\n assert (WF' : Wf G) by apply WF.\n assert (transitive sb) as TSB by apply sb_trans.\n red. \n unfold imm_s.ar. rewrite union_false_l.\n rewrite ct_unionE, seq_union_r. \n assert (fsupp (⦗set_compl is_init⦘ ⨾ s_ar_int⁺)) as AA.\n { rewrite imm_s_ppo.ar_int_in_sb; auto.\n rewrite ct_of_trans; auto.\n by apply fsupp_sb. }\n apply fsupp_union; auto.\n rewrite <- seqA, clos_refl_trans_domb_l.\n 2: { rewrite no_ar_int_to_init. basic_solver. }\n rewrite <- seqA. rewrite seqA with (r2 := ⦗set_compl is_init⦘). \n apply fsupp_seq.\n { rewrite rtE, seq_union_r. apply fsupp_union; auto.\n rewrite <- id_inter. apply fsupp_eqv. }\n arewrite (rfe ⊆ rfe ⨾ ⦗set_compl is_init⦘).\n { apply domb_helper. rewrite rfe_in_rf, no_rf_to_init; basic_solver. }\n rewrite (wf_rfeD WF), !seqA.\n rewrite ct_rotl. rewrite <- seqA. \n \n rewrite <- id_inter. rewrite <- seqA. apply fsupp_seq.\n 2: { rewrite <- seqA. apply fsupp_seq.\n { rewrite inclusion_seq_eqv_r, rfe_in_rf. by apply fsupp_rf. }\n rewrite rtE, seq_union_r. apply fsupp_union; auto.\n rewrite <- id_inter. apply fsupp_eqv. }\n \n seq_rewrite <- id_inter. erewrite eqv_rel_mori with (x := R ∩₁ _).\n 2: { unfolder. intros ?. apply proj1. }\n rewrite !seqA.\n arewrite (⦗R⦘ ⨾ s_ar_int* ⨾ ⦗W⦘ ⊆ ⦗R⦘ ⨾ s_ar_int⁺ ⨾ ⦗W⦘).\n { rewrite rtE. clear. type_solver. }\n rewrite s_ar_int_in_ord.\n arewrite (rfe ⊆ (obs ∪ dob ∪ aob ∪ boba')⁺).\n { rewrite <- ct_step. unfold Arm.obs. eauto with hahn. }\n rewrite ct_ct, rt_of_ct.\n rewrite rtE, seq_union_r.\n rewrite <- id_inter. apply fsupp_union; [by apply fsupp_eqv| ].\n eapply fsupp_mori; [| by apply FSUPP]. red. basic_solver.\nQed.\n\nLemma IMM_s_consistent\n (NOSC : E ∩₁ F ∩₁ Sc ⊆₁ ∅):\n imm_psc_consistent G ∅₂.\nProof using W_EX_ACQ_SB RMW_DEPS REX_IN_RMW_CTRL DEPS_RMW_SB CON. \n assert (WF' : Wf G) by apply WF.\n assert (transitive sb) as TSB by apply sb_trans.\n red; splits.\n 2: now apply C_SC.\n red. splits; try apply CON.\n { constructor; rewrite ?NOSC.\n all: basic_solver. }\n { red. basic_solver. }\n { now apply IMM_s_coherence. }\n red. unfold imm_s.ar.\n arewrite (∅₂ ⊆ ⦗F∩₁Sc⦘ ⨾ s_hb ⨾ eco ⨾ s_hb ⨾ ⦗F∩₁Sc⦘).\n apply C_EXT_helper.\nQed. \n \nLemma IMM_s_fsupp_consistent\n (* NEXT TODO: note that here we use boba' instead of original Arm.bob *)\n (FSUPP : fsupp (⦗set_compl is_init⦘ ⨾ (obs ∪ dob ∪ aob ∪ boba')⁺))\n (NOSC : E ∩₁ F ∩₁ Sc ⊆₁ ∅) : \n ⟪ CONS : imm_psc_consistent G ∅₂ ⟫ /\\\n ⟪ FSUPP : imm_s_fair G ∅₂⟫. \nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n auto using IMM_s_consistent, IMM_s_fsupp. \nQed.\n\nEnd immToARM.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/hardware/imm_sToARM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1488997377470555}} {"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable goal_ : Prop.\nVariable dom_ : Universe -> Prop.\nVariable bin_count_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\n\nVariable num_1_ : Universe.\nVariable num_0_ : Universe.\n\nVariable initial_model_1 : (dom_ num_0_ /\\ (dom_ num_1_ /\\ bin_count_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable qed3_2 : (forall A B C D E F G H I J K L M N O P Q R S T U V W X : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X num_1_ num_1_ num_1_ -> goal_)).\nVariable qed5_3 : (forall A B C D E F G H I J K L M N O P Q R S T U V : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed10_4 : (forall A B C D E F G H I J K L M N O P Q : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed11_5 : (forall A B C D E F G H I J K L M N O P : Universe, (bin_count_ A B C D E F G H I J K L M N O P num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed12_6 : (forall A B C D E F G H I J K L M N O : Universe, (bin_count_ A B C D E F G H I J K L M N O num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed13_7 : (forall A B C D E F G H I J K L M N : Universe, (bin_count_ A B C D E F G H I J K L M N num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed14_8 : (forall A B C D E F G H I J K L M : Universe, (bin_count_ A B C D E F G H I J K L M num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed15_9 : (forall A B C D E F G H I J K L : Universe, (bin_count_ A B C D E F G H I J K L num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed16_10 : (forall A B C D E F G H I J K : Universe, (bin_count_ A B C D E F G H I J K num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed17_11 : (forall A B C D E F G H I J : Universe, (bin_count_ A B C D E F G H I J num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed18_12 : (forall A B C D E F G H I : Universe, (bin_count_ A B C D E F G H I num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed19_13 : (forall A B C D E F G H : Universe, (bin_count_ A B C D E F G H num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed20_14 : (forall A B C D E F G : Universe, (bin_count_ A B C D E F G num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed21_15 : (forall A B C D E F : Universe, (bin_count_ A B C D E F num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed22_16 : (forall A B C D E : Universe, (bin_count_ A B C D E num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed23_17 : (forall A B C D : Universe, (bin_count_ A B C D num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed24_18 : (forall A B C : Universe, (bin_count_ A B C num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed25_19 : (forall A B : Universe, (bin_count_ A B num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed26_20 : (forall A : Universe, (bin_count_ A num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_)).\nVariable qed27_21 : (bin_count_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> goal_).\nVariable p27_22 : (forall A B C D E F G H I J K L M N O P Q R S T U V W X Y Z : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z num_0_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z num_1_)).\nVariable p26_23 : (forall A B C D E F G H I J K L M N O P Q R S T U V W X Y : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X Y num_0_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X Y num_1_ num_0_)).\nVariable p25_24 : (forall A B C D E F G H I J K L M N O P Q R S T U V W X : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X num_0_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W X num_1_ num_0_ num_0_)).\nVariable p24_25 : (forall A B C D E F G H I J K L M N O P Q R S T U V W : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W num_0_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U V W num_1_ num_0_ num_0_ num_0_)).\nVariable p23_26 : (forall A B C D E F G H I J K L M N O P Q R S T U V : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U V num_0_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U V num_1_ num_0_ num_0_ num_0_ num_0_)).\nVariable p22_27 : (forall A B C D E F G H I J K L M N O P Q R S T U : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T U num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T U num_1_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p21_28 : (forall A B C D E F G H I J K L M N O P Q R S T : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S T num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S T num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p20_29 : (forall A B C D E F G H I J K L M N O P Q R S : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R S num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R S num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p19_30 : (forall A B C D E F G H I J K L M N O P Q R : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q R num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q R num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p18_31 : (forall A B C D E F G H I J K L M N O P Q : Universe, (bin_count_ A B C D E F G H I J K L M N O P Q num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P Q num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p17_32 : (forall A B C D E F G H I J K L M N O P : Universe, (bin_count_ A B C D E F G H I J K L M N O P num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O P num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p16_33 : (forall A B C D E F G H I J K L M N O : Universe, (bin_count_ A B C D E F G H I J K L M N O num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N O num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p15_34 : (forall A B C D E F G H I J K L M N : Universe, (bin_count_ A B C D E F G H I J K L M N num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M N num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p14_35 : (forall A B C D E F G H I J K L M : Universe, (bin_count_ A B C D E F G H I J K L M num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L M num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p13_36 : (forall A B C D E F G H I J K L : Universe, (bin_count_ A B C D E F G H I J K L num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K L num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p12_37 : (forall A B C D E F G H I J K : Universe, (bin_count_ A B C D E F G H I J K num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J K num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p11_38 : (forall A B C D E F G H I J : Universe, (bin_count_ A B C D E F G H I J num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I J num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p10_39 : (forall A B C D E F G H I : Universe, (bin_count_ A B C D E F G H I num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H I num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p9_40 : (forall A B C D E F G H : Universe, (bin_count_ A B C D E F G H num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G H num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p8_41 : (forall A B C D E F G : Universe, (bin_count_ A B C D E F G num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F G num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p7_42 : (forall A B C D E F : Universe, (bin_count_ A B C D E F num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E F num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p6_43 : (forall A B C D E : Universe, (bin_count_ A B C D E num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D E num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p5_44 : (forall A B C D : Universe, (bin_count_ A B C D num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C D num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p4_45 : (forall A B C : Universe, (bin_count_ A B C num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B C num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p3_46 : (forall A B : Universe, (bin_count_ A B num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A B num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p2_47 : (forall A : Universe, (bin_count_ A num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ A num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_)).\nVariable p1_48 : (bin_count_ num_0_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ num_1_ -> bin_count_ num_1_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_ num_0_).\n\nTheorem hdn_020_49 : goal_.\nProof.\n time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/coherent-logic-benches/hdn020_in.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1484482486461082}} {"text": "Require Import Relations.\nRequire Import Permutation.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nFrom sflib Require Import sflib.\nRequire Import PacoNotation.\nRequire Import HahnRelationsBasic.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.HahnRelationsMore.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\nRequire Import PromisingArch.promising.Promising.\nRequire Import PromisingArch.promising.StateExecFacts.\nRequire Import PromisingArch.axiomatic.Axiomatic.\nRequire Import PromisingArch.axiomatic.CommonAxiomatic.\n\nSet Implicit Arguments.\n\n\nInductive sim_trace (p: program) (mem: Memory.t) (tid: Id.t):\n forall (tr: list (ExecUnit.t (A:=unit))) (atr: list AExecUnit.t)\n (wl: list (nat -> option (Loc.t * Time.t))) (rl: list (nat -> option (Loc.t * Time.t)))\n (cov: list (nat -> Time.t)) (vext: list (nat -> Time.t)), Prop :=\n| sim_trace_init\n st lc stmts\n (FIND: IdMap.find tid (Machine.init_with_promises p mem).(Machine.tpool) = Some (st, lc))\n (STMT: IdMap.find tid p = Some stmts):\n sim_trace p mem tid [ExecUnit.mk st lc mem] [AExecUnit.mk (State.init stmts) ALocal.init]\n [fun _ => None] [fun _ => None] [fun _ => Time.bot] [fun _ => Time.bot]\n| sim_trace_step\n e ae tr eu1 eu2 atr aeu1 aeu2 rl r1 r2 wl w1 w2 covl cov1 cov2 vextl vext1 vext2\n (STEP: ExecUnit.state_step0 tid e e eu1 eu2)\n (ASTATE_STEP: State.step ae aeu1.(AExecUnit.state) aeu2.(AExecUnit.state))\n (ALOCAL_STEP: ALocal.step ae aeu1.(AExecUnit.local) aeu2.(AExecUnit.local))\n (EVENT: sim_event e ae)\n (STATE: sim_state_weak eu2.(ExecUnit.state) aeu2.(AExecUnit.state))\n (LOCAL: sim_local_weak eu2.(ExecUnit.local) aeu2.(AExecUnit.local))\n (W: w2 = match e with\n | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n Memory.latest_ts\n vloc.(ValA.val)\n (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n mem)\n else w1 eid)\n | _ => w1\n end)\n (R: r2 = match e with\n | Event.read _ _ vloc _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n Memory.latest_ts\n vloc.(ValA.val)\n (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n mem)\n else r1 eid)\n | _ => r1\n end)\n (COV: cov2 = match e with\n | Event.read _ _ vloc _\n | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Memory.latest_ts\n vloc.(ValA.val)\n (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n mem\n else cov1 eid)\n | _ => cov1\n end)\n (VEXT: vext2 = match e with\n | Event.read _ _ _ res =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then res.(ValA.annot).(View.ts)\n else vext1 eid)\n | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n else vext1 eid)\n | _ => vext1\n end)\n (TRACE: sim_trace p mem tid (eu1::tr) (aeu1::atr) (w1::wl) (r1::rl) (cov1::covl) (vext1::vextl)):\n sim_trace p mem tid (eu2::eu1::tr) (aeu2::aeu1::atr) (w2::w1::wl) (r2::r1::rl) (cov2::cov1::covl) (vext2::vext1::vextl)\n.\n\nDefinition sim_traces\n (p: program) (mem: Memory.t)\n (trs: IdMap.t (list (ExecUnit.t (A:=unit))))\n (atrs: IdMap.t (list AExecUnit.t))\n (ws: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n (rs: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n (covs: IdMap.t (list (nat -> Time.t)))\n (vexts: IdMap.t (list (nat -> Time.t)))\n : Prop :=\n IdMap.Forall6 (sim_trace p mem) trs atrs ws rs covs vexts.\n\nLemma sim_trace_last\n p mem tid tr atr wl rl covl vextl\n (SIM: sim_trace p mem tid tr atr wl rl covl vextl):\n exists eu tr' aeu atr' w wl' r rl' cov covl' vext vextl',\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n inv SIM; esplits; eauto.\nQed.\n\nLemma sim_trace_length\n p mem tid tr atr wl rl covl vextl\n (SIM: sim_trace p mem tid tr atr wl rl covl vextl):\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n induction SIM; ss. des. splits; congr.\nQed.\n\nLemma sim_trace_memory\n p mem tid tr atr rl wl covl vextl\n eu tr'\n (SIM: sim_trace p mem tid tr atr rl wl covl vextl)\n (EU: tr = eu :: tr'):\n mem = eu.(ExecUnit.mem).\nProof.\n revert eu tr' EU.\n induction SIM.\n - ii. inv EU. ss.\n - ii. inv EU. exploit IHSIM; try refl. i.\n inv STEP. ss.\nQed.\n\nLemma sim_traces_memory\n p trs atrs rs ws covs vexts\n m\n ts loc val tid\n (STEP: Machine.pf_exec p m)\n (SIM: sim_traces p m.(Machine.mem) trs atrs ws rs covs vexts)\n (TR: IdMap.Forall2\n (fun tid tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n trs m.(Machine.tpool))\n (GET: Memory.get_msg ts m.(Machine.mem) = Some (Msg.mk loc val tid)):\n exists eu, IdMap.find tid trs = Some eu.\nProof.\n generalize (SIM tid). intro X. inv X; eauto.\n generalize (TR tid). rewrite <- H0. intro X. inv X.\n inv STEP. hexploit state_exec_rtc_state_step; [by eauto|]. i. des.\n exploit Machine.step_get_msg_tpool.\n - etrans.\n + eapply Machine.rtc_step_mon; [|by eauto]. right. ss.\n + eapply Machine.rtc_step_mon; [|by eauto]. left. ss.\n - inv EQUIV. rewrite <- MEM. eauto.\n - s. i. des. inv EQUIV. generalize (TPOOL tid). congr.\nQed.\n\nLtac simplify :=\n repeat\n (try match goal with\n | [H1: _ = IdMap.find ?id ?m, H2: _ = IdMap.find ?id ?m |- _] =>\n rewrite <- H1 in H2; inv H2\n | [H1: IdMap.find ?id ?m = _, H2: IdMap.find ?id ?m = _ |- _] =>\n rewrite H1 in H2; inv H2\n | [H1: IdMap.find ?id ?m = _, H2: _ = IdMap.find ?id ?m |- _] =>\n rewrite H1 in H2; inv H2\n | [H: Some _ = Some _ |- _] => inv H\n | [H: _::_ = _::_ |- _] => inv H\n end).\n\nLemma promising_pf_sim_step\n tid e (eu1 eu2:ExecUnit.t (A:=unit)) aeu1\n (STATE1: sim_state_weak eu1.(ExecUnit.state) aeu1.(AExecUnit.state))\n (LOCAL1: sim_local_weak eu1.(ExecUnit.local) aeu1.(AExecUnit.local))\n (STEP: ExecUnit.state_step0 tid e e eu1 eu2):\n exists ae aeu2,\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n destruct eu1 as [st1 lc1 mem1].\n destruct eu2 as [st2 lc2 mem2].\n destruct aeu1 as [[astmt1 armap1] alc1].\n inv STATE1. inv STEP. ss. subst. inv STATE; inv LOCAL; inv EVENT; ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 1.\n + econs; ss.\n + ss.\n + ss.\n + inv LOCAL1; [econs 1|econs 2]; eauto.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 2. ss.\n + econs; ss.\n + econs; ss.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + inv LOCAL1; [econs 1|econs 2]; eauto.\n - inv STEP. ss.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 3; ss.\n + econs 2; ss.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + destruct ex0.\n * econs 2; ss.\n rewrite List.nth_error_app2, minus_diag; ss.\n specialize (@sim_rmap_weak_expr rmap armap1 eloc RMAP). i.\n inv H. rewrite VAL. refl.\n * inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n rewrite List.nth_error_app1; eauto.\n eapply List.nth_error_Some. ii. congr.\n - inv STEP. ss.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 4; ss.\n + econs 3; ss. inv WRITABLE. i. specialize (EX H). des.\n inv LOCAL1; try congr.\n rewrite TSX in LOCAL_EX. inv LOCAL_EX.\n esplits; eauto. rewrite LABEL_EX; eauto.\n + econs; ss.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + destruct ex0; eauto.\n inv LOCAL1; [econs 1|econs 2]; ss.\n { eauto. }\n { eauto. }\n rewrite List.nth_error_app1; eauto.\n eapply List.nth_error_Some. ii. congr.\n - inv STEP. destruct ex0; ss.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 4; ss.\n + econs 4; ss.\n + econs; ss.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + eauto.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 5; ss.\n + econs 5; ss.\n + econs; ss.\n + econs; ss.\n + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n rewrite List.nth_error_app1; eauto.\n eapply List.nth_error_Some. ii. congr.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 5; ss.\n + econs 5; ss.\n + econs; ss.\n + econs; ss.\n + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n rewrite List.nth_error_app1; eauto.\n eapply List.nth_error_Some. ii. congr.\n - inv LC.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 6; ss.\n + econs 6; ss.\n + econs; ss.\n exploit sim_rmap_weak_expr; eauto. intro X. inv X.\n inv VAL. rewrite <- H0. ss.\n + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n rewrite List.nth_error_app1; eauto.\n eapply List.nth_error_Some. ii. congr.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 7. ss.\n + econs; ss.\n + ss.\n + ss.\n + inv LOCAL1; [econs 1|econs 2]; eauto.\nQed.\n\nLemma promising_pf_sim_traces\n p m\n (STEP: Machine.pf_exec p m):\n exists trs atrs ws rs covs vexts ex (PRE: Valid.pre_ex p ex),\n <> /\\\n < exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n trs m.(Machine.tpool)>> /\\\n < exists l, atr = aeu :: l)\n atrs PRE.(Valid.aeus)>>.\nProof.\n inv STEP. exploit state_exec_rtc_state_step; eauto. i. des.\n eapply Machine.equiv_no_promise in NOPROMISE; eauto. revert NOPROMISE.\n cut (exists trs atrs ws rs covs vexts ex (PRE: Valid.pre_ex p ex),\n <> /\\\n < exists l, tr = (ExecUnit.mk (fst sl) (snd sl) (Machine.mem m2')) :: l)\n (IdMap.find tid trs)\n (IdMap.find tid (Machine.tpool m2'))>> /\\\n < exists l, atr = aeu :: l)\n atrs PRE.(Valid.aeus)>>).\n { inv EQUIV. rewrite MEM. i. des. esplits; eauto. ii. rewrite TPOOL. ss. }\n clear m STEP2 EQUIV.\n apply clos_rt_rt1n_iff, clos_rt_rtn1_iff in EXEC. induction EXEC.\n { eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n eexists (IdMap.mapi (fun _ _ => [bot]) p).\n eexists (IdMap.mapi (fun _ _ => [bot]) p).\n eexists (Execution.mk (IdMap.mapi (fun _ _ => _) p) bot bot bot bot bot bot).\n eexists (@Valid.mk_pre_ex _ _ (IdMap.mapi (fun tid stmts => AExecUnit.mk (State.init stmts) ALocal.init) p) _ _ _ _ _ _).\n hexploit Machine.rtc_promise_step_spec; eauto. s. intro X.\n s. splits; cycle 1.\n - i. specialize (X tid). rewrite ? IdMap.map_spec, ? IdMap.mapi_spec in *.\n rewrite X. destruct (IdMap.find tid p); ss. econs. eauto.\n - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p); ss. eauto.\n - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p) eqn:STMTS; ss. econs.\n econs 1; ss. rewrite IdMap.mapi_spec, STMTS. s. ss.\n }\n des.\n destruct y as [tpool1 mem1].\n destruct z as [tpool2 mem2].\n ss. inv H. ss. subst. inv STEP. inv STEP0. ss. subst.\n generalize (TR tid). rewrite FIND. intro Y. inv Y. des. subst. rename H0 into TRS. symmetry in TRS.\n generalize (SIM tid). intro Y. inv Y; [congr|]. rewrite TRS in H0. inv H0.\n hexploit sim_trace_last; eauto. i. des. subst. simplify.\n exploit promising_pf_sim_step; eauto.\n { inv REL6; eauto. s.\n unfold Machine.init_with_promises in FIND0. ss.\n rewrite IdMap.mapi_spec, STMT in *. inv FIND0.\n apply sim_state_weak_init.\n }\n { inv REL6; eauto. s.\n unfold Machine.init_with_promises in FIND0. ss.\n rewrite IdMap.mapi_spec, STMT in *. inv FIND0.\n auto.\n }\n { instantiate (1 := ExecUnit.mk _ _ _). econs; ss; eauto. }\n i. des.\n\n eexists (IdMap.add tid _ trs).\n eexists (IdMap.add tid _ atrs).\n eexists (IdMap.add tid _ ws).\n eexists (IdMap.add tid _ rs).\n eexists (IdMap.add tid _ covs).\n eexists (IdMap.add tid _ vexts).\n eexists (Execution.mk _ _ _ _ _ _ _).\n eexists (@Valid.mk_pre_ex _ _ (IdMap.add tid _ PRE.(Valid.aeus)) _ _ _ _ _ _).\n s. splits; cycle 1.\n - i. rewrite ? IdMap.add_spec. condtac; eauto.\n - ii. rewrite ? IdMap.add_spec. condtac; eauto.\n - s. ii. rewrite ? IdMap.add_spec. condtac; eauto. inversion e0. subst. clear e0 X. econs.\n econs 2; eauto. econs; eauto.\nUnshelve.\nall: ss.\nall: try apply bot.\n1: { econs. }\n3: { funext. i. funext. i. propext. econs; ss. i. inv H.\n rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n inv RELS. inv REL. ss.\n}\n3: { funext. i. funext. i. propext. econs; ss. i. inv H.\n rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n inv RELS. inv REL. ss.\n}\n3: { funext. i. funext. i. propext. econs; ss. i. inv H.\n rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n inv RELS. inv REL. ss.\n}\n3: { funext. i. funext. i. propext. econs; ss. i. inv H.\n rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n inv RELS. inv REL. ss.\n}\n1: { ii. rewrite IdMap.mapi_spec. destruct (IdMap.find id p); ss. econs. refl. }\n1: { unfold IdMap.map. rewrite IdMap.mapi_mapi. f_equal. }\n1: { ii. generalize (PRE.(Valid.AEUS) id). intro X.\n rewrite IdMap.add_spec. condtac; ss. inversion e0. subst. clear e0 X0.\n generalize (ATR tid). rewrite <- H. intro Y. inv Y. des. inv REL.\n rewrite <- H6 in X. inv X. econs. etrans; eauto.\n}\nQed.\n\nInductive sim_th\n (p:program) (mem:Memory.t) (tid:Id.t)\n (eu:ExecUnit.t (A:=unit))\n (aeu:AExecUnit.t)\n (w: nat -> option (Loc.t * Time.t))\n (r: nat -> option (Loc.t * Time.t))\n (cov: nat -> Time.t)\n (vext: nat -> Time.t): Prop := mk {\n WPROP1:\n forall ts loc val\n (GET: Memory.get_msg ts mem = Some (Msg.mk loc val tid)),\n ((Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = true /\\\n forall eid, w eid <> Some (loc, ts)) \\/\n (Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = false /\\\n exists eid ex ord,\n w eid = Some (loc, ts) /\\\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val)));\n WPROP2:\n forall eid ex ord loc val\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val)),\n exists ts,\n w eid = Some (loc, ts) /\\\n Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n WPROP3:\n forall eid loc ts (GET: w eid = Some (loc, ts)),\n Time.lt Time.bot ts /\\\n cov eid = ts /\\\n vext eid = ts /\\\n le ts (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n exists ex ord val,\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val) /\\\n Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n WPROP4:\n forall eid1 loc1 eid2 loc2 ts (W1: w eid1 = Some (loc1, ts)) (W2: w eid2 = Some (loc2, ts)),\n eid1 = eid2;\n RPROP1:\n forall eid ex ord loc val\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.read ex ord loc val)),\n exists ts tid',\n r eid = Some (loc, ts) /\\\n __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n Memory.get_msg ts mem = Some (Msg.mk loc val tid'));\n RPROP2:\n forall eid loc ts (GET: r eid = Some (loc, ts)),\n cov eid = ts /\\\n le ts (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n exists ex ord val tid',\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.read ex ord loc val) /\\\n __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n Memory.get_msg ts mem = Some (Msg.mk loc val tid'));\n COVPROP:\n forall eid (COV: cov eid > 0),\n AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access eid;\n VEXTPROP:\n forall eid (VEXT: vext eid > 0),\n AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access eid;\n\n PO: forall iid1 iid2 label1 label2\n (PO: iid1 < iid2)\n (LABEL1: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid1 = Some label1)\n (LABEL2: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid2 = Some label2)\n (REL: Execution.label_loc label1 label2),\n <\n Time.lt (cov iid1) (cov iid2)>> /\\\n <\n Time.le (cov iid1) (cov iid2)>>;\n EU_WF: ExecUnit.wf tid eu;\n AEU_WF: AExecUnit.wf aeu;\n MEM: eu.(ExecUnit.mem) = mem;\n}.\n\nLemma sim_trace_sim_state_weak\n p mem tid\n tr eu tr'\n atr aeu atr'\n wl w wl'\n rl r rl'\n covl cov covl'\n vextl vext vextl'\n (SIM: sim_trace p mem tid tr atr wl rl covl vextl)\n (EU: tr = eu :: tr')\n (AEU: atr = aeu :: atr')\n (RL: rl = r :: rl')\n (WL: wl = w :: wl')\n (COV: covl = cov :: covl')\n (VEXT: vextl = vext :: vextl'):\n sim_state_weak eu.(ExecUnit.state) aeu.(AExecUnit.state).\nProof.\n subst. inv SIM; ss.\n rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n eapply sim_state_weak_init.\nQed.\n\nLemma sim_trace_sim_th\n p mem tid\n tr eu tr'\n atr aeu atr'\n wl w wl'\n rl r rl'\n covl cov covl'\n vextl vext vextl'\n (SIM: sim_trace p mem tid tr atr wl rl covl vextl)\n (EU: tr = eu :: tr')\n (AEU: atr = aeu :: atr')\n (RL: rl = r :: rl')\n (WL: wl = w :: wl')\n (COV: covl = cov :: covl')\n (VEXT: vextl = vext :: vextl'):\n sim_th p mem tid eu aeu w r cov vext.\nProof.\n revert r rl' w wl' eu tr' aeu atr' cov covl' vext vextl' RL WL EU AEU COV VEXT. induction SIM.\n { i. simplify. ss. econs; ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n left. splits; ss. destruct ts; ss.\n eapply Machine.promises_from_mem_lookup. eauto.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n destruct eid; ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n destruct eid; ss.\n - unfold Time.bot. i. lia.\n - unfold Time.bot. i. lia.\n - i. destruct iid1; ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n econs; ss.\n + econs. i. unfold RMap.find. rewrite IdMap.gempty. ss. apply bot_spec.\n + econs; ss; i; try by apply bot_spec.\n (* * unfold bot. unfold fun_bot. unfold bot. unfold Time.bot. lia. *)\n (* * eexists. unfold bot. unfold fun_bot. unfold Memory.read. ss. *)\n * econs; esplits; ss.\n * destruct ts; ss.\n rewrite Machine.promises_from_mem_spec in IN. des.\n apply lt_le_S. rewrite <- List.nth_error_Some. ii. congr.\n * destruct ts; ss.\n unfold Memory.get_msg in *. ss. destruct msg.\n exploit Machine.promises_from_mem_lookup; eauto. ss. subst. ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n econs; ss.\n + ii. unfold RMap.init in N. unfold RMap.find in N.\n rewrite IdMap.gempty in N. ss.\n + ii. apply List.nth_error_In in LABEL. inv LABEL.\n }\n clear LOCAL.\n i. simplify.\n destruct eu1 as [st1 lc1 mem1].\n destruct eu as [st2 lc2 mem2].\n destruct aeu1 as [ast1 alc1].\n destruct aeu as [ast2 alc2].\n assert (mem1 = mem); subst.\n { exploit sim_trace_memory; eauto. }\n ss. exploit IHSIM; eauto. intro IH.\n assert (EU_WF2: ExecUnit.wf tid (ExecUnit.mk st2 lc2 mem2)).\n { destruct IH.\n eapply ExecUnit.state_step_wf; eauto. econs; eauto. }\n assert (AEU_WF2: AExecUnit.wf (AExecUnit.mk ast2 alc2)).\n { destruct IH.\n eapply AExecUnit.step_future; eauto. }\n inv STEP. inv ALOCAL_STEP; inv EVENT; ss; eauto.\n { (* internal *)\n inv LOCAL; ss. inv EVENT. econs; ss; try by apply IH.\n }\n { (* read *)\n inv LOCAL; ss. generalize IH.(EU_WF). i. inv H.\n specialize (Local.read_spec LOCAL STEP). intro READ_SPEC. guardH READ_SPEC.\n inv STEP. inv STATE0. inv ASTATE_STEP. ss. inv EVENT.\n exploit sim_trace_sim_state_weak; eauto. s. intro Y. inv Y. ss. inv STMTS.\n exploit sim_rmap_weak_expr; eauto. intro Y. inv Y.\n\n econs; ss; clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n { exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n }\n esplits; eauto.\n + rewrite fun_add_spec. des_ifs; eauto. inv e.\n ss. etrans; eauto. apply join_l.\n + eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(RPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n rewrite fun_add_spec in *. condtac; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move READ_SPEC at bottom. desH READ_SPEC. rewrite <- COH0.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n - i. des_ifs.\n + apply Nat.eqb_eq in Heq. subst.\n rewrite fun_add_spec in *. des_ifs; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move READ_SPEC at bottom. desH READ_SPEC. rewrite <- COH0.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n all: try by rewrite COH0 at 1; eapply Memory.latest_ts_spec.\n all: try by rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss.\n + exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto. ss. apply join_l.\n * eapply nth_error_app_mon. eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. destruct label1; ss.\n * destruct (equiv_dec loc0 loc); ss. inv e0.\n destruct (equiv_dec (ValA.val (sem_expr rmap0 eloc0)) loc); ss. inv e0.\n exploit IH.(RPROP1); eauto. i. des.\n exploit IH.(RPROP2); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x2. rewrite VAL1 in *.\n desH x5.\n { rewrite x5. apply bot_spec. }\n exploit Memory.latest_ts_read_le; try eapply Memory.get_msg_read; eauto. i.\n rewrite x2. apply Memory.latest_ts_mon. apply join_l.\n * destruct (equiv_dec loc0 loc); ss. inv e0.\n destruct (equiv_dec (ValA.val (sem_expr rmap0 eloc0)) loc); ss. inv e0.\n exploit IH.(WPROP2); eauto. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n exploit Memory.latest_ts_read_le; try eapply Memory.get_msg_read; eauto. i.\n rewrite x3. apply Memory.latest_ts_mon. apply join_l.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n }\n { (* write *)\n inv LOCAL; ss; inv EVENT; inv RES; inv STEP; ss. inv STATE. ss.\n destruct IH.(EU_WF).\n econs; ss; clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. rewrite Promises.unset_o. des_ifs.\n { inv e. right. rewrite MSG in GET. inv GET. esplits; ss.\n - instantiate (1 := ALocal.next_eid alc1). des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. congr. }\n rewrite fun_add_spec. des_ifs; ss; try congr.\n repeat f_equal. destruct ts; ss.\n unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n - rewrite List.nth_error_app2, Nat.sub_diag; ss.\n inv VLOC. inv VVAL. rewrite VAL0, VAL1. eauto.\n }\n des; [left|right]; splits; ss.\n + i. des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. ii. inv H.\n rewrite fun_add_spec in *. des_ifs; [|congr]. ss. apply c.\n specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n + esplits; eauto.\n * des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon. eauto.\n - i. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n + des_ifs.\n { apply Nat.eqb_eq in Heq. subst. lia. }\n eapply IH.(WPROP2); eauto.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. lia. }\n esplits; eauto.\n * inv VLOC. rewrite VAL0. eauto.\n * rewrite fun_add_spec in *. des_ifs; [|congr]. ss.\n inv VLOC. inv VVAL. rewrite <- VAL0, <- VAL1.\n specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n destruct ts; ss. unfold Memory.get_msg in MSG. ss.\n rewrite MSG. ss. des_ifs.\n - i. unfold ALocal.next_eid in *. des_ifs.\n + apply Nat.eqb_eq in Heq. subst. rewrite fun_add_spec. des_ifs; [|congr]. inv e.\n destruct ts; ss. esplits; eauto.\n * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n unfold Time.lt, Time.bot. lia.\n * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n * rewrite List.nth_error_app2, Nat.sub_diag; ss.\n inv VLOC. rewrite VAL0. eauto.\n * generalize MSG. intro X. inv VVAL. rewrite <- VAL0.\n unfold Memory.get_msg in X. ss. rewrite X. des_ifs.\n + exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. apply Nat.lt_le_incl. ss.\n * eapply nth_error_app_mon. eauto.\n - i. unfold ALocal.next_eid in *.\n specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n exploit Memory.latest_ts_read_le; [|refl|i; exploit le_antisym; try eapply LE; eauto; i].\n { eapply Memory.get_msg_read; eauto. }\n des_ifs.\n + apply Nat.eqb_eq in Heq. apply Nat.eqb_eq in Heq0. subst. ss.\n + clear Heq0. rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite x1 in *.\n rewrite PROMISE. i. des; ss.\n rewrite MSG in x7. inv x7. clear - WRITABLE x5. unfold le in x5. inv WRITABLE. lia.\n + rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite x1 in *.\n rewrite PROMISE. i. des; ss.\n rewrite MSG in x7. inv x7. clear -WRITABLE x5. unfold le in x5. inv WRITABLE. lia.\n + eapply IH.(WPROP4); eauto.\n - i. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. apply Nat.lt_le_incl. ss.\n * eapply nth_error_app_mon. eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - inv ASTATE_STEP; ss; eauto. subst.\n inv VLOC. inv VVAL. rewrite VAL0, VAL1 in *. unfold ALocal.next_eid in *.\n i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. destruct label1; ss.\n * destruct (equiv_dec loc0 loc); ss. inv e0.\n destruct (equiv_dec (ValA.val (sem_expr rmap eloc)) loc); ss. inv e0.\n exploit IH.(RPROP1); eauto. i. des.\n exploit IH.(RPROP2); eauto. s. i. des. subst.\n destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n eapply Nat.le_lt_trans; eauto. inv WRITABLE. rewrite VAL0 in *. ss.\n * destruct (equiv_dec loc0 loc); ss. inv e0.\n destruct (equiv_dec (ValA.val (sem_expr rmap eloc)) loc); ss. inv e0.\n exploit IH.(WPROP2); eauto. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n eapply Nat.le_lt_trans; eauto. inv WRITABLE. rewrite VAL0 in *. ss.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n }\n { (* write failure *)\n inv RES. destruct res1. ss. subst.\n inv LOCAL; ss; inv STEP; ss. inv EVENT. econs; ss; try by apply IH.\n }\n { (* barrier *)\n inv LOCAL; ss.\n { (* isb *)\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(WPROP3); eauto. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n { subst. inv REL. inv X. }\n apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n { subst. inv REL. inv Y. }\n eapply IH.(PO); eauto.\n }\n { (* dmb *)\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n { subst. inv REL. inv X. }\n apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n { subst. inv REL. inv Y. }\n eapply IH.(PO); eauto.\n }\n }\n { (* control *)\n inv LOCAL; ss. inv LC. inv STATE0. inv ASTATE_STEP. ss. inv EVENT.\n econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(WPROP3); eauto. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. congr.\n - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n { subst. inv REL. inv X. }\n apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n { subst. inv REL. inv Y. }\n eapply IH.(PO); eauto.\n }\nUnshelve.\nall: auto. (* tid *)\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-arm", "sha": "10291375ccd03152eadf739d280e2c59e10fa9af", "save_path": "github-repos/coq/snu-sf-promising-arm", "path": "github-repos/coq/snu-sf-promising-arm/promising-arm-10291375ccd03152eadf739d280e2c59e10fa9af/src/axiomatic/PFtoA1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.14844824539828816}} {"text": "Require Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Cop Ctypes ClightC.\nRequire SimMemId SimMemExt SimMemInj.\nRequire SoundTop UnreachC.\nRequire SimSymbId SimSymbDrop.\nRequire Import MutrecABspec.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\n\nRequire Import MatchSimModSem ModSemProps.\nRequire Import IdSimExtra.\nRequire Import CopC.\nRequire Import sflib.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nInductive match_states_ext_ab\n : unit -> state -> state -> SimMemExt.t' -> Prop :=\n| match_ext_Callstate\n i m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMemExt.src))\n (MWFTGT: m_tgt = sm0.(SimMemExt.tgt))\n (MWF: Mem.extends m_src m_tgt)\n :\n match_states_ext_ab\n tt\n (Callstate i m_src)\n (Callstate i m_tgt)\n sm0\n| match_return_Callstate\n i m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMemExt.src))\n (MWFTGT: m_tgt = sm0.(SimMemExt.tgt))\n (MWF: Mem.extends m_src m_tgt)\n :\n match_states_ext_ab\n tt\n (Returnstate i m_src)\n (Returnstate i m_tgt)\n sm0.\n\nSection ABSOUNDSTATE.\n\n Variable skenv_link: SkEnv.t.\n Variable su: Sound.t.\n\n Inductive sound_state_ab\n : state -> Prop :=\n | sound_Callstate\n i m\n (WF: Sound.wf su)\n (MEM: UnreachC.mem' su m)\n (SKE: su.(Unreach.ge_nb) = skenv_link.(Genv.genv_next))\n :\n sound_state_ab (Callstate i m)\n | sound_Returnstate\n i m\n (WF: Sound.wf su)\n (MEM: UnreachC.mem' su m)\n (SKE: su.(Unreach.ge_nb) = skenv_link.(Genv.genv_next))\n :\n sound_state_ab (Returnstate i m)\n .\n\nEnd ABSOUNDSTATE.\n\n\nSection ABSOUND.\n\n Variable skenv_link: SkEnv.t.\n\n Lemma ab_unreach_local_preservation\n :\n exists sound_state, <>\n .\n Proof.\n esplits.\n eapply local_preservation_strong_horizontal_spec with (lift := UnreachC.le') (sound_state := sound_state_ab skenv_link); eauto.\n econs; ss; i.\n { eapply UnreachC.liftspec; et. }\n - inv INIT. ss. unfold Sound.args in SUARG. des_ifs. des. esplits.\n + refl.\n + ss. econs; eauto. inv SKENV. ss.\n + instantiate (1:=get_mem). ss. refl.\n - inv STEP; inv SUST. esplits; eauto.\n + refl.\n + econs; eauto.\n + ss. refl.\n - inv FINAL; inv SUST. esplits; eauto.\n + refl.\n + econs; eauto. ss.\n + ss. refl.\n Qed.\n\nEnd ABSOUND.\n\nInductive match_states_ab_internal:\n state -> state -> meminj -> mem -> mem -> Prop :=\n| match_Callstate\n i m_src m_tgt j\n :\n match_states_ab_internal\n (Callstate i m_src)\n (Callstate i m_tgt)\n j m_src m_tgt\n| match_Returnstate\n i m_src m_tgt j\n :\n match_states_ab_internal\n (Returnstate i m_src)\n (Returnstate i m_tgt)\n j m_src m_tgt\n.\n\nInductive match_states_ab\n : unit -> state -> state -> SimMemInj.t' -> Prop :=\n| match_states_ab_intro\n st_src st_tgt j m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMemInj.src))\n (MWFTGT: m_tgt = sm0.(SimMemInj.tgt))\n (MWFINJ: j = sm0.(SimMemInj.inj))\n (MATCHST: match_states_ab_internal st_src st_tgt j m_src m_tgt)\n (MWF: SimMemInj.wf' sm0)\n :\n match_states_ab\n tt st_src st_tgt sm0\n.\n\nLemma a_id\n (WF: Sk.wf MutrecABspec.module)\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eapply any_id; auto.\nQed.\n\nLemma a_ext_unreach\n (WF: Sk.wf MutrecABspec.module)\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimSymbId.mk _ _).\n econs; ss; i.\n destruct SIMSKENVLINK.\n exploit ab_unreach_local_preservation. i. des.\n eapply match_states_sim with (match_states := match_states_ext_ab)\n (match_states_at := top4); ss.\n - apply unit_ord_wf.\n - eauto.\n - i. ss. inv INITTGT. inv SAFESRC. inv H. clarify.\n inv SIMARGS; ss. esplits; eauto; ss.\n + econs; eauto.\n + assert (i = i0).\n { subst. inv VALS. inv H2. ss. }\n subst. econs; eauto. ss.\n\n - i. ss. des. inv SAFESRC. esplits. econs; ss.\n + inv SIMARGS; ss. inv FPTR; eauto. clarify.\n + instantiate (1:=i). inv SIMARGS; ss.\n rewrite VS in *. inv VALS. inv H3. inv H1. ss.\n + auto.\n\n - i. inv MATCH; auto.\n\n - i. ss. inv FINALSRC. inv MATCH.\n esplits; eauto.\n + econs.\n + econs; eauto. econs.\n\n - right. ii. des.\n esplits.\n + i. inv MATCH; ss.\n * unfold ModSem.is_step. do 2 eexists. ss.\n * unfold safe_modsem in H.\n exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n + ii. inv STEPTGT; inv MATCH; ss.\n esplits; eauto.\n { left. eapply plus_one. econs. }\n econs; eauto.\nQed.\n\nLemma a_ext_top \n (WF: Sk.wf MutrecABspec.module)\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimSymbId.mk _ _).\n econs; ss; i.\n destruct SIMSKENVLINK.\n eapply match_states_sim with (match_states := match_states_ext_ab)\n (match_states_at := top4); ss.\n - apply unit_ord_wf.\n - eapply SoundTop.sound_state_local_preservation.\n - i. ss. inv INITTGT. inv SAFESRC. inv H. clarify.\n inv SIMARGS; ss. esplits; eauto; ss.\n + econs; eauto.\n + assert (i = i0).\n { subst. inv VALS. inv H2. ss. }\n subst. econs; eauto. ss.\n\n - i. ss. des. inv SAFESRC. esplits. econs; ss.\n + inv SIMARGS; ss. inv FPTR; eauto. clarify.\n + instantiate (1:=i). inv SIMARGS; ss.\n rewrite VS in *. inv VALS. inv H3. inv H1. ss.\n + auto.\n\n - i. inv MATCH; auto.\n\n - i. ss. inv FINALSRC. inv MATCH.\n esplits; eauto.\n + econs.\n + econs; eauto. econs.\n\n - right. ii. des.\n esplits.\n + i. inv MATCH; ss.\n * unfold ModSem.is_step. do 2 eexists. ss.\n * unfold safe_modsem in H.\n exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n + ii. inv STEPTGT; inv MATCH; ss.\n esplits; eauto.\n { left. eapply plus_one. econs. }\n econs; eauto.\nQed.\n\nLemma ab_inj_drop_bot\n (WF: Sk.wf (MutrecABspec.module))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto.\n econs; ss; i.\n { econs; ss; i; clarify.\n inv WF. auto. }\n eapply match_states_sim with (match_states := match_states_ab)\n (match_states_at := top4); ss.\n - apply unit_ord_wf.\n - eapply SoundTop.sound_state_local_preservation.\n\n - i. ss. inv INITTGT. inv SAFESRC. inv SIMARGS; ss. inv H.\n esplits; eauto.\n + econs; eauto.\n + refl.\n + econs; eauto.\n assert (i = i0).\n { subst. inv VALS. inv H2; ss. inv VS0. ss. }\n subst i0. econs.\n\n - i. des. inv SAFESRC. inv SIMARGS; ss.\n rewrite VS in *. inv VALS. inv H1. inv H3.\n unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs.\n inv SIMSKENV. ss. inv SIMSKE. ss. inv FPTR. exploit SIMDEF; eauto.\n i. des. clarify. esplits; eauto. econs; ss; eauto.\n unfold Genv.find_funct_ptr. des_ifs.\n\n - i. inv MATCH; eauto.\n\n - i. ss. inv FINALSRC. inv MATCH. inv MATCHST. esplits; eauto.\n + econs.\n + econs; eauto. econs.\n + refl.\n\n - right. ii. des.\n esplits.\n + i. inv MATCH; inv MATCHST; ss.\n * unfold ModSem.is_step. do 2 eexists. ss.\n * unfold safe_modsem in H.\n exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n + ii. inv STEPTGT; inv MATCH; inv MATCHST; ss.\n esplits; eauto.\n { left. eapply plus_one. econs. }\n { refl. }\n econs; eauto. econs; eauto.\nQed.\n\nLemma ab_inj_drop\n (WF: Sk.wf (MutrecABspec.module))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n exploit ab_inj_drop_bot; eauto. i. des. eauto.\nQed.\n\nLemma ab_inj_id\n (WF: Sk.wf (MutrecABspec.module))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eapply sim_inj_drop_bot_id. apply ab_inj_drop_bot; auto.\nQed.\n\nRequire Import IdSimInvExtra.\n\nSection INJINV.\n\nLocal Existing Instance SimSymbDropInv.SimMemInvTop.\nLocal Existing Instance SimSymbDropInv.SimSymbDropInv.\nLocal Existing Instance SoundTop.Top.\n\n\nInductive match_states_ab_inv\n : unit -> state -> state -> SimMem.t -> Prop :=\n| match_states_ab_inv_intro\n st_src st_tgt j m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMem.src))\n (MWFTGT: m_tgt = sm0.(SimMem.tgt))\n (MWFINJ: j = sm0.(SimMemInjInv.minj).(SimMemInj.inj))\n (MATCHST: match_states_ab_internal st_src st_tgt j m_src m_tgt)\n (MWF: SimMem.wf sm0)\n :\n match_states_ab_inv\n tt st_src st_tgt sm0.\n\n\nLemma ab_inj_inv_id\n (WF: Sk.wf (MutrecABspec.module))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimSymbDropInv.mk bot1 _ _).\n econs; ss; i.\n { econs; ss; i; clarify. inv WF. eauto. }\n eapply match_states_sim with (match_states := match_states_ab_inv)\n (match_states_at := top4); ss.\n - apply unit_ord_wf.\n - eapply SoundTop.sound_state_local_preservation.\n\n - i. ss. inv INITTGT. inv SAFESRC. inv SIMARGS; ss. inv H.\n esplits; eauto.\n + econs; eauto.\n + refl.\n + econs; eauto.\n assert (i = i0).\n { subst. inv VALS. inv H2; ss. inv VS0. ss. }\n subst i0. econs.\n\n - i. des. inv SAFESRC. inv SIMARGS; ss.\n rewrite VS in *. inv VALS. inv H1. inv H3.\n unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs.\n inv SIMSKENV. ss. inv SIMSKE. ss. inv FPTR. exploit SIMDEF; eauto.\n i. des. clarify. esplits; eauto. econs; ss; eauto.\n unfold Genv.find_funct_ptr. des_ifs.\n\n - i. inv MATCH; eauto.\n\n - i. ss. inv FINALSRC. inv MATCH. inv MATCHST. esplits; eauto.\n + econs.\n + econs; eauto. econs.\n + refl.\n\n - right. ii. des.\n esplits.\n + i. inv MATCH; inv MATCHST; ss.\n * unfold ModSem.is_step. do 2 eexists. ss.\n * unfold safe_modsem in H.\n exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n + ii. inv STEPTGT; inv MATCH; inv MATCHST; ss.\n esplits; eauto.\n { left. eapply plus_one. econs. }\n { refl. }\n econs; eauto. econs; eauto.\nQed.\n\nEnd INJINV.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/demo/mutrec/IdSimMutrecAB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.2658804614657028, "lm_q1q2_score": 0.1484482428106613}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of VMM *)\n(* *)\n(* Refinement Proof for PThreadInit *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between PThreadIntro layer and PThreadInit layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import ThreadInitGenSpec.\nRequire Import PThreadIntro.\nRequire Import PThreadInit.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n Local Open Scope string_scope.\n Local Open Scope error_monad_scope.\n Local Open Scope Z_scope.\n\n Context `{real_params: RealParams}.\n \n Notation HDATA := RData.\n Notation LDATA := RData.\n\n Notation HDATAOps := (cdata (cdata_ops := pthreadinit_data_ops) HDATA).\n Notation LDATAOps := (cdata (cdata_ops := mshareintro_data_ops) LDATA).\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** Relation between raw data at two layers*)\n Record relate_RData (f: meminj) (hadt: LDATA) (ladt: LDATA) :=\n mkrelate_RData {\n flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n devout_re: devout hadt = devout ladt;\n CR3_re: CR3 hadt = CR3 ladt;\n ikern_re: ikern hadt = ikern ladt;\n pg_re: pg hadt = pg ladt;\n ihost_re: ihost hadt = ihost ladt;\n AC_re: AC hadt = AC ladt;\n ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n LAT_re: LAT hadt = LAT ladt;\n nps_re: nps hadt = nps ladt;\n init_re: init hadt = init ladt;\n\n pperm_re: pperm hadt = pperm ladt;\n PT_re: PT hadt = PT ladt;\n ptp_re: ptpool hadt = ptpool ladt;\n idpde_re: idpde hadt = idpde ladt;\n ipt_re: ipt hadt = ipt ladt;\n smspool_re: smspool hadt = smspool ladt;\n\n kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n tcb_re: tcb hadt = tcb ladt\n }.\n\n Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n | MATCH_RDATA: forall habd m f s, match_RData s habd m f. \n\n Local Hint Resolve MATCH_RDATA.\n\n Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n {\n relate_AbData s f d1 d2 := relate_RData f d1 d2;\n match_AbData s d1 m f := match_RData s d1 m f;\n new_glbl := nil\n }. \n\n (** ** Properties of relations*)\n Section Rel_Property.\n\n (** Prove that after taking one step, the refinement relation still holds*) \n Lemma relate_incr: \n forall abd abd' f f',\n relate_RData f abd abd'\n -> inject_incr f f'\n -> relate_RData f' abd abd'.\n Proof.\n inversion 1; subst; intros; inv H; constructor; eauto.\n - eapply kctxt_inj_incr; eauto.\n Qed.\n\n Lemma relate_kernel_mode:\n forall abd abd' f,\n relate_RData f abd abd' \n -> (kernel_mode abd <-> kernel_mode abd').\n Proof.\n inversion 1; simpl; split; congruence.\n Qed.\n\n Lemma relate_observe:\n forall p abd abd' f,\n relate_RData f abd abd' ->\n observe p abd = observe p abd'.\n Proof.\n inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n Qed.\n\n Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n Proof.\n constructor; intros; simpl; trivial.\n eapply relate_incr; eauto.\n eapply relate_kernel_mode; eauto.\n eapply relate_observe; eauto.\n Qed.\n\n End Rel_Property.\n\n (** * Proofs the one-step forward simulations for the low level specifications*)\n Section OneStep_Forward_Relation.\n\n (** ** The low level specifications exist*)\n Section Exists.\n\n Lemma thread_init_exist:\n forall habd habd' labd i f,\n ObjQueue.thread_init_spec i habd = ret habd'\n -> relate_RData f habd labd\n -> exists labd', thread_init_spec i labd = Some labd' \n /\\ relate_RData f habd' labd'\n /\\ kernel_mode labd.\n Proof.\n unfold ObjQueue.thread_init_spec, thread_init_spec, sharedmem_init_spec, \n thread_init_spec. \n intros until f. exist_simpl.\n Qed.\n\n (*\n Lemma thread_free_exist:\n forall habd habd' labd n f,\n thread_free_spec habd n = Some habd'\n -> relate_RData f habd labd\n -> high_level_invariant habd\n -> exists labd', thread_free_spec labd n = Some labd' \n /\\ relate_RData f habd' labd'\n /\\ kernel_mode labd.\n Proof.\n unfold thread_free_spec, thread_free_spec,\n pt_free_spec, tcb_init_spec. \n intros until f.\n intros HP HR; inv HR; revert HP; simpl;\n subrewrite'; intros HQ; subdestruct.\n rewrite zle_true; [|omega]. \n inv HQ. refine_split'; eauto.\n econstructor; eauto.\n Qed.*)\n\n End Exists.\n\n Section FRESH_PRIM.\n\n (*Lemma thread_free_spec_ref:\n compatsim (crel HDATA LDATA) (gensem thread_free_spec) \n thread_free_spec_low.\n Proof. \n compatsim_simpl (@match_AbData).\n exploit thread_free_exist; eauto 1.\n intros [labd' [HP [HM Hkern]]].\n refine_split; try econstructor; eauto. constructor.\n Qed.*)\n\n Lemma thread_init_spec_ref:\n compatsim (crel HDATA LDATA) (gensem ObjQueue.thread_init_spec) thread_init_spec_low.\n Proof. \n compatsim_simpl (@match_AbData).\n exploit thread_init_exist; eauto 1.\n intros [labd' [HP [HM Hkern]]].\n refine_split; try econstructor; eauto. constructor.\n Qed.\n\n End FRESH_PRIM.\n\n Section PASSTHROUGH_RPIM.\n\n Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n Proof.\n accessor_prop_tac.\n - eapply flatmem_store_exists; eauto.\n Qed. \n\n Lemma passthrough_correct:\n sim (crel HDATA LDATA) pthreadinit_passthrough pthreadintro.\n Proof.\n sim_oplus.\n - apply fload_sim.\n - apply fstore_sim.\n - apply flatmem_copy_sim.\n - apply vmxinfo_get_sim.\n - apply device_output_sim.\n - apply pfree_sim.\n - apply setPT_sim.\n - apply ptRead_sim. \n - apply ptResv_sim.\n - apply kctxt_new_sim.\n - apply shared_mem_status_sim.\n - apply offer_shared_mem_sim.\n - apply get_state_sim.\n - apply get_prev_sim.\n - apply get_next_sim.\n - apply set_state_sim.\n - apply set_prev_sim.\n - apply set_next_sim.\n - apply ptin_sim.\n - apply ptout_sim.\n - apply clearCR2_sim.\n - apply container_get_nchildren_sim.\n - apply container_get_quota_sim.\n - apply container_get_usage_sim.\n - apply container_can_consume_sim.\n - apply alloc_sim.\n - apply trapin_sim.\n - apply trapout_sim.\n - apply hostin_sim.\n - apply hostout_sim.\n - apply trap_info_get_sim.\n - apply trap_info_ret_sim.\n - apply kctxt_switch_sim.\n - layer_sim_simpl.\n + eapply load_correct2.\n + eapply store_correct2.\n Qed.\n\n End PASSTHROUGH_RPIM.\n\n End OneStep_Forward_Relation.\n\n End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/ThreadInitGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2658804614657029, "lm_q1q2_score": 0.14844823890264824}} {"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Bool.Bool.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.AST.\nRequire Import compcert.cfrontend.Clight.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory. Import Memory.\nRequire Import compcert.common.Memdata. Import Memdata.\nRequire Import compcert.common.Values.\n\nRequire Import msl.Coqlib2.\nRequire Import msl.eq_dec.\nRequire Import msl.seplog.\nRequire Import veric.Clight_new.\nRequire Import veric.coqlib4.\nRequire Import sepcomp.Address.\nRequire Import sepcomp.mem_lemmas.\nRequire Import concurrency.permissions.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(** * Results on cl_step *)\n\nLemma cl_step_decay ge c m c' m' : @cl_step ge c m c' m' -> @decay m m'.\nProof.\n intros step.\n induction step\n as [ ve te k m a1 a2 b ofs v2 v m' H H0 H1 H2 ASS | |\n ve te k m optid a al tyagrs tyres cc vf vargs f m' ve' le' H H0 H1 H2 H3 H4 NRV ALLOC H6\n | | | | | | | | | f ve te optexp optid k m v' m' ve' te'' k' H H0 FREE H2 H3 | | | ];\n try apply decay_refl || apply IHstep.\n\n - (* assign: no change in permission *)\n intros b' ofs'.\n split.\n + inversion ASS as [v0 chunk m'0 H3 BAD H5 H6 | b'0 ofs'0 bytes m'0 H3 H4 H5 H6 H7 BAD H9 H10]; subst.\n -- pose proof storev_valid_block_2 _ _ _ _ _ BAD b'. tauto.\n -- pose proof Mem.storebytes_valid_block_2 _ _ _ _ _ BAD b'. tauto.\n + intros V; right; intros kind.\n (* destruct m as [c acc nb max no def]. simpl in *. *)\n inversion ASS as [v0 chunk m'0 H3 STO H5 H6 | b'0 ofs'0 bytes m'0 H3 H4 H5 H6 H7 STO H9 H10]; subst.\n -- simpl in *.\n Transparent Mem.store.\n unfold Mem.store in *; simpl in *.\n destruct (Mem.valid_access_dec m chunk b (Int.unsigned ofs) Writable).\n 2:discriminate.\n injection STO as <-. simpl.\n reflexivity.\n -- Transparent Mem.storebytes.\n unfold Mem.storebytes in *.\n destruct (Mem.range_perm_dec\n m b (Int.unsigned ofs)\n (Int.unsigned ofs + Z.of_nat (Datatypes.length bytes)) Cur Writable).\n 2:discriminate.\n injection STO as <-. simpl.\n reflexivity.\n\n - (* internal call : allocations *)\n clear -ALLOC.\n induction ALLOC. now apply decay_refl.\n apply decay_trans with m1. 3:apply IHALLOC.\n\n + clear -H.\n Transparent Mem.alloc.\n unfold Mem.alloc in *.\n injection H as <- <-.\n intros b V.\n unfold Mem.valid_block in *. simpl.\n apply Coqlib.Plt_trans_succ, V.\n\n + clear -H.\n unfold Mem.alloc in *.\n injection H as E <-.\n intros b ofs.\n split.\n * intros N V.\n subst m1.\n simpl in *.\n rewrite PMap.gsspec.\n unfold Mem.valid_block in *; simpl in *.\n if_tac; subst; auto.\n -- if_tac; auto.\n -- destruct N.\n apply Coqlib.Plt_succ_inv in V.\n tauto.\n * intros V.\n right.\n intros k.\n subst.\n simpl.\n rewrite PMap.gsspec.\n if_tac.\n -- subst b. inversion V. rewrite Pos.compare_lt_iff in *. edestruct Pos.lt_irrefl; eauto.\n -- reflexivity.\n\n - (* return: free_list *)\n revert FREE; clear.\n generalize (blocks_of_env ge ve); intros l.\n revert m m'; induction l as [| [[b o] o'] l IHl]; intros m m'' E.\n + simpl. injection E as <- ; apply decay_refl.\n + simpl in E.\n destruct (Mem.free m b o o') as [m' |] eqn:F.\n 2:discriminate.\n specialize (IHl _ _ E).\n Transparent Mem.free.\n unfold Mem.free in *.\n if_tac in F. rename H into G.\n 2:discriminate.\n apply decay_trans with m'. 3:now apply IHl.\n * injection F as <-.\n intros.\n unfold Mem.unchecked_free, Mem.valid_block in *.\n simpl in *.\n assumption.\n\n * injection F as <-.\n clear -G.\n unfold Mem.unchecked_free in *.\n intros b' ofs; simpl. unfold Mem.valid_block; simpl.\n split.\n tauto.\n intros V.\n rewrite PMap.gsspec.\n if_tac; auto. subst b'.\n hnf in G.\n destruct (Coqlib.proj_sumbool (Coqlib.zle o ofs)&&Coqlib.proj_sumbool (Coqlib.zlt ofs o'))%bool eqn:E.\n 2: now auto.\n left. split; auto.\n destruct m as [co acc nb max noa def] eqn:Em; simpl in *.\n unfold Mem.perm in G; simpl in *.\n specialize (G ofs).\n cut (acc !! b ofs Cur = Some Freeable). {\n destruct k; auto.\n pose proof Mem.access_max m b ofs as M.\n subst m; simpl in M.\n intros A; rewrite A in M.\n destruct (acc !! b ofs Max) as [ [] | ]; inversion M; auto.\n }\n assert (R: (o <= ofs < o')%Z). {\n rewrite andb_true_iff in *. destruct E as [E F].\n apply Coqlib.proj_sumbool_true in E.\n apply Coqlib.proj_sumbool_true in F.\n auto.\n }\n autospec G.\n destruct (acc !! b ofs Cur) as [ [] | ]; inversion G; auto.\nQed.\n\nLemma cl_step_unchanged_on ge c m c' m' b ofs :\n @cl_step ge c m c' m' ->\n Mem.valid_block m b ->\n ~ Mem.perm m b ofs Cur Writable ->\n Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m)) =\n Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m')).\nProof.\n intros step.\n induction step\n as [ ve te k m a1 a2 b0 ofs0 v2 v m' H H0 H1 H2 ASS | |\n ve te k m optid a al tyagrs tyres cc vf vargs f m' ve' le' H H0 H1 H2 H3 H4 NRV ALLOC H6\n | | | | | | | | | f ve te optexp optid k m v' m' ve' te'' k' H H0 FREE H2 H3 | | | ];\n intros V NW; auto.\n\n - (* assign: some things are updated, but not the chunk in non-writable permission *)\n inversion ASS; subst.\n + inversion H4.\n unfold Mem.store in *.\n destruct (Mem.valid_access_dec m chunk b0 (Int.unsigned ofs0) Writable); [|discriminate].\n injection H6 as <- ; clear ASS H4.\n simpl.\n destruct (eq_dec b b0) as [e|n]; swap 1 2.\n * rewrite PMap.gso; auto.\n * subst b0. rewrite PMap.gss.\n generalize ((Mem.mem_contents m) !! b); intros t.\n destruct v0 as [v0 align].\n specialize (v0 ofs).\n {\n destruct (adr_range_dec (b, Int.unsigned ofs0) (size_chunk chunk) (b, ofs)) as [a|a].\n - simpl in a; destruct a as [_ a].\n autospec v0.\n tauto.\n - simpl in a.\n symmetry.\n apply Mem.setN_outside.\n rewrite encode_val_length.\n replace (Z_of_nat (size_chunk_nat chunk)) with (size_chunk chunk); swap 1 2.\n { unfold size_chunk_nat in *. rewrite Z2Nat.id; auto. destruct chunk; simpl; omega. }\n assert (a' : ~ (Int.unsigned ofs0 <= ofs < Int.unsigned ofs0 + size_chunk chunk)%Z) by intuition.\n revert a'; clear.\n generalize (Int.unsigned ofs0).\n generalize (size_chunk chunk).\n intros.\n omega.\n }\n\n + (* still the case of assignment (copying) *)\n unfold Mem.storebytes in *.\n destruct (Mem.range_perm_dec m b0 (Int.unsigned ofs0) (Int.unsigned ofs0 + Z.of_nat (Datatypes.length bytes)) Cur Writable); [ | discriminate ].\n injection H8 as <-; clear ASS; simpl.\n destruct (eq_dec b b0) as [e|n]; swap 1 2.\n * rewrite PMap.gso; auto.\n * subst b0. rewrite PMap.gss.\n generalize ((Mem.mem_contents m) !! b); intros t.\n specialize (r ofs).\n {\n destruct (adr_range_dec (b, Int.unsigned ofs0) (Z.of_nat (Datatypes.length bytes)) (b, ofs)) as [a|a].\n - simpl in a; destruct a as [_ a].\n autospec r.\n tauto.\n - simpl in a.\n symmetry.\n apply Mem.setN_outside.\n assert (a' : ~ (Int.unsigned ofs0 <= ofs < Int.unsigned ofs0 + Z.of_nat (Datatypes.length bytes))%Z) by intuition.\n revert a'; clear.\n generalize (Int.unsigned ofs0).\n intros.\n omega.\n }\n\n - (* internal call : things are allocated -- each time in a new block *)\n clear -V ALLOC.\n induction ALLOC. easy.\n rewrite <-IHALLOC; swap 1 2.\n + unfold Mem.alloc in *.\n injection H as <- <-.\n unfold Mem.valid_block in *.\n simpl.\n apply Plt_trans_succ.\n auto.\n + clear IHALLOC.\n unfold Mem.alloc in *.\n injection H as <- <- . simpl.\n f_equal.\n rewrite PMap.gso. auto.\n unfold Mem.valid_block in *.\n auto with *.\n\n - (* return: free_list *)\n revert FREE NW V; clear.\n generalize (blocks_of_env ge ve); intros l.\n revert m m'; induction l as [| [[b' o] o'] l IHl]; intros m m'' E NW V.\n + simpl. injection E as <- . easy.\n + simpl in E.\n destruct (Mem.free m b' o o') as [m' |] eqn:F.\n 2:discriminate.\n specialize (IHl _ _ E).\n unfold Mem.free in *.\n if_tac in F. 2:discriminate.\n injection F as <- .\n rewrite <-IHl. easy.\n * unfold Mem.perm in *.\n unfold Mem.unchecked_free.\n simpl.\n rewrite PMap.gsspec.\n if_tac; [ | easy ].\n subst.\n unfold Mem.range_perm in *.\n destruct (zle o ofs); auto.\n destruct (zlt ofs o'); simpl; auto.\n * unfold Mem.unchecked_free, Mem.valid_block; simpl. auto.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/cl_step_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2814056074291439, "lm_q1q2_score": 0.14729342123320072}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Locations.\nRequire Import DataType.\nRequire Import LAsm.\nRequire Import CDataTypes.\nRequire Import AsmExtra.\nRequire Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import MPTOp.\nRequire Import MPTIntro.\nRequire Export PTOpGen.\nRequire Import MPTIntroCode.\nRequire Import ZArith.Zwf.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import Maps.\nRequire Import Heap.\nRequire Import RefinementTactic.\nRequire Import AuxLemma.\nRequire Import LayerTemplate2.\nRequire Import Implementation.\nRequire Import SeparateCompiler.\nRequire Import ClightImplemExtra.\nRequire Import LayerDefinition.\nRequire Import RealParams.\n\nOpen Local Scope string_scope.\nOpen Local Scope error_monad_scope.\n\nModule PTOPGENIMPL.\n Export PTOpGen.PTOPGEN.\n\n Lemma hprim_finite_type:\n forall\n (Q: MPTOP.primOp -> Prop)\n (Q_dec: forall p, {Q p} + {~ Q p}),\n {forall p, Q p} + {~ forall p, Q p}.\n Proof with (try (right; eauto; fail)).\n intros.\n destruct (Q_dec MPTOP.PSetPE)...\n destruct (Q_dec MPTOP.PAlloc)...\n destruct (Q_dec MPTOP.PFree)...\n destruct (Q_dec MPTOP.PSetPT)...\n destruct (Q_dec MPTOP.PSetPDX)...\n destruct (Q_dec MPTOP.PPTRead)...\n destruct (Q_dec MPTOP.PPTInsert)...\n destruct (Q_dec MPTOP.PPTRmv)...\n destruct (Q_dec MPTOP.PPTIn)...\n destruct (Q_dec MPTOP.PPTOut)...\n destruct (Q_dec MPTOP.PTrapIn)...\n destruct (Q_dec MPTOP.PTrapOut)...\n destruct (Q_dec MPTOP.PHostIn)...\n destruct (Q_dec MPTOP.PHostOut)...\n destruct (Q_dec MPTOP.PTrapGet)...\n destruct (Q_dec MPTOP.PTrapRet)...\n destruct (Q_dec MPTOP.PMemInit)...\n left; destruct p; assumption.\n Defined. \n\n Section WithPrimitives.\n\n Context `{real_params: RealParams}.\n\n Notation HDATA := (MPTINTRO.AbData (PgSize:=PgSize) (num_proc:=num_proc) (kern_low:=kern_low) \n (kern_high:=kern_high) (maxpage:=maxpage)).\n Notation LDATA := (MPTINTRO.AbData (PgSize:=PgSize) (num_proc:=num_proc) (kern_low:=kern_low) \n (kern_high:=kern_high) (maxpage:=maxpage)).\n \n Notation Hfundef := (fundef (external_function:= MPTOP.primOp)).\n Notation Lfundef := (fundef (external_function:= MPTINTRO.primOp)).\n\n Notation funkind := (funkind (low := MPTINTRO.primOp) Asm.code (Clight.fundef (external_function := MPTINTRO.primOp))).\n\n Notation dummy := (AST.Internal nil).\n\n Definition source_implem_extfuns (p: MPTOP.primOp): funkind :=\n match p with\n | MPTOP.PSetPE => Code _ (AST.External MPTINTRO.PSetPE)\n | MPTOP.PAlloc => Code _ (AST.External MPTINTRO.PAlloc)\n | MPTOP.PFree => Code _ (AST.External MPTINTRO.PFree)\n | MPTOP.PSetPT => Code _ (AST.External MPTINTRO.PSetPT)\n | MPTOP.PSetPDX => Code _ (AST.External MPTINTRO.PSetPDX)\n | MPTOP.PPTRead => SourceFun (Clight.Internal MPTINTROCODE.f_pt_read) dummy\n | MPTOP.PPTInsert => SourceFun (Clight.Internal MPTINTROCODE.f_pt_insert) dummy\n | MPTOP.PPTRmv => SourceFun (Clight.Internal MPTINTROCODE.f_pt_rmv) dummy\n | MPTOP.PPTIn => Code _ (AST.External MPTINTRO.PPTIn)\n | MPTOP.PPTOut => Code _ (AST.External MPTINTRO.PPTOut)\n | MPTOP.PTrapIn => Code _ (AST.External MPTINTRO.PTrapIn)\n | MPTOP.PTrapOut => Code _ (AST.External MPTINTRO.PTrapOut)\n | MPTOP.PHostIn => Code _ (AST.External MPTINTRO.PHostIn)\n | MPTOP.PHostOut => Code _ (AST.External MPTINTRO.PHostOut)\n | MPTOP.PTrapGet => Code _ (AST.External MPTINTRO.PTrapGet)\n | MPTOP.PTrapRet => Code _ (AST.External MPTINTRO.PTrapRet)\n | MPTOP.PMemInit => Code _ (AST.External MPTINTRO.PMemInit)\n end.\n\n Notation varkind := (varkind unit Ctypes.type).\n\n Definition source_implem_impl_globs : list (ident * option (globdef funkind varkind)) :=\n (get_PTX, Some (Gfun (SourceFun (Clight.External (MPTINTRO.PGetPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tint) dummy)))\n :: (set_PTX, Some (Gfun (SourceFun (Clight.External (MPTINTRO.PSetPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))))) Ctypes.Tvoid) dummy)))\n :: (rmv_PTX, Some (Gfun (SourceFun (Clight.External (MPTINTRO.PRmvPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tvoid) dummy)))\n :: nil.\n\n Let NOREPET_IMPL: list_norepet (map fst source_implem_impl_globs).\n Proof.\n case_eq (list_norepet_dec peq (map fst source_implem_impl_globs)); try discriminate; tauto.\n Qed.\n\n Definition source_implem : source_implem Asm.code unit MPTOP.primOp (low := MPTINTRO.primOp) (Clight.fundef (external_function := MPTINTRO.primOp)) Ctypes.type.\n Proof.\n split.\n exact source_implem_extfuns.\n exact source_implem_impl_globs.\n Defined.\n\n Let im : implem Asm.code unit MPTOP.primOp (low := MPTINTRO.primOp) := implem_of_source_implem transf_clight_fundef Cshmgen.transl_globvar source_implem.\n\n Notation Hprogram := (Asm.program (external_function:= MPTOP.primOp)). \n Notation Lprogram := (Asm.program (external_function:= MPTINTRO.primOp)).\n\n Let Im_pt_read: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns MPTOP.PPTRead).\n Let Im_pt_insert: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns MPTOP.PPTInsert).\n Let Im_pt_rmv: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns MPTOP.PPTRmv).\n\n Definition impl_glbl : list (ident * option (globdef Lfundef unit)) :=\n map\n (transf_source_def' transf_clight_fundef\n Cshmgen.transl_globvar)\n source_implem_impl_globs.\n\n Let well_new_glb: Genv.well_idglob_list impl_glbl = true.\n Proof. reflexivity. Qed.\n \n (* This is basically an axiom that can be easily checked because MPTOP.primOp is a finite type. However, in practice, generation of CertiKOS code will be very slow because compilation will have to occur twice, one for this check, and a second independently for the generation of the actual code. *)\n \n Lemma extfun_compilation_succeeds_dec:\n {forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm} +\n {~ forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm}.\n Proof.\n apply hprim_finite_type.\n intro.\n destruct (source_implem_extfuns p); try (left; discriminate).\n case_eq (transf_clight_fundef sf).\n left. intros. inv H0. eauto.\n intros. right. intro. exploit H0; eauto. destruct 1. congruence.\n Defined.\n\n Hypothesis extfun_compilation_succeeds:\n forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm.\n\n Section WithProg.\n\n Variable prog: Hprogram.\n\n Definition tprog: Lprogram := Implementation.transf_program im prog.\n\n Let TRANSF: PTOPGEN.transf_program Im_pt_insert Im_pt_rmv Im_pt_read impl_glbl prog = OK tprog.\n Proof.\n unfold tprog.\n unfold Asm.program, Asm.fundef.\n generalize (transf_program_eq im prog).\n intros.\n rewrite <- H.\n unfold transf_program.\n simpl.\n f_equal.\n apply FunctionalExtensionality.functional_extensionality.\n destruct x; simpl.\n reflexivity.\n destruct p; reflexivity.\n Qed.\n\n Notation ge := (Genv.globalenv prog).\n Notation tge := (Genv.globalenv tprog).\n\n Hypothesis prog_main_valid:\n ~ Plt' (prog_main prog) (prog_first_symbol prog).\n\n Hypothesis prog_first_valid:\n ~ Plt' (prog_first_symbol prog) (get_next_symbol (map fst impl_glbl)).\n\n Hypothesis prog_nonempty:\n prog_defs_names prog <> nil.\n \n Lemma tprog_first_next:\n prog_first_symbol tprog = get_first_symbol (map fst impl_glbl) /\\\n prog_next_symbol tprog = prog_next_symbol prog.\n Proof.\n replace (get_first_symbol (map fst impl_glbl)) with (implem_first_symbol im) by reflexivity.\n unfold tprog.\n apply transf_program_first_next_symbol.\n assumption.\n assumption.\n discriminate.\n Qed.\n\n Lemma tprog_main_valid:\n ~ Plt' (prog_main tprog) (prog_first_symbol tprog).\n Proof.\n Opaque Plt'.\n simpl.\n destruct tprog_first_next.\n rewrite H.\n apply Ple'_not_Plt'.\n eapply Ple'_trans.\n apply first_le_next.\n discriminate.\n eapply Ple'_trans.\n apply not_Plt'_Ple'.\n eassumption.\n apply not_Plt'_Ple'.\n assumption.\n Qed.\n\n Lemma tprog_nonempty:\n prog_defs_names tprog <> nil.\n Proof.\n apply transf_program_nonempty.\n assumption.\n Qed.\n\n Let NEW_INJ: (forall s', Genv.find_symbol ge s' <> None -> \n ~ In s' (map fst impl_glbl)).\n Proof.\n change impl_glbl with (implem_new_globs im).\n apply new_ids_fresh.\n assumption.\n Qed.\n\n Let sprog : Clight.program (external_function := MPTINTRO.primOp) := source_program_only source_implem prog.\n Let sge := Genv.globalenv sprog.\n\n Ltac elim_or H t :=\n match type of H with\n | False => contradiction\n | _ \\/ _ =>\n let K := fresh \"K\" in\n destruct H as [H | K]; [ elim_or H t | elim_or K t ]\n | _ => t H\n end.\n\n Let tsprog_strong : {tsprog | transf_clight_program sprog = OK tsprog}.\n Proof.\n case_eq (transf_clight_program sprog); eauto.\n intros. exfalso.\n refine (_ (Implementation.compilation_succeeds\n transf_clight_fundef\n Cshmgen.transl_globvar\n source_implem _ _ _\n prog)).\n destruct 1.\n generalize (transf_clight_fundef_to_program _ _ H0).\n unfold sprog in H.\n congruence.\n assumption.\n simpl. \n intros until fallback.\n intro K.\n let t J := (inv J; rewrite transf_clight_fundef_external; eauto) in elim_or K t.\n unfold Cshmgen.transl_globvar. eauto.\n Qed.\n\n Let tsprog := let (p, _) := tsprog_strong in p.\n\n Let tsprog_prop : transf_clight_program sprog = OK tsprog.\n Proof.\n unfold tsprog.\n destruct tsprog_strong.\n assumption.\n Qed.\n\n Let tsge := Genv.globalenv tsprog.\n\n (** get_PTX *)\n\n Let bget_PTX: block := Genv.genv_next ge + Z.of_nat 0.\n\n Let hget_PTX1 : Genv.find_symbol sge get_PTX = Some bget_PTX. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ get_PTX).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed. \n \n Let hget_PTX2 : Genv.find_funct sge (Vptr bget_PTX Int.zero) = Some (Clight.External (MPTINTRO.PGetPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tint).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ get_PTX _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hget_PTX3 : Clight.type_of_global sge bget_PTX = Some (Ctypes.Tfunction (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tint).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bget_PTX).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bget_PTX. unfold Asm.fundef. omega.\n intros.\n simpl in hget_PTX2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hget_PTX2. reflexivity.\n Qed. \n\n (** set_PTX *)\n\n Let bset_PTX: block := Genv.genv_next ge + Z.of_nat 1.\n\n Let hset_PTX1 : Genv.find_symbol sge set_PTX = Some bset_PTX. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ set_PTX).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let hset_PTX2 : Genv.find_funct sge (Vptr bset_PTX Int.zero) = Some (Clight.External (MPTINTRO.PSetPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))))) Ctypes.Tvoid).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ set_PTX _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hset_PTX3 : Clight.type_of_global sge bset_PTX = Some (Ctypes.Tfunction (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))))) Ctypes.Tvoid).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bset_PTX).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bset_PTX. unfold Asm.fundef. omega.\n intros.\n simpl in hset_PTX2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hset_PTX2. reflexivity.\n Qed. \n\n (** rmv_PTX *)\n\n Let brmv_PTX: block := Genv.genv_next ge + Z.of_nat 2.\n\n Let hrmv_PTX1 : Genv.find_symbol sge rmv_PTX = Some brmv_PTX. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ rmv_PTX).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let hrmv_PTX2 : Genv.find_funct sge (Vptr brmv_PTX Int.zero) = Some (Clight.External (MPTINTRO.PRmvPTX) (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tvoid).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ rmv_PTX _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hrmv_PTX3 : Clight.type_of_global sge brmv_PTX = Some (Ctypes.Tfunction (Ctypes.Tcons tint (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil))) tvoid).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge brmv_PTX).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold brmv_PTX. unfold Asm.fundef. omega.\n intros.\n simpl in hrmv_PTX2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hrmv_PTX2. reflexivity.\n Qed.\n\n Context `{PageFaultHandler_LOC: ident}.\n\n Section WITHMEM.\n \n Context {mem__MPTOP} {mem__MPTINTRO}\n `{HHmem: !LayerMemoryModel HDATA mem__MPTOP}\n `{HLmem: !LayerMemoryModel LDATA mem__MPTINTRO}\n `{HLayerInject: !LayerMemoryInjections HDATA LDATA mem__MPTOP mem__MPTINTRO}.\n\n Notation LLoad := (MPTINTRO.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n Notation LStore := (MPTINTRO.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n Notation HLoad := (MPTOP.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n Notation HStore := (MPTOP.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n\n Instance HLayer: LayerDefinition (layer_mem:= HHmem) HDATA MPTOP.primOp mem__MPTOP :=\n MPTOP.layer_def (maxpage := maxpage) (real_nps:= real_nps) (real_AT:= real_AT) (Hmem:= HHmem) (HPS:= HPS).\n\n Instance LLayer: LayerDefinition (layer_mem:= HLmem) LDATA MPTINTRO.primOp mem__MPTINTRO :=\n MPTINTRO.layer_def (maxpage := maxpage) (real_nps:= real_nps) (real_AT:= real_AT) (Hmem:= HLmem) (HPS:= HPS).\n\n Notation lstep := (MPTINTRO.step (NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC) (HPS:= HPS)\n (real_nps:= real_nps) (real_AT:= real_AT)).\n\n Let pt_insert_spec:\n forall m rs b adt n sig p vadr padr,\n rs PC = Vptr b Int.zero\n -> MPTINTRO.ptInsert (HPS:=HPS) (Mem.get_abstract_data m) (Int.unsigned n)\n (Int.unsigned vadr) (Int.unsigned padr) (Int.unsigned p) = Some adt\n -> Genv.find_funct_ptr tge b = Some (Im_pt_insert)\n -> sig = mksignature (Tint :: Tint :: Tint :: Tint :: nil) None \n -> (forall b o, rs ESP = Vptr b o -> Mem.tget m b = Some Tag_stack)\n -> rs ESP <> Vundef\n -> rs RA <> Vundef\n -> Genv.find_funct_ptr ge b = Some (External MPTOP.PPTInsert)\n -> asm_invariant tge (State rs m)\n -> extcall_arguments rs m sig (Vint n :: Vint vadr :: Vint padr :: Vint p :: nil)\n -> exists f' m0' r_, \n inject_incr (Mem.flat_inj (Mem.nextblock m)) f' \n /\\ Memtype.Mem.inject f' m m0'\n /\\ Mem.nextblock m <= Mem.nextblock m0'\n /\\ plus lstep tge (State rs m) E0 (State r_ (Mem.put_abstract_data m0' adt))\n /\\ True\n /\\ r_ PC = rs RA\n /\\ r_ # ESP = rs # ESP\n /\\ (forall l,\n ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n -> Val.lessdef (rs (preg_of l)) (r_ (preg_of l))).\n Proof.\n intros. \n exploit (ClightImplemExtra.bigstep_clight_to_lsem\n MPTOP.primOp\n (exec_load := LLoad)\n (exec_store := LStore)\n (primitive_call := MPTINTRO.primitive_call)\n (is_primitive_call := MPTINTRO.is_primitive_call)\n (kernel_mode := MPTINTRO.kernel_mode)\n ).\n apply MPTINTRO.exec_load_exec_loadex.\n apply MPTINTRO.exec_store_exec_storeex.\n apply MPTINTRO.extcall_not_primitive.\n apply MPTINTRO.primitive_kernel_mode.\n 3: eassumption.\n assumption.\n assumption.\n 2: eassumption.\n 5: eassumption.\n 9: eassumption.\n 7: reflexivity.\n intros.\n eapply MPTINTROCODE.pt_insert_correct.\n 2: eassumption. eassumption. assumption.\n assumption.\n (* BEGIN hypotheses coming from refinement proof *)\n eassumption.\n reflexivity.\n (* END hypotheses coming from refinement proof *)\n assumption.\n assumption.\n assumption.\n assumption.\n assumption.\n unfold MPTINTRO.kernel_mode.\n apply MPTINTRO.ptInsert_eq in H0.\n functional inversion H0.\n functional inversion H10.\n unfold adt0 in *.\n destruct (MPTINTRO.INV (Mem.get_abstract_data m)).\n auto.\n destruct 1 as [? [? [m_asm [? [INJ [NB [PLUS [? [? [? ?]]]]]]]]]].\n generalize (Mem.put_abstract_data_inject_inside _ _ _ INJ (Mem.get_abstract_data m)).\n rewrite Mem.put_put_abstract_data.\n rewrite Mem.put_get_abstract_data.\n intro.\n replace (Mem.nextblock m_asm) with (Mem.nextblock (Mem.put_abstract_data m_asm (Mem.get_abstract_data m))) in NB by (rewrite Mem.nextblock_put_abstract_data; reflexivity).\n replace m_asm with (Mem.put_abstract_data (Mem.put_abstract_data m_asm (Mem.get_abstract_data m)) adt) in PLUS.\n unfold loc_external_result.\n eauto 11.\n rewrite Mem.put_put_abstract_data.\n replace adt with (Mem.get_abstract_data m_asm).\n rewrite Mem.put_get_abstract_data.\n reflexivity.\n erewrite <- Mem.get_abstract_data_inject_inside; eauto.\n rewrite Mem.get_put_abstract_data.\n reflexivity.\n Qed.\n\n Let pt_rmv_spec:\n forall m rs b adt n vadr sig,\n rs PC = Vptr b Int.zero\n -> MPTINTRO.ptRmv (Mem.get_abstract_data m) (Int.unsigned n)\n (Int.unsigned vadr) = Some adt\n -> Genv.find_funct_ptr tge b = Some (Im_pt_rmv)\n -> sig = mksignature (Tint :: Tint :: nil) None \n -> (forall b o, rs ESP = Vptr b o -> Mem.tget m b = Some Tag_stack)\n -> rs ESP <> Vundef\n -> rs RA <> Vundef\n -> Genv.find_funct_ptr ge b = Some (External MPTOP.PPTRmv)\n -> asm_invariant tge (State rs m)\n -> extcall_arguments rs m sig (Vint n :: Vint vadr :: nil)\n -> exists f' m0' r_, \n inject_incr (Mem.flat_inj (Mem.nextblock m)) f' \n /\\ Memtype.Mem.inject f' m m0'\n /\\ Mem.nextblock m <= Mem.nextblock m0'\n /\\ plus lstep tge (State rs m) E0 (State r_ (Mem.put_abstract_data m0' adt))\n /\\ True\n /\\ r_ PC = rs RA\n /\\ r_ # ESP = rs # ESP\n /\\ (forall l,\n ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n -> Val.lessdef (rs (preg_of l)) (r_ (preg_of l))).\n Proof.\n intros. \n exploit (ClightImplemExtra.bigstep_clight_to_lsem\n MPTOP.primOp\n (exec_load := LLoad)\n (exec_store := LStore)\n (primitive_call := MPTINTRO.primitive_call)\n (is_primitive_call := MPTINTRO.is_primitive_call)\n (kernel_mode := MPTINTRO.kernel_mode)\n ).\n apply MPTINTRO.exec_load_exec_loadex.\n apply MPTINTRO.exec_store_exec_storeex.\n apply MPTINTRO.extcall_not_primitive.\n apply MPTINTRO.primitive_kernel_mode.\n 3: eassumption.\n assumption.\n assumption.\n 2: eassumption.\n 5: eassumption.\n 9: eassumption.\n 7: reflexivity.\n intros.\n eapply MPTINTROCODE.pt_rmv_correct.\n 2: eassumption. eassumption. assumption.\n assumption.\n (* BEGIN hypotheses coming from refinement proof *)\n eassumption.\n reflexivity.\n (* END hypotheses coming from refinement proof *)\n assumption.\n assumption.\n assumption.\n assumption.\n assumption.\n unfold MPTINTRO.kernel_mode.\n apply MPTINTRO.ptRmv_eq in H0.\n functional inversion H0.\n destruct (MPTINTRO.INV (Mem.get_abstract_data m)).\n functional inversion H10; unfold adt1 in *; auto.\n destruct 1 as [? [? [m_asm [? [INJ [NB [PLUS [? [? [? ?]]]]]]]]]].\n generalize (Mem.put_abstract_data_inject_inside _ _ _ INJ (Mem.get_abstract_data m)).\n rewrite Mem.put_put_abstract_data.\n rewrite Mem.put_get_abstract_data.\n intro.\n replace (Mem.nextblock m_asm) with (Mem.nextblock (Mem.put_abstract_data m_asm (Mem.get_abstract_data m))) in NB by (rewrite Mem.nextblock_put_abstract_data; reflexivity).\n replace m_asm with (Mem.put_abstract_data (Mem.put_abstract_data m_asm (Mem.get_abstract_data m)) adt) in PLUS.\n eauto 11.\n rewrite Mem.put_put_abstract_data.\n replace adt with (Mem.get_abstract_data m_asm).\n rewrite Mem.put_get_abstract_data.\n reflexivity.\n erewrite <- Mem.get_abstract_data_inject_inside; eauto.\n rewrite Mem.get_put_abstract_data.\n reflexivity.\n Qed.\n\n Let pt_read_spec:\n forall m rs b n sig vadr padr,\n rs PC = Vptr b Int.zero\n -> MPTINTRO.ptRead (Mem.get_abstract_data m) (Int.unsigned n)\n (Int.unsigned vadr) = Some (Int.unsigned padr)\n -> Genv.find_funct_ptr tge b = Some (Im_pt_read)\n -> sig = mksignature (Tint :: Tint :: nil) (Some Tint) \n -> (forall b o, rs ESP = Vptr b o -> Mem.tget m b = Some Tag_stack)\n -> rs ESP <> Vundef\n -> rs RA <> Vundef\n -> Genv.find_funct_ptr ge b = Some (External MPTOP.PPTRead)\n -> asm_invariant tge (State rs m)\n -> extcall_arguments rs m sig (Vint n :: Vint vadr :: nil)\n -> exists f' m0' r_, \n inject_incr (Mem.flat_inj (Mem.nextblock m)) f' \n /\\ Memtype.Mem.inject f' m m0'\n /\\ Mem.nextblock m <= Mem.nextblock m0'\n /\\ plus lstep tge (State rs m) E0 (State r_ m0')\n /\\ r_ # (loc_external_result sig) = (Vint padr)\n /\\ r_ PC = rs RA\n /\\ r_ # ESP = rs # ESP\n /\\ (forall l,\n ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n -> Val.lessdef (rs (preg_of l)) (r_ (preg_of l))).\n Proof.\n intros. \n exploit (ClightImplemExtra.bigstep_clight_to_lsem\n MPTOP.primOp\n (exec_load := LLoad)\n (exec_store := LStore)\n (primitive_call := MPTINTRO.primitive_call)\n (is_primitive_call := MPTINTRO.is_primitive_call)\n (kernel_mode := MPTINTRO.kernel_mode)\n ).\n apply MPTINTRO.exec_load_exec_loadex.\n apply MPTINTRO.exec_store_exec_storeex.\n apply MPTINTRO.extcall_not_primitive.\n apply MPTINTRO.primitive_kernel_mode.\n 3: eassumption.\n assumption.\n assumption.\n 2: eassumption.\n 5: eassumption.\n 9: eassumption.\n 7: reflexivity.\n intros.\n eapply MPTINTROCODE.pt_read_correct.\n 2: eassumption. eassumption. assumption.\n assumption.\n eassumption.\n assumption.\n assumption.\n assumption.\n assumption.\n assumption.\n unfold MPTINTRO.kernel_mode.\n unfold MPTINTRO.ptRead in H0.\n unfold MPTINTRO.getPTX in H0.\n destruct (MPTINTRO.INV (Mem.get_abstract_data m)).\n destruct (MPTOP.ipt (MPTINTRO.ADT (Mem.get_abstract_data m))); try discriminate H0.\n destruct (MPTOP.ihost (MPTINTRO.ADT (Mem.get_abstract_data m))); try discriminate H0.\n auto.\n destruct 1 as [? [? [m_asm [? [INJ [NB [PLUS [? [? [? ?]]]]]]]]]].\n generalize (Mem.put_abstract_data_inject_inside _ _ _ INJ (Mem.get_abstract_data m)).\n rewrite Mem.put_get_abstract_data.\n intro.\n replace (Mem.nextblock m_asm) with (Mem.nextblock (Mem.put_abstract_data m_asm (Mem.get_abstract_data m))) in NB by (rewrite Mem.nextblock_put_abstract_data; reflexivity).\n replace m_asm with (Mem.put_abstract_data (Mem.put_abstract_data m_asm (Mem.get_abstract_data m)) (Mem.get_abstract_data m)) in PLUS.\n inversion H10.\n rewrite Mem.put_put_abstract_data in PLUS.\n eauto 11.\n rewrite Mem.put_put_abstract_data.\n rewrite (Mem.get_abstract_data_inject_inside x m m_asm).\n rewrite Mem.put_get_abstract_data.\n reflexivity.\n assumption.\n Qed.\n\n Theorem transf_program_correct:\n Smallstep.backward_simulation \n (MPTOP.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC) \n (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= HHmem) (HPS:= HPS) prog) \n (MPTINTRO.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC) \n (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= HLmem) (HPS:= HPS) tprog). \n Proof.\n eapply PTOPGEN.transf_program_correct; simpl; eauto.\n Qed.\n\n End WITHMEM.\n\n End WithProg.\n\n End WithPrimitives.\n\nEnd PTOPGENIMPL.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTOpGenImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.1466035581861199}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of VMM: MPTOP *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the MPTOp layer, which will introduce high-level primitives to operate on page table*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\n\n(*Require Import CalRealPTPool.*)\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\n\nRequire Export MPTIntro.\nRequire Import AbstractDataType.\n\nSection WITHMEM.\n\n Local Open Scope Z_scope.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n Context `{real_params: RealParams}.\n\n (** * Proofs that the primitives satisfies the invariants at this layer *)\n Section INV.\n\n Global Instance ptInsertAux_inv: PreservesInvariants ptInsertAux_spec.\n Proof.\n unfold ptInsertAux_spec.\n preserves_invariants_simpl low_level_invariant high_level_invariant; auto;\n subdestruct; try (inv H8; rewrite ZMap.gso; auto).\n Qed.\n\n Global Instance ptInsertPDE_inv: PreservesInvariants ptInsertPDE_spec.\n Proof.\n unfold ptInsertPDE_spec.\n preserves_invariants_simpl low_level_invariant high_level_invariant; auto;\n try (rewrite ZMap.gso; eauto; fail).\n - apply consistent_ppage_alloc_hide; assumption. \n - apply dirty_ppage_gss; assumption. \n Qed.\n\n (** * Proofs that the primitives satisfies the invariants at this layer *)\n Global Instance ptRmvAux_inv: PreservesInvariants ptRmvAux_spec.\n Proof.\n unfold ptRmvAux_spec.\n preserves_invariants_simpl low_level_invariant high_level_invariant; auto;\n subdestruct; try (inv H7; rewrite ZMap.gso; auto).\n Qed.\n\n (** * Proofs that the primitives satisfies the invariants at this layer *)\n Global Instance ptRmvPDE_inv: PreservesInvariants ptRmvPDE_spec.\n Proof.\n unfold ptRmvPDE_spec.\n preserves_invariants_simpl low_level_invariant high_level_invariant; auto;\n try (rewrite ZMap.gso; eauto; fail).\n - eapply consistent_ppage_hide_alloc; eassumption.\n - eapply dirty_ppage_gso_alloc; eauto.\n - eapply consistent_ppage_hide_alloc; eassumption.\n - eapply dirty_ppage_gso_alloc; eauto.\n Qed.\n\n Global Instance idpde_init_inv: PreservesInvariants idpde_init_spec.\n Proof.\n preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n - apply real_nps_range.\n - apply real_at_kern_valid.\n - apply real_at_usr_valid.\n - apply real_container_valid.\n - apply real_quota_bounded_AT.\n - rewrite init_pperm; try assumption.\n apply real_pperm_valid. \n Qed.\n\n End INV.\n\n (** * Layer Definition *)\n (** ** Layer Definition newly introduced *)\n Definition mptop_fresh : compatlayer (cdata RData) :=\n pt_read ↦ gensem ptRead_spec\n ⊕ pt_read_pde ↦ gensem ptReadPDE_spec\n ⊕ pt_insert_aux ↦ gensem ptInsertAux_spec\n ⊕ pt_insert_pde ↦ gensem ptInsertPDE_spec\n ⊕ pt_rmv_aux ↦ gensem ptRmvAux_spec\n ⊕ pt_rmv_pde ↦ gensem ptRmvPDE_spec\n ⊕ idpde_init ↦ gensem idpde_init_spec.\n\n (** ** Layer Definition passthrough *)\n Definition mptop_passthrough : compatlayer (cdata RData) :=\n fload ↦ gensem fload_spec\n ⊕ fstore ↦ gensem fstore_spec\n ⊕ flatmem_copy ↦ gensem flatmem_copy_spec\n ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n ⊕ device_output ↦ gensem device_output_spec\n ⊕ set_pg ↦ gensem setPG1_spec\n ⊕ at_get_c ↦ gensem get_at_c_spec\n ⊕ at_set_c ↦ gensem set_at_c0_spec\n ⊕ pfree ↦ gensem pfree'_spec\n ⊕ set_pt ↦ gensem setPT'_spec\n ⊕ set_PDE ↦ gensem setPDE_spec\n ⊕ rmv_PDE ↦ gensem rmvPDE_spec\n ⊕ rmv_PTE ↦ gensem rmvPTE_spec\n ⊕ pt_in ↦ primcall_general_compatsem' ptin'_spec (prim_ident:= pt_in)\n ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n ⊕ clear_cr2 ↦ gensem clearCR2_spec\n ⊕ container_get_parent ↦ gensem container_get_parent_spec\n ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n ⊕ container_get_quota ↦ gensem container_get_quota_spec\n ⊕ container_get_usage ↦ gensem container_get_usage_spec\n ⊕ container_can_consume ↦ gensem container_can_consume_spec\n ⊕ container_split ↦ gensem container_split_spec\n ⊕ container_alloc ↦ gensem container_alloc_spec\n ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n ⊕ accessors ↦ {| exec_load := (@exec_loadex _ _ Hmwd); \n exec_store := (@exec_storeex _ _ Hmwd) |}.\n\n (** * Layer Definition *)\n Definition mptop : compatlayer (cdata RData) := mptop_fresh ⊕ mptop_passthrough.\n\n (* Definition semantics := LAsm.Lsemantics mptintro.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MPTOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.14639575004366803}} {"text": "From cap_machine Require Export logrel.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine.ftlr Require Import ftlr_base interp_weakening.\nFrom cap_machine.rules Require Import rules_base rules_Seal.\n\nSection fundamental.\n Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg: sealStoreG Σ}\n {nainv: logrel_na_invs Σ}\n `{MachineParameters}.\n\n Notation D := ((leibnizO Word) -n> iPropO Σ).\n Notation R := ((leibnizO Reg) -n> iPropO Σ).\n Implicit Types w : (leibnizO Word).\n Implicit Types interp : (D).\n\n (* Proving the meaning of sealing in the LR sane *)\n Lemma sealing_preserves_interp sb p0 b0 e0 a0:\n permit_seal p0 = true →\n withinBounds b0 e0 a0 = true →\n fixpoint interp1 (WSealable sb) -∗\n fixpoint interp1 (WSealRange p0 b0 e0 a0) -∗\n fixpoint interp1 (WSealed a0 sb).\n Proof.\n iIntros (Hpseal Hwb) \"#HVsb #HVsr\".\n rewrite (fixpoint_interp1_eq (WSealRange _ _ _ _)) (fixpoint_interp1_eq (WSealed _ _)) /= Hpseal /interp_sb.\n iDestruct \"HVsr\" as \"[Hss _]\".\n apply seq_between_dist_Some in Hwb.\n iDestruct (big_sepL_delete with \"Hss\") as \"[HSa0 _]\"; eauto.\n iDestruct \"HSa0\" as (P) \"[% [HsealP HWcond]]\".\n iExists P.\n repeat iSplitR; auto.\n by iApply \"HWcond\".\n Qed.\n\n Lemma seal_case (r : leibnizO Reg) (p : Perm)\n (b e a : Addr) (w : Word) (dst r1 r2 : RegName) (P:D):\n ftlr_instr r p b e a w (Seal dst r1 r2) P.\n Proof.\n intros Hp Hsome i Hbae Hi.\n iIntros \"#IH #Hinv #Hinva #Hreg #[Hread Hwrite] Hown Ha HP Hcls HPC Hmap\".\n rewrite delete_insert_delete.\n iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n iApply (wp_Seal with \"[$Ha $Hmap]\"); eauto.\n { simplify_map_eq; auto. }\n { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n destruct HSpec as [ * Hr1 Hr2 Hseal Hwb HincrPC | ].\n { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n\n assert (p'' = p ∧ a'' = a ∧ b'' = b ∧ e'' = e) as (-> & -> & -> & ->).\n { destruct (decide (PC = dst)); simplify_map_eq; auto. }\n assert (r1 ≠ PC) as Hne.\n { destruct (decide (PC = r1)); last auto. simplify_map_eq; auto. }\n rewrite lookup_insert_ne in Hr1; auto.\n iAssert (fixpoint interp1 (WSealable sb)) as \"HVsb\". {\n destruct (decide (r2 = PC)) eqn:Heq.\n - subst r2. simplify_map_eq; auto.\n - simplify_map_eq. unshelve iSpecialize (\"Hreg\" $! r2 _ _ Hr2); eauto.\n }\n\n iApply wp_pure_step_later; auto.\n iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n iNext; iIntros \"_\".\n iApply (\"IH\" $! regs' with \"[%] [] [Hmap] [$Hown]\").\n { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n { iIntros (ri v Hri Hvs).\n subst regs'.\n rewrite lookup_insert_ne in Hvs; auto.\n destruct (decide (ri = dst)).\n { subst ri.\n rewrite lookup_insert in Hvs; inversion Hvs. simplify_eq.\n (* Sealrange is valid -> validity implies P *)\n unshelve iDestruct (\"Hreg\" $! r1 _ _ Hr1) as \"HVsr\"; eauto.\n iApply (sealing_preserves_interp with \"HVsb HVsr\"); auto. }\n { repeat (rewrite lookup_insert_ne in Hvs); auto.\n iApply \"Hreg\"; auto. } }\n { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n iModIntro.\n iApply (interp_weakening with \"IH Hinv\"); auto; try solve_addr.\n { destruct Hp; by subst p. }\n { by rewrite PermFlowsToReflexive. }\n }\n { iApply wp_pure_step_later; auto.\n iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n iNext; iIntros \"_\".\n iApply wp_value; auto. iIntros; discriminate. }\n Qed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/ftlr/Seal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.14615148818860355}} {"text": "(*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *)\nFrom stdpp Require Import base strings gmap stringmap fin_maps.\nFrom iris.base_logic Require Import upred derived.\nFrom iris.base_logic.lib Require Import iprop own.\nFrom iris.algebra Require Import ofe cmra gmap_view.\nFrom iris.proofmode Require Import tactics.\n\nFrom shack Require Import lang progdef subtype eval.\nFrom shack Require Import heap modality interp typing.\nFrom shack.soundness Require Import expr defs.\n\nSection proofs.\n (* assume a given set of class definitions and their SDT annotations. *)\n Context `{SDTCVS: SDTClassVarianceSpec}.\n\n (* Iris semantic context *)\n Context `{!sem_heapGS Θ}.\n\n Lemma get_priv_soundness C cdef Δ rigid Γ lhs name fty:\n wf_cdefs →\n wf_lty Γ →\n pdefs !! C = Some cdef →\n cdef.(classfields) !! name = Some (Private, fty) →\n ∀ t tdef Σt σ,\n pdefs !! t = Some tdef →\n length Σt = length tdef.(generics) →\n inherits_using t C σ →\n ∀ Σ st st' n,\n length Σ = rigid →\n rigid ≥ length cdef.(generics) →\n cmd_eval C st (GetC lhs ThisE name) st' n →\n let Σthis := interp_exact_tag interp_type t Σt in\n ⌜interp_list interp_nothing Σt σ ≡ take (length cdef.(generics)) Σ⌝ -∗\n □ interp_as_mixed Σthis -∗\n □ interp_env_as_mixed Σ -∗\n □ Σinterp Σthis Σ Δ -∗\n heap_models st.2 ∗ interp_local_tys Σthis Σ Γ st.1 -∗\n |=▷^n heap_models st'.2 ∗ interp_local_tys Σthis Σ (<[lhs:=fty]> Γ) st'.1.\n Proof.\n move => wfpdefs wflty hcdef hf.\n move => t tdef Σt σ htdef hlenΣt hin_t_C_σ.\n move => Σ st st' n hrigid hge hc /=.\n iIntros \"%heq #hΣthis #hΣ #hΣΔ\".\n elim/cmd_eval_getI: hc.\n move => {n}.\n move => Ω h vis _fty orig l t0 vs v heval hheap hvs hf0 hvis.\n iIntros \"[Hh Hle]\".\n iModIntro. (* keep the later *)\n destruct Ω as [vthis Ω].\n case: heval => ->.\n simpl in *.\n iDestruct \"Hle\" as \"[#Hthis #Hle]\" => /=.\n iAssert (interp_exact_tag interp_type t Σt (LocV l)) as \"#Hl\"; first by done.\n rewrite {3}interp_exact_tag_unseal /interp_exact_tag_def /=.\n iDestruct \"Hthis\" as (l0 ? fields ifields H) \"(#hconstr & #hf0 & #H◯)\".\n destruct H as ([= <-] & ? & hfields & hidom); simplify_eq.\n assert (hlen: length σ = length cdef.(generics) ∧\n Forall (λ ty : lang_ty, no_this ty) σ).\n { destruct wfpdefs.\n apply inherits_using_wf in hin_t_C_σ => //.\n destruct hin_t_C_σ as (? & ?& ? & hh & ?).\n apply wf_tyI in hh as (? & ? & hlenC & ?); simplify_eq.\n by eauto.\n }\n destruct hlen as (hlen & hnothis).\n iAssert (⌜t0 = t⌝ ∗ heap_models h ∗ ▷ interp_type fty (interp_exact_tag interp_type t Σt) Σ v)%I with \"[Hh]\" as \"[%Ht [Hh Hv]]\".\n { iDestruct \"Hh\" as (sh) \"(H● & %hdom & #Hh)\".\n iDestruct (sem_heap_own_valid_2 with \"H● H◯\") as \"#HΦ\".\n iDestruct (\"Hh\" with \"[//]\") as (iFs) \"[H H▷]\".\n iRewrite \"H\" in \"HΦ\".\n rewrite option_equivI prod_equivI /=.\n iDestruct \"HΦ\" as \"[%Ht HΦ]\".\n fold_leibniz; subst.\n iSplitR; first done.\n iSplitL. { iExists _. iFrame. by iSplit. }\n assert (hfC: has_field name t Private (subst_ty σ fty) C).\n { destruct wfpdefs.\n apply has_field_inherits_using with C => //.\n change Private with (Private, fty).1.\n by apply HasField with cdef.\n }\n case: (has_field_fun _ _ _ _ _ hf0 _ _ _ hfC) => hvis_ [hfty horig].\n simplify_eq.\n iSpecialize (\"hf0\" $! name Private (subst_ty σ fty) C hfC).\n iDestruct \"H▷\" as \"[hdf h]\".\n rewrite later_equivI.\n iNext.\n iDestruct \"hf0\" as (iF) \"[hf0 hiff]\".\n iRewrite -\"HΦ\" in \"hf0\".\n iSpecialize (\"h\" $! name _ with \"[hf0]\"); first done.\n iDestruct \"h\" as (w) \"[%hw hiw]\".\n simplify_eq.\n iDestruct (\"hiff\" with \"hiw\") as \"hiw_\"; iClear \"hiw\".\n iAssert (interp_type (subst_ty σ fty) (interp_exact_tag interp_type t Σt) Σt v) with \"[hiw_]\" as \"#hiw\".\n { rewrite /subst_gen -hlenΣt.\n by iApply interp_type_subst_this.\n }\n iClear \"hiw_\".\n rewrite interp_type_subst; last first.\n { destruct wfpdefs.\n apply wf_fields_bounded in hcdef.\n apply hcdef in hf.\n by rewrite hlen.\n }\n rewrite -(interp_type_take fty _ Σ); first last.\n { exact hge. }\n { destruct wfpdefs.\n apply wf_fields_bounded in hcdef.\n by apply hcdef in hf.\n }\n assert (heq2: interp_list (interp_exact_tag interp_type t Σt) Σt σ ≡\n take (length cdef.(generics)) Σ).\n { rewrite -heq.\n by apply interp_list_no_this.\n }\n by rewrite heq2.\n }\n subst.\n iNext.\n iFrame.\n iApply interp_local_tys_update => //.\n by iSplit.\n Qed.\n\n Lemma get_pub_soundness C Δ kd rigid Γ lhs recv exact_ t σ name fty orig:\n wf_cdefs →\n wf_lty Γ →\n Forall wf_constraint Δ →\n expr_has_ty Δ Γ rigid kd recv (ClassT exact_ t σ) →\n has_field name t Public fty orig →\n (is_true exact_ ∨ no_this fty) →\n ∀ Σthis Σ st st' n,\n length Σ = rigid →\n cmd_eval C st (GetC lhs recv name) st' n →\n □ interp_as_mixed Σthis -∗\n □ interp_env_as_mixed Σ -∗\n □ Σinterp Σthis Σ Δ -∗\n heap_models st.2 ∗ interp_local_tys Σthis Σ Γ st.1 -∗\n |=▷^n heap_models st'.2 ∗ interp_local_tys Σthis Σ (<[lhs:=subst_fty exact_ t σ fty]> Γ) st'.1.\n Proof.\n move => wfpdefs ?? hrecv hf hex Σthis Σ st st' n hrigid hc.\n iIntros \"hΣthis hΣ hΣΔ\".\n elim/cmd_eval_getI: hc.\n move => {n}.\n move => Ω h vis0 fty0 orig0 l t0 vs v heval hheap hvs hf0 hvis.\n iIntros \"[Hh #Hle]\".\n iModIntro. (* keep the later *)\n assert (hwf0: wf_ty (ClassT exact_ t σ)) by (by apply expr_has_ty_wf in hrecv).\n assert (hwf0_ := hwf0).\n apply wf_tyI in hwf0_ as (tdef & htdef & hlen & hfσ); simplify_eq.\n iDestruct (expr_soundness with \"hΣthis hΣ hΣΔ Hle\") as \"He\" => //; try (by apply wfpdefs).\n destruct exact_.\n (* receiver class is exact *)\n - rewrite interp_exact_tag_unfold interp_exact_tag_unseal /interp_exact_tag_def /=.\n iDestruct \"He\" as (l0 tdef' fields ifields H) \"(#hconstr & #hf0 & #H◯)\".\n destruct H as ([= <-] & htdef' & hfields & hidom); simplify_eq.\n simpl.\n iAssert (⌜t0 = t⌝ ∗ heap_models h ∗\n ▷ interp_type (subst_gen t tdef fty) interp_nothing (interp_list Σthis Σ σ) v)%I with \"[Hh]\" as \"[%Ht [Hh Hv]]\".\n { iDestruct \"Hh\" as (sh) \"(H● & %hdom & #Hh)\".\n iDestruct (sem_heap_own_valid_2 with \"H● H◯\") as \"#HΦ\".\n iDestruct (\"Hh\" with \"[//]\") as (iFs) \"[H H▷]\".\n iRewrite \"H\" in \"HΦ\".\n rewrite option_equivI prod_equivI /=.\n iDestruct \"HΦ\" as \"[%Ht HΦ]\".\n fold_leibniz; subst.\n iSplitR; first done.\n iSplitL. { iExists _. iFrame. by iSplit. }\n iSpecialize (\"hf0\" $! name Public fty orig hf).\n iDestruct \"hf0\" as (iF) \"[hf0 hiff]\".\n iNext.\n iDestruct \"H▷\" as \"[%hdf h]\".\n iRewrite -\"HΦ\" in \"hf0\".\n iSpecialize (\"h\" $! name _ with \"[hf0]\"); first done.\n iDestruct \"h\" as (w) \"[%hw hiw]\".\n iApply \"hiff\".\n by simplify_eq.\n }\n subst; simpl.\n iNext.\n iFrame.\n destruct wfpdefs.\n iApply interp_local_tys_update => //.\n assert (hlen2: length (interp_list Σthis Σ σ) = length tdef.(generics)) by by rewrite /interp_list fmap_length.\n rewrite /subst_gen /subst_fty -hlen2.\n rewrite interp_type_subst_this => //.\n rewrite interp_type_subst; last first.\n { apply has_field_bounded in hf => //.\n destruct hf as (?&?&hf); simplify_eq.\n apply bounded_subst_this.\n + by rewrite hlen.\n + constructor.\n by apply bounded_gen_targs.\n }\n rewrite hlen -hlen2.\n rewrite interp_type_subst_this; first last.\n { by rewrite /interp_list map_length. }\n { by assumption. }\n done.\n - (* receiver is not exact, so it can't call anything using the `this`\n * type yet.\n *)\n case: hex => // hnothis.\n rewrite interp_tag_unfold interp_tag_equiv //; first last.\n { by rewrite /interp_list fmap_length. }\n { by apply wfpdefs. }\n iDestruct \"He\" as (?? def def1 σ0 ???) \"(%H & #hmixed & #? & #hf0 & #hdyn & #H◯)\".\n destruct H as ([= <-] & hdef & hdef0 & hlenΣt & hinherits & hfields & hidom).\n assert (hl0: length (generics def) = length σ0).\n { apply inherits_using_wf in hinherits; try (by apply wfpdefs).\n destruct hinherits as (?&?&?&hh&?).\n apply wf_tyI in hh as (? & ? & ? & ?); by simplify_eq.\n }\n assert (hl1: length σ0 = length σ).\n { rewrite -hl0.\n apply wf_tyI in hwf0 as (? & ? & ? & ?); by simplify_eq.\n }\n assert (hff: has_field name t1 Public (subst_ty σ0 fty) orig).\n { by apply has_field_inherits_using with (A := t1) (σB := σ0) in hf => //; try (by apply wfpdefs). }\n iAssert (⌜t0 = t1⌝ ∗ heap_models h ∗\n ▷ interp_type (subst_gen t1 def1 (subst_ty σ0 fty)) interp_nothing Σt v)%I with \"[Hh]\" as \"[%Ht [Hh Hv]]\".\n { iDestruct \"Hh\" as (sh) \"(H● & %hdom & #Hh)\".\n iDestruct (sem_heap_own_valid_2 with \"H● H◯\") as \"#HΦ\".\n iDestruct (\"Hh\" with \"[//]\") as (iFs) \"[H H▷]\".\n iRewrite \"H\" in \"HΦ\".\n rewrite option_equivI prod_equivI /=.\n iDestruct \"HΦ\" as \"[%Ht HΦ]\".\n fold_leibniz; subst.\n iSplitR; first done.\n iSplitL. { iExists _. iFrame. by iSplit. }\n iSpecialize (\"hdyn\" $! name Public (subst_ty σ0 fty) orig hff).\n iNext.\n iDestruct \"H▷\" as \"[%hdf h]\".\n iDestruct \"hdyn\" as (iF) \"[hdyn hiff]\".\n iRewrite -\"HΦ\" in \"hdyn\".\n iSpecialize (\"h\" $! name _ with \"[hdyn]\"); first done.\n iDestruct \"h\" as (w) \"[%hw hiw]\".\n iApply \"hiff\".\n by simplify_eq.\n }\n subst; simpl.\n iNext.\n iFrame.\n destruct wfpdefs.\n iApply interp_local_tys_update => //.\n rewrite /subst_gen -hlenΣt.\n rewrite interp_type_subst_this => //.\n rewrite interp_type_subst; last first.\n { apply has_field_bounded in hf => //.\n destruct hf as (?&?&hf); simplify_eq.\n by rewrite -hl0.\n }\n rewrite (interp_list_no_this _ _ (interp_exact_tag interp_type t1 Σt) interp_nothing); last first.\n { apply inherits_using_wf in hinherits => //.\n by destruct hinherits as (? & ? & ? & ? & hh); simplify_eq.\n }\n iAssert (interp_type fty (interp_exact_tag interp_type t1 Σt)\n (interp_list Σthis Σ σ) v) with \"[Hv]\" as \"Hv\".\n { iApply interp_with_mono => //.\n - apply has_field_mono in hf => //.\n destruct hf as (?&?&hh); simplify_eq.\n by destruct hh.\n - by apply has_field_wf in hf.\n }\n rewrite interp_type_subst; first last.\n { apply bounded_subst_this.\n - apply has_field_bounded in hf => //.\n destruct hf as (?&?&hf).\n apply wf_tyI in hwf0 as (? & ? & -> & ?).\n by simplify_eq.\n - constructor; by apply bounded_gen_targs.\n }\n rewrite subst_this_no_this_id; last done.\n by rewrite (interp_type_no_this _ _ _ _ Σthis); last done.\n Qed.\n\n (* TODO: factorize the priv vs pub mechanics. This proof is using both *)\n Lemma get_this_soundness C cdef Δ kd rigid Γ lhs recv name fty orig:\n wf_cdefs →\n wf_lty Γ →\n Forall wf_constraint Δ →\n pdefs !! C = Some cdef →\n expr_has_ty Δ Γ rigid kd recv ThisT →\n has_field name C Public fty orig →\n ∀ t tdef Σt σ,\n pdefs !! t = Some tdef →\n length Σt = length tdef.(generics) →\n inherits_using t C σ →\n ∀ Σ st st' n,\n length Σ = rigid →\n rigid ≥ length cdef.(generics) →\n cmd_eval C st (GetC lhs recv name) st' n →\n let Σthis := interp_exact_tag interp_type t Σt in\n ⌜interp_list interp_nothing Σt σ ≡ take (length cdef.(generics)) Σ⌝ -∗\n □ interp_as_mixed Σthis -∗\n □ interp_env_as_mixed Σ -∗\n □ Σinterp Σthis Σ Δ -∗\n heap_models st.2 ∗ interp_local_tys Σthis Σ Γ st.1 -∗\n |=▷^n heap_models st'.2 ∗ interp_local_tys Σthis Σ (<[lhs:=fty]> Γ) st'.1.\n Proof.\n move => wfpdefs ?? hcdef hrecv hf.\n move => t tdef Σt σ htdef hlenΣt hin_t_C.\n move => Σ st st' n hrigid hge hc Σthis.\n iIntros \"%hΣeq hΣthis hΣ hΣΔ\".\n elim/cmd_eval_getI: hc.\n move => {n}.\n move => Ω h vis0 fty0 orig0 l t0 vs v heval hheap hvs hf0 hvis.\n iIntros \"[Hh #Hle]\".\n iModIntro. (* keep the later *)\n iDestruct (expr_soundness with \"hΣthis hΣ hΣΔ Hle\") as \"He\" => //; try (by apply wfpdefs).\n rewrite interp_this_unfold /= {2}/Σthis.\n rewrite interp_exact_tag_unseal /interp_exact_tag_def /=.\n iDestruct \"He\" as (l0 tdef' fields ifields H) \"(#hconstr & #hf0 & #H◯)\".\n destruct H as ([= <-] & htdef' & hfields & hidom); simplify_eq.\n assert (hlen: length σ = length cdef.(generics) ∧\n Forall (λ ty : lang_ty, no_this ty) σ).\n { destruct wfpdefs.\n apply inherits_using_wf in hin_t_C => //.\n destruct hin_t_C as (? & ?& ? & hh & ?).\n apply wf_tyI in hh as (? & ? & hlenC & ?); simplify_eq.\n by eauto.\n }\n destruct hlen as (hlen & hnothis).\n iAssert (⌜t0 = t⌝ ∗ heap_models h ∗\n ▷ interp_type fty (interp_exact_tag interp_type t Σt) Σ v)%I with \"[Hh]\" as \"[%Ht [Hh Hv]]\".\n { iDestruct \"Hh\" as (sh) \"(H● & %hdom & #Hh)\".\n iDestruct (sem_heap_own_valid_2 with \"H● H◯\") as \"#HΦ\".\n iDestruct (\"Hh\" with \"[//]\") as (iFs) \"[H H▷]\".\n iRewrite \"H\" in \"HΦ\".\n rewrite option_equivI prod_equivI /=.\n iDestruct \"HΦ\" as \"[%Ht HΦ]\".\n fold_leibniz; subst.\n iSplitR; first done.\n iSplitL. { iExists _. iFrame. by iSplit. }\n assert (hff: has_field name t Public (subst_ty σ fty) orig).\n { apply has_field_inherits_using\n with (A := t) (σB := σ) in hf => //; by apply wfpdefs.\n }\n iSpecialize (\"hf0\" $! name Public (subst_ty σ fty) orig hff).\n iDestruct \"hf0\" as (iF) \"[hf0 hiff]\".\n iNext.\n iDestruct \"H▷\" as \"[%hdf h]\".\n iRewrite -\"HΦ\" in \"hf0\".\n iSpecialize (\"h\" $! name _ with \"[hf0]\"); first done.\n iDestruct \"h\" as (w) \"[%hw hiw]\".\n iDestruct (\"hiff\" with \"hiw\") as \"hw\".\n simplify_eq.\n rewrite /subst_gen -hlenΣt.\n iAssert (□ interp_type\n (subst_ty σ fty) (interp_exact_tag interp_type t Σt) Σt v)%I as \"#hw2\".\n { iModIntro.\n by rewrite -interp_type_subst_this.\n }\n iClear \"hiw hiff hw\".\n rewrite interp_type_subst; last first.\n { apply has_field_bounded in hf => //; try by apply wfpdefs.\n destruct hf as (? & ? & ?); simplify_eq.\n by rewrite hlen.\n }\n assert (heq:\n interp_list (interp_exact_tag interp_type t Σt) Σt σ ≡\n interp_list interp_nothing Σt σ).\n { by apply interp_list_no_this. }\n rewrite (interp_type_equivI _ _ _ heq).\n rewrite (interp_type_equivI _ _ _ hΣeq).\n rewrite interp_type_take //.\n { apply has_field_bounded in hf => //; try by apply wfpdefs.\n by destruct hf as (? & ? & ?); simplify_eq.\n }\n }\n subst; simpl.\n iNext.\n iFrame.\n destruct wfpdefs.\n by iApply interp_local_tys_update.\n Qed.\nEnd proofs.\n", "meta": {"author": "facebookresearch", "repo": "shack", "sha": "e51cfcd3e72a0941feb337f9e152f6c429f3af63", "save_path": "github-repos/coq/facebookresearch-shack", "path": "github-repos/coq/facebookresearch-shack/shack-e51cfcd3e72a0941feb337f9e152f6c429f3af63/theories/soundness/getc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.14613191410299625}} {"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv.simplepb Require Export config.\nFrom iris.base_logic Require Export lib.ghost_var mono_nat.\nFrom iris.algebra Require Import dfrac_agree mono_list.\nFrom Perennial.program_proof Require Import marshal_stateless_proof std_proof.\nFrom Perennial.program_proof.simplepb Require Import config_marshal_proof.\nFrom Perennial.program_proof.grove_shared Require Import urpc_proof urpc_spec.\n\nSection config_global.\n\nRecord config_names :=\n{\n epoch_gn:gname ;\n config_val_gn:gname;\n}.\n\nClass configG Σ := {\n config_epochG :> mono_natG Σ ;\n config_configG :> ghost_varG Σ (list u64) ;\n config_urpcG :> urpcregG Σ ;\n}.\n\nDefinition configΣ := #[mono_natΣ ; ghost_varΣ (list u64) ; urpcregΣ].\n\nGlobal Instance subG_configΣ {Σ} : subG configΣ Σ → configG Σ.\nProof. intros. solve_inG. Qed.\n\nImplicit Type γ : config_names.\n\nContext `{!gooseGlobalGS Σ}.\nContext `{!configG Σ}.\n\nDefinition own_epoch γ (epoch:u64) : iProp Σ :=\n mono_nat_auth_own γ.(epoch_gn) (1/2) (int.nat epoch).\n\nDefinition is_epoch_lb γ (epoch:u64) : iProp Σ :=\n mono_nat_lb_own γ.(epoch_gn) (int.nat epoch).\n\nDefinition own_config γ (conf:list u64) : iProp Σ :=\n ghost_var γ.(config_val_gn) (1/2) conf\n.\n\nProgram Definition GetEpochAndConfig_core_spec γ Φ :=\n (£ 1 ={⊤,∅}=∗ ∃ epoch conf, own_epoch γ epoch ∗ own_config γ conf ∗\n (⌜int.nat epoch < int.nat (word.add epoch (U64 1))⌝ -∗ own_epoch γ (word.add epoch (U64 1)) -∗ own_config γ conf ={∅,⊤}=∗\n Φ (word.add epoch 1) conf\n )\n )%I.\n\nProgram Definition GetConfig_core_spec γ Φ :=\n (£ 1 ={⊤,∅}=∗ ∃ conf, own_config γ conf ∗ (own_config γ conf ={∅,⊤}=∗ Φ conf))%I.\n\nProgram Definition WriteConfig_core_spec γ (epoch:u64) (new_conf:list u64) Φ : iProp Σ :=\n (£ 1 -∗ |={⊤,∅}=> ∃ latest_epoch, own_epoch γ latest_epoch ∗\n if (decide (latest_epoch = epoch)) then\n ∃ conf, own_config γ conf ∗ (own_config γ new_conf -∗ own_epoch γ epoch ={∅,⊤}=∗\n Φ (U64 0))\n else\n (own_epoch γ latest_epoch ={∅,⊤}=∗ (∀ (err:u64), ⌜err ≠ 0⌝ → Φ err))\n ).\n\nProgram Definition GetEpochAndConfig_spec γ :=\n λ (encoded_args:list u8), λne (Φ : list u8 -d> iPropO Σ) ,\n ( (* no args *)\n GetEpochAndConfig_core_spec γ (λ newEpoch conf,\n ∀ reply enc_conf,\n ⌜Config.has_encoding enc_conf conf⌝ -∗\n ⌜reply = u64_le newEpoch ++ enc_conf⌝ -∗\n Φ reply\n )\n )%I.\nNext Obligation.\n solve_proper.\nDefined.\n\nProgram Definition GetConfig_spec γ :=\n λ (encoded_args:list u8), λne (Φ : list u8 -d> iPropO Σ) ,\n ( (* no args *)\n GetConfig_core_spec γ (λ conf, ∀ reply,\n ⌜Config.has_encoding reply conf⌝ -∗\n Φ reply\n )\n )%I.\nNext Obligation.\n solve_proper.\nDefined.\n\nProgram Definition WriteConfig_spec γ :=\n λ (enc_args:list u8), λne (Φ : list u8 -d> iPropO Σ) ,\n ( ∃ epoch new_conf enc_new_conf,\n ⌜enc_args = u64_le epoch ++ enc_new_conf⌝ ∗\n ⌜Config.has_encoding enc_new_conf new_conf⌝ ∗\n WriteConfig_core_spec γ epoch new_conf (λ err, ∀ reply,\n ⌜reply = u64_le err⌝ -∗\n Φ reply\n )\n )%I.\nNext Obligation.\n unfold WriteConfig_core_spec.\n solve_proper.\nDefined.\n\nDefinition is_host (host:u64) γ : iProp Σ :=\n ∃ γrpc,\n handler_spec γrpc host (U64 0) (GetEpochAndConfig_spec γ) ∗\n handler_spec γrpc host (U64 1) (GetConfig_spec γ) ∗\n handler_spec γrpc host (U64 2) (WriteConfig_spec γ) ∗\n handlers_dom γrpc {[ (U64 0) ; (U64 1) ; (U64 2)]}\n.\n\nEnd config_global.\n\nSection config_proof.\n\nContext `{!heapGS Σ}.\nContext `{!configG Σ}.\n\nDefinition is_Clerk (ck:loc) γ : iProp Σ :=\n ∃ (cl:loc) srv,\n \"#Hcl\" ∷ readonly (ck ↦[config.Clerk :: \"cl\"] #cl) ∗\n \"#Hcl_rpc\" ∷ is_uRPCClient cl srv ∗\n \"#Hhost\" ∷ is_host srv γ\n.\n\nLemma wp_MakeClerk configHost γ:\n {{{\n is_host configHost γ\n }}}\n config.MakeClerk #configHost\n {{{\n ck, RET #ck; is_Clerk ck γ\n }}}\n.\nProof.\n iIntros (Φ) \"#Hhost HΦ\".\n wp_call.\n wp_apply (wp_MakeClient).\n iIntros (cl) \"#Hcl\".\n iApply wp_fupd.\n wp_apply (wp_allocStruct).\n { eauto. }\n iIntros (ck) \"Hck\".\n iDestruct (struct_fields_split with \"Hck\") as \"HH\".\n iNamed \"HH\".\n iMod (readonly_alloc_1 with \"cl\") as \"#cl\".\n iModIntro.\n iApply \"HΦ\".\n iExists _, _. iFrame \"#\".\nQed.\n\nDefinition own_Server (s:loc) γ : iProp Σ :=\n ∃ (epoch:u64) (conf:list u64) conf_sl,\n \"Hepoch\" ∷ s ↦[config.Server :: \"epoch\"] #epoch ∗\n \"Hconf\" ∷ s ↦[config.Server :: \"config\"] (slice_val conf_sl) ∗\n \"Hconf_sl\" ∷ is_slice_small conf_sl uint64T 1 conf ∗\n \"Hepoch_ghost\" ∷ own_epoch γ epoch ∗\n \"Hconf_ghost\" ∷ own_config γ conf\n.\n\nDefinition configN := nroot .@ \"config\".\n\nDefinition is_Server (s:loc) γ : iProp Σ :=\n ∃ mu,\n \"#Hmu\" ∷ readonly (s ↦[config.Server :: \"mu\"] mu) ∗\n \"#His_mu\" ∷ is_lock configN mu (own_Server s γ).\n\nLemma wp_Server__GetEpochAndConfig (server:loc) γ :\n {{{\n is_Server server γ\n }}}\n config.Server__GetEpochAndConfig #server\n {{{\n (f:val), RET f; impl_handler_spec2 f (GetEpochAndConfig_spec γ)\n }}}.\nProof.\n iIntros (Φ) \"#His_srv HΦ\".\n wp_call.\n iApply \"HΦ\".\n iModIntro.\n unfold impl_handler_spec2.\n clear Φ.\n iIntros (enc_args Φ Ψ req_sl rep_ptr dummy_sl dummy) \"!# Harg_sl Hrep _ HΦ HΨ\".\n wp_call.\n\n iNamed \"His_srv\".\n wp_loadField.\n wp_apply (acquire_spec with \"[$His_mu]\").\n iIntros \"[Hlocked Hown]\".\n iNamed \"Hown\".\n wp_pures.\n wp_loadField.\n wp_apply (wp_SumAssumeNoOverflow).\n iIntros (Hno_overflow).\n wp_storeField.\n wp_loadField.\n wp_apply (wp_slice_len).\n wp_apply (wp_NewSliceWithCap).\n { apply encoding.unsigned_64_nonneg. }\n iIntros (ptr) \"Hsl\".\n wp_pure1_credit \"Hlc\".\n wp_store.\n wp_loadField.\n wp_load.\n wp_apply (wp_WriteInt with \"Hsl\").\n iIntros (enc_sl) \"Hrep_sl\".\n wp_store.\n wp_loadField.\n wp_apply (Config.wp_Encode with \"[Hconf_sl]\").\n { iFrame. }\n iIntros (enc_conf enc_conf_sl) \"(%Hconf_enc & Hconf_sl & Henc_conf_sl)\".\n wp_load.\n wp_apply (wp_WriteBytes with \"[$Hrep_sl Henc_conf_sl]\").\n {\n iDestruct (is_slice_to_small with \"Henc_conf_sl\") as \"$\".\n }\n iIntros (rep_sl) \"[Hrep_sl Henc_conf_sl]\".\n replace (int.nat 0%Z) with 0%nat by word.\n wp_store.\n wp_loadField.\n\n iApply fupd_wp.\n iMod (\"HΨ\" with \"Hlc\") as \"HΨ\".\n iDestruct \"HΨ\" as (??) \"(Hepoch_ghost2 & Hconf_ghost2 & Hupd)\".\n iDestruct (ghost_var_agree with \"Hconf_ghost Hconf_ghost2\") as %->.\n iDestruct (mono_nat_auth_own_agree with \"Hepoch_ghost Hepoch_ghost2\") as %[_ Heq].\n replace (epoch0) with (epoch) by word.\n iCombine \"Hepoch_ghost Hepoch_ghost2\" as \"Hepoch_ghost\".\n iMod (mono_nat_own_update (int.nat (word.add epoch 1)) with \"Hepoch_ghost\") as \"[[Hepoch_ghost Hepoch_ghost2] _]\".\n { word. }\n iSpecialize (\"Hupd\" with \"[%] Hepoch_ghost2 Hconf_ghost2\").\n { word. }\n iMod \"Hupd\".\n iModIntro.\n\n wp_apply (release_spec with \"[$Hlocked $His_mu Hepoch Hconf Hconf_ghost Hconf_sl Hepoch_ghost]\").\n {\n iNext.\n iExists _, _, _.\n eauto with iFrame.\n }\n wp_pures.\n iDestruct (is_slice_to_small with \"Hrep_sl\") as \"Hrep_sl\".\n iSpecialize (\"Hupd\" with \"[% //] [% //]\").\n iApply (\"HΦ\" with \"Hupd Hrep Hrep_sl\").\nQed.\n\nLemma wp_Server__GetConfig (server:loc) γ :\n {{{\n is_Server server γ\n }}}\n config.Server__GetConfig #server\n {{{\n (f:val), RET f; impl_handler_spec2 f (GetConfig_spec γ)\n }}}.\nProof.\n iIntros (Φ) \"#His_srv HΦ\".\n wp_call.\n iApply \"HΦ\".\n iModIntro.\n unfold impl_handler_spec2.\n clear Φ.\n iIntros (enc_args Φ Ψ req_sl rep_ptr dummy_sl dummy) \"!# Harg_sl Hrep _ HΦ HΨ\".\n wp_call.\n\n iNamed \"His_srv\".\n wp_loadField.\n wp_apply (acquire_spec with \"[$His_mu]\").\n iIntros \"[Hlocked Hown]\".\n iNamed \"Hown\".\n wp_pure1_credit \"Hlc\".\n wp_loadField.\n wp_apply (Config.wp_Encode with \"[Hconf_sl]\").\n { iFrame. }\n iIntros (enc_conf rep_sl) \"(%Hconf_enc & Hconf_sl & Hrep_sl)\".\n wp_store.\n wp_loadField.\n\n iApply fupd_wp.\n iMod (\"HΨ\" with \"Hlc\") as \"HΨ\".\n iDestruct \"HΨ\" as (?) \"(Hconf_ghost2 & Hupd)\".\n iDestruct (ghost_var_agree with \"Hconf_ghost Hconf_ghost2\") as %->.\n iMod (\"Hupd\" with \"Hconf_ghost2\") as \"Hupd\".\n iModIntro.\n\n wp_apply (release_spec with \"[$Hlocked $His_mu Hepoch Hconf Hconf_ghost Hconf_sl Hepoch_ghost]\").\n {\n iNext.\n iExists _, _, _.\n iFrame.\n }\n wp_pures.\n iDestruct (is_slice_to_small with \"Hrep_sl\") as \"Hrep_sl\".\n iSpecialize (\"Hupd\" with \"[% //]\").\n iApply (\"HΦ\" with \"Hupd Hrep Hrep_sl\").\nQed.\n\nLemma wp_Server__WriteConfig (server:loc) γ :\n {{{\n is_Server server γ\n }}}\n config.Server__WriteConfig #server\n {{{\n (f:val), RET f; impl_handler_spec2 f (WriteConfig_spec γ)\n }}}.\nProof.\n iIntros (Φ) \"#His_srv HΦ\".\n wp_call.\n iApply \"HΦ\".\n iModIntro.\n unfold impl_handler_spec2.\n clear Φ.\n iIntros (enc_args Φ Ψ req_sl rep_ptr dummy_sl dummy) \"!# Harg_sl Hrep _ HΦ HΨ\".\n wp_call.\n iNamed \"His_srv\".\n wp_loadField.\n wp_apply (acquire_spec with \"[$His_mu]\").\n iIntros \"[Hlocked Hown]\".\n iNamed \"Hown\".\n wp_pures.\n\n unfold WriteConfig_spec.\n iDestruct \"HΨ\" as (new_epoch new_conf enc_new_conf) \"(%Henc & %Henc_conf & HΨ)\".\n rewrite Henc.\n wp_apply (wp_ReadInt with \"Harg_sl\").\n iIntros (args_sl) \"Hargs_sl\".\n wp_pure1_credit \"Hlc\".\n\n replace (slice.nil) with (slice_val Slice.nil) by done.\n wp_loadField.\n wp_if_destruct.\n {\n wp_apply (wp_WriteInt with \"[]\").\n {\n iApply is_slice_zero.\n }\n iIntros (rep_sl) \"Hrep_sl\".\n wp_store.\n wp_loadField.\n\n iApply fupd_wp.\n iMod (\"HΨ\" with \"Hlc\") as \"HΨ\".\n iDestruct \"HΨ\" as (?) \"(Hepoch_ghost2 & HΨ)\".\n iDestruct (mono_nat_auth_own_agree with \"Hepoch_ghost Hepoch_ghost2\") as %[_ Heq].\n replace (epoch) with (latest_epoch) in * by word.\n destruct (decide (_)).\n {\n exfalso. rewrite e in Heqb.\n done.\n }\n simpl.\n iMod (\"HΨ\" with \"Hepoch_ghost2\") as \"HΨ\".\n iDestruct (is_slice_to_small with \"Hrep_sl\") as \"Hrep_sl\".\n iDestruct (\"HΨ\" with \"[%] [% //]\") as \"HΨ\".\n { instantiate (1:=1). done. }\n iDestruct (\"HΦ\" with \"HΨ Hrep Hrep_sl\") as \"HΦ\".\n iModIntro.\n\n wp_apply (release_spec with \"[$Hlocked $His_mu Hepoch Hconf Hconf_sl Hepoch_ghost Hconf_ghost]\").\n {\n iNext.\n iExists _,_,_.\n eauto with iFrame.\n }\n wp_pures.\n iModIntro.\n done.\n }\n {\n wp_apply (Config.wp_Decode with \"[$Hargs_sl]\").\n { done. }\n iIntros (new_conf_sl) \"Hnew_conf_sl\".\n wp_storeField.\n wp_apply (wp_WriteInt with \"[]\").\n {\n iApply is_slice_zero.\n }\n iIntros (rep_sl) \"Hrep_sl\".\n wp_store.\n\n iApply fupd_wp.\n iMod (\"HΨ\" with \"Hlc\") as \"HΨ\".\n iDestruct \"HΨ\" as (?) \"[Hepoch_ghost2 HΨ]\".\n iDestruct (mono_nat_auth_own_agree with \"Hepoch_ghost Hepoch_ghost2\") as %[_ Heq].\n replace (epoch) with (latest_epoch) in * by word.\n destruct (decide (_)); last first.\n {\n exfalso.\n done.\n }\n {\n iDestruct \"HΨ\" as (?) \"[Hconf_ghost2 HΨ]\".\n iDestruct (ghost_var_agree with \"Hconf_ghost Hconf_ghost2\") as %->.\n iCombine \"Hconf_ghost Hconf_ghost2\" as \"Hconf_ghost\".\n iMod (ghost_var_update new_conf with \"Hconf_ghost\") as \"[Hconf_ghost Hconf_ghost2]\".\n iMod (\"HΨ\" with \"Hconf_ghost2 Hepoch_ghost2\") as \"HΨ\".\n iDestruct (is_slice_to_small with \"Hrep_sl\") as \"Hrep_sl\".\n iSpecialize (\"HΨ\" with \"[%]\").\n { done. }\n iSpecialize (\"HΦ\" with \"HΨ Hrep Hrep_sl\").\n iModIntro.\n\n wp_loadField.\n wp_apply (release_spec with \"[$Hlocked $His_mu Hepoch Hconf Hnew_conf_sl Hepoch_ghost Hconf_ghost]\").\n {\n iNext.\n iExists _,_,_.\n eauto with iFrame.\n }\n wp_pures.\n iModIntro.\n done.\n }\n }\nQed.\n\nLemma wp_Clerk__GetEpochAndConfig (ck:loc) γ Φ :\n is_Clerk ck γ -∗\n □ (£ 1 ={⊤,∅}=∗ ∃ epoch conf, own_epoch γ epoch ∗\n own_config γ conf ∗\n (⌜int.nat epoch < int.nat (word.add epoch (U64 1))⌝ -∗ own_epoch γ (word.add epoch (U64 1)) -∗ own_config γ conf ={∅,⊤}=∗\n (∀ conf_sl, is_slice_small conf_sl uint64T 1 conf -∗ Φ (#(LitInt (word.add epoch (U64 1))), slice_val conf_sl)%V)\n )\n ) -∗\n WP config.Clerk__GetEpochAndConfig #ck {{ Φ }}\n.\nProof.\n iIntros \"#Hck #HΦ\".\n wp_call.\n wp_apply (wp_ref_of_zero).\n { done. }\n iIntros (reply_ptr) \"Hreply\".\n wp_pures.\n\n wp_forBreak.\n wp_pures.\n iNamed \"Hck\".\n\n wp_apply (wp_NewSlice).\n iIntros (dummy_args) \"Hargs\".\n wp_loadField.\n iDestruct (is_slice_to_small with \"Hargs\") as \"Hargs_sl\".\n iNamed \"Hhost\".\n wp_apply (wp_Client__Call2 with \"Hcl_rpc [] Hargs_sl Hreply\").\n {\n iDestruct \"Hhost\" as \"[$ _]\".\n }\n {\n iModIntro.\n iNext.\n iIntros \"Hlc\".\n iMod (\"HΦ\" with \"Hlc\") as \"Hupd\".\n iModIntro.\n iDestruct \"Hupd\" as (??) \"(H1&H2&Hupd)\".\n iExists _, _.\n iFrame \"H1 H2\".\n iIntros.\n iMod (\"Hupd\" with \"[% //] [$] [$]\") as \"Hupd\".\n iModIntro.\n iIntros (??) \"%Hconf_enc %Henc Hargs_sl\".\n iIntros (?) \"Hrep Hrep_sl\".\n wp_pures.\n iRight.\n iModIntro.\n iSplitR; first done.\n wp_pures.\n wp_apply (wp_ref_of_zero).\n { done. }\n iIntros (epoch_ptr) \"Hepoch\".\n wp_pures.\n wp_load.\n rewrite Henc.\n wp_apply (wp_ReadInt with \"Hrep_sl\").\n iIntros (rep_sl1) \"Hrep_sl\".\n wp_pures.\n wp_store.\n wp_store.\n wp_load.\n wp_apply (Config.wp_Decode with \"[$Hrep_sl]\").\n { done. }\n iIntros (?) \"Hconf_own\".\n wp_pures.\n wp_load.\n wp_pures.\n iModIntro.\n iApply \"Hupd\".\n iFrame.\n }\n {\n iIntros (err) \"%Herr Hargs_sl Hrep\".\n wp_pures.\n wp_if_destruct.\n {\n exfalso. done.\n }\n iLeft.\n iModIntro.\n iSplitR; first done.\n iFrame.\n }\nQed.\n\nLemma wp_Clerk__GetConfig (ck:loc) γ Φ :\n is_Clerk ck γ -∗\n □ (£ 1 ={⊤,∅}=∗ ∃ conf, own_config γ conf ∗ (own_config γ conf ={∅,⊤}=∗\n (∀ conf_sl, is_slice_small conf_sl uint64T 1 conf -∗ Φ (slice_val conf_sl)%V)\n )\n ) -∗\n WP config.Clerk__GetConfig #ck {{ Φ }}\n.\nProof.\n iIntros \"#Hck #HΦ\".\n wp_call.\n wp_apply (wp_ref_of_zero).\n { done. }\n iIntros (reply_ptr) \"Hreply\".\n wp_pures.\n\n wp_forBreak.\n wp_pures.\n iNamed \"Hck\".\n\n wp_apply (wp_NewSlice).\n iIntros (dummy_args) \"Hargs\".\n wp_loadField.\n iDestruct (is_slice_to_small with \"Hargs\") as \"Hargs_sl\".\n iNamed \"Hhost\".\n wp_apply (wp_Client__Call2 with \"Hcl_rpc [] Hargs_sl Hreply\").\n {\n iDestruct \"Hhost\" as \"[_ [$ _]]\".\n }\n {\n iModIntro.\n iNext.\n iIntros \"Hlc\".\n iMod (\"HΦ\" with \"Hlc\") as \"Hupd\".\n iModIntro.\n iDestruct \"Hupd\" as (?) \"(H1&Hupd)\".\n iExists _.\n iFrame \"H1\".\n iIntros.\n iMod (\"Hupd\" with \"[$]\") as \"Hupd\".\n iModIntro.\n iIntros (?) \"%Henc_rep Hargs\".\n iIntros (?) \"Hrep Hrep_sl\".\n wp_pures.\n iRight.\n iModIntro.\n iSplitR; first done.\n wp_pures.\n wp_load.\n wp_apply (Config.wp_Decode with \"[$Hrep_sl]\").\n { done. }\n iIntros (?) \"Hconf_own\".\n wp_pures.\n iModIntro.\n iApply \"Hupd\".\n iFrame.\n }\n {\n iIntros (err) \"%Herr Hargs_sl Hrep\".\n wp_pures.\n wp_if_destruct.\n {\n exfalso. done.\n }\n iLeft.\n iModIntro.\n iSplitR; first done.\n iFrame.\n }\nQed.\n\nLemma wp_Clerk__WriteConfig (ck:loc) new_conf new_conf_sl epoch γ Φ :\n is_Clerk ck γ -∗\n is_slice_small new_conf_sl uint64T 1 new_conf -∗\n □ (£ 1 -∗ |={⊤,∅}=> ∃ latest_epoch, own_epoch γ latest_epoch ∗\n if (decide (latest_epoch = epoch)) then\n ∃ conf, own_config γ conf ∗ (own_config γ new_conf -∗ own_epoch γ epoch ={∅,⊤}=∗\n is_slice_small new_conf_sl uint64T 1 new_conf -∗\n Φ #0)\n else\n (own_epoch γ latest_epoch ={∅,⊤}=∗ (∀ (err:u64), ⌜err ≠ 0⌝ →\n is_slice_small new_conf_sl uint64T 1 new_conf -∗\n Φ #err))\n ) -∗\n (∀ (err:u64) , ⌜err ≠ 0⌝ → is_slice_small new_conf_sl uint64T 1 new_conf -∗ Φ #err) -∗\n WP config.Clerk__WriteConfig #ck #epoch (slice_val new_conf_sl)\n {{ Φ }}\n.\nProof.\n iIntros \"#Hck Hconf_sl #HΦ Hfail\".\n wp_call.\n wp_apply (wp_ref_of_zero).\n { done. }\n iIntros (reply_ptr) \"Hreply\".\n wp_pures.\n\n wp_pures.\n iNamed \"Hck\".\n wp_apply (wp_slice_len).\n wp_apply (wp_NewSliceWithCap).\n { apply encoding.unsigned_64_nonneg. }\n iIntros (?) \"Hargs_sl\".\n wp_apply (wp_ref_to).\n { done. }\n iIntros (args_ptr) \"Hargs\".\n wp_pures.\n\n wp_load.\n wp_apply (wp_WriteInt with \"Hargs_sl\").\n iIntros (args_sl) \"Hargs_sl\".\n wp_store.\n wp_apply (Config.wp_Encode with \"Hconf_sl\").\n iIntros (enc_new_conf enc_new_conf_sl) \"(%Henc_new_conf & Hconf & Henc_conf_sl)\".\n wp_load.\n iDestruct (is_slice_to_small with \"Henc_conf_sl\") as \"Henc_conf_sl\".\n wp_apply (wp_WriteBytes with \"[$Hargs_sl $Henc_conf_sl]\").\n iIntros (args_sl2) \"[Hargs_sl Henc_conf_sl]\".\n replace (int.nat 0%Z) with 0%nat by word.\n wp_store.\n\n wp_apply (wp_frame_wand with \"Hconf\").\n\n wp_load.\n wp_loadField.\n iDestruct (is_slice_to_small with \"Hargs_sl\") as \"Hargs_sl\".\n iNamed \"Hhost\".\n wp_apply (wp_Client__Call2 with \"Hcl_rpc [] Hargs_sl Hreply\").\n {\n iDestruct \"Hhost\" as \"[_ [_ [$ _]]]\".\n }\n {\n iModIntro.\n iNext.\n iExists _, _, _.\n iSplitR; first done.\n iSplitR; first done.\n iIntros \"Hlc\".\n iMod (\"HΦ\" with \"Hlc\") as \"Hupd\".\n iModIntro.\n iDestruct \"Hupd\" as (?) \"(H1 & Hupd)\".\n iExists _.\n iFrame \"H1\".\n destruct (decide (_)).\n {\n iDestruct \"Hupd\" as (?) \"[H1 Hupd]\".\n iExists _.\n iFrame \"H1\".\n iIntros \"H1 H2\".\n iMod (\"Hupd\" with \"H1 H2\") as \"Hupd\".\n iModIntro.\n iIntros (?) \"%Henc_rep Hargs_sl\".\n iIntros (?) \"Hrep Hrep_sl\".\n wp_pures.\n wp_load.\n rewrite Henc_rep.\n wp_apply (wp_ReadInt with \"Hrep_sl\").\n iIntros (?) \"_\".\n wp_pures.\n iModIntro.\n iIntros \"Hconf\".\n iApply \"Hupd\".\n iFrame.\n }\n {\n iIntros \"H1\".\n iMod (\"Hupd\" with \"H1\") as \"Hupd\".\n iModIntro.\n iIntros (err Herr_nz reply Henc_rep) \"Hargs_sl\".\n iIntros (?) \"Hrep Hrep_sl\".\n wp_pures.\n wp_load.\n rewrite Henc_rep.\n wp_apply (wp_ReadInt with \"Hrep_sl\").\n iIntros (?) \"_\".\n wp_pures.\n iModIntro.\n iIntros.\n iApply \"Hupd\".\n { done. }\n { iFrame. }\n }\n }\n {\n iIntros (err) \"%Herr_nz Hargssl Hrep\".\n wp_pures.\n wp_if_destruct.\n {\n exfalso. done.\n }\n iModIntro.\n iIntros.\n iApply \"Hfail\".\n { done. }\n done.\n }\nQed.\n\nDefinition makeConfigServer_pre γ conf : iProp Σ := own_epoch γ 0 ∗ own_config γ conf.\n\nLemma wp_MakeServer γ conf_sl conf :\n {{{\n makeConfigServer_pre γ conf ∗\n is_slice_small conf_sl uint64T 1 conf\n }}}\n config.MakeServer (slice_val conf_sl)\n {{{\n (s:loc), RET #s; is_Server s γ\n }}}.\nProof.\n iIntros (Φ) \"([Hepoch Hconf] & Hconf_sl) HΦ\".\n wp_call.\n wp_apply (wp_allocStruct).\n { Transparent slice.T. repeat econstructor. Opaque slice.T. }\n iIntros (s) \"Hs\".\n iDestruct (struct_fields_split with \"Hs\") as \"HH\".\n iNamed \"HH\".\n simpl.\n wp_pures.\n wp_apply (wp_new_free_lock).\n iIntros (mu) \"Hmu_inv\".\n wp_storeField.\n wp_storeField.\n wp_storeField.\n iMod (readonly_alloc_1 with \"mu\") as \"#Hmu\".\n iApply \"HΦ\".\n iExists _.\n iMod (alloc_lock with \"Hmu_inv [Hepoch Hconf epoch config Hconf_sl]\") as \"$\".\n {\n iNext.\n iExists _, _, _.\n iFrame.\n }\n iFrame \"Hmu\".\n done.\nQed.\n\nLemma wp_Server__Serve s γ host :\n is_host host γ -∗ is_Server s γ -∗\n {{{\n True\n }}}\n config.Server__Serve #s #host\n {{{\n RET #(); True\n }}}.\nProof.\n iIntros \"#Hhost #His_srv !#\" (Φ) \"_ HΦ\".\n wp_call.\n\n wp_apply (map.wp_NewMap).\n iIntros (handlers) \"Hhandlers\".\n\n wp_pures.\n wp_apply (wp_Server__GetEpochAndConfig).\n { done. }\n iIntros (getEpochFn) \"#HgetEpochSpec\".\n wp_apply (map.wp_MapInsert with \"Hhandlers\").\n iIntros \"Hhandlers\".\n wp_pures.\n\n wp_pures.\n wp_apply (wp_Server__GetConfig).\n { done. }\n iIntros (getFn) \"#HgetSpec\".\n wp_apply (map.wp_MapInsert with \"Hhandlers\").\n iIntros \"Hhandlers\".\n wp_pures.\n\n wp_pures.\n wp_apply (wp_Server__WriteConfig).\n { done. }\n iIntros (writeConfigFn) \"#HwriteSpec\".\n wp_apply (map.wp_MapInsert with \"Hhandlers\").\n iIntros \"Hhandlers\".\n wp_pures.\n\n wp_apply (urpc_proof.wp_MakeServer with \"Hhandlers\").\n iIntros (r) \"Hr\".\n wp_pures.\n\n iNamed \"Hhost\".\n wp_apply (wp_StartServer2 with \"[$Hr]\").\n {\n set_solver.\n }\n {\n iDestruct \"Hhost\" as \"(H1&H2&H3&Hhandlers)\".\n unfold handlers_complete.\n repeat rewrite dom_insert_L.\n rewrite dom_empty_L.\n iSplitL \"\".\n {\n iExactEq \"Hhandlers\".\n f_equal.\n set_solver.\n }\n\n iApply (big_sepM_insert_2 with \"\").\n {\n iExists _; iFrame \"#\".\n }\n iApply (big_sepM_insert_2 with \"\").\n {\n iExists _; iFrame \"#\".\n }\n iApply (big_sepM_insert_2 with \"\").\n {\n iExists _; iFrame \"#\".\n }\n by iApply big_sepM_empty.\n }\n wp_pures.\n by iApply \"HΦ\".\nQed.\n\nEnd config_proof.\n\n(*\n handler_spec γ.(urpc_gn) host (U64 0) (GetEpochAndConfig_spec γ) ∗\n handler_spec γ.(urpc_gn) host (U64 1) (GetConfig_spec γ) ∗\n handler_spec γ.(urpc_gn) host (U64 2) (WriteConfig_spec γ) ∗\n handlers_dom γ.(urpc_gn) {[ (U64 0) ; (U64 1) ; (U64 2)]}\n*)\n\nSection config_init.\n\nContext `{!configG Σ}.\nContext `{!gooseGlobalGS Σ}.\n\nDefinition config_spec_list γ :=\n [ (U64 0, GetEpochAndConfig_spec γ) ;\n (U64 1, GetConfig_spec γ) ;\n (U64 2, WriteConfig_spec γ)].\n\nLemma config_ghost_init conf :\n ⊢ |==> ∃ γ,\n makeConfigServer_pre γ conf ∗\n own_epoch γ 0 ∗ own_config γ conf.\nProof.\n iMod (mono_nat_own_alloc 0) as (γepoch) \"[[Hepoch Hepoch2] _]\".\n iMod (ghost_var_alloc conf) as (γconf) \"[Hconf Hconf2]\".\n iExists {| epoch_gn := _ ; config_val_gn:= _ |}.\n iModIntro.\n iFrame.\nQed.\n\nLemma config_server_init host γ :\n host c↦ ∅ ={⊤}=∗\n is_host host γ.\nProof.\n iIntros \"Hchan\".\n iMod (handler_is_init_list2 host (config_spec_list γ) with \"Hchan\") as (γrpc) \"H\".\n { simpl. set_solver. }\n iModIntro.\n iExists γrpc.\n simpl.\n iDestruct \"H\" as \"(H1 & $ & $ & $ & _)\".\n iExactEq \"H1\".\n f_equal.\n set_solver.\nQed.\n\nEnd config_init.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/simplepb/config_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.146131911001175}} {"text": "Require Import CoqlibC Maps Integers AST Linking.\nRequire Import ValuesC Memory Events Globalenvs Smallstep.\nRequire Import Op Registers RTLC Conventions Tailcall.\nRequire Import sflib.\n(** newly added **)\nRequire Export Tailcallproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem.\nRequire SimMemExt.\nRequire SoundTop.\n\nSet Implicit Arguments.\n\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariables prog tprog: program.\nLet md_src: Mod.t := (RTLC.module prog).\nLet md_tgt: Mod.t := (RTLC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\n\nHypothesis TRANSL: match_prog prog tprog.\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat) (st_src0: RTL.state) (st_tgt0: RTL.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: Tailcallproof.match_states st_src0 st_tgt0)\n (MCOMPATSRC: (get_mem st_src0) = sm0.(SimMem.src))\n (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt))\n (MCOMPATIDX: idx = Tailcallproof.measure st_src0).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun cu f tf => tf = transf_fundef f) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nLet SEGESRC: senv_genv_compat skenv_link ge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.\nLet SEGETGT: senv_genv_compat skenv_link tge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.\n\nTheorem sim_modsem: ModSemPair.sim msp.\nProof.\n eapply match_states_sim with (match_states := match_states)\n (match_states_at := fun _ _ => eq);\n eauto; ii; ss.\n - eapply Nat.lt_wf_0.\n - eapply SoundTop.sound_state_local_preservation.\n - (* init bsim *)\n destruct sm_arg; ss. clarify.\n inv INITTGT. inv SIMARGS; ss. clarify.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n eexists. eexists (SimMemExt.mk _ _). esplits; eauto.\n + econs; eauto; ss.\n * inv TYP. rpapply match_states_call; eauto.\n { econs; eauto. }\n { eapply lessdef_list_typify_list; try apply VALS; eauto. rewrite <- LEN.\n symmetry. eapply lessdef_list_length; eauto. }\n folder. inv SAFESRC. inv TYP.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. folder. des_ifs.\n inv FPTR; ss. unfold transf_function in *. des_ifs.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss. inv FPTR; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. folder. des_ifs.\n inv TYP. erewrite <- (sig_preserved fd) in *. esplits; eauto. econs; eauto.\n + econs; eauto. erewrite <- lessdef_list_length; eauto.\n + erewrite <- lessdef_list_length; eauto.\n - (* call wf *)\n inv MATCH; ss. destruct sm0; ss. clarify. u in CALLSRC. des. inv CALLSRC. inv MATCHST; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify. inv CALLSRC. inv MATCHST; ss.\n folder. esplits; eauto.\n + econs; eauto.\n * folder. des. r in TRANSL. r in TRANSL.\n exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.\n { apply SIMSKENV. }\n intro GE. apply (fsim_external_funct_id GE); ss.\n folder. inv FPTR; ss.\n * des. esplits; eauto. eapply SimSymb.simskenv_func_fsim; eauto; ss.\n + econs; ss; eauto.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; econs; ss; eauto.\n + econs; ss; eauto. eapply lessdef_typify; ss.\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss. inv H2. destruct sm0; ss. clarify.\n eexists (SimMemExt.mk _ _). esplits; ss; eauto. econs; eauto.\n - left; i. esplits; eauto.\n { apply modsem_receptive; et. }\n inv MATCH. ii. hexploit (@transf_step_correct prog skenv_link); eauto.\n { inv SIMSKENV. ss. }\n { apply make_match_genvs; eauto. apply SIMSKENV. }\n i; des.\n + esplits; eauto.\n * left. apply plus_one. ss. unfold DStep in *. des; ss. esplits; eauto. apply modsem_determinate; et.\n * instantiate (1:= (SimMemExt.mk _ _)). ss.\n + esplits; eauto.\n * right. subst tr. split. econs. eauto.\n * instantiate (1:= (SimMemExt.mk _ _)). ss.\nUnshelve.\n all: ss. apply msp.\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariables prog tprog: program.\nHypothesis TRANSL: match_prog prog tprog.\n\nDefinition mp: ModPair.t := SimSymbId.mk_mp (RTLC.module prog) (RTLC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. eapply Sk.match_program_eq; eauto. ii. destruct f1; ss.\n + clarify. right. esplits; eauto. rewrite sig_preserved; et.\n + clarify. left. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/TailcallproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14564526805361402}} {"text": "From stdpp Require Import finite vector.\nFrom trace_program_logic.prelude Require Import finitary classical quantifiers.\nFrom trace_program_logic.program_logic Require Import traces.\nFrom aneris.prelude Require Import misc.\nFrom aneris.prelude Require Import time.\nFrom aneris.aneris_lang Require Import state_interp adequacy.\nFrom aneris.aneris_lang Require Import tactics proofmode.\nFrom aneris_examples.crdt.gcounter_convergence Require Import\n crdt_model crdt_resources crdt_runner vc.\nFrom trace_program_logic.traces Require Import trace_properties.\n\nImport InfListNotations.\n\nLocal Instance: ∀ gcdata st st', ProofIrrel (GCounterM gcdata st st').\nProof. intros ?????; apply ProofIrrelevance. Qed.\n\nLemma GcounterM_rel_finitary gcdata : aneris_model_rel_finitary (GCounterM gcdata).\nProof.\n intros st.\n apply finite_smaller_card_nat.\n apply (@in_list_finite\n _ _ (λ st', GCounterM gcdata st st') _\n (all_crdt_states_smaller (GClen gcdata) (vmap S (max_vc st)))).\n intros ? ?.\n apply elem_of_all_crdt_states_smaller.\n intros ?.\n apply crdt_next_bounded; done.\nQed.\n\nDefinition oloc_less_defined (ol ol' : option loc) : Prop :=\n match ol with\n | Some l =>\n match ol' with\n | Some l' => l' = l\n | None => False\n end\n | None => True\n end.\n\nGlobal Instance oloc_less_defined_PO : PartialOrder oloc_less_defined.\nProof.\n constructor; first constructor.\n - intros []; split; auto.\n - intros [] [] [] [] []; split; intros; simplify_eq/=; eauto.\n - intros [] [] [] []; auto.\nQed.\n\nDefinition locs_less_defined (locs locs' : list (option loc)) : Prop :=\n Forall2 oloc_less_defined locs locs'.\n\nLemma locs_less_defined_lookup locs locs' i :\n locs_less_defined locs locs' → oloc_less_defined (locs !!! i) (locs' !!! i).\nProof.\n rewrite /locs_less_defined Forall2_lookup.\n intros Hlocs.\n specialize (Hlocs i).\n rewrite !list_lookup_total_alt.\n destruct (locs !! i); destruct (locs' !! i); inversion Hlocs; simplify_eq; done.\nQed.\n\nGlobal Instance locs_less_defined_PO : PartialOrder locs_less_defined.\nProof.\n constructor; first constructor.\n - intros l; apply (_ : Reflexive (Forall2 _)).\n - intros l1 l2 l3; apply (_ : Transitive (Forall2 _)).\n - intros l1 l2; apply (_ : AntiSymm _ (Forall2 _)).\nQed.\n\nLemma locs_all_defined locs locs' :\n locs_less_defined (Some <$> locs) locs' → locs' = (Some <$> locs).\n intros Hld.\n apply list_eq; intros i.\n destruct (decide (i < length locs)) as [Hlt|Hnlt].\n - destruct (lookup_lt_is_Some_2 locs i) as [l Hl]; first done.\n destruct (lookup_lt_is_Some_2 locs' i) as [ol Hol].\n { erewrite <- (Forall2_length); last apply Hld.\n rewrite fmap_length; done. }\n apply (locs_less_defined_lookup _ _ i) in Hld.\n revert Hld.\n rewrite list_lookup_fmap list_lookup_total_fmap //.\n erewrite !list_lookup_total_correct; eauto.\n intros Hld.\n rewrite Hl Hol; simpl.\n destruct ol; simplify_eq/=; done.\n - rewrite list_lookup_fmap (lookup_ge_None_2 locs); last lia.\n rewrite lookup_ge_None_2; first done.\n erewrite <- (Forall2_length); last apply Hld.\n rewrite fmap_length; lia.\nQed.\n\nSection crdt_main_rel.\n Context (gcdata : GCData).\n\n Implicit Types ex : execution_trace aneris_lang.\n Implicit Types iex : inf_execution_trace aneris_lang.\n Implicit Types atr : finite_trace (GCounterM gcdata) ().\n Implicit Types iatr : inflist (() * GCounterM gcdata).\n\n Notation ith_sa i := (gcd_addr_list gcdata !!! i).\n\n Definition loc_of_trace_i (i : nat) (evs : event_obs aneris_lang) : option loc :=\n match evs with\n | [] => None\n | ev :: evs' =>\n match expr_e ev.(post_expr) with\n | Val #(LitLoc l) => Some l\n | _ => None\n end\n end.\n\n Definition locs_of_trace_now (ex : execution_trace aneris_lang) : list (option loc) :=\n (λ i, loc_of_trace_i i (events_of_trace (allocEV (StringOfZ i)) ex) ) <$> seq 0 (GClen gcdata).\n\n Fixpoint locs_of_trace (ex : execution_trace aneris_lang) : finite_trace (list (option loc)) () :=\n match ex with\n | trace_singleton _ => {tr[replicate (GClen gcdata) None]}\n | trace_extend ex' _ c => (locs_of_trace ex') :tr[()]: (locs_of_trace_now ex)\n end.\n\n Lemma locs_of_trace_last ex :\n trace_last (locs_of_trace ex) = locs_of_trace_now ex.\n Proof.\n destruct ex; last done.\n rewrite /locs_of_trace_now.\n rewrite (const_fmap _ _ None); first by rewrite seq_length.\n intros ?; rewrite events_of_singleton_trace; done.\n Qed.\n\n Lemma locs_of_trace_now_length ex : length (locs_of_trace_now ex) = GClen gcdata.\n Proof. rewrite /locs_of_trace fmap_length seq_length; done. Qed.\n\n Lemma locs_of_trace_length ex : trace_forall (λ tr, length tr = GClen gcdata) (locs_of_trace ex).\n Proof.\n induction ex as [|ex IHex c]; simpl in *.\n - constructor. rewrite replicate_length //.\n - constructor; first done. apply locs_of_trace_now_length.\n Qed.\n\n Lemma locs_of_trace_now_extend_less_defined ex c oζ:\n valid_exec (ex :tr[oζ]: c) →\n locs_less_defined (locs_of_trace_now ex) (locs_of_trace_now (ex :tr[oζ]: c)).\n Proof.\n intros Hvl.\n apply Forall2_lookup; intros i.\n destruct (decide (i < GClen gcdata)); last first.\n { rewrite !lookup_ge_None_2; first by constructor.\n - rewrite locs_of_trace_now_length; lia.\n - rewrite locs_of_trace_now_length; lia. }\n rewrite !list_lookup_fmap !lookup_seq_lt //=; [].\n constructor.\n destruct (events_of_trace_extend_app (allocEV (StringOfZ i)) ex c oζ) as (evs & _ & Heq & _);\n first done.\n rewrite Heq.\n destruct (events_of_trace (allocEV (StringOfZ i)) ex); reflexivity.\n Qed.\n\n Lemma locs_of_trace_less_defined ex :\n valid_exec ex → trace_steps (λ x _ y, locs_less_defined x y) (locs_of_trace ex).\n Proof.\n induction ex as [|ex IHex c]; simpl; first by constructor.\n intros Hvl.\n econstructor; [done| |by apply IHex; eapply valid_exec_exec_extend_inv; eauto].\n rewrite locs_of_trace_last.\n apply locs_of_trace_now_extend_less_defined; done.\n Qed.\n\n Lemma locs_of_trace_now_lookup_singleton i ex ip lbl l v σ h :\n i < GClen gcdata →\n events_of_trace (allocEV (StringOfZ i)) ex = [allocObs ip lbl l v σ h] →\n locs_of_trace_now ex !! i = Some (Some l).\n Proof.\n intros Hi Hevs.\n rewrite /locs_of_trace list_lookup_fmap lookup_seq_lt /=; last done.\n rewrite /loc_of_trace_i Hevs; done.\n Qed.\n\n Lemma locs_of_trace_now_lookup_nil i ex :\n i < GClen gcdata →\n events_of_trace (allocEV (StringOfZ i)) ex = [] →\n locs_of_trace_now ex !! i = Some None.\n Proof.\n intros Hi Hevs.\n rewrite /locs_of_trace list_lookup_fmap lookup_seq_lt /=; last done.\n rewrite /loc_of_trace_i Hevs; done.\n Qed.\n\n Definition valid_model_fin_trace (mtr : finite_trace (GCounterM gcdata) ()) : Prop :=\n trace_forall valid_crdt_state mtr ∧ trace_steps (λ st _ st', st = st' ∨ CrdtNext st tt st') mtr.\n\n Definition gcounter_values_related_now (lcs : (list (option loc)))\n (c : cfg aneris_lang) (δ : GCounterM gcdata) : Prop :=\n ∀ i : fin (GClen gcdata),\n match lcs !!! (fin_to_nat i) with\n | Some l =>\n ∃ h, c.2.(state_heaps) !! (ip_of_address (ith_sa (fin_to_nat i))) = Some h ∧\n h !! l = Some (vector_clock_to_val (vec_to_list (δ !!! i)))\n | None => δ !!! i = vreplicate (GClen gcdata) 0\n end.\n\n Definition gcounter_values_related (locs : finite_trace (list (option loc)) ())\n (ex : execution_trace aneris_lang) (mtr : finite_trace (GCounterM gcdata) ()) : Prop :=\n trace_forall3 gcounter_values_related_now locs ex mtr.\n\n Definition gcounter_values_related_now_locs_resolved (lcs : (list loc))\n (c : cfg aneris_lang) (δ : GCounterM gcdata) : Prop :=\n ∀ i : fin (GClen gcdata),\n ∃ h, c.2.(state_heaps) !! (ip_of_address (ith_sa (fin_to_nat i))) = Some h ∧\n h !! (lcs !!! (fin_to_nat i)) = Some (vector_clock_to_val (vec_to_list (δ !!! i))).\n\n Lemma gcounter_values_related_now_resolve_locs locs c δ :\n length locs = GClen gcdata →\n gcounter_values_related_now (Some <$> locs) c δ →\n gcounter_values_related_now_locs_resolved locs c δ.\n Proof.\n intros Hlen Hvrel i.\n specialize (Hvrel i).\n rewrite list_lookup_total_fmap in Hvrel; [done|by rewrite Hlen; apply fin_to_nat_lt].\n Qed.\n\n Definition gcounter_monotone (locs : finite_trace (list (option loc)) ())\n (ex : execution_trace aneris_lang) : Prop :=\n trace_steps2\n (λ lcs c _ _ lcs' c',\n ∀ i, i < GClen gcdata →\n match lcs !!! i with\n | Some l =>\n match lcs' !!! i with\n | Some l' =>\n l' = l ∧\n ∃ h h' (vc vc' : vector_clock (GClen gcdata)),\n c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h ∧\n c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' ∧\n h !! l = Some (vector_clock_to_val vc) ∧\n h' !! l = Some (vector_clock_to_val vc') ∧\n vc_le vc vc'\n | None => False\n end\n | None => True\n end) locs ex.\n\n Definition gcounter_monotone_configs (lcs : list loc) (c c' : cfg aneris_lang) : Prop :=\n c = c' ∨\n ∀ i, i < GClen gcdata →\n ∃ h h' (vc vc' : vector_clock (GClen gcdata)),\n c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h ∧\n c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' ∧\n h !! (lcs !!! i) = Some (vector_clock_to_val vc) ∧\n h' !! (lcs !!! i) = Some (vector_clock_to_val vc') ∧\n vc_le vc vc'.\n\n Lemma gcounter_monotone_configs_vc_le lcs i c c' h h' (vc vc' : vector_clock (GClen gcdata)) :\n i < GClen gcdata →\n gcounter_monotone_configs lcs c c' →\n c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h →\n c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' →\n h !! (lcs !!! i) = Some (vector_clock_to_val (vec_to_list vc)) →\n h' !! (lcs !!! i) = Some (vector_clock_to_val (vec_to_list vc')) →\n vc_le vc vc'.\n Proof.\n intros Hi Hgmc Hh Hh' Hvc Hvc'.\n destruct Hgmc as [<-|Hgmc].\n { simplify_eq.\n match goal with\n | Heq : _ = _ |- _ =>\n apply vec_to_list_inj2 in Heq; simplify_eq; done\n end. }\n specialize (Hgmc i Hi) as (?&?&?&?&?&?&?&?&?); simplify_eq.\n repeat\n match goal with\n | Heq : _ = _ |- _ =>\n apply vec_to_list_inj2 in Heq; simplify_eq\n end; done.\n Qed.\n\n Global Instance gcounter_monotone_configs_PreOrder lcs : PreOrder (gcounter_monotone_configs lcs).\n Proof.\n split.\n - by left.\n - intros c1 c2 c3 Hc12 Hc23.\n destruct Hc12 as [->|Hc12]; first done.\n destruct Hc23 as [<-|Hc23]; first by right.\n right.\n intros i Hi.\n destruct (Hc12 i Hi) as (h1&h2&vc1&vc2&?&?&?&?&?).\n destruct (Hc23 i Hi) as (h2'&h3&vc2'&vc3&?&?&?&?&?).\n simplify_eq/=.\n match goal with\n | Heq : _ = _ |- _ =>\n apply vec_to_list_inj2 in Heq; simplify_eq\n end.\n eexists h1, h3, vc1, vc3; split_and!; [by eauto|by eauto|done|done|etrans; eauto].\n Qed.\n\n Definition gcounter_monotone_locs_resolved_simple\n (lcs : list loc) (l : list (cfg aneris_lang)) : Prop :=\n ∀ i c1 c2, l !! i = Some c1 → l !! (S i) = Some c2 → gcounter_monotone_configs lcs c1 c2.\n\n Definition gcounter_monotone_locs_resolved (lcs : list loc) (l : list (cfg aneris_lang)) : Prop :=\n ∀ i j c1 c2, i ≤ j → l !! i = Some c1 → l !! j = Some c2 → gcounter_monotone_configs lcs c1 c2.\n\n Lemma gcounter_monotone_locs_resolved_if_simple lcs l :\n gcounter_monotone_locs_resolved_simple lcs l → gcounter_monotone_locs_resolved lcs l.\n Proof.\n intros Hgms i j c1 c2 Hij Hi Hj.\n apply nat_le_sum in Hij as [k Hk].\n revert i j Hk c1 c2 Hi Hj.\n induction k as [|k IHk]; intros i j Hk c1 c2 Hi Hj.\n { assert (j = i) by lia; clear Hk; simplify_eq; reflexivity. }\n destruct (lookup_lt_is_Some_2 l (i + k)) as [c Hc].\n { apply lookup_lt_Some in Hj; lia. }\n etrans; first by apply (IHk i (i + k) eq_refl c1 c); auto.\n replace j with (S (i + k)) in Hj by lia.\n eapply Hgms; eauto.\n Qed.\n\n Lemma gcounter_monotone_resolve_locs lcs ex il l :\n length il = length l →\n length lcs = GClen gcdata →\n valid_exec (ex +trl+ l) →\n trace_last (locs_of_trace ex) = (Some <$> lcs) →\n trace_steps (λ x _ y, locs_less_defined x y) (locs_of_trace ex +trl+ il) →\n gcounter_monotone (locs_of_trace ex +trl+ il) (ex +trl+ l) →\n gcounter_monotone_locs_resolved lcs (trace_last ex :: map snd l).\n Proof.\n intros Hlen Hlcs Hvl Hld Hldl Hgms.\n apply gcounter_monotone_locs_resolved_if_simple.\n revert il Hlen Hvl Hld Hldl Hgms; induction l as [|[oζ c] l IHl] using rev_ind;\n intros il Hlen Hvl Hld Hldl Hgms.\n { intros i j c1 c2; rewrite list_lookup_singleton; done. }\n intros i c1 c2 Hi HSi.\n destruct il as [|[[] locs] il _] using rev_ind.\n { rewrite app_length /= in Hlen; lia. }\n rewrite -!trace_append_list_assoc /= in Hvl, Hgms, Hldl.\n assert (i < S (length l)).\n { cut (S i < length (trace_last ex :: map snd l ++ [c])).\n - rewrite /= app_length map_length /=; lia.\n - apply lookup_lt_is_Some_1; eauto.\n rewrite map_app in HSi. rewrite HSi; eauto. }\n rewrite map_app (lookup_app_l (_ :: _)) in Hi; last first.\n { list_simplifier. rewrite map_length //. }\n destruct (decide (i < length l)) as [Hlt|Hnlt].\n - rewrite /= map_app lookup_app_l in HSi; last by rewrite map_length.\n eapply (IHl il); [rewrite !app_length /= in Hlen| |done| | |by eauto|by eauto].\n + rewrite !Nat.add_1_r in Hlen. by injection Hlen.\n + eapply valid_exec_exec_extend_inv; eauto.\n + eapply trace_steps_step_inv in Hldl as [? ?]; done.\n + eapply trace_steps2_step_inv in Hgms as [? ?]; done.\n - assert (i = length l) as HSieq by lia.\n rewrite HSieq in HSi.\n rewrite map_app (lookup_app_r (_ :: _)) in HSi; last by rewrite /= map_length.\n rewrite /= map_length Nat.sub_diag in HSi; simplify_eq/=.\n apply trace_steps2_step_inv in Hgms as [_ Hgms].\n destruct Hgms as (? & ? & ?%last_eq_trace_ends_in & ?%last_eq_trace_ends_in & Hgms).\n simplify_eq.\n destruct l as [|[? c'] l _] using rev_ind.\n + assert (length il = 0) by by rewrite app_length /= in Hlen; lia.\n destruct il; last done.\n simplify_eq/=.\n rewrite Hld in Hgms.\n right; intros i Hi.\n specialize (Hgms i Hi).\n rewrite list_lookup_total_fmap in Hgms; last lia.\n destruct (locs !!! i); last done.\n destruct Hgms as [-> Hgms]; done.\n + rewrite -!trace_append_list_assoc /= in Hgms.\n rewrite app_length /= in Hi.\n rewrite map_app (lookup_app_r (_ ::_)) in Hi; last by rewrite /= map_length; lia.\n rewrite /= in Hi.\n replace (length l + 1 - S (length l)) with 0 in Hi by lia.\n simplify_eq/=.\n apply valid_exec_exec_extend_inv in Hvl as [Hvl _].\n apply locs_of_trace_less_defined in Hvl.\n apply trace_steps_step_inv in Hldl as [Hldl _].\n eapply trace_append_list_steps_rtc_nl in Hldl;\n [|apply trace_ends_in_last|apply trace_ends_in_last].\n revert Hldl; rewrite rt_rtc_same Hld; intros Hldl.\n right. intros i Hilen.\n apply (locs_less_defined_lookup _ _ i) in Hldl.\n rewrite list_lookup_total_fmap in Hldl; last lia.\n specialize (Hgms i Hilen).\n destruct (trace_last (locs_of_trace ex +trl+ il) !!! i) as [ol'|]; last done.\n simplify_eq/=.\n destruct (locs !!! i); last done.\n destruct Hgms as (-> & Hgms).\n by list_simplifier.\n Qed.\n\n Definition send_evs_rel (locs : list (option loc)) (ex : execution_trace aneris_lang) : Prop :=\n ∃ sevss,\n length sevss = GClen gcdata ∧\n ∀ i, i < GClen gcdata →\n ∃ sevs,\n sevss !! i = Some sevs ∧\n sendevs_valid sevs ∧\n match locs !!! i with\n | Some l =>\n Forall2\n (@send_events_correspond gcdata (ith_sa i) l)\n (events_of_trace (sendonEV (ith_sa i)) ex)\n sevs\n | None => events_of_trace (sendonEV (ith_sa i)) ex = [] ∧ sevs = []\n end.\n\n Definition send_evs_rel_locs_resolved\n (locs : list loc) (ex : execution_trace aneris_lang) : Prop :=\n ∃ sevss,\n length sevss = GClen gcdata ∧\n ∀ i, i < GClen gcdata →\n ∃ sevs,\n sevss !! i = Some sevs ∧\n sendevs_valid sevs ∧\n Forall2\n (@send_events_correspond gcdata (ith_sa i) (locs !!! i))\n (events_of_trace (sendonEV (ith_sa i)) ex)\n sevs.\n\n Lemma send_evs_rel_resolve_locs locs ex :\n length locs = GClen gcdata →\n send_evs_rel (Some <$> locs) ex →\n send_evs_rel_locs_resolved locs ex.\n Proof.\n intros Hlen [sevss [? Hsevs]].\n exists sevss; split; first done.\n intros i Hi.\n specialize (Hsevs i Hi).\n setoid_rewrite list_lookup_total_fmap in Hsevs; [eauto|lia].\n Qed.\n\n\n Definition receive_evs_rel (locs : list (option loc)) (ex : execution_trace aneris_lang) : Prop :=\n ∃ revss,\n length revss = GClen gcdata ∧\n ∀ i, i < GClen gcdata →\n ∃ revs,\n revss !! i = Some revs ∧\n match locs !!! i with\n | Some l =>\n Forall2 (rec_events_correspond (ith_sa i))\n (events_of_trace (receiveonEV (ith_sa i)) ex) revs ∧\n ∃ h (vc : vector_clock (GClen gcdata)),\n (trace_last ex).2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h ∧\n h !! l = Some (vector_clock_to_val vc) ∧\n forall j rev, S j < length revs → revs !! j = Some rev → vc_le rev vc\n | None => events_of_trace (receiveonEV (ith_sa i)) ex = [] ∧ revs = []\n end.\n\n Definition receive_evs_rel_locs_resolved\n (locs : list loc) (ex : execution_trace aneris_lang) : Prop :=\n ∃ revss,\n length revss = GClen gcdata ∧\n ∀ i, i < GClen gcdata →\n ∃ revs,\n revss !! i = Some revs ∧\n Forall2 (rec_events_correspond (ith_sa i))\n (events_of_trace (receiveonEV (ith_sa i)) ex) revs ∧\n ∃ h (vc : vector_clock (GClen gcdata)),\n (trace_last ex).2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h ∧\n h !! (locs !!! i) = Some (vector_clock_to_val vc) ∧\n forall j rev, S j < length revs → revs !! j = Some rev → vc_le rev vc.\n\n Lemma receive_evs_rel_resolve_locs locs ex :\n length locs = GClen gcdata →\n receive_evs_rel (Some <$> locs) ex →\n receive_evs_rel_locs_resolved locs ex.\n Proof.\n intros Hlen [revss [? Hrevs]].\n exists revss; split; first done.\n intros i Hi.\n specialize (Hrevs i Hi).\n setoid_rewrite list_lookup_total_fmap in Hrevs; [eauto|lia].\n Qed.\n\n Definition crdt_main_rel (ex: execution_trace aneris_lang)\n (mtr : auxiliary_trace (@aneris_AS (GCounterM gcdata))) : Prop :=\n valid_exec ex ∧\n valid_model_fin_trace mtr ∧\n gcounter_values_related (locs_of_trace ex) ex mtr ∧\n send_evs_rel (trace_last (locs_of_trace ex)) ex ∧\n receive_evs_rel (trace_last (locs_of_trace ex)) ex.\n\n Lemma crdt_main_rel_monotone ex mtr :\n crdt_main_rel ex mtr → gcounter_monotone (locs_of_trace ex) ex.\n Proof.\n intros (Hvl & Hmvl & Hvrel & _).\n revert mtr Hvl Hmvl Hvrel.\n induction ex as [|ex IHex c]; simpl;\n intros mtr Hvl Hmvl Hvrel; first by apply trace_steps2_singleton.\n econstructor; [done|done| |]; last first.\n { apply trace_forall3_extend_inv_l in Hvrel as (? & ? & ? & mtr' & ? & [] & ? & ? & ? & ?); simplify_eq.\n eapply IHex; [by eapply valid_exec_exec_extend_inv; eauto| |by eauto].\n destruct Hmvl as [[? ?]%trace_forall_extend_inv [? [??]]%trace_steps_step_inv]; done.\n }\n apply trace_forall3_extend_inv_l in Hvrel as (c' & ex' & st & mtr' & oζ & ? & ? & ? & Hrel1 & Hrel2);\n simplify_eq/=.\n apply trace_forall3_last in Hrel1.\n intros i Hi.\n specialize (Hrel1 (nat_to_fin Hi)).\n specialize (Hrel2 (nat_to_fin Hi)).\n rewrite locs_of_trace_last in Hrel1.\n rewrite locs_of_trace_last.\n rewrite !fin_to_nat_to_fin in Hrel1, Hrel2.\n destruct (locs_of_trace_now (ex' :tr[ oζ ]: c') !!! i) eqn:Heq; last first.\n { pose proof (locs_of_trace_now_extend_less_defined ex' c' _ Hvl) as Hld.\n apply (locs_less_defined_lookup _ _ i) in Hld.\n rewrite Heq in Hld.\n destruct (locs_of_trace_now ex' !!! i); done. }\n pose proof (locs_of_trace_now_extend_less_defined ex' c' _ Hvl) as Hld.\n apply (locs_less_defined_lookup _ _ i) in Hld.\n rewrite Heq in Hld.\n destruct (locs_of_trace_now ex' !!! i); simplify_eq/=; last done.\n split; first done.\n destruct Hrel1 as (h & Hh1 & Hh2).\n destruct Hrel2 as (h' & Hh'1 & Hh'2).\n eexists _, _, _, _; split_and!; [by eauto|by eauto|by eauto|by eauto|].\n destruct Hmvl as [_ Hmvl].\n apply trace_steps_step_inv in Hmvl as [_ (st' & -> & [->|Hmvl])]; first done.\n apply crdt_next_vc_le; done.\n Qed.\n\n Lemma crdt_main_rel_initially (ps : programs_using_gcounters gcdata) v :\n crdt_main_rel\n {tr[ ([{| expr_n := \"system\"; expr_e := runner gcdata 0 (progs ps) v |}],\n init_state gcdata) ]}\n {tr[ initial_crdt_state (GClen gcdata) ]}.\n Proof.\n rewrite /crdt_main_rel /=; split_and!.\n - constructor.\n - repeat constructor. apply valid_initial_crdt_state.\n - constructor; intros i.\n rewrite lookup_total_replicate_2; last by apply fin_to_nat_lt.\n rewrite vlookup_replicate; done.\n - exists (replicate (length (gcd_addr_list gcdata)) []).\n split; first by rewrite replicate_length.\n intros i Hi.\n exists []; split; first by rewrite lookup_replicate_2.\n split.\n { intros ????; rewrite lookup_nil; done. }\n rewrite lookup_total_replicate_2; last done.\n rewrite events_of_singleton_trace; done.\n - exists (replicate (length (gcd_addr_list gcdata)) []).\n split; first by rewrite replicate_length.\n intros i Hi.\n exists []; split; first by rewrite lookup_replicate_2.\n rewrite lookup_total_replicate_2; last done.\n rewrite events_of_singleton_trace; done.\n Qed.\n\n Lemma crdt_main_rel_step (ps : programs_using_gcounters gcdata) v ex\n (atr atr': auxiliary_trace (@aneris_AS (GCounterM gcdata))) ex' oζ ℓ:\n valid_system_trace ex atr →\n trace_contract ex oζ ex' →\n trace_contract atr ℓ atr' →\n crdt_main_rel ex' atr' →\n trace_starts_in ex\n ([{| expr_n := \"system\"; expr_e := runner gcdata 0 (progs ps) v |}], init_state gcdata) →\n trace_starts_in atr (initial_crdt_state (GClen gcdata)) →\n valid_state_evolution ex' atr' oζ ℓ (trace_last ex) (trace_last atr) →\n (∀ i : fin (length (gcd_addr_list gcdata)),\n match locs_of_trace_now ex !!! (fin_to_nat i) with\n | Some l =>\n ∃ h : heap,\n (trace_last ex).2.(state_heaps) !! ip_of_address (ith_sa (fin_to_nat i)) = Some h ∧\n h !! l = Some (vector_clock_to_val (vec_to_list ((trace_last atr) !!! i)))\n | None => (trace_last atr) !!! i = vreplicate (length (gcd_addr_list gcdata)) 0\n end) →\n send_evs_rel (locs_of_trace_now ex) ex →\n receive_evs_rel (locs_of_trace_now ex) ex →\n crdt_main_rel ex atr.\n Proof.\n intros Hvls [c ->] [δ ->] Hmrel Hex's Hatr's Hvse Hstrel Hsevsrel Hrevsrel; simpl in *.\n rewrite /crdt_main_rel /=; split_and!.\n - eapply valid_system_trace_valid_exec_trace; by eauto.\n - split.\n + constructor; first by apply Hmrel.\n destruct Hmrel as (_ & [Hvst _] & _).\n apply trace_forall_last in Hvst.\n destruct Hvse as [<-|]; first done.\n eapply CrdtNext_preserves_validity; done.\n + destruct Hmrel as (_ & [_ Hststep] & _).\n econstructor; [done | | done].\n destruct Hvse as [<-|]; by auto.\n - constructor; [by apply Hmrel|done].\n - done.\n - done.\n Qed.\n\n CoFixpoint locs_of_inf_trace\n (ex : execution_trace aneris_lang)\n (iex: inf_execution_trace aneris_lang) : inflist (() * list (option loc)) :=\n match iex with\n | []%inflist => []\n | ((oζ, c) :: iex')%inflist =>\n (tt, (locs_of_trace_now (ex :tr[oζ]: c))) :: locs_of_inf_trace (ex :tr[oζ]: c) iex'\n end.\n\n Lemma locs_of_inf_trace_take ex iex n :\n ((locs_of_trace ex) +trl+ (inflist_take n (locs_of_inf_trace ex iex))) =\n locs_of_trace (ex +trl+ (inflist_take n iex)).\n Proof.\n revert ex iex; induction n as [|n IHn]; intros ex iex; simpl; first done.\n destruct iex as [|[??]?]; simpl; first done.\n rewrite -IHn; done.\n Qed.\n\n Lemma locs_of_inf_trace_length ex iex : inflist_same_length (locs_of_inf_trace ex iex) iex.\n Proof.\n intros n.\n revert ex iex.\n induction n; simpl; intros ex iex.\n - rewrite (inflist_unfold_fold (locs_of_inf_trace ex iex)).\n destruct iex as [|[??]?]; simpl; done.\n - destruct iex as [|[??]?]; done.\n Qed.\n\n Lemma locs_of_inf_trace_cons_inv ex iex lcs ilocs:\n locs_of_inf_trace ex iex = (lcs :: ilocs)%inflist →\n ∃ oζ c iex',\n iex = ((oζ, c):: iex')%inflist ∧\n lcs = (tt, locs_of_trace_now (ex :tr[oζ]: c)) ∧\n ilocs = locs_of_inf_trace (ex :tr[oζ]: c) iex'.\n Proof.\n rewrite (inflist_unfold_fold (locs_of_inf_trace ex iex)).\n destruct iex as [|[??]?]; simpl; first done.\n intros; simplify_eq; eauto 10.\n Qed.\n\n Lemma locs_of_inf_trace_less_defined ex iex :\n valid_inf_exec ex iex →\n always\n (λ locs ilocs, trace_steps (λ x _ y, locs_less_defined x y) locs)\n (locs_of_trace ex) (locs_of_inf_trace ex iex).\n Proof.\n intros Hvex.\n apply always_take_drop; intros n.\n rewrite locs_of_inf_trace_take.\n apply locs_of_trace_less_defined.\n eapply valid_inf_exe_valid_exec.\n apply valid_inf_exe_take_drop; done.\n Qed.\n\n Definition crdt_main_rel_ternary\n (locs : finite_trace (list (option loc)) ()) (ex: execution_trace aneris_lang)\n (mtr : finite_trace (GCounterM gcdata) ())\n (ilocs : inflist (() * list (option loc))) (iex: inf_execution_trace aneris_lang)\n (imtr : inflist (() * GCounterM gcdata)) : Prop :=\n valid_exec ex ∧\n valid_model_fin_trace mtr ∧\n gcounter_values_related locs ex mtr ∧\n send_evs_rel (trace_last locs) ex ∧\n receive_evs_rel (trace_last locs) ex.\n\n Lemma crdt_main_rel_ternary_crdt_main_rel ex mtr ilocs iex imtr :\n crdt_main_rel_ternary (locs_of_trace ex) ex mtr ilocs iex imtr → crdt_main_rel ex mtr.\n Proof. intros (?&?&?&?&?); split_and!; done. Qed.\n\n (* move *)\n Lemma valid_inf_system_trace_take_drop n\n {Λ : language} {AS : AuxState Λ} (φ : execution_trace Λ → auxiliary_trace AS → Prop)\n (ex : execution_trace Λ) (atr : auxiliary_trace AS)\n (iex : inf_execution_trace Λ) (iatr : inf_auxiliary_trace AS) :\n valid_inf_system_trace φ ex atr iex iatr →\n valid_inf_system_trace φ\n (ex +trl+ inflist_take n iex) (atr +trl+ inflist_take n iatr)\n (inflist_drop n iex) (inflist_drop n iatr).\n Proof.\n revert ex atr iex iatr.\n induction n as [|n IHn]; first done.\n intros ex atr iex iatr Hvisf.\n inversion Hvisf; simplify_eq/=; first done.\n apply IHn; done.\n Qed.\n Lemma valid_inf_system_trace_length\n {Λ : language} {AS : AuxState Λ} (φ : execution_trace Λ → auxiliary_trace AS → Prop)\n (ex : execution_trace Λ) (atr : auxiliary_trace AS)\n (iex : inf_execution_trace Λ) (iatr : inf_auxiliary_trace AS) :\n valid_inf_system_trace φ ex atr iex iatr → inflist_same_length iex iatr.\n Proof.\n intros Hvisf n.\n apply (valid_inf_system_trace_take_drop n) in Hvisf.\n inversion Hvisf; simplify_eq/=; done.\n Qed.\n Lemma valid_inf_system_trace_mono\n {Λ : language} {AS : AuxState Λ} (φ ψ : execution_trace Λ → auxiliary_trace AS → Prop)\n (ex : execution_trace Λ) (atr : auxiliary_trace AS)\n (iex : inf_execution_trace Λ) (iatr : inf_auxiliary_trace AS) :\n (∀ (ex' : execution_trace Λ) (atr' : auxiliary_trace AS), φ ex' atr' → ψ ex' atr') →\n valid_inf_system_trace φ ex atr iex iatr → valid_inf_system_trace ψ ex atr iex iatr.\n Proof.\n revert ex atr iex iatr; cofix IH; intros ex atr iex iatr Hφψ Hφ.\n inversion Hφ; simplify_eq.\n - constructor; apply Hφψ; done.\n - econstructor; eauto.\n Qed.\n Lemma valid_inf_system_trace_rel\n {Λ : language} {AS : AuxState Λ} (φ : execution_trace Λ → auxiliary_trace AS → Prop)\n (ex : execution_trace Λ) (atr : auxiliary_trace AS)\n (iex : inf_execution_trace Λ) (iatr : inf_auxiliary_trace AS) :\n valid_inf_system_trace φ ex atr iex iatr → φ ex atr.\n Proof. inversion 1; done. Qed.\n\n Lemma crdt_main_rel_always_ternary\n (ex : execution_trace aneris_lang) (iex : inf_execution_trace aneris_lang)\n (atr : auxiliary_trace (@aneris_AS (GCounterM gcdata))) :\n valid_inf_exec ex iex →\n continued_simulation crdt_main_rel ex atr →\n ∃ imtr,\n always3\n crdt_main_rel_ternary\n (locs_of_trace ex) ex atr (locs_of_inf_trace ex iex) iex imtr.\n Proof.\n intros Hvl Hcs.\n pose proof (produced_inf_aux_trace_valid_inf _ _ Hcs iex Hvl) as Hvisf.\n exists (produce_inf_aux_trace ex atr Hcs iex Hvl).\n pose proof (valid_inf_system_trace_length _ _ _ _ _ Hvisf) as Hlen.\n apply (valid_inf_system_trace_mono _ crdt_main_rel) in Hvisf; last first.\n { apply continued_simulation_rel. }\n revert Hlen Hvisf.\n generalize (produce_inf_aux_trace ex atr Hcs iex Hvl); intros iatr.\n clear Hcs.\n revert ex iex atr iatr Hvl.\n cofix IH; intros ex iex atr iatr Hvl Hlen Hvisf.\n constructor; [| | |].\n - apply valid_inf_system_trace_rel in Hvisf; done.\n - apply locs_of_inf_trace_length.\n - eapply inflist_same_length_trans; done.\n - simpl.\n intros ?????????\n (?&?&?&?&?&?)%locs_of_inf_trace_cons_inv\n -> ->; simplify_eq.\n apply (IH (_ :tr[_]: _)).\n + apply traces.valid_inf_exec_adjust; done.\n + rewrite -inflist_same_length_cons; done.\n + apply (valid_inf_system_trace_take_drop 1) in Hvisf; done.\n Qed.\n\n Lemma eventually_sent_eventually_exists_loc_one i ex iex mtr imtr :\n i < GClen gcdata →\n valid_inf_exec ex iex →\n eventually (λ ex' _, events_of_trace (sendonEV (ith_sa i)) ex' ≠ []) ex iex →\n always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr →\n eventually3\n (always3 (λ locs _ _ _ _ _, ∃ l, (trace_last locs) !! i = Some (Some l)))\n (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n Proof.\n intros Hi Hvex Hev Hal.\n apply eventually_take_drop in Hev as [n Hev].\n assert ((always (λ ex' _, events_of_trace (sendonEV (ith_sa i)) ex' ≠ []))\n (ex +trl+ inflist_take n iex) (inflist_drop n iex)) as Hev'.\n { apply always_take_drop; intros k.\n destruct (events_of_trace_app\n (sendonEV (ith_sa i))\n (ex +trl+ inflist_take n iex)\n (inflist_take k (inflist_drop n iex))) as (evs & ? & -> & _).\n { rewrite trace_append_list_assoc -inflist_take_add.\n eapply valid_inf_exe_valid_exec; eapply valid_inf_exe_take_drop; done. }\n intros []%app_eq_nil; simplify_eq. }\n clear Hev.\n apply eventually3_take_drop; exists n.\n split; last by eapply always3_inflist_same_length; eauto.\n apply (always3_unroll_n _ n) in Hal.\n apply always3_take_drop; intros k.\n split; last by eapply always3_inflist_same_length; eauto.\n apply (always3_unroll_n _ k), always3_holds in Hal.\n apply (always_unroll_n _ k), always_holds in Hev'.\n revert Hal Hev'.\n rewrite !trace_append_list_assoc -!inflist_take_add.\n intros Hal Hev.\n destruct Hal as (_&_&_& (sevss & Hlen & Hsevs) &_).\n specialize (Hsevs i Hi) as (sevs & ? & ? & Hlocs).\n rewrite list_lookup_total_alt in Hlocs.\n revert Hlocs.\n rewrite locs_of_inf_trace_take locs_of_trace_last.\n destruct (lookup_lt_is_Some_2 (locs_of_trace_now (ex +trl+ inflist_take (n + k) iex)) i)\n as [ol Hol].\n { rewrite locs_of_trace_now_length; done. }\n rewrite Hol; simpl.\n destruct ol; first by eauto.\n intros [? ?]; simplify_eq.\n Qed.\n\n Lemma eventually_sent_eventually_exists_loc_all ex iex mtr imtr :\n (∀ i, i < GClen gcdata →\n eventually (λ ex' _, events_of_trace (sendonEV (ith_sa i)) ex' ≠ []) ex iex) →\n valid_inf_exec ex iex →\n always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr →\n eventually3\n (λ locs ex' mtr' ilocs' iex' imtr',\n ∀ (j : fin (S (GClen gcdata))),\n always3 (λ locs' ex'' mtr'' ilocs'' iex'' imtr'',\n match fin_to_nat j with\n | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n | S k => ∃ l, (trace_last locs') !! k = Some (Some l)\n end) locs ex' mtr' ilocs' iex' imtr')\n (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n Proof.\n intros Hev Hvex Hal.\n apply eventually3_forall_combine.\n intros j.\n destruct (fin_to_nat j) as [|j'] eqn:Hj'.\n - pose proof (always3_inflist_same_length _ _ _ _ _ _ _ Hal) as [? ?].\n apply holds_eventually3; done.\n - assert (j' < GClen gcdata).\n { assert (S j' < S (GClen gcdata)) by by rewrite -Hj'; apply fin_to_nat_lt. lia. }\n apply eventually_sent_eventually_exists_loc_one; auto.\n Qed.\n\n Lemma eventually_sent_eventually_allocated_helper len locs ex mtr ilocs iex imtr :\n (∀ j : fin (S len),\n always3\n (λ locs' ex'' mtr'' ilocs'' iex'' imtr'',\n match fin_to_nat j with\n | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n | S k => ∃ l : loc, trace_last locs' !! k = Some (Some l)\n end) locs ex mtr ilocs iex imtr) →\n ∃ lcssg : {lcs : list loc | length lcs = len},\n take len (trace_last locs) = Some <$> `lcssg ∧\n always3 crdt_main_rel_ternary locs ex mtr ilocs iex imtr.\n Proof.\n intros Hex.\n induction len as [|n IHn].\n - exists (exist (λ l, length l = 0) (@nil loc) eq_refl).\n rewrite take_0 /=.\n split; first done.\n specialize (Hex 0%fin); done.\n - destruct IHn as [[lcs Hlcslen] [Hlcs1 Hlcs2]].\n { intros j.\n assert (fin_to_nat j < S (S n)) as Hlt.\n { etrans; first apply fin_to_nat_lt; lia. }\n specialize (Hex (nat_to_fin Hlt)).\n eapply always3_mono; last apply Hex.\n clear.\n rewrite fin_to_nat_to_fin; done. }\n assert (S n < S (S n)) as Hlt by lia.\n specialize (Hex (nat_to_fin Hlt)).\n apply always3_holds in Hex.\n rewrite fin_to_nat_to_fin in Hex.\n destruct Hex as [l Hl].\n assert (length (lcs ++ [l]) = S n) as Hlcslen'.\n { rewrite app_length Hlcslen; simpl; lia. }\n exists (exist _ (lcs ++ [l]) Hlcslen').\n split; last done.\n erewrite take_S_r; last by eauto.\n rewrite Hlcs1 fmap_app; simpl; done.\n Qed.\n\n Lemma eventually_sent_eventually_allocated_helper' locs ex mtr ilocs iex imtr :\n length (trace_last locs) = GClen gcdata →\n (∀ j : fin (S (GClen gcdata)),\n always3\n (λ locs' ex'' mtr'' ilocs'' iex'' imtr'',\n match fin_to_nat j with\n | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n | S k => ∃ l : loc, trace_last locs' !! k = Some (Some l)\n end) locs ex mtr ilocs iex imtr) →\n ∃ lcssg : {lcs : list loc | length lcs = GClen gcdata},\n trace_last locs = Some <$> `lcssg ∧\n always3 crdt_main_rel_ternary locs ex mtr ilocs iex imtr.\n Proof.\n intros Hlen Hex.\n rewrite -(firstn_all (trace_last locs)) Hlen.\n apply eventually_sent_eventually_allocated_helper; done.\n Qed.\n\n Lemma eventually_sent_eventually_allocated ex iex mtr imtr :\n (∀ i, i < GClen gcdata →\n eventually (λ ex' _, events_of_trace (sendonEV (ith_sa i)) ex' ≠ []) ex iex) →\n valid_inf_exec ex iex →\n always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr →\n ∃ lcs : list loc,\n length lcs = GClen gcdata ∧\n eventually3\n (λ locs ex' mtr' ilocs' iex' imtr',\n (trace_last locs = Some <$> lcs) ∧\n always3 crdt_main_rel_ternary locs ex' mtr' ilocs' iex' imtr')\n (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n Proof.\n intros Hev Hvex Hal.\n cut (∃ lcssg : {lcs : list loc | length lcs = GClen gcdata},\n eventually3\n (λ locs ex' mtr' ilocs' iex' imtr',\n (trace_last locs = Some <$> `lcssg) ∧\n always3 crdt_main_rel_ternary locs ex' mtr' ilocs' iex' imtr')\n (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr).\n { intros [[? ?] ?]; eauto. }\n apply eventually3_exists.\n epose proof (eventually_sent_eventually_exists_loc_all _ _ _ _ Hev Hvex Hal) as Hex.\n apply eventually3_take_drop in Hex as [n [Hex [Hilen1 Hilen2]]].\n apply eventually3_take_drop.\n exists n; split; last done.\n apply eventually_sent_eventually_allocated_helper'; last done.\n rewrite locs_of_inf_trace_take locs_of_trace_last locs_of_trace_now_length; done.\n Qed.\n\n Definition crdt_main_rel_locs_resolved (locs : list loc) (ex: execution_trace aneris_lang)\n (mtr : finite_trace (GCounterM gcdata) ())\n (iex: inf_execution_trace aneris_lang)\n (imtr : inflist (() * GCounterM gcdata)) : Prop :=\n valid_model_fin_trace mtr ∧\n gcounter_values_related_now_locs_resolved locs (trace_last ex) (trace_last mtr) ∧\n send_evs_rel_locs_resolved locs ex ∧\n receive_evs_rel_locs_resolved locs ex.\n\n Definition monotone_from_now_on locs ex iex :=\n (always (λ ex' _,\n ∃ l, ex' = ex +trl+ l ∧\n gcounter_monotone_locs_resolved locs (trace_last ex :: map snd l)) ex iex).\n\n (* TODO: put in aneris *)\n\n Lemma monotone_from_now_on_unroll_n n locs ex iex :\n monotone_from_now_on locs ex iex →\n monotone_from_now_on locs (ex +trl+ inflist_take n iex) (inflist_drop n iex).\n Proof.\n intros Hfno.\n apply always_take_drop; intros m.\n apply (always_unroll_n _ n) in Hfno.\n apply (always_unroll_n _ m) in Hfno.\n apply always_holds in Hfno.\n destruct Hfno as [l [Hl Hgms]].\n rewrite Hl.\n rewrite !trace_append_list_assoc -!inflist_take_add in Hl.\n apply trace_append_list_inj2 in Hl.\n rewrite inflist_take_add in Hl.\n simplify_eq.\n eexists _; split.\n { rewrite !trace_append_list_assoc; done. }\n intros i j ?????.\n apply (Hgms (length (inflist_take n iex) + i) (length (inflist_take n iex) + j)).\n - lia.\n - destruct i as [|i]; simpl in *.\n + rewrite map_app (lookup_app_l (_ :: _)) /=; last by rewrite map_length /=; lia.\n rewrite Nat.add_0_r.\n rewrite trace_last_of_append_list_map //.\n + rewrite Nat.add_comm /= Nat.add_comm.\n rewrite map_app lookup_app_r; last by rewrite map_length; lia.\n rewrite map_length minus_plus; done.\n - destruct j as [|j]; simpl in *.\n + rewrite map_app (lookup_app_l (_ :: _)); last by rewrite /= map_length /=; lia.\n rewrite Nat.add_0_r.\n rewrite trace_last_of_append_list_map; done.\n + rewrite Nat.add_comm /= Nat.add_comm.\n rewrite map_app lookup_app_r; last by rewrite map_length; lia.\n rewrite map_length minus_plus; done.\n Qed.\n\n Definition closed_model_relation locs ex mtr iex imtr :=\n (monotone_from_now_on locs ex iex) ∧\n always2 (crdt_main_rel_locs_resolved locs) ex mtr iex imtr.\n\n Lemma eventually_sent_eventually_locs_resolved ex iex mtr imtr :\n (∀ i, i < GClen gcdata →\n eventually (λ ex' _, events_of_trace (sendonEV (ith_sa i)) ex' ≠ []) ex iex) →\n valid_inf_exec ex iex →\n always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr →\n ∃ locs, length locs = GClen gcdata ∧ eventually2 (closed_model_relation locs) ex mtr iex imtr.\n Proof.\n intros Hev Hvl Hal3.\n edestruct (eventually_sent_eventually_allocated ex iex mtr imtr) as (locs & Hlocslen & Hal);\n [done|done|done|].\n exists locs; split; first done.\n apply eventually3_take_drop in Hal as [n [[Hex1 Hex2] [Hilen1 Hilen2]]].\n apply eventually2_take_drop.\n exists n; split; last done.\n split.\n - apply always_take_drop; intros k.\n apply (always3_unroll_n _ n), (always3_unroll_n _ k), always3_holds in Hal3.\n rewrite !trace_append_list_assoc -!inflist_take_add in Hal3.\n rewrite !locs_of_inf_trace_take in Hal3.\n apply crdt_main_rel_ternary_crdt_main_rel in Hal3.\n apply crdt_main_rel_monotone in Hal3.\n rewrite !inflist_take_add -!trace_append_list_assoc in Hal3.\n pose proof (locs_of_inf_trace_less_defined _ _ Hvl) as Hld.\n apply (always_unroll_n _ n), (always_unroll_n _ k), always_holds in Hld.\n eexists _; split; first reflexivity.\n eapply (gcounter_monotone_resolve_locs\n locs\n (ex +trl+ inflist_take n iex)\n (inflist_take\n k\n (locs_of_inf_trace (ex +trl+ inflist_take n iex) (inflist_drop n iex)))).\n + apply inflist_take_of_same_length, locs_of_inf_trace_length.\n + done.\n + eapply valid_inf_exe_valid_exec.\n do 2 apply valid_inf_exe_take_drop; done.\n + rewrite -locs_of_inf_trace_take; done.\n + rewrite !locs_of_inf_trace_take.\n rewrite trace_append_list_assoc -inflist_take_add.\n rewrite trace_append_list_assoc in Hld.\n rewrite -inflist_take_add in Hld.\n rewrite !locs_of_inf_trace_take in Hld.\n done.\n + rewrite !locs_of_inf_trace_take. done.\n - apply always2_take_drop; intros k; split; last by apply inflist_same_length_drop.\n apply (always3_unroll_n _ k), always3_holds in Hex2.\n pose proof (locs_of_inf_trace_less_defined _ _ Hvl) as Hld.\n apply (always_unroll_n _ n), (always_unroll_n _ k), always_holds in Hld.\n eapply trace_append_list_steps_rtc_nl in Hld; [|done|done].\n revert Hld; rewrite rt_rtc_same.\n rewrite !trace_append_list_assoc -!inflist_take_add.\n rewrite !trace_append_list_assoc -!inflist_take_add in Hex2.\n intros Hld.\n apply locs_all_defined in Hld.\n destruct Hex2 as (_ & vmf & Hvrel%trace_forall3_last & Hsevs & Hrevs).\n rewrite Hld in Hvrel, Hrevs, Hsevs.\n split_and!.\n + done.\n + apply gcounter_values_related_now_resolve_locs; auto.\n + apply send_evs_rel_resolve_locs; auto.\n + apply receive_evs_rel_resolve_locs; auto.\n Qed.\n\nEnd crdt_main_rel.\n", "meta": {"author": "fresheed", "repo": "trillium-experiments", "sha": "a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef", "save_path": "github-repos/coq/fresheed-trillium-experiments", "path": "github-repos/coq/fresheed-trillium-experiments/trillium-experiments-a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef/theories/crdt/gcounter_convergence/crdt_main_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.25386101825929835, "lm_q1q2_score": 0.14563458466926676}} {"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import RealmSyncHandlerAux.Spec.\nRequire Import RealmSyncHandler.Specs.handle_data_abort.\nRequire Import RealmSyncHandler.LowSpecs.handle_data_abort.\nRequire Import RealmSyncHandler.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n Hint Unfold\n sysreg_read_spec\n access_in_par_spec\n set_rec_last_run_info_esr_spec\n esr_is_write_spec\n get_write_value_spec\n set_rec_run_esr_spec\n set_rec_run_far_spec\n set_rec_run_hpfar_spec\n set_rec_run_emulated_write_val_spec\n .\n\n Lemma handle_data_abort_spec_exists:\n forall habd habd' labd rec esr\n (Hspec: handle_data_abort_spec rec esr habd = Some habd')\n (Hrel: relate_RData habd labd),\n exists labd', handle_data_abort_spec0 rec esr labd = Some labd' /\\ relate_RData habd' labd'.\n Proof.\n Local Opaque ptr_eq.\n intros. destruct Hrel. destruct rec.\n unfold handle_data_abort_spec, handle_data_abort_spec0 in *.\n repeat autounfold in *. simpl in *.\n rewrite get_reg_85, get_reg_94.\n hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec; repeat destruct_con;\n destruct (Z.land (r_spsr_el2 (cpu_regs (priv labd))) 16 =? 0);\n repeat destruct_dis; try match goal with\n | [H: negb ?a = true |- _] => apply negb_true_iff in H\n | [H: negb ?a = false |- _] => apply negb_false_iff in H\n end; simpl;\n repeat (repeat grewrite; simpl; try solve_bool_range);\n try solve[eexists; split; [reflexivity|constructor; reflexivity]].\n - unfold ref_accessible in *.\n destruct (__esr_is_write z0);\n repeat (repeat grewrite; simpl; try solve_bool_range; try rewrite ZMap.gss; repeat simpl_update_reg).\n destruct (__esr_srt z0 =? 31); simpl.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n solve_bool_range. grewrite.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n assumption. assumption.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n - unfold ref_accessible in *.\n destruct (__esr_is_write (Z.land z0 18446744073692774399));\n repeat (repeat grewrite; simpl; try solve_bool_range; try rewrite ZMap.gss; repeat simpl_update_reg).\n destruct (__esr_srt (Z.land z0 18446744073692774399) =? 31); simpl.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n solve_bool_range. grewrite.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n assumption. assumption.\n eexists; split. reflexivity. constructor; simpl. reflexivity.\n Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmSyncHandler/RefProof/handle_data_abort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.14509833139742118}} {"text": "Require Import Coq.ZArith.BinInt.\nRequire Import riscv.util.Monads.\nRequire Import riscv.Utility.\nRequire Import riscv.Decode.\nRequire Import riscv.Memory.\nRequire Import riscv.Program.\nRequire Import riscv.RiscvMachine.\nRequire Import riscv.util.BitWidths.\n\n\nSet Implicit Arguments.\n\n(* Note: Register 0 is not considered valid because it cannot be written *)\nDefinition valid_register(r: Register): Prop := (0 < r < 32)%Z.\n\nSection AxiomaticRiscv.\n\n Context {t: Set}.\n Context {MW: MachineWidth t}.\n Context {RF: Type}.\n Context {RFI: RegisterFile RF Register t}.\n\n Context {Mem: Set}.\n Context {MemIsMem: Memory Mem t}.\n\n Local Notation RiscvMachine := (@RiscvMachine t Mem RF).\n\n Context {RVM: RiscvProgram (OState RiscvMachine) t}.\n \n (* assumes generic translate and raiseException functions *)\n Context {RVS: @RiscvState (OState RiscvMachine) t _ _ RVM}. \n\n Class AxiomaticRiscv := mkAxiomaticRiscv {\n \n Bind_getRegister0: forall {A: Type} (f: t -> OState RiscvMachine A),\n Bind (getRegister Register0) f = f (ZToReg 0);\n \n Bind_getRegister: forall {A: Type} x (f: t -> OState RiscvMachine A)\n (initialL: RiscvMachine),\n valid_register x ->\n (Bind (getRegister x) f) initialL =\n (f (getReg initialL.(core).(registers) x)) initialL;\n\n Bind_setRegister: forall {A: Type} x (v: t)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n valid_register x ->\n (Bind (setRegister x v) f) initialL =\n (f tt) (with_registers (setReg initialL.(core).(registers) x v) initialL);\n\n Bind_setRegister0: forall {A: Type} (v: t)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (setRegister Register0 v) f) initialL =\n (f tt) initialL;\n\n Bind_loadByte: forall {A: Type} (addr: t) (f: word 8 -> OState RiscvMachine A)\n (initialL: RiscvMachine),\n (Bind (loadByte addr) f) initialL =\n (f (Memory.loadByte initialL.(machineMem) addr)) initialL;\n\n Bind_loadHalf: forall {A: Type} (addr: t) (f: word 16 -> OState RiscvMachine A)\n (initialL: RiscvMachine),\n (Bind (loadHalf addr) f) initialL =\n (f (Memory.loadHalf initialL.(machineMem) addr)) initialL;\n\n Bind_loadWord: forall {A: Type} (addr: t) (f: word 32 -> OState RiscvMachine A)\n (initialL: RiscvMachine),\n (Bind (loadWord addr) f) initialL =\n (f (Memory.loadWord initialL.(machineMem) addr)) initialL;\n \n Bind_loadDouble: forall {A: Type} (addr: t) (f: word 64 -> OState RiscvMachine A)\n (initialL: RiscvMachine),\n (Bind (loadDouble addr) f) initialL =\n (f (Memory.loadDouble initialL.(machineMem) addr)) initialL;\n\n Bind_storeByte: forall {A: Type} (addr: t) (v: word 8)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (storeByte addr v) f) initialL =\n (f tt) (with_machineMem (Memory.storeByte initialL.(machineMem) addr v)\n initialL);\n\n Bind_storeHalf: forall {A: Type} (addr: t) (v: word 16)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (storeHalf addr v) f) initialL =\n (f tt) (with_machineMem (Memory.storeHalf initialL.(machineMem) addr v)\n initialL);\n\n Bind_storeWord: forall {A: Type} (addr: t) (v: word 32)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (storeWord addr v) f) initialL =\n (f tt) (with_machineMem (Memory.storeWord initialL.(machineMem) addr v)\n initialL);\n\n Bind_storeDouble: forall {A: Type} (addr: t) (v: word 64)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (storeDouble addr v) f) initialL =\n (f tt) (with_machineMem (Memory.storeDouble initialL.(machineMem) addr v)\n initialL);\n\n Bind_getPC: forall {A: Type} (f: t -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind getPC f) initialL =\n (f initialL.(core).(pc)) initialL;\n\n Bind_setPC: forall {A: Type} (v: t)\n (f: unit -> OState RiscvMachine A) (initialL: RiscvMachine),\n (Bind (setPC v) f) initialL =\n (f tt) (with_nextPC v initialL);\n \n Bind_step: forall {A: Type} (f: unit -> OState RiscvMachine A) m,\n (Bind step f) m =\n (f tt) (with_nextPC (add m.(core).(nextPC) (ZToReg 4)) (with_pc m.(core).(nextPC) m));\n\n execState_step: forall m,\n step m = (Some tt, with_nextPC (add m.(core).(nextPC) (ZToReg 4)) (with_pc m.(core).(nextPC) m));\n \n execState_Return: forall {S A} (s: S) (a: A),\n (Return a) s = (Some a, s);\n\n }.\n\nEnd AxiomaticRiscv.\n", "meta": {"author": "samuelgruetter", "repo": "riscv-coq", "sha": "bd89fbff49704b4476633a88abdedb4e410c200b", "save_path": "github-repos/coq/samuelgruetter-riscv-coq", "path": "github-repos/coq/samuelgruetter-riscv-coq/riscv-coq-bd89fbff49704b4476633a88abdedb4e410c200b/src/AxiomaticRiscv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.1446633646952621}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of PM: PKContext *)\n(* *)\n(* Provide abstraction of Context *)\n(* *)\n(* Ronghui Gu *)\n(* Yu Guo *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the PKContext layer, \nwhich will introduce abstraction of kernel context*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\n\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\n\nRequire Import AbstractDataType.\n\nRequire Export MShare.\nRequire Export ObjThread.\n\n(** * Abstract Data and Primitives at MPMap layer*)\n(** The abstract data at MPMap layer is the same with MPTNew layer*)\nSection WITHMEM.\n\n Local Open Scope Z_scope.\n\n Context `{real_params: RealParams}.\n\n (** **Definition of the raw data at MPTBit layer*)\n (*Record RData :=\n mkRData {\n HP: flatmem; (**r we model the memory from 1G to 3G as heap*)\n ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)\n pe: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)\n ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)\n ihost: bool; (**r logic flag, shows whether it's in the host mode or not*) \n\n AT: ATable; (**r allocation table*)\n nps: Z; (**r number of the pages*)\n\n PT: Z; (**r the current page table index*)\n ptpool: PTPool; (**r page table pool*)\n ipt: bool; (**r pure logic flag, shows whether it's using the kernel's page table*)\n pb : PTBitMap; (**r [page table bit map], indicating which page table has been used*)\n\n kctxt: KContextPool (**r kernel context pool*)\n }.*)\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** * Proofs that the primitives satisfies the invariants at this layer *)\n Section INV.\n\n Global Instance kctxt_switch_inv: KCtxtSwitchInvariants kctxt_switch_spec.\n Proof.\n constructor; intros; functional inversion H. \n - inv H1. constructor; trivial. \n eapply kctxt_inject_neutral_gss_mem; eauto.\n - inv H0. subst. constructor; auto; simpl in *; intros; try congruence.\n Qed.\n\n Require Import compcert.cfrontend.Ctypes.\n\n Section kctxt_ra.\n\n Inductive extcall_kctxtra_sem (s: stencil) (WB: block -> Prop):\n list val -> (mwd (cdata RData)) -> val -> (mwd (cdata RData)) -> Prop :=\n | extcall_kctxtra_sem_intro: \n forall m adt adt' n b ofs,\n (exists fun_id, find_symbol s fun_id = Some b) ->\n kctxt_ra_spec adt (Int.unsigned n) b ofs = Some adt'\n -> extcall_kctxtra_sem s WB (Vint n::Vptr b ofs::nil) (m, adt) Vundef (m, adt'). \n\n Definition extcall_kctxtra_info: sextcall_info :=\n {|\n sextcall_step := extcall_kctxtra_sem;\n sextcall_csig := mkcsig (type_of_list_type (Tint32::Tpointer Tvoid noattr::nil)) Tvoid;\n sextcall_valid s := true\n |}.\n\n Global Instance extcall_kctxtra_invs:\n ExtcallInvariants extcall_kctxtra_info.\n Proof.\n constructor; intros; inv H;\n try (unfold kctxt_ra_spec in *; \n inv H0; subdestruct; inv H8; constructor; simpl; eauto 2); try congruence.\n - (* low_level_invariant *) \n eapply kctxt_inject_neutral_gss_ptr; eauto.\n - (* nextblock *)\n reflexivity.\n - (* inject neutral *)\n split; auto.\n - (* well typed *)\n simpl. trivial.\n Qed.\n\n Global Instance extcall_kctxtra_props:\n ExtcallProperties extcall_kctxtra_info.\n Proof.\n constructor; intros.\n - (* well typed *)\n inv H. simpl. trivial.\n - (* valid_block *)\n inv H. unfold Mem.valid_block in *.\n lift_unfold. trivial.\n - (* perm *)\n inv H. lift_unfold. trivial.\n - (* unchanges *)\n inv H. simpl. apply Mem.unchanged_on_refl.\n - (* extend *)\n inv H. inv_val_inject. lift_simpl.\n destruct H0 as [HT1 HT2].\n destruct m1' as [? ?]. simpl in *. subst.\n exists Vundef, (m0, adt'). \n refine_split; eauto.\n + econstructor; eauto.\n + lift_unfold. split; trivial.\n + simpl. apply Mem.unchanged_on_refl.\n - (* inject *)\n inv H0. destruct H3 as [fun_id Hsymbol].\n pose proof Hsymbol as Hsymbol'. apply H in Hsymbol'. \n inv_val_inject.\n lift_simpl. destruct H1 as [HT1 HT2].\n destruct m1' as [? ?]. simpl in *. subst.\n exists f, Vundef, (m0, adt'). \n refine_split; eauto.\n + econstructor; eauto.\n + lift_unfold. split; trivial.\n + apply Mem.unchanged_on_refl.\n + simpl. apply Mem.unchanged_on_refl.\n + constructor; congruence.\n - (* deterministic*)\n inv H. inv H0. rewrite H2 in H10.\n inv H10. split; reflexivity.\n - (* WB *)\n inv H0. econstructor; eauto.\n - (* load *)\n inv H. lift_unfold. trivial.\n Qed.\n\n Definition kctxt_ra_compatsem : compatsem (cdata RData) :=\n compatsem_inl {|\n sextcall_primsem_step := extcall_kctxtra_info;\n sextcall_props := OK _;\n sextcall_invs := OK _\n |}.\n\n End kctxt_ra.\n\n Section kctxt_sp.\n\n Inductive extcall_kctxtsp_sem (s: stencil) (WB: block -> Prop):\n list val -> (mwd (cdata RData)) -> val -> (mwd (cdata RData)) -> Prop :=\n | extcall_kctxtsp_sem_intro: \n forall m adt adt' n b ofs,\n (exists fun_id, find_symbol s fun_id = Some b) ->\n (Int.unsigned ofs) = ((Int.unsigned n) + 1) * PgSize - 4 ->\n kctxt_sp_spec adt (Int.unsigned n) b ofs = Some adt' ->\n extcall_kctxtsp_sem s WB (Vint n::Vptr b ofs::nil) (m, adt) Vundef (m, adt'). \n\n Definition extcall_kctxtsp_info: sextcall_info :=\n {|\n sextcall_step := extcall_kctxtsp_sem;\n sextcall_csig := mkcsig (type_of_list_type (Tint32::Tpointer Tvoid noattr::nil)) Tvoid;\n sextcall_valid s := true\n |}.\n\n Global Instance extcall_kctxtsp_invs:\n ExtcallInvariants extcall_kctxtsp_info.\n Proof.\n constructor; intros; inv H;\n try (unfold kctxt_sp_spec in *;\n inv H0; subdestruct; inv H9; constructor; simpl; eauto 2); try congruence.\n - (* low_level_invariant *)\n eapply kctxt_inject_neutral_gss_ptr; eauto.\n - (* nextblock *)\n reflexivity.\n - (* well typed *)\n simpl. trivial.\n Qed.\n\n Global Instance extcall_kctxtsp_props:\n ExtcallProperties extcall_kctxtsp_info.\n Proof.\n constructor; intros.\n - (* well typed *)\n inv H. simpl. trivial.\n - (* valid_block *)\n inv H. unfold Mem.valid_block in *.\n lift_unfold. trivial.\n - (* perm *)\n inv H. lift_unfold. trivial.\n - (* unchanges *)\n inv H. simpl. apply Mem.unchanged_on_refl.\n - (* extend *)\n inv H. inv_val_inject. lift_simpl.\n destruct H0 as [HT1 HT2].\n destruct m1' as [? ?]. simpl in *. subst.\n exists Vundef, (m0, adt'). \n refine_split; eauto.\n + econstructor; eauto.\n + lift_unfold. split; trivial.\n + simpl. apply Mem.unchanged_on_refl.\n - (* inject *)\n inv H0. destruct H3 as [fun_id Hsymbol].\n pose proof Hsymbol as Hsymbol'. apply H in Hsymbol'. \n inv_val_inject.\n lift_simpl. destruct H1 as [HT1 HT2].\n destruct m1' as [? ?]. simpl in *. subst.\n exists f, Vundef, (m0, adt'). \n refine_split; eauto.\n + econstructor; eauto.\n + lift_unfold. split; trivial.\n + apply Mem.unchanged_on_refl.\n + simpl. apply Mem.unchanged_on_refl.\n + constructor; congruence.\n - (* deterministic*)\n inv H. inv H0. rewrite H3 in H12.\n inv H12. split; reflexivity.\n - (* WB *)\n inv H0. econstructor; eauto.\n - (* load *)\n inv H. lift_unfold. trivial.\n Qed.\n\n Definition kctxt_sp_compatsem : compatsem (cdata RData) :=\n compatsem_inl {|\n sextcall_primsem_step := extcall_kctxtsp_info;\n sextcall_props := OK _;\n sextcall_invs := OK _\n |}.\n\n End kctxt_sp.\n\n End INV.\n\n (** * Layer Definition *)\n Definition pkcontext_fresh_c : compatlayer (cdata RData) :=\n set_RA ↦ kctxt_ra_compatsem\n ⊕ set_SP ↦ kctxt_sp_compatsem.\n\n Definition pkcontext_fresh_asm : compatlayer (cdata RData) :=\n kctxt_switch ↦ primcall_kctxt_switch_compatsem kctxt_switch_spec.\n\n Definition pkcontext_fresh : compatlayer (cdata RData) :=\n pkcontext_fresh_c\n ⊕ pkcontext_fresh_asm.\n\n Definition pkcontext_passthrough : compatlayer (cdata RData) :=\n fload ↦ gensem fload_spec\n ⊕ fstore ↦ gensem fstore_spec\n ⊕ flatmem_copy ↦ gensem flatmem_copy_spec\n ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n ⊕ device_output ↦ gensem device_output_spec\n ⊕ pfree ↦ gensem pfree_spec\n ⊕ set_pt ↦ gensem setPT_spec\n ⊕ pt_read ↦ gensem ptRead_spec\n ⊕ pt_resv ↦ gensem ptResv_spec\n ⊕ pt_new ↦ gensem pt_new_spec\n (*⊕ pt_free ↦ gensem pt_free_spec*)\n ⊕ shared_mem_init ↦ gensem sharedmem_init_spec\n ⊕ shared_mem_status ↦ gensem ObjShareMem.shared_mem_status_spec\n ⊕ offer_shared_mem ↦ gensem ObjShareMem.offer_shared_mem_spec\n ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n ⊕ clear_cr2 ↦ gensem clearCR2_spec\n ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n ⊕ container_get_quota ↦ gensem container_get_quota_spec\n ⊕ container_get_usage ↦ gensem container_get_usage_spec\n ⊕ container_can_consume ↦ gensem container_can_consume_spec\n ⊕ container_alloc ↦ gensem alloc_spec\n ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n ⊕ accessors ↦ {| exec_load := (@exec_loadex _ _ Hmwd); \n exec_store := (@exec_storeex _ _ Hmwd) |}.\n\n Definition pkcontext : compatlayer (cdata RData) := pkcontext_fresh ⊕ pkcontext_passthrough.\n\n (*Definition semantics := LAsm.Lsemantics pkcontext.*)\n \nEnd WITHMEM.\n\nSection WITHPARAM.\n\n (*Context `{real_params: RealParams}.*)\n\n Local Open Scope Z_scope.\n\n Section Impl.\n\n Function kctxt_new_spec (abd: RData) (b: block) (b':block) (ofs':int) id q : option (RData * Z) :=\n match pt_new_spec id q abd with\n | Some (abd0, i) =>\n if zeq i num_proc then Some (abd0, num_proc)\n else\n let ofs := Int.repr ((i + 1) * PgSize -4) in\n match kctxt_sp_spec abd0 i b ofs with\n | Some abd1 =>\n match kctxt_ra_spec abd1 i b' ofs' with\n | Some abd2 => Some (abd2, i)\n | _ => None\n end\n | _ => None\n end\n | _ => None\n end.\n\n End Impl.\n\nEnd WITHPARAM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PKContext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.14451107739264807}} {"text": "(******************************************************************************)\n(** Events of compiled program's execution graph follow the compilation scheme*)\n(******************************************************************************)\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\nRequire Import Omega.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_s_hb.\nRequire Import imm_s.\n(* Require Import OCamlToimm_s_prog. *)\nRequire Import OmmImmCompScheme.\nRequire Import OmmImmSimulation.\nRequire Import BoundedRelsProperties. \nRequire Import BlockSteps.\nRequire Import Utils.\nRequire Import ClosuresProperties. \nRequire Import Prog.\nRequire Import ProgToExecution.\nRequire Import ProgToExecutionProperties.\nRequire Import Logic.Decidable. \nFrom PromisingLib Require Import Basic Loc.\nRequire Import Basics. \nSet Implicit Arguments.\n\n\nSection CompCorrHelpers.\n \n Notation \"'E' G\" := G.(acts_set) (at level 1).\n Notation \"'R' G\" := (fun a => is_true (is_r G.(lab) a)) (at level 1).\n Notation \"'W' G\" := (fun a => is_true (is_w G.(lab) a)) (at level 1).\n Notation \"'RW' G\" := (R G ∪₁ W G) (at level 1).\n Notation \"'F' G\" := (fun a => is_true (is_f G.(lab) a)) (at level 1).\n Notation \"'AcqF' G\" := (fun a => is_true (is_f_acq G.(lab) a)) (at level 1).\n Notation \"'AcqrelF' G\" := (fun a => is_true (is_f_acqrel G.(lab) a)) (at level 1).\n Notation \"'ORlx' G\" := (fun a => is_true (is_only_rlx G.(lab) a)) (at level 1).\n Notation \"'ORlxW' G\" := (fun a => is_true (is_orlx_w G.(lab) a)) (at level 1).\n Notation \"'Sc' G\" := (fun a => is_true (is_sc G.(lab) a)) (at level 1). \n Notation \"'Acq' G\" := (fun a => is_true (is_acq G.(lab) a)) (at level 1). \n Notation \"'Acqrel' G\" := (fun a => is_true (is_acqrel G.(lab) a)) (at level 1). \n Notation \"'R_ex' G\" := (fun a => is_true (R_ex G.(lab) a)) (at level 1).\n Notation \"'hbo'\" := (OCaml.hb). \n Notation \"'same_loc' G\" := (same_loc G.(lab)) (at level 1).\n Notation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\n\n Definition omm_premises_hold G :=\n ⟪ WSCFACQRMW : E G ∩₁ W G ∩₁ Sc G ≡₁ codom_rel (⦗AcqF G⦘ ⨾ immediate (sb G) ⨾ rmw G) ⟫ /\\\n ⟪ RMWSC : rmw G ≡ ⦗Sc G⦘ ⨾ rmw G⨾ ⦗Sc G⦘ ⟫ /\\\n ⟪ WRLXF : E G ∩₁ ORlxW G ⊆₁ codom_rel (⦗AcqrelF G⦘ ⨾ immediate (sb G)) ⟫ /\\\n ⟪ RSCF : E G ∩₁ R G ∩₁ Sc G ⊆₁ codom_rel (⦗AcqF G⦘ ⨾ immediate (sb G)) ⟫.\n\n Hint Resolve r_pl w_pl acq_pl acqrel_pl sc_pl orlx_w_pl f_acqrel_pl f_acq_pl : label_ext.\n \n Definition step0 st1 st2 tid :=\n ⟪STEP: step tid st1 st2 ⟫ /\\\n ⟪ADD0: G st2 = G st1⟫. \n \n Definition step1 st1 st2 tid index label :=\n ⟪STEP: step tid st1 st2 ⟫ /\\\n ⟪ADD1: exists foo bar baz bazz, G st2 = add (G st1) tid index label foo bar baz bazz⟫.\n\n Definition step2 st1 st2 tid index label1 label2 :=\n ⟪STEP: step tid st1 st2 ⟫ /\\\n ⟪ADD1: exists foo bar baz bazz, G st2 = add_rmw (G st1) tid index label1 label2 foo bar baz bazz⟫.\n\n Lemma step1_index_exact st1 st2 tid index label (STEP1: step1 st1 st2 tid index label):\n index = eindex st1 /\\ eindex st2 = eindex st1 + 1. \n Proof.\n red in STEP1. desc.\n assert (forall G a b c d e f g, G <> add G a b c d e f g) as ADD_NEQ.\n { ins. red. ins. unfold add in H.\n apply (@f_equal _ _ acts) in H. simpl in H.\n apply (@f_equal _ _ (@length _)) in H. simpl in H. omega. }\n assert (forall G a b c d e f g a' b' c' d' e' f' g' h',\n add_rmw G a' b' c' d' e' f' g' h' <> add G a b c d e f g) as ADD_RMW_NEQ.\n { ins. red. ins. unfold add, add_rmw in H.\n apply (@f_equal _ _ acts) in H. simpl in H.\n apply (@f_equal _ _ (@length _)) in H. simpl in H. omega. }\n do 2 (red in STEP; desc).\n inversion ISTEP0.\n all: try (rewrite UG in ADD1; apply ADD_NEQ in ADD1; by vauto).\n all: try (rewrite UG in ADD1; apply ADD_RMW_NEQ in ADD1; by vauto).\n all: split; auto. \n all: rewrite ADD1 in UG; apply (@f_equal _ _ acts) in UG; simpl in UG.\n all: inversion UG; auto.\n Qed. \n \n Lemma step2_index_exact st1 st2 tid index label1 label2 (STEP1: step2 st1 st2 tid index label1 label2):\n index = eindex st1 /\\ eindex st2 = eindex st1 + 2. \n Proof.\n red in STEP1. desc.\n assert (forall G a b c d e f g h, G <> add_rmw G a b c d e f g h) as ADD_RMW_NEQ.\n { ins. red. ins. unfold add in H.\n apply (@f_equal _ _ acts) in H. simpl in H.\n apply (@f_equal _ _ (@length _)) in H. simpl in H. omega. }\n assert (forall G a b c d e f g a' b' c' d' e' f' g' h',\n add G a b c d e f g <> add_rmw G a' b' c' d' e' f' g' h') as ADD_RMW_ADD_NEQ.\n { ins. red. ins. unfold add, add_rmw in H.\n apply (@f_equal _ _ acts) in H. simpl in H.\n apply (@f_equal _ _ (@length _)) in H. simpl in H. omega. }\n do 2 (red in STEP; desc).\n inversion ISTEP0.\n all: try (rewrite UG in ADD1; apply ADD_RMW_NEQ in ADD1; by vauto).\n all: try (rewrite UG in ADD1; apply ADD_RMW_ADD_NEQ in ADD1; by vauto).\n all: split; auto. \n all: rewrite ADD1 in UG; apply (@f_equal _ _ acts) in UG; simpl in UG.\n all: inversion UG; auto.\n Qed. \n \n\n Lemma immediate_sb_repr st thread (WFT: wf_thread_state thread st):\n immediate (sb (G st)) ≡ (fun e1 e2 =>\n exists ind, e1 = ThreadEvent thread ind /\\\n e2 = ThreadEvent thread (ind + 1) /\\\n ind + 1 < eindex st). \n Proof.\n split.\n { red. ins. red in H. desc.\n unfold sb in H. apply seq_eqv_lr in H. destruct H as [Ex [ESBxy Ey]]. \n destruct y.\n { red in ESBxy. destruct x; vauto. }\n assert (thread0 = thread); [| subst thread0]. \n { destruct WFT. specialize (acts_rep _ Ey). desc. vauto. }\n destruct x.\n { destruct WFT. specialize (acts_rep _ Ex). desc. vauto. }\n red in ESBxy. desc. subst.\n exists index0. splits; auto.\n 2: { destruct WFT. specialize (acts_rep _ Ey). desc. inversion REP.\n subst. omega. }\n f_equal.\n destruct (NPeano.Nat.eq_decidable index (index0 + 1)); auto.\n assert (E (G st) (ThreadEvent thread (index0 + 1))) as E'.\n { destruct WFT. specialize (acts_clos (index0 + 1)).\n apply acts_clos.\n specialize (acts_rep _ Ey). desc. inversion REP. omega. }\n exfalso. apply (H0 (ThreadEvent thread (index0 + 1))).\n all: red; apply seq_eqv_lr; splits; auto; red; splits; [auto| omega]. }\n red. ins. desc. subst. \n assert (E (G st) (ThreadEvent thread ind)) as Ex. \n { destruct WFT. specialize (acts_clos ind).\n subst. apply acts_clos. omega. }\n assert (E (G st) (ThreadEvent thread (ind + 1))) as Ey. \n { destruct WFT. specialize (acts_clos (ind + 1)).\n subst. apply acts_clos. omega. }\n red. split.\n { apply seq_eqv_lr. splits; auto. red. split; [auto| omega]. }\n ins. apply seq_eqv_lr in R1. apply seq_eqv_lr in R2. desc. \n destruct c; vauto. red in R4. red in R0. desc. subst. omega. \n Qed. \n \n Lemma singl_rel_event_repr thread ind:\n singl_rel (ThreadEvent thread ind) (ThreadEvent thread (ind + 1)) ≡\n (fun e1 e2 => e1 = ThreadEvent thread ind /\\\n e2 = ThreadEvent thread (ind + 1)). \n Proof. basic_solver. Qed. \n\n Lemma step_1_label_ext_helper st1 st2 tid new_label index \n (STEP1: step1 st1 st2 tid index new_label)\n n (REACH: (step tid) ^^ n (init (instrs st1)) st1):\n let lbl_ext (S: (actid -> label) -> actid -> bool)\n (matcher : label -> bool) :=\n S (lab (G st2)) ≡₁ S (lab (G st1)) ∪₁ (if matcher new_label then eq (ThreadEvent tid index) else ∅) in\n ⟪E_EXT: E (G st2) ≡₁ E (G st1) ∪₁ eq (ThreadEvent tid index) ⟫ /\\\n ⟪RMW_EXT: rmw (G st2) ≡ rmw (G st1) ⟫ /\\\n ⟪SB_EXT: E (G st1) ≡₁ ∅ \\/ immediate (sb (G st2)) ≡ immediate (sb (G st1)) ∪ singl_rel (ThreadEvent tid (index - 1)) (ThreadEvent tid index) ⟫ /\\\n ⟪R_EXT: lbl_ext (@is_r actid) r_matcher ⟫ /\\\n ⟪W_EXT: lbl_ext (@is_w actid) w_matcher ⟫ /\\\n ⟪W_ORLX_EXT: lbl_ext (@is_orlx_w actid) orlx_w_matcher ⟫ /\\\n ⟪F_ACQ_EXT: lbl_ext (@is_f_acq actid) f_acq_matcher ⟫ /\\\n ⟪F_ACQREL_EXT: lbl_ext (@is_f_acqrel actid) f_acqrel_matcher ⟫ /\\\n ⟪SC_EXT: lbl_ext (@is_sc actid) sc_matcher⟫ .\n Proof.\n forward eapply step1_index_exact; eauto. ins. destruct H as [H EINDEX2]. subst. \n red in STEP1. desc. \n pose proof label_set_step as LBL_STEP.\n specialize LBL_STEP with (st1 := st1) (st2 := st2) (tid := tid).\n assert (E (G st2) ≡₁ E (G st1) ∪₁ eq (ThreadEvent tid (eindex st1))) as E_EXT. \n { desc. rewrite ADD1. unfold acts_set. basic_solver. }\n simpl. splits; auto. \n { desc. rewrite ADD1. basic_solver. }\n { assert (wf_thread_state tid st1) as WFT.\n { eapply wf_thread_state_steps with (s := init (instrs st1)); [apply wf_thread_state_init| ].\n apply crt_num_steps. eauto. }\n destruct (gt_0_eq (eindex st1)).\n 2: { left. split; [| basic_solver]. red. ins. red in H0.\n destruct WFT. specialize (acts_rep x H0). desc. omega. }\n right.\n assert (wf_thread_state tid st1) as WFT1. \n { eapply wf_thread_state_steps with (s := init (instrs st1)); [apply wf_thread_state_init| ].\n apply crt_num_steps. eauto. }\n assert (wf_thread_state tid st2) as WFT2.\n { eapply wf_thread_state_step; eauto. }\n rewrite (immediate_sb_repr WFT1), (immediate_sb_repr WFT2); eauto.\n replace (eindex st1) with ((eindex st1 - 1) + 1) at 2 by omega.\n rewrite EINDEX2. \n rewrite singl_rel_event_repr.\n split.\n { red. ins. desc. subst. destruct (Nat.lt_decidable (ind + 1) (eindex st1)).\n { red. left. eexists. splits; eauto. }\n red. right. splits.\n all: f_equal; omega. }\n red. ins. red in H0. des.\n { subst. eexists. splits; eauto. omega. }\n subst. eexists. splits; eauto. omega. }\n all: apply LBL_STEP; eauto with label_ext.\n all: eapply nonnop_bounded; eauto with label_ext; vauto.\n Qed. \n \n Lemma step_2_label_ext_helper st1 st2 tid new_label1 new_label2 index \n (STEP2: step2 st1 st2 tid index new_label1 new_label2)\n n (REACH: (step tid) ^^ n (init (instrs st1)) st1):\n let ev1 := (ThreadEvent tid index) in\n let ev2 := (ThreadEvent tid (index + 1)) in\n let lbl_ext2 (S: (actid -> label) -> actid -> bool)\n (matcher : label -> bool) :=\n S (lab (G st2)) ≡₁ S (lab (G st1)) ∪₁ (if matcher new_label1 then eq ev1 else ∅) ∪₁ (if matcher new_label2 then eq ev2 else ∅) in\n ⟪E_EXT: E (G st2) ≡₁ E (G st1) ∪₁ eq ev1 ∪₁ eq ev2 ⟫ /\\\n ⟪RMW_EXT: rmw (G st2) ≡ rmw (G st1) ∪ singl_rel ev1 ev2 ⟫ /\\\n ⟪SB_EXT: E (G st1) ≡₁ ∅ \\/ immediate (sb (G st2)) ≡ immediate (sb (G st1)) ∪ singl_rel (ThreadEvent tid (index - 1)) ev1 ∪ singl_rel ev1 ev2 ⟫ /\\\n ⟪R_EXT: lbl_ext2 (@is_r actid) r_matcher ⟫ /\\\n ⟪W_EXT: lbl_ext2 (@is_w actid) w_matcher ⟫ /\\\n ⟪W_ORLX_EXT: lbl_ext2 (@is_orlx_w actid) orlx_w_matcher ⟫ /\\\n ⟪F_ACQ_EXT: lbl_ext2 (@is_f_acq actid) f_acq_matcher ⟫ /\\\n ⟪F_ACQREL_EXT: lbl_ext2 (@is_f_acqrel actid) f_acqrel_matcher ⟫ /\\\n ⟪SC_EXT: lbl_ext2 (@is_sc actid) sc_matcher⟫ .\n Proof.\n forward eapply step2_index_exact; eauto. ins. destruct H as [H EINDEX2]. subst. \n red in STEP2. desc. \n pose proof label_set_rmw_step as LBL_STEP.\n specialize LBL_STEP with (st1 := st1) (st2 := st2) (tid := tid).\n assert (E (G st2) ≡₁ E (G st1) ∪₁ eq (ThreadEvent tid (eindex st1)) ∪₁ eq (ThreadEvent tid (eindex st1 + 1))) as E_EXT. \n { desc. rewrite ADD1. unfold acts_set. basic_solver. }\n simpl. splits; auto. \n { desc. rewrite ADD1. unfold add_rmw. simpl. basic_solver. }\n { assert (wf_thread_state tid st1) as WFT1. \n { eapply wf_thread_state_steps with (s := init (instrs st1)); [apply wf_thread_state_init| ].\n apply crt_num_steps. eauto. }\n assert (wf_thread_state tid st2) as WFT2.\n { eapply wf_thread_state_step; eauto. }\n destruct (gt_0_eq (eindex st1)).\n 2: { left. split; [| basic_solver]. red. ins. red in H0.\n destruct WFT1. specialize (acts_rep x H0). desc. omega. }\n right.\n rewrite (immediate_sb_repr WFT1), (immediate_sb_repr WFT2); eauto.\n replace (eindex st1) with ((eindex st1 - 1) + 1) at 2 by omega. \n do 2 rewrite singl_rel_event_repr.\n rewrite EINDEX2. split.\n { rewrite unionA. red. ins. desc. subst.\n destruct (Const.lt_ge_cases (ind + 1) (eindex st1)).\n { red. left. eexists. splits; eauto. }\n red. right. destruct (NPeano.Nat.eq_decidable (ind + 1) (eindex st1)).\n { red. left. splits; vauto; f_equal; omega. }\n red. right. splits; vauto; f_equal; omega. }\n red. ins. destruct H0 as [[SB1 | SB'] | SB''].\n { desc. eexists. splits; eauto. omega. }\n { desc. subst. eexists. splits; eauto. omega. }\n desc. subst. eexists. splits; eauto. omega.\n }\n all: apply LBL_STEP; eauto with label_ext.\n all: eapply nonnop_bounded; eauto with label_ext; vauto.\n Qed. \n \n Lemma EXTSB_IRR e:\n ⦗eq e⦘ ⨾ ext_sb ⨾ ⦗eq e⦘ ≡ ∅₂.\n Proof. \n split; [| basic_solver]. rewrite seq_eqv_lr. red. ins.\n desc. subst. red in H0. destruct y; vauto. desc. omega.\n Qed. \n\n Lemma EXTSB_MON e1 e2 (GT: index e1 > index e2):\n ⦗eq e1⦘ ⨾ ext_sb ⨾ ⦗eq e2⦘ ≡ ∅₂. \n Proof.\n split; [| basic_solver]. rewrite seq_eqv_lr. red. ins.\n desc. subst. destruct x.\n { simpl in GT. omega. }\n destruct y; vauto. simpl in H0. simpl in GT. desc. omega.\n Qed. \n\n Lemma step_11_label_ext_helper st1 st2 st3 tid new_label1 new_label2 index1 index2\n (IND1: index1 >= eindex st1) (IND2: index2 >= eindex st2)\n (STEP11: step1 st1 st2 tid index1 new_label1)\n (STEP12: step1 st2 st3 tid index2 new_label2)\n n (REACH: (step tid) ^^ n (init (instrs st1)) st1):\n let ev1 := (ThreadEvent tid index1) in\n let ev2 := (ThreadEvent tid index2) in\n let lbl_ext2 (S: (actid -> label) -> actid -> bool)\n (matcher : label -> bool) :=\n S (lab (G st3)) ≡₁ S (lab (G st1)) ∪₁ (if matcher new_label1 then eq ev1 else ∅) ∪₁ (if matcher new_label2 then eq ev2 else ∅) in\n ⟪E_EXT: E (G st3) ≡₁ E (G st1) ∪₁ eq ev1 ∪₁ eq ev2 ⟫ /\\\n ⟪RMW_EXT: rmw (G st3) ≡ rmw (G st1) ⟫ /\\\n ⟪SB_EXT: (E (G st1) ≡₁ ∅ /\\ sb (G st3) ≡ singl_rel ev1 ev2) \\/\n immediate (sb (G st3)) ≡ immediate (sb (G st1)) ∪ singl_rel (ThreadEvent tid (index1 - 1)) ev1 ∪ singl_rel ev1 ev2 ⟫ /\\\n ⟪R_EXT: lbl_ext2 (@is_r actid) r_matcher ⟫ /\\\n ⟪W_EXT: lbl_ext2 (@is_w actid) w_matcher ⟫ /\\\n ⟪W_ORLX_EXT: lbl_ext2 (@is_orlx_w actid) orlx_w_matcher ⟫ /\\\n ⟪F_ACQ_EXT: lbl_ext2 (@is_f_acq actid) f_acq_matcher ⟫ /\\\n ⟪F_ACQREL_EXT: lbl_ext2 (@is_f_acqrel actid) f_acqrel_matcher ⟫ /\\\n ⟪SC_EXT: lbl_ext2 (@is_sc actid) sc_matcher⟫ .\n Proof.\n forward eapply (@step1_index_exact st1 st2) as [H EINDEX2]; eauto.\n forward eapply (@step1_index_exact st2 st3) as [H' EINDEX3]; eauto.\n ins. subst. \n forward eapply (@step_1_label_ext_helper st1 st2 tid) as STEP1; eauto.\n red in STEP11. desc.\n forward eapply (@step_1_label_ext_helper st2 st3 tid new_label2 (eindex st2)) as STEP2; eauto.\n { Unshelve. 2: exact (S n). replace (instrs st2) with (instrs st1). \n 2: { apply steps_same_instrs. exists tid. apply rt_step. auto. }\n apply step_prev. exists st1. split; auto. }\n simpl in *. desc. simpl. splits.\n 4: { rewrite R_EXT, R_EXT0. auto. }\n 4: { rewrite W_EXT, W_EXT0. auto. }\n 4: { rewrite W_ORLX_EXT, W_ORLX_EXT0. auto. }\n 4: { rewrite F_ACQ_EXT, F_ACQ_EXT0. auto. }\n 4: { rewrite F_ACQREL_EXT, F_ACQREL_EXT0. auto. }\n 4: { rewrite SC_EXT, SC_EXT0. auto. }\n { rewrite E_EXT, E_EXT0. auto. }\n { rewrite RMW_EXT, RMW_EXT0. auto. }\n { clear W_EXT. clear W_EXT0. clear W_ORLX_EXT. clear W_ORLX_EXT0. clear F_ACQ_EXT. clear F_ACQ_EXT0. clear F_ACQREL_EXT. clear F_ACQREL_EXT0. clear SC_EXT. clear SC_EXT0. clear R_EXT. clear R_EXT0. clear RMW_EXT. clear RMW_EXT0.\n destruct SB_EXT as [NO_E2 | E2_ADD].\n { exfalso. generalize E_EXT0. rewrite NO_E2. basic_solver. }\n desc.\n destruct SB_EXT0 as [NO_E1 | E1_ADD].\n { left. split; auto.\n unfold sb. rewrite E_EXT, E_EXT0, NO_E1. remove_emptiness.\n rewrite id_union. rewrite seq_union_l, !seq_union_r.\n repeat rewrite EXTSB_IRR.\n rewrite EXTSB_MON with (e1 := (ThreadEvent tid (eindex st2))). \n 2: { simpl. omega. }\n remove_emptiness.\n apply unique_restr. red. split; [auto| omega]. }\n right. rewrite E2_ADD, E1_ADD.\n replace (eindex st2 - 1) with (eindex st1); auto. omega. }\n Qed. \n\n Lemma step_12_label_ext_helper st1 st2 st3 tid new_label1 new_label21 new_label22 index1 index2\n (IND1: index1 >= eindex st1) (IND2: index2 >= eindex st2)\n (STEP11: step1 st1 st2 tid index1 new_label1)\n (STEP12: step2 st2 st3 tid index2 new_label21 new_label22)\n n (REACH: (step tid) ^^ n (init (instrs st1)) st1):\n let ev1 := (ThreadEvent tid index1) in\n let ev2 := (ThreadEvent tid index2) in\n let ev3 := (ThreadEvent tid (index2 + 1)) in\n let lbl_ext3 (S: (actid -> label) -> actid -> bool)\n (matcher : label -> bool) :=\n S (lab (G st3)) ≡₁ S (lab (G st1)) ∪₁\n (if matcher new_label1 then eq ev1 else ∅) ∪₁\n (if matcher new_label21 then eq ev2 else ∅) ∪₁\n (if matcher new_label22 then eq ev3 else ∅) in\n ⟪E_EXT: E (G st3) ≡₁ E (G st1) ∪₁ eq ev1 ∪₁ eq ev2 ∪₁ eq ev3 ⟫ /\\\n ⟪RMW_EXT: rmw (G st3) ≡ rmw (G st1) ∪ singl_rel ev2 ev3⟫ /\\\n ⟪SB_EXT: (E (G st1) ≡₁ ∅ /\\ sb (G st3) ≡ singl_rel ev1 ev2 ∪ singl_rel ev2 ev3 ∪ singl_rel ev1 ev3) \\/\n immediate (sb (G st3)) ≡ immediate (sb (G st1)) ∪ singl_rel (ThreadEvent tid (index1 - 1)) ev1 ∪ singl_rel ev1 ev2 ∪ singl_rel ev2 ev3 ⟫ /\\\n ⟪R_EXT: lbl_ext3 (@is_r actid) r_matcher ⟫ /\\\n ⟪W_EXT: lbl_ext3 (@is_w actid) w_matcher ⟫ /\\\n ⟪W_ORLX_EXT: lbl_ext3 (@is_orlx_w actid) orlx_w_matcher ⟫ /\\\n ⟪F_ACQ_EXT: lbl_ext3 (@is_f_acq actid) f_acq_matcher ⟫ /\\\n ⟪F_ACQREL_EXT: lbl_ext3 (@is_f_acqrel actid) f_acqrel_matcher ⟫ /\\\n ⟪SC_EXT: lbl_ext3 (@is_sc actid) sc_matcher⟫ .\n Proof.\n forward eapply (@step1_index_exact st1 st2) as [H EINDEX2]; eauto.\n forward eapply (@step2_index_exact st2 st3) as [H' EINDEX3]; eauto.\n ins. subst. \n forward eapply (@step_1_label_ext_helper st1 st2 tid) as STEP1; eauto.\n red in STEP11. desc.\n forward eapply (@step_2_label_ext_helper st2 st3 tid new_label21 new_label22 (eindex st2)) as STEP2; eauto.\n { Unshelve. 2: exact (S n). replace (instrs st2) with (instrs st1). \n 2: { apply steps_same_instrs. exists tid. apply rt_step. auto. }\n apply step_prev. exists st1. split; auto. }\n simpl in *. desc. simpl. splits.\n 4: { rewrite R_EXT, R_EXT0. auto. }\n 4: { rewrite W_EXT, W_EXT0. auto. }\n 4: { rewrite W_ORLX_EXT, W_ORLX_EXT0. auto. }\n 4: { rewrite F_ACQ_EXT, F_ACQ_EXT0. auto. }\n 4: { rewrite F_ACQREL_EXT, F_ACQREL_EXT0. auto. }\n 4: { rewrite SC_EXT, SC_EXT0. auto. }\n { rewrite E_EXT, E_EXT0. auto. }\n { rewrite RMW_EXT, RMW_EXT0. auto. }\n { clear W_EXT. clear W_EXT0. clear W_ORLX_EXT. clear W_ORLX_EXT0. clear F_ACQ_EXT. clear F_ACQ_EXT0. clear F_ACQREL_EXT. clear F_ACQREL_EXT0. clear SC_EXT. clear SC_EXT0. clear R_EXT. clear R_EXT0. clear RMW_EXT. clear RMW_EXT0.\n destruct SB_EXT as [NO_E2 | E2_ADD].\n { exfalso. generalize E_EXT0. rewrite NO_E2. basic_solver. }\n desc.\n destruct SB_EXT0 as [NO_E1 | E1_ADD].\n { left. split; auto.\n unfold sb. rewrite E_EXT, E_EXT0, NO_E1. remove_emptiness.\n rewrite id_union. repeat rewrite id_union. expand_rels. \n rewrite EINDEX2. \n repeat rewrite EXTSB_IRR.\n rewrite EXTSB_MON with (e1 := (ThreadEvent tid (eindex st1 + 1))). \n 2: { simpl. omega. }\n rewrite EXTSB_MON with (e1 := (ThreadEvent tid (eindex st1 + 1 + 1))). \n 2: { simpl. omega. }\n rewrite EXTSB_MON with (e1 := (ThreadEvent tid (eindex st1 + 1 + 1))). \n 2: { simpl. omega. }\n remove_emptiness.\n repeat rewrite unique_restr.\n 2-4: by (simpl; split; [auto | omega]).\n basic_solver. }\n right. rewrite E2_ADD, E1_ADD.\n replace (eindex st2 - 1) with (eindex st1); auto. omega. }\n Qed.\n \n Lemma GI_1thread_omm_premises_block bst tid PO \n (COMP: is_thread_block_compiled PO (binstrs bst))\n (GOTO_RESTR: goto_addresses_restricted PO)\n (BLOCK_STEPS: (omm_block_step_PO PO tid)* (binit (binstrs bst)) bst):\n omm_premises_hold (bG bst).\n Proof.\n apply crt_num_steps in BLOCK_STEPS. destruct BLOCK_STEPS as [n_steps BLOCK_STEPS].\n generalize dependent bst. induction n_steps.\n { ins. red in BLOCK_STEPS. desc. rewrite <- BLOCK_STEPS. simpl.\n red. simpl. splits; basic_solver. }\n ins. red in BLOCK_STEPS. destruct BLOCK_STEPS as [bst_prev [STEPS_PREV STEP_NEXT]].\n assert (binstrs bst = binstrs bst_prev) as BINSTRS_SAME.\n { red in STEP_NEXT. desc. auto. }\n specialize (IHn_steps bst_prev).\n specialize_full IHn_steps; [congruence| congruence |]. \n red in STEP_NEXT. desc. \n red in BLOCK_STEP. desc.\n remember (bpc bst_prev) as b. remember (bst2st bst_prev) as st_prev.\n assert (exists oinstr, is_instruction_compiled oinstr block) as [oinstr COMP_BLOCK].\n { eapply resulting_block_compiled; eauto. eapply COMPILED_NONEMPTY. eauto. }\n assert (forall i block_i, Some block_i = nth_error block i -> Some block_i = nth_error (instrs st_prev) (pc st_prev + i)) as BLOCK_CONTENTS. \n { ins. forward eapply (@near_pc block_i block i H bst_prev); eauto.\n { congruence. }\n apply nth_error_Some, OPT_VAL. exists block. congruence. }\n assert (forall i instr (BLOCK_I: Some instr = nth_error block i) instr' (OTHER: Some instr' = nth_error (instrs st_prev) (pc st_prev + i)) (NEQ: instr <> instr'), False).\n { ins. specialize (BLOCK_CONTENTS _ _ BLOCK_I). congruence. }\n assert (exists k, (step tid) ^^ k (init (instrs st_prev)) st_prev) as [k REACH].\n { apply crt_num_steps. subst st_prev. apply ommblocks_imply_steps with (PO := PO); auto. \n apply crt_num_steps. eexists. rewrite BINSTRS_SAME0. eauto. }\n assert (forall st', (step tid) st_prev st' -> (step tid) ^^ (k + 1) (init (instrs st')) st') as REACH'. \n { ins. replace (instrs st') with (instrs st_prev).\n 2: { apply steps_same_instrs. eexists. apply rt_step. basic_solver. }\n rewrite Nat.add_1_r. apply step_prev. eexists. splits; eauto. } \n assert (wf_thread_state tid st_prev) as WFT.\n { apply wf_thread_state_steps with (s := init (instrs st_prev)); [apply wf_thread_state_init| ]. \n apply crt_num_steps. eauto. }\n assert (forall {A: Type} (D: A -> Prop) r, immediate (restr_rel D r) ≡ restr_rel D (immediate (restr_rel D r))) as RESTR_IMM. \n { ins. basic_solver. }\n\n inv COMP_BLOCK; simpl in *.\n all: remember (bst2st bst_prev) as st_prev.\n { apply (same_relation_exp (seq_id_l (step tid))) in BLOCK_STEP0.\n do 2 (red in BLOCK_STEP0; desc).\n forward eapply (BLOCK_CONTENTS 0 ld) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 ld eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n assert (instr = ld). \n { cut (Some instr = Some ld); [ins; vauto| ].\n rewrite ISTEP, INSTR. rewrite Nat.add_0_r.\n vauto. }\n subst instr. inversion H0. subst ord. subst reg. subst lexpr. \n remember (Aload false Orlx (RegFile.eval_lexpr (regf st_prev) loc) val) as lbl. \n remember (bst2st bst) as st.\n replace (init (flatten (binstrs bst_prev))) with (init (instrs st_prev)) in * by vauto. \n red.\n replace (bG bst) with (G st) by vauto.\n forward eapply step_1_label_ext_helper as LBL_EXT; eauto.\n { red. splits; eauto. red. eexists. red. splits; eauto. }\n simpl in LBL_EXT. desc. \n assert (forall max_event index (IND: index >= eindex st_prev),\n singl_rel max_event (ThreadEvent tid (eindex st_prev)) ⨾ rmw (G st_prev) ≡ ∅₂) as SB_RMW_HELPER. \n { split; [| basic_solver].\n rewrite rmw_bibounded; vauto. \n red. ins. red in H1. desc. red in H1. desc. subst.\n simpl in H2. omega. }\n subst lbl. simpl in *.\n des.\n { assert (sb (G st) ≡ ∅₂) as NO_SB.\n { split; [| basic_solver]. unfold Execution.sb.\n rewrite E_EXT, SB_EXT. remove_emptiness.\n rewrite seq_eqv_lr. red. ins. desc.\n subst. unfold ext_sb in H2. desc. omega. }\n assert (immediate (sb (G st)) ≡ ∅₂) as NO_ISB.\n { generalize NO_SB. basic_solver. }\n rewrite SB_EXT in *. clear SB_EXT. \n splits.\n all: unfold_clear_updated; expand_rels; simplify_updated_sets.\n 2: by_IH IHn_steps. \n all: basic_solver. }\n splits.\n { unfold_clear_updated. expand_rels. simplify_updated_sets.\n rewrite SB_RMW_HELPER; eauto. remove_emptiness.\n by_IH IHn_steps. }\n { unfold_clear_updated. expand_rels. simplify_updated_sets.\n by_IH IHn_steps. }\n { unfold_clear_updated. expand_rels. simplify_updated_sets.\n rewrite codom_union. apply set_subset_union_r. left. \n by_IH IHn_steps. }\n { unfold_clear_updated. expand_rels. simplify_updated_sets.\n rewrite codom_union. apply set_subset_union_r. left.\n by_IH IHn_steps. } }\n { apply (same_relation_exp (@seqA _ _ _ _)) in BLOCK_STEP0.\n apply (same_relation_exp (seq_id_l (step tid ⨾ step tid))) in BLOCK_STEP0.\n red in BLOCK_STEP0. destruct BLOCK_STEP0 as [st_prev' [STEP1 STEP2]]. \n do 2 (red in STEP1; desc). do 2 (red in STEP2; desc).\n forward eapply (BLOCK_CONTENTS 0 f) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 f eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n assert (instr = f). \n { cut (Some instr = Some f); [ins; vauto| ].\n rewrite ISTEP, INSTR. rewrite Nat.add_0_r.\n vauto. }\n rewrite <- INSTRS, UPC in *. \n subst instr. inversion H0. subst ord. (* subst reg. subst lexpr. *)\n forward eapply (BLOCK_CONTENTS 1 st) as INSTR'; eauto.\n inversion ISTEP2.\n all: try (forward eapply (@H 1 st eq_refl instr0); by vauto).\n assert (instr0 = st). \n { cut (Some instr0 = Some st); [ins; vauto| ].\n rewrite ISTEP1. vauto. }\n subst instr0. inversion H1. subst ord. subst lexpr. subst expr.\n subst x. subst l. subst v. \n \n remember (Afence Oacqrel) as lbl. \n remember (Astore Xpln Orlx (RegFile.eval_lexpr (regf st_prev') loc)) as lbl'.\n rename st into st_.\n remember (bst2st bst) as st.\n replace (init (flatten (binstrs bst_prev))) with (init (instrs st_prev)) in * by vauto. \n red.\n replace (bG bst) with (G st) by vauto.\n forward eapply (@step_11_label_ext_helper st_prev st_prev' st) as LBL_EXT; eauto.\n { red. splits; eauto. do 2 (red; eexists); eauto. } \n { red. splits; eauto. red. eexists. red. splits.\n { congruence. }\n exists st_. splits; eauto. rewrite INSTR'. f_equal; vauto. } \n\n rewrite Heqlbl, Heqlbl' in LBL_EXT. simpl in LBL_EXT. desc. \n remember (ThreadEvent tid (eindex st_prev)) as ev.\n remember (ThreadEvent tid (eindex st_prev')) as ev'. \n destruct SB_EXT as [[NO_E SB_TRIVIAL] | SB_EXT]. \n { assert (immediate (sb (G st)) ≡ singl_rel ev ev') as IMM_SB. \n { rewrite SB_TRIVIAL. split; [basic_solver| ].\n red. ins. red. split; auto.\n ins. red in H2, R1, R2. desc. subst.\n inversion R2. rewrite UINDEX in H3. simpl in H3. omega. }\n rewrite NO_E in *. (* clear NO_E. *)\n subst ev ev'. rewrite UINDEX in *. \n splits. all: try rewrite IMM_SB.\n { rewrite E_EXT, RMW_EXT. \n rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)). rewrite NO_E.\n unfold_clear_updated; expand_rels; simplify_updated_sets. \n basic_solver 10. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n by_IH IHn_steps. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver 10. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver. }\n } \n \n splits.\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n assert (forall x d, singl_rel x (ThreadEvent tid (eindex st_prev + d)) ⨾ rmw (G st_prev) ≡ ∅₂).\n { ins. rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)).\n rewrite singl_rel_restr. rewrite !seqA. rewrite <- seqA with (r2 := ⦗E (G st_prev)⦘).\n rewrite <- id_inter. simplify_updated_sets. basic_solver. }\n rewrite <- Nat.add_0_r with (n := (eindex st_prev)) at 4. \n repeat rewrite H2. remove_emptiness.\n rewrite id_union. expand_rels.\n unfold sb at 2. rewrite <- restr_relE, RESTR_IMM, restr_relE.\n rewrite !seqA. rewrite <- seqA with (r1 := ⦗eq (ThreadEvent tid (eindex st_prev))⦘).\n rewrite <- id_inter. simplify_updated_sets.\n by_IH IHn_steps. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n by_IH IHn_steps. }\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n apply set_subset_union_l. split; [| basic_solver 10]. \n rewrite id_union. expand_rels.\n repeat rewrite codom_union. \n repeat (apply set_subset_union_r; left).\n by_IH IHn_steps. }\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite id_union. expand_rels.\n repeat rewrite codom_union. \n repeat (apply set_subset_union_r; left).\n by_IH IHn_steps. } }\n { apply (same_relation_exp (@seqA _ _ _ _)) in BLOCK_STEP0.\n apply (same_relation_exp (seq_id_l (step tid ⨾ step tid))) in BLOCK_STEP0.\n red in BLOCK_STEP0. destruct BLOCK_STEP0 as [st_prev' [STEP1 STEP2]]. \n do 2 (red in STEP1; desc). do 2 (red in STEP2; desc).\n forward eapply (BLOCK_CONTENTS 0 f) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 f eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n assert (instr = f). \n { cut (Some instr = Some f); [ins; vauto| ].\n rewrite ISTEP, INSTR. rewrite Nat.add_0_r.\n vauto. }\n rewrite <- INSTRS, UPC in *. \n subst instr. inversion H0. subst ord. (* subst reg. subst lexpr. *)\n forward eapply (BLOCK_CONTENTS 1 ld) as INSTR'; eauto.\n inversion ISTEP2.\n all: try (forward eapply (@H 1 ld eq_refl instr0); by vauto).\n assert (instr0 = ld). \n { cut (Some instr0 = Some ld); [ins; vauto| ].\n rewrite ISTEP1. vauto. }\n subst instr0. inversion H1. subst ord. subst lexpr. subst reg.\n subst l.\n \n remember (Afence Oacq) as lbl. \n remember (Aload false Osc (RegFile.eval_lexpr (regf st_prev') loc) val) as lbl'.\n remember (bst2st bst) as st.\n replace (init (flatten (binstrs bst_prev))) with (init (instrs st_prev)) in * by vauto. \n red.\n replace (bG bst) with (G st) by vauto.\n forward eapply (@step_11_label_ext_helper st_prev st_prev' st) as LBL_EXT; eauto.\n { red. splits; eauto. do 2 (red; eexists); eauto. } \n { red. splits; eauto. red. eexists. red. splits.\n { congruence. }\n exists ld. splits; eauto. rewrite INSTR'. f_equal; vauto. } \n\n rewrite Heqlbl, Heqlbl' in LBL_EXT. simpl in LBL_EXT. desc. \n remember (ThreadEvent tid (eindex st_prev)) as ev.\n remember (ThreadEvent tid (eindex st_prev')) as ev'. \n destruct SB_EXT as [[NO_E SB_TRIVIAL] | SB_EXT]. \n { assert (immediate (sb (G st)) ≡ singl_rel ev ev') as IMM_SB. \n { rewrite SB_TRIVIAL. split; [basic_solver| ].\n red. ins. red. split; auto.\n ins. red in H2, R1, R2. desc. subst.\n inversion R2. rewrite UINDEX in H3. simpl in H3. omega. }\n rewrite NO_E in *. (* clear NO_E. *)\n subst ev ev'. rewrite UINDEX in *. \n splits. all: try rewrite IMM_SB.\n { rewrite E_EXT, RMW_EXT. \n rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)). rewrite NO_E.\n unfold_clear_updated; expand_rels; simplify_updated_sets. \n basic_solver 10. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite wft_rmwE at 2; eauto. fold (acts_set (G st_prev)).\n rewrite !seqA. repeat seq_rewrite <- id_inter.\n unfold_clear_updated; expand_rels; simplify_updated_sets.\n repeat rewrite id_inter. rewrite !seqA.\n unfold acts_set. seq_rewrite <- wft_rmwE; eauto. \n by_IH IHn_steps. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver 10. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver 10. }\n } \n \n splits.\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite set_interA with (s'' := eq (ThreadEvent tid (eindex st_prev + 1))). simplify_updated_sets. \n rewrite singl_rel_restr. rewrite singl_rel_restr with (y := (ThreadEvent tid (eindex st_prev + 1))). \n rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)).\n rewrite !seqA. repeat seq_rewrite <- id_inter.\n simplify_updated_sets.\n repeat rewrite eqv_empty. remove_emptiness.\n rewrite id_union, seq_union_l.\n (* TODO: refactor with previous case; also maybe add tactic especially for rmw; add id_inter folding into simplification *)\n arewrite (⦗eq (ThreadEvent tid (eindex st_prev))⦘\n ⨾ immediate (sb (G st_prev)) ≡ ∅₂).\n { unfold sb. rewrite <- restr_relE, RESTR_IMM, restr_relE.\n seq_rewrite <- id_inter. simplify_updated_sets. basic_solver. }\n remove_emptiness. unfold acts_set. rewrite <- wft_rmwE; eauto.\n by_IH IHn_steps. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite wft_rmwE at 2; eauto. fold (acts_set (G st_prev)).\n rewrite !seqA. repeat seq_rewrite <- id_inter.\n unfold_clear_updated; expand_rels; simplify_updated_sets.\n subst ev ev'. simplify_updated_sets. repeat rewrite id_inter.\n rewrite !seqA.\n unfold acts_set. seq_rewrite <- wft_rmwE; eauto. \n by_IH IHn_steps. }\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite unionA, codom_union. apply set_subset_union_r. left.\n by_IH IHn_steps. }\n { subst ev ev'. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite set_interA with (s'' := eq (ThreadEvent tid (eindex st_prev + 1))). simplify_updated_sets. \n rewrite id_union. apply set_subset_union_l. split.\n { expand_rels.\n repeat rewrite codom_union. \n repeat (apply set_subset_union_r; left).\n by_IH IHn_steps. }\n repeat rewrite codom_union. \n repeat (apply set_subset_union_r; right).\n basic_solver 10. }\n }\n { apply (same_relation_exp (@seqA _ _ _ _)) in BLOCK_STEP0.\n apply (same_relation_exp (seq_id_l (step tid ⨾ step tid))) in BLOCK_STEP0.\n red in BLOCK_STEP0. destruct BLOCK_STEP0 as [st_prev' [STEP1 STEP2]]. \n do 2 (red in STEP1; desc). do 2 (red in STEP2; desc).\n forward eapply (BLOCK_CONTENTS 0 f) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 f eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n assert (instr = f). \n { cut (Some instr = Some f); [ins; vauto| ].\n rewrite ISTEP, INSTR. rewrite Nat.add_0_r.\n vauto. }\n rewrite <- INSTRS, UPC in *. \n subst instr. inversion H0. subst ord. (* subst reg. subst lexpr. *)\n forward eapply (BLOCK_CONTENTS 1 exc) as INSTR'; eauto.\n inversion ISTEP2.\n all: try (forward eapply (@H 1 exc eq_refl instr0); by vauto).\n assert (instr0 = exc). \n { cut (Some instr0 = Some exc); [ins; vauto| ].\n rewrite ISTEP1. vauto. }\n subst instr0. inversion H1. subst expr_new xmod ordr ordw reg lexpr rexmod. \n remember (Afence Oacq) as lbl. \n remember (Aload true Osc (RegFile.eval_lexpr (regf st_prev') loc) val0) as lbl'.\n remember (Astore Xpln Osc (RegFile.eval_lexpr (regf st_prev') loc) nval) as lbl''. \n rename st into st_. remember (bst2st bst) as st.\n replace (init (flatten (binstrs bst_prev))) with (init (instrs st_prev)) in * by vauto. \n red.\n replace (bG bst) with (G st) by vauto.\n forward eapply (@step_12_label_ext_helper st_prev st_prev' st) as LBL_EXT; eauto.\n { red. splits; eauto. do 2 (red; eexists); eauto. } \n { red. splits; eauto. red. eexists. red. splits.\n { congruence. }\n exists exc. splits; eauto. rewrite INSTR'. f_equal; vauto. } \n rewrite Heqlbl(* , Heqlbl', Heqlbl'' *) in LBL_EXT. simpl in LBL_EXT. desc. \n remember (ThreadEvent tid (eindex st_prev)) as ev.\n remember (ThreadEvent tid (eindex st_prev')) as ev'. \n remember (ThreadEvent tid (eindex st_prev' + 1)) as ev''.\n assert (wf_thread_state tid st_prev') as WFT'.\n { eapply wf_thread_state_step; eauto. red. eexists. red. splits; eauto. }\n assert (wf_thread_state tid st) as WFT''.\n { eapply wf_thread_state_step; eauto. red. eexists. red.\n splits; [congruence| ]. exists exc. splits; eauto. congruence. }\n \n destruct SB_EXT as [[NO_E SB_TRIVIAL] | SB_EXT]. \n { assert (immediate (sb (G st)) ≡ singl_rel ev ev' ∪ singl_rel ev' ev'') as IMM_SB. \n { rewrite immediate_sb_repr; eauto.\n rewrite UINDEX0, UINDEX. \n assert (eindex st_prev = 0) as EINDEX0.\n { destruct (gt_0_eq (eindex st_prev)); auto.\n exfalso. destruct WFT. forward eapply (@acts_clos 0); [omega| ].\n generalize NO_E. unfold acts_set. basic_solver 100. }\n rewrite EINDEX0. \n split.\n { red. ins. desc. subst ev ev' ev'' x y. rewrite UINDEX.\n destruct ind.\n { red. left. rewrite EINDEX0. red. split; f_equal; omega. }\n assert (ind = 0); [by omega| subst ind].\n red. right. rewrite EINDEX0. red. split; f_equal; omega. }\n red. ins. red in H2. des.\n { subst ev ev'. red in H2. desc. subst. eexists. splits; eauto. omega. }\n { subst ev ev'. red in H2. desc. subst. eexists. splits; eauto. omega. }\n }\n rewrite NO_E in *. (* clear NO_E. *)\n (* subst ev ev' ev''. rewrite UINDEX in *. *)\n splits. all: try rewrite IMM_SB.\n { subst ev ev' ev''. rewrite UINDEX in *. \n rewrite E_EXT, RMW_EXT. \n rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)). rewrite NO_E.\n rewrite eqv_empty. remove_emptiness. \n unfold_clear_updated. expand_rels. simplify_updated_sets. \n basic_solver 10. }\n { unfold_clear_updated. remove_emptiness.\n rewrite set_unionA. expand_rels.\n arewrite (⦗Sc (G st_prev) ∪₁ (eq ev' ∪₁ eq ev'')⦘\n ⨾ rmw (G st_prev) ⨾ ⦗Sc (G st_prev) ∪₁ (eq ev' ∪₁ eq ev'')⦘ ≡ rmw (G st_prev)).\n { rewrite rel_endpoints_dom.\n 2: { eapply wft_rmwE; eauto. }\n fold (acts_set (G st_prev)).\n expand_sets_only. subst ev ev' ev''. simplify_updated_sets.\n rewrite set_interC at 2. rewrite !id_inter, !seqA.\n unfold acts_set. seq_rewrite <- wft_rmwE; eauto.\n symmetry. by_IH IHn_steps. } \n apply union_more; [basic_solver| ].\n rewrite rel_endpoints_dom.\n 2: { symmetry. eapply unique_restr. basic_solver. }\n expand_sets_only. subst ev ev' ev''. simplify_updated_sets.\n rewrite unique_restr; basic_solver. }\n { subst ev ev' ev''. rewrite UINDEX. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver 10. }\n { subst ev ev' ev''. rewrite UINDEX.\n unfold_clear_updated; expand_rels; simplify_updated_sets.\n basic_solver 10. }\n }\n assert (forall st_, immediate (sb (G st_)) ≡ ⦗E (G st_)⦘ ⨾ immediate (sb (G st_)) ⨾ ⦗E (G st_)⦘) as SB_IMM_E.\n { ins. unfold sb. rewrite <- restr_relE. rewrite RESTR_IMM.\n rewrite restr_relE. basic_solver 10. }\n splits.\n { subst ev ev' ev''. rewrite UINDEX in *.\n rewrite E_EXT, W_EXT, SC_EXT at 1. \n remove_emptiness. expand_sets_only. simplify_updated_sets. \n repeat rewrite set_interA. simplify_updated_sets.\n rewrite RMW_EXT. expand_rels. rewrite codom_union.\n apply set_equiv_union.\n { rewrite SB_EXT. rewrite !seq_union_l.\n rewrite wft_rmwE; eauto. fold (acts_set (G st_prev)).\n rewrite singl_rel_restr. rewrite singl_rel_restr with (x := (ThreadEvent tid (eindex st_prev))). rewrite singl_rel_restr with (x := (ThreadEvent tid (eindex st_prev + 1))). \n rewrite !seqA. repeat seq_rewrite <- id_inter. simplify_updated_sets.\n unfold acts_set. seq_rewrite <- wft_rmwE; eauto.\n rewrite SB_IMM_E. rewrite !seqA. seq_rewrite <- id_inter.\n unfold_clear_updated. expand_sets_only. simplify_updated_sets.\n rewrite id_inter, seqA. seq_rewrite <- SB_IMM_E.\n rewrite <- set_interA. by_IH IHn_steps. }\n rewrite SB_EXT. expand_rels.\n rewrite singl_rel_restr with (x := (ThreadEvent tid (eindex st_prev - 1))). rewrite singl_rel_restr with (x := (ThreadEvent tid (eindex st_prev))). rewrite singl_rel_restr with (x := (ThreadEvent tid (eindex st_prev + 1))). \n rewrite !seqA. repeat seq_rewrite <- id_inter. simplify_updated_sets.\n rewrite SB_IMM_E. rewrite !seqA. repeat seq_rewrite <- id_inter. simplify_updated_sets.\n rewrite <- singl_rel_restr.\n unfold_clear_updated. expand_sets_only. simplify_updated_sets.\n basic_solver 10. }\n { unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite wft_rmwE at 2; eauto. fold (acts_set (G st_prev)).\n rewrite !seqA. repeat seq_rewrite <- id_inter.\n unfold_clear_updated; expand_rels; simplify_updated_sets.\n subst ev ev' ev''. simplify_updated_sets. repeat rewrite id_inter.\n rewrite !seqA. unfold acts_set. seq_rewrite <- wft_rmwE; eauto.\n apply union_more; [by_IH IHn_steps| ].\n rewrite singl_rel_restr. rewrite !seqA. repeat seq_rewrite <- id_inter.\n rewrite UINDEX. expand_rels. simplify_updated_sets.\n basic_solver. }\n { subst ev ev' ev''. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite unionA.\n do 2 (rewrite codom_union; apply set_subset_union_r; left). \n by_IH IHn_steps. }\n { subst ev ev' ev''. rewrite UINDEX in *. \n unfold_clear_updated; expand_rels; simplify_updated_sets.\n rewrite !set_interA. simplify_updated_sets.\n rewrite !unionA, codom_union. apply set_subset_union. \n { rewrite id_union. expand_rels. rewrite codom_union.\n apply set_subset_union_r. left. rewrite <- set_interA. by_IH IHn_steps. }\n basic_solver 10. }\n }\n { apply (same_relation_exp (seq_id_l (step tid))) in BLOCK_STEP0.\n do 2 (red in BLOCK_STEP0; desc).\n forward eapply (BLOCK_CONTENTS 0 asn) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 asn eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n subst st_prev. simpl in *. congruence. }\n { apply (same_relation_exp (seq_id_l (step tid))) in BLOCK_STEP0.\n do 2 (red in BLOCK_STEP0; desc).\n forward eapply (BLOCK_CONTENTS 0 igt) as INSTR; eauto.\n inversion ISTEP0.\n all: try (forward eapply (@H 0 igt eq_refl instr); vauto; rewrite Nat.add_0_r; vauto).\n subst st_prev. simpl in *. congruence. }\n Qed. \n\n Lemma GI_1thread_omm_premises tid PO PI Gi\n (COMP: is_thread_compiled PO PI)\n (EXEC: thread_execution tid PI Gi)\n (GOTO_RESTR: goto_addresses_restricted PO):\n omm_premises_hold Gi.\n Proof.\n red in EXEC. destruct EXEC as [st_fin [STEPS [TERM GRAPH]]]. \n red in COMP. desc. red in COMP. desc.\n set (bst_fin := bst_from_st st_fin BPI (length BPI)).\n assert (st_fin = bst2st bst_fin) as BST.\n { replace PI with (instrs st_fin) in *.\n 2: { apply eq_trans with (y := instrs (init PI)); auto.\n symmetry. apply steps_same_instrs. eauto. }\n unfold bst2st. simpl. rewrite firstn_all.\n red in TERM. rewrite (@is_terminal_pc_bounded st_fin tid PO (flatten BPI)) in TERM; [| rewrite <- COMP0; auto | vauto]. \n rewrite <- COMP0 in *.\n rewrite <- TERM. by destruct st_fin. }\n forward eapply (@steps_imply_ommblocks bst_fin) as BLOCK_STEPS; eauto.\n { simpl. rewrite <- COMP0, <- BST. eauto. }\n replace Gi with (bG bst_fin).\n eapply GI_1thread_omm_premises_block; eauto. \n Qed. \n\nEnd CompCorrHelpers.", "meta": {"author": "fresheed", "repo": "omm-imm", "sha": "59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2", "save_path": "github-repos/coq/fresheed-omm-imm", "path": "github-repos/coq/fresheed-omm-imm/omm-imm-59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2/src/ocamlmm/CompSchemeGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.14451107546979897}} {"text": "Require Import Stack2 Stack3A HoareDef SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n Events.MapDefault.\nFrom ExtLib Require Import\n Core.RelDec\n Structures.Maps\n Data.Map.FMapAList.\nRequire Import HTactics ProofMode IPM.\nRequire Import OpenDef STB.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\nSection SIMMODSEM.\n\n Context `{Σ: GRA.t}.\n Context `{@GRA.inG stkRA Σ}.\n\n Let W: Type := Any.t * Any.t.\n\n Inductive sim_loc: URA.car (t:=(Excl.t _)) -> option (list val) -> option (list val) -> Prop :=\n | sim_loc_k stk0: sim_loc (Some stk0) None (Some stk0)\n | sim_loc_u stk0: sim_loc ε (Some stk0) (Some stk0)\n | sim_loc_absent: sim_loc ε None None\n .\n\n Notation sim res0 mgr_src0 mgr_tgt0 :=\n (∀ h, sim_loc ((res0: URA.car (t:=_stkRA)) h)\n ((mgr_src0: gmap mblock (list val)) !! h) ((mgr_tgt0: gmap mblock (list val)) !! h)).\n\n Let wf: _ -> W -> Prop :=\n @mk_wf _ unit\n (fun _ _mgr_src0 _mgr_tgt0 =>\n (∃ mgr_src0 mgr_tgt0 (res0: URA.car (t:=_stkRA)),\n (⌜(<>) /\\ (<>) /\\\n (<>)⌝)\n ∧ ({{\"O\": OwnM ((Auth.black res0): URA.car (t:=stkRA))}})\n )%I)\n .\n\n Variable global_stb: gname -> option fspec.\n Hypothesis STBINCL: stb_incl (to_stb StackStb) global_stb.\n\n Lemma _is_stack_wf\n h stk\n :\n <>\n .\n Proof. ur. ur. i. unfold _is_stack. des_ifs; ur; ss. Qed.\n\n Hint Constructors sim_loc.\n Lemma sim_fresh_k\n res0 mgr_src0 mgr_tgt0\n (SIM: sim res0 mgr_src0 mgr_tgt0)\n (h: mblock) (stk: (list val))\n (FRESH: mgr_tgt0 !! h = None)\n :\n <res0) mgr_src0 (<[h:=stk]> mgr_tgt0)>>\n .\n Proof.\n ii.\n destruct (dec h h0).\n - subst. rewrite ! lookup_insert. unfold insert, fn_insert. des_ifs. ss.\n specialize (SIM h0). inv SIM; ss; et.\n { econs; ss; et. }\n { rewrite FRESH in *. clarify. }\n { econs; ss; et. }\n - rewrite lookup_insert_ne; ss. unfold insert, fn_insert. des_ifs.\n Qed.\n\n Lemma sim_update_k\n res0 mgr_src0 mgr_tgt0\n (SIM: sim res0 mgr_src0 mgr_tgt0)\n (h: mblock) (stk: (list val))\n (FRESH: mgr_src0 !! h = None)\n :\n <res0) mgr_src0 (<[h:=stk]> mgr_tgt0)>>\n .\n Proof.\n ii.\n destruct (dec h h0).\n - subst. rewrite ! lookup_insert. unfold insert, fn_insert. des_ifs. ss.\n specialize (SIM h0). inv SIM; ss; et.\n { econs; ss; et. }\n { rewrite FRESH in *. clarify. }\n { econs; ss; et. }\n - rewrite lookup_insert_ne; ss. unfold insert, fn_insert. des_ifs.\n Qed.\n\n Lemma sim_fresh_u\n res0 mgr_src0 mgr_tgt0\n (SIM: sim res0 mgr_src0 mgr_tgt0)\n (h: mblock) (stk: (list val))\n (FRESH: mgr_tgt0 !! h = None)\n :\n <mgr_src0) (<[h:=stk]> mgr_tgt0)>>\n .\n Proof.\n ii.\n destruct (dec h h0).\n - subst. rewrite ! lookup_insert. unfold insert, fn_insert. des_ifs. ss.\n specialize (SIM h0). inv SIM; ss; et.\n { rewrite FRESH in *. clarify. }\n - rewrite ! lookup_insert_ne; ss.\n Qed.\n\n Lemma sim_update_u\n res0 mgr_src0 mgr_tgt0\n (SIM: sim res0 mgr_src0 mgr_tgt0)\n (h: mblock) (stk: (list val))\n (FRESH: res0 h = ε)\n :\n < mgr_src0) (<[h:=stk]> mgr_tgt0)>>\n .\n Proof.\n ii.\n destruct (dec h h0).\n - subst. rewrite ! lookup_insert. unfold insert, fn_insert. des_ifs. ss.\n specialize (SIM h0). inv SIM; ss; et.\n { rewrite FRESH in *. clarify. }\n - rewrite ! lookup_insert_ne; ss.\n Qed.\n\n Lemma add_disj_insert\n (stk_res0: _stkRA) h stk\n (DISJ: stk_res0 h = ε)\n :\n (stk_res0 ⋅ _is_stack h stk) = <[h:=Excl.just stk]>stk_res0\n .\n Proof.\n unfold insert, fn_insert. extensionality b. ur. unfold _is_stack. des_ifs.\n - rewrite DISJ. rewrite URA.unit_idl. ss.\n - rewrite URA.unit_id. ss.\n Qed.\n\n (* Ltac renamer := *)\n (* match goal with *)\n (* | [mp_src: gmap nat (list val) |- _ ] => *)\n (* let tmp := fresh \"_tmp_\" in *)\n (* rename mp_src into tmp; *)\n (* let name := fresh \"stk_mgr0\" in *)\n (* rename tmp into name *)\n (* end; *)\n (* match goal with *)\n (* | [ACC: current_iPropL _ ?Hns |- _ ] => *)\n (* match Hns with *)\n (* | context[(?name, ([∗ map] _↦_ ∈ _, _))%I] => mRename name into \"SIM\" *)\n (* end *)\n (* end *)\n (* . *)\n\n Ltac renamer :=\n let tmp := fresh \"_tmp_\" in\n\n match goal with\n | H: context[OwnM (Auth.black ?x)] |- _ =>\n rename x into tmp; let name := fresh \"res0\" in rename tmp into name\n end;\n\n match goal with\n | |- gpaco8 _ _ _ _ _ _ _ _ _ _ (Any.pair ?mp_src↑ _, _) ((?mp_tgt↑), _) =>\n\n (* rename mr_src into tmp; let name := fresh \"res0\" in rename tmp into name *)\n (* ; *)\n (* try match goal with *)\n (* | H: _stkRA |- _ => rename H into tmp; let name := fresh \"res0\" in rename tmp into name *)\n (* end *)\n (* ; *)\n\n repeat multimatch mp_src with\n | context[?g] =>\n match (type of g) with\n | gmap mblock (list val) =>\n rename g into tmp; let name := fresh \"mgr_src0\" in rename tmp into name\n | _ => fail\n end\n end\n ;\n\n repeat multimatch mp_tgt with\n | context[?g] =>\n match (type of g) with\n | gmap mblock (list val) =>\n rename g into tmp; let name := fresh \"mgr_tgt0\" in rename tmp into name\n | _ => fail\n end\n end\n end\n .\n Ltac post_call :=\n fold wf; clear_fast; mDesAll; des_safe; subst; try rewrite Any.upcast_downcast in *; clarify; renamer.\n\n Theorem sim_modsem: ModSemPair.sim (Stack3A.StackSem global_stb) (Stack2.StackSem).\n Proof.\n econstructor 1 with (wf:=wf) (le:=top2); ss; et; swap 2 3.\n { esplits. econs; ss.\n - eapply to_semantic. iIntros \"H\". iExists _, _, _. iSplits; ss; et.\n }\n econs; ss.\n { unfold Stack2.new_body, cfunN, cfunU. init.\n - harg. mDesAll. des; clarify. steps.\n post_call.\n rename x0 into h.\n astart 0. astop. steps. force_l. eexists. steps.\n\n mOwnWf \"O\".\n assert(WF1: forall k, res0 k <> Excl.boom).\n { eapply Auth.black_wf in WF0. eapply pw_wf in WF0. des. ii. specialize (WF0 k).\n destruct (res0 k); ss. ur in WF0; ss. }\n\n hret _; ss.\n { iPoseProof (OwnM_Upd with \"O\") as \"O\".\n { eapply Auth.auth_alloc2. instantiate (1:=(_is_stack h [])).\n rewrite add_disj_insert; ss.\n { eapply (@pw_insert_wf); et.\n { eapply Auth.black_wf; et. }\n { ur; ss. }\n }\n specialize (WF1 h). destruct (res0 h) eqn:T; ss; et.\n { spc SIM. rewrite T in *. inv SIM. rewrite _GUARANTEE in *. ss. }\n }\n iMod \"O\". iDestruct \"O\" as \"[A B]\". iModIntro. iSplitL \"A\"; ss; et.\n iSplits; ss; et. iPureIntro. ii.\n assert(B: res0 h = Excl.unit).\n { destruct (res0 h) eqn:V; ss.\n - specialize (SIM h). rewrite V in SIM. inv SIM. rewrite _GUARANTEE in *. ss.\n - exploit WF1; et; ss.\n }\n rewrite add_disj_insert; ss. eapply sim_fresh_k; et.\n }\n - harg. mDesAll. des; clarify. unfold new_body. cbn. steps. astop. steps.\n rename x0 into h. force_l. exists h. steps.\n unfold pget. steps.\n assert(S:=SIM h). rewrite _GUARANTEE in *. inv S; ss. astop. steps.\n astop. steps. force_l; ss. steps. astop. steps.\n\n hret _; ss.\n iModIntro. iSplits; ss; et. iPureIntro. eapply sim_fresh_u; et.\n }\n\n econs; ss.\n { unfold Stack2.pop_body, cfunN. init.\n - harg. mDesAll. des; clarify. steps. ss. mDesAll. des; clarify.\n renamer. rename n into h. rename l into stk0.\n\n mCombine \"O\" \"A\".\n mOwnWf \"O\".\n assert(A: forall k, URA.wf ((res0 k): URA.car (t:=Excl.t _))).\n { eapply URA.wf_mon in WF0.\n eapply Auth.black_wf in WF0. eapply pw_wf in WF0. des. ii. specialize (WF0 k). ss. }\n assert(B: res0 h = Some stk0).\n { dup WF0.\n eapply Auth.auth_included in WF0. des. unfold _is_stack in WF0. eapply pw_extends in WF0. des.\n spc WF0. des_ifs. ss. eapply Excl.extends in WF0; ss. }\n assert(S:=SIM h). rewrite B in *. inv S; ss. steps.\n astart 0. astop.\n destruct stk0 as [|x stk1].\n + steps. force_l. esplits. steps.\n rewrite <- H3. steps. hret _; ss.\n iDestruct \"O\" as \"[A B]\". iModIntro. iFrame. iSplitL \"A\"; ss; et.\n + steps.\n\n set (res1:=<[h:=Excl.just stk1]>res0).\n assert(WF1: URA.wf (res1: URA.car (t:=_stkRA))).\n { subst res1. eapply (@pw_insert_wf); et.\n { eapply URA.wf_mon in WF0. eapply Auth.black_wf in WF0. ss. }\n ur; ss.\n }\n\n mAssert _ with \"O\".\n { iApply (OwnM_Upd with \"O\").\n eapply Auth.auth_update with (a':=res1) (b':=_is_stack h (stk1)).\n bar. ii. ss. des. clarify. esplits; et.\n assert(D: ctx0 h = Excl.unit).\n { clear - B. repeat ur in B. unfold _is_stack in *. des_ifs. }\n extensionality h0. subst res1. unfold insert, fn_insert. des_ifs.\n - ur. rewrite D. unfold _is_stack. ur. des_ifs.\n - unfold _is_stack. ur. des_ifs.\n }\n mUpd \"A\". mDesOwn \"A\".\n\n assert(SIM0: sim res1 mgr_src0 (<[h:=stk1]> mgr_tgt0)).\n { eapply sim_update_k; et. }\n\n force_l. esplits. steps.\n rewrite <- H3. steps. hret _; ss.\n iModIntro. iFrame. iSplitL \"A\"; ss; et.\n - harg. mDesAll. des; clarify. unfold pop_body. cbn.\n steps. astop. steps. astop. steps. astop. steps.\n rename n into h. rename l into stk0. destruct v; ss. des_ifs_safe.\n assert(S:=SIM h). rewrite _UNWRAPU1 in *. inv S; ss. steps.\n destruct stk0 as [|x0 stk1].\n + steps. hret _; ss. iModIntro. iSplits; ss; et.\n + steps. unfold pput. astop. steps.\n\n hret _; ss.\n { iModIntro. iSplits; ss; et. iPureIntro. eapply sim_update_u; et. }\n }\n\n econs; ss.\n { unfold Stack2.push_body, cfunN. init.\n - harg. mDesAll. des; clarify. steps. ss. mDesAll. des; clarify.\n renamer. rename n into h. rename l into stk0. rename v into x.\n mCombine \"O\" \"A\".\n mOwnWf \"O\".\n assert(A: forall k, URA.wf ((res0 k): URA.car (t:=Excl.t _))).\n { eapply URA.wf_mon in WF0.\n eapply Auth.black_wf in WF0. eapply pw_wf in WF0. des. ii. specialize (WF0 k). ss. }\n assert(B: res0 h = Some stk0).\n { dup WF0.\n eapply Auth.auth_included in WF0. des. unfold _is_stack in WF0. eapply pw_extends in WF0. des.\n spc WF0. des_ifs. ss. eapply Excl.extends in WF0; ss. }\n assert(S:=SIM h). rewrite B in *. inv S; ss. steps.\n\n set (res1:=<[h:=Excl.just (x::stk0)]>res0).\n assert(WF1: URA.wf (res1: URA.car (t:=_stkRA))).\n { subst res1. eapply (@pw_insert_wf); et.\n { eapply URA.wf_mon in WF0. eapply Auth.black_wf in WF0. ss. }\n ur; ss.\n }\n\n mAssert _ with \"O\".\n { iApply (OwnM_Upd with \"O\").\n eapply Auth.auth_update with (a':=res1) (b':=_is_stack h (x::stk0)).\n bar. ii. ss. des. clarify. esplits; et.\n assert(D: ctx0 h = Excl.unit).\n { clear - B. repeat ur in B. unfold _is_stack in *. des_ifs. }\n extensionality h0. subst res1. unfold insert, fn_insert. des_ifs.\n - ur. rewrite D. unfold _is_stack. ur. des_ifs.\n - unfold _is_stack. ur. des_ifs.\n }\n mUpd \"A\". mDesOwn \"A\".\n\n assert(SIM0: sim res1 mgr_src0 (<[h:=x::stk0]> mgr_tgt0)).\n { eapply sim_update_k; et. }\n\n astop. steps.\n force_l. esplits. steps.\n rewrite <- H3. steps. hret _; ss.\n iModIntro. iFrame. iSplitL \"A\"; ss; et.\n - harg. mDesAll. des; clarify. unfold push_body. cbn.\n steps. astop. steps. astop. steps. astop. steps. astop. steps.\n rename n into h. rename l into stk0. destruct v; ss. des_ifs_safe.\n assert(S:=SIM h). rewrite _UNWRAPU0 in *. inv S; ss. steps.\n unfold pput. steps.\n\n hret _; ss.\n { iModIntro. iSplits; ss; et. iPureIntro. eapply sim_update_u; et. }\n }\n Unshelve.\n all: try exact 0. all: ss.\n Qed.\n\nEnd SIMMODSEM.\n\n\n\nSection SIMMOD.\n\n Context `{Σ: GRA.t}.\n Context `{@GRA.inG stkRA Σ}.\n\n Variable global_stb: Sk.t -> gname -> option fspec.\n Hypothesis STBINCL: forall sk, stb_incl (to_stb StackStb) (global_stb sk).\n\n Theorem correct: refines2 [Stack2.Stack] [Stack3A.Stack global_stb].\n Proof.\n eapply adequacy_local2. econs; ss.\n { ii. eapply sim_modsem; ss. }\n Qed.\n\nEnd SIMMOD.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/stack/Stack23Aproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1445110712303212}} {"text": "\nRequire Export Iron.Language.SystemF2.Ki.\nRequire Export Iron.Language.SystemF2.KiJudge.\nRequire Export Iron.Language.SystemF2.TyEnv.\nRequire Export Iron.Language.SystemF2.TySubsts.\nRequire Export Iron.Language.SystemF2Store.Def.\nRequire Export Iron.Language.SystemF2Store.Exp.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n\n(******************************************************************************)\n(* Builtin in types. *)\nDefinition tUnit \n := makeTApps (TCon tcUnit) nil.\n\nDefinition tFun (t1: ty) (t2: ty)\n := TApp (TApp (TCon TyConFun) t1) t2.\nHint Unfold tFun.\n\n\n(* TODO: move this to Env module *)\n(* Store Typing holds the types of locations *)\nDefinition stenv := list ty.\n\n\n(******************************************************************************)\n(* Type Judgement assigns a type to an expression. *)\nInductive TYPE (ds: defs) (ke: kienv) (te: tyenv) (se: stenv)\n : exp -> ty -> Prop :=\n\n (* Variables *)\n | TyVar \n : forall i t\n , DEFSOK ds\n -> get i te = Some t\n -> TYPE ds ke te se (XVar i) t\n\n (* Locations must refer to data types.\n Naked functions are not place in the store because\n they are not updatable and have no region annotations. *)\n | TyLoc\n : forall i t tc\n , DEFSOK ds\n -> get i se = Some t\n -> getCtorOfType t = Some tc\n -> isTyConData tc\n\n -> TYPE ds ke te se (XLoc i) t\n\n (* Type abstraction *)\n | TyLAM \n : forall x1 t1\n , TYPE ds (ke :> KStar) (liftTE 0 te) (liftTE 0 se) x1 t1 \n -> TYPE ds ke te se (XLAM x1) (TForall t1)\n\n (* Type application *)\n | TyAPP\n : forall x1 t1 t2\n , TYPE ds ke te se x1 (TForall t1)\n -> KIND ke t2 KStar\n -> TYPE ds ke te se (XAPP x1 t2) (substTT 0 t2 t1)\n\n (* Function abstraction *)\n | TyLam\n : forall x t1 t2\n , KIND ke t1 KStar\n -> TYPE ds ke (te :> t1) se x t2\n -> TYPE ds ke te se (XLam t1 x) (tFun t1 t2)\n\n (* Applications *)\n | TyApp\n : forall x1 x2 t1 t2\n , TYPE ds ke te se x1 (tFun t1 t2)\n -> TYPE ds ke te se x2 t1\n -> TYPE ds ke te se (XApp x1 x2) t2\n\n (* Data Constructors *)\n | TyCon \n : forall tc (ks: list ki) tsFields tsParam xs dc dcs\n , hasDef ds (DefType tc ks dcs)\n -> hasDef ds (DefData dc tsFields tc)\n -> Forall2 (KIND ke) tsParam ks\n -> Forall2 (TYPE ds ke te se) xs (map (substTTs 0 tsParam) tsFields)\n -> TYPE ds ke te se (XCon dc tsParam xs) (makeTApps (TCon tc) tsParam)\n\n (* Case Expressions *)\n | TyCase\n : forall xObj tObj tcObj ks tResult alts dcs\n\n (* check types of expression and alternatives *)\n , TYPE ds ke te se xObj tObj\n -> Forall (fun alt => TYPEA ds ke te se alt tObj tResult) alts\n\n (* All data cons must have a corresponding alternative. \n Maybe we should move this to the well-formedness judgement *)\n -> getCtorOfType tObj = Some tcObj\n -> hasDef ds (DefType tcObj ks dcs)\n -> Forall (fun dc => In dc (map dcOfAlt alts)) dcs\n\n -> TYPE ds ke te se (XCase xObj alts) tResult\n\n (* Update data object *)\n | TyUpdate\n : forall i xObj dcObj tcObj tsParam tsFields ks dcs xField tField\n , hasDef ds (DefType tcObj ks dcs)\n -> hasDef ds (DefData dcObj tsFields tcObj)\n -> Forall2 (KIND ke) tsParam ks\n -> get i tsFields = Some tField\n -> TYPE ds ke te se xObj (makeTApps (TCon tcObj) tsParam) \n -> TYPE ds ke te se xField (substTTs 0 tsParam tField)\n -> TYPE ds ke te se (XUpdate dcObj i tsParam xObj xField) tUnit\n\nwith TYPEA (ds: defs) (ke: kienv) (te: tyenv) (se: stenv)\n : alt -> ty -> ty -> Prop :=\n (* Case Alternatives *)\n | TyAlt \n : forall x1 dc tc ks tsParam tsFields tResult dcs\n , hasDef ds (DefType tc ks dcs)\n -> hasDef ds (DefData dc tsFields tc)\n -> Forall2 (KIND ke) tsParam ks\n -> TYPE ds ke (te >< map (substTTs 0 tsParam) tsFields) se x1 tResult\n -> TYPEA ds ke te se (AAlt dc x1) (makeTApps (TCon tc) tsParam) tResult.\n\nHint Constructors TYPE.\nHint Constructors TYPEA.\n\n\n(* Invert all hypothesis that are compound typing statements. *)\nLtac inverts_type :=\n repeat \n (match goal with \n | [ H: TYPE _ _ _ _ (XVar _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XLoc _) _ |- _ ] => inverts H \n | [ H: TYPE _ _ _ _ (XLAM _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XAPP _ _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XLam _ _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XApp _ _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XCon _ _ _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XCase _ _) _ |- _ ] => inverts H\n | [ H: TYPE _ _ _ _ (XUpdate _ _ _ _ _) _ |- _ ] => inverts H\n | [ H: TYPEA _ _ _ _ (AAlt _ _) _ _ |- _ ] => inverts H\n end).\n\n\n(********************************************************************)\n(* Well typing imples data type defs are ok *)\nLemma type_defsok\n : forall ds ke te se x t\n , TYPE ds ke te se x t\n -> DEFSOK ds.\nProof.\n intros. gen ke te se t.\n induction x using exp_mutind with\n (PA := fun a => forall ke te se t1 t2\n , TYPEA ds ke te se a t1 t2\n -> DEFSOK ds)\n ; intros; inverts_type; try eauto.\nQed.\nHint Resolve type_defsok.\n\n\n(********************************************************************)\n(* Uniqueness of typing *)\nLemma type_unique\n : forall ds ke te se x t1 t2 \n , TYPE ds ke te se x t1\n -> TYPE ds ke te se x t2\n -> t1 = t2.\nProof.\n intros. gen ds ke te se t1 t2.\n induction x using exp_mutind with \n (PA := fun a => forall ds ke te se t2 t3 t3'\n , TYPEA ds ke te se a t2 t3\n -> TYPEA ds ke te se a t2 t3'\n -> t3 = t3');\n intros; try (solve [inverts_type; try congruence]).\n\n inverts_type. spec IHx H1 H2. auto. congruence.\n inverts_type. spec IHx H2 H3. auto. congruence.\n inverts_type. spec IHx H5 H6. auto. congruence.\n\n Case \"XApp\".\n inverts_type.\n spec IHx1 H3 H2. auto.\n spec IHx2 H5 H6. auto.\n unfold tFun in *.\n congruence.\n\n Case \"XCon\".\n inverts_type.\n defs_merge.\n auto.\n \n Case \"XCase\".\n inverts_type.\n have (tObj0 = tObj).\n eauto. subst.\n\n repeat nforall.\n assert (length aa > 0).\n lets D: @length_in_in_nonempty H9.\n have (DEFOK ds (DefType tcObj ks dcs)) as HD.\n inverts HD.\n lists. rip.\n\n destruct aa. \n nope.\n have (TYPEA ds ke te se a tObj t1) as HT1.\n have (TYPEA ds ke te se a tObj t2) as HT2.\n spec H a HT1 HT2; burn.\n\n Case \"Alt\".\n inverts_type.\n eapply makeTApps_eq_params in H2. rip.\n defs_merge.\n lets D1: IHx H8 H11; auto.\nQed.\n\n\n(********************************************************************)\n(* Forms of values. \n If we know the type of a value,\n then we know the form of that value. *)\nLemma value_lam \n : forall x ds ke te se t1 t2\n , value x \n -> TYPE ds ke te se x (tFun t1 t2)\n -> (exists t x', x = XLam t x').\nProof.\n intros. destruct x; eauto; nope.\n\n (* 'x' can't be a XLoc because we don't store naked functions in the heap *)\n Case \"XLoc n = XLam t x'\".\n inverts H0. \n unfold tFun in H4.\n simpl in *. inverts H4.\n nope.\nQed.\nHint Resolve value_lam.\n\n\nLemma value_loc\n : forall x ds ke te se tcObj ts\n , value x\n -> isTyConData tcObj\n -> TYPE ds ke te se x (makeTApps (TCon tcObj) ts)\n -> (exists l, x = XLoc l).\nProof.\n intros. destruct x; eauto; nope.\n \n Case \"XLAM x = XLoc l\".\n inverts_type.\n symmetry in H3.\n apply makeTApps_takeTCon in H3.\n nope.\n\n Case \"XLam t x = XLoc l\".\n inverts_type. \n symmetry in H4.\n unfold tFun in *.\n apply makeTApps_takeTCon in H4.\n simpl in H4.\n inverts H4.\n nope.\nQed.\n\n\n(********************************************************************)\n(* Forms of types *)\nLemma type_XLAM\n : forall ds ke te se x t\n , TYPE ds ke te se (XLAM x) t\n -> (exists t', t = TForall t').\nProof.\n intros. destruct t; nope.\n eauto.\nQed.\nHint Resolve type_XLAM.\n\n\nLemma type_XLam\n : forall ds ke te se x t1 t2\n , TYPE ds ke te se (XLam t1 x) t2\n -> (exists t21 t22, t2 = tFun t21 t22).\nProof.\n intros. destruct t2; nope.\n inverts H. \n unfold tFun. eauto.\nQed.\nHint Resolve type_XLam.\n\n\n(********************************************************************)\n(* A well typed expression is well formed *)\n\nTheorem type_wfX\n : forall ds ke te se x t\n , TYPE ds ke te se x t\n -> wfX (length ke) (length te) (length se) x.\nProof.\n intros. gen ds ke te se t.\n induction x using exp_mutind with \n (PA := fun a => forall ds ke te se t1 t2\n , TYPEA ds ke te se a t1 t2 \n -> wfA (length ke) (length te) (length se) a)\n ; intros; inverts_type; eauto.\n\n Case \"XLAM\".\n eapply WfX_XLAM.\n apply IHx in H1.\n rrwrite (length (ke :> KStar) = S (length ke)) in H1.\n rewrite <- length_liftTE in H1.\n rewrite <- length_liftTE in H1.\n auto.\n\n Case \"XLam\".\n eapply WfX_XLam; eauto.\n apply IHx in H4.\n rrwrite (length (te :> t) = S (length te)) in H4.\n auto.\n\n Case \"XCon\".\n apply WfX_XCon.\n repeat nforall. intros.\n have (exists k, KIND ke x k).\n dest k. eauto.\n repeat nforall. intros.\n have (exists t, TYPE ds ke te se x t).\n dest t. eauto.\n\n Case \"XCase\".\n eapply WfX_XCase; eauto.\n repeat nforall. eauto.\n\n Case \"XAlt\".\n destruct dc.\n eapply WfA_AAlt. eauto.\n apply IHx in H7.\n rr. lists.\n rrwrite (length te + length tsFields = length tsFields + length te).\n eauto.\nQed.\nHint Resolve type_wfX.\n\n\nLemma type_wfX_Forall2\n : forall ds ke te se xs ts\n , Forall2 (TYPE ds ke te se) xs ts\n -> Forall (wfX (length ke) (length te) (length se)) xs.\nProof.\n intros.\n eapply (Forall2_Forall_left (TYPE ds ke te se)).\n intros. nforall. eauto.\n eauto.\nQed.\nHint Resolve type_wfX_Forall2.\n\n\n(********************************************************************)\n(* Weakening Kind Env in Type Judgement. *)\nLemma type_kienv_insert\n : forall ix ds ke te se x1 t1 k2\n , TYPE ds ke te se x1 t1\n -> TYPE ds (insert ix k2 ke) (liftTE ix te) (liftTE ix se) (liftTX ix x1) (liftTT 1 ix t1).\nProof.\n intros. gen ix ds ke te se t1 k2.\n induction x1 using exp_mutind with \n (PA := fun a => forall ix ds ke te se k2 t3 t4\n , TYPEA ds ke te se a t3 t4 \n -> TYPEA ds (insert ix k2 ke) (liftTE ix te) (liftTE ix se)\n (liftTA ix a) (liftTT 1 ix t3) (liftTT 1 ix t4))\n ; intros; inverts_type; simpl; eauto.\n\n Case \"XVar\".\n apply TyVar; auto.\n apply get_map; auto.\n\n Case \"XLoc\".\n eapply TyLoc; eauto.\n apply get_map; auto.\n burn.\n\n Case \"XLAM\".\n eapply TyLAM. \n rewrite insert_rewind. \n rewrite (liftTE_liftTE 0 ix).\n rewrite (liftTE_liftTE 0 ix).\n burn.\n\n Case \"XAPP\".\n rewrite (liftTT_substTT' 0 ix). \n simpl.\n eapply TyAPP.\n eapply (IHx1 ix) in H2. simpl in H2. eauto.\n apply kind_kienv_insert; auto.\n\n Case \"XLam\".\n apply TyLam.\n apply kind_kienv_insert. auto.\n rrwrite ( liftTE ix te :> liftTT 1 ix t\n = liftTE ix (te :> t)).\n burn.\n\n Case \"XApp\".\n eapply TyApp.\n eapply IHx1_1 in H2. simpl in H2. eauto.\n eapply IHx1_2 in H4. eauto.\n\n Case \"XCon\".\n (* unpack the data type definition *)\n have (DEFOK ds (DefData dc tsFields tc)).\n\n (* show XCon has the correct type *)\n rr. eapply TyCon; eauto.\n\n (* type args have correct kinds *)\n eapply Forall2_map_left.\n eapply Forall2_impl; eauto.\n eauto using kind_kienv_insert.\n\n (* exp args have correct types *)\n apply Forall2_map.\n apply Forall2_map_right' in H8.\n\n eapply Forall2_impl_in; eauto.\n simpl. intros.\n\n nforall.\n lets D: H x ix k2; auto. clear H.\n eauto.\n\n have (wfT (length ks) y) as HT.\n have (length ts = length ks) as HL.\n rewrite <- HL in HT.\n\n assert ( liftTT 1 ix (substTTs 0 ts y)\n = substTTs 0 (map (liftTT 1 ix) ts) y) as HF.\n rrwrite (ix = ix + 0).\n rewrite liftTT_substTTs'.\n rrwrite (ix + 0 = ix).\n f_equal.\n rr. auto.\n\n rewrite <- HF.\n auto.\n\n Case \"XCase\".\n eapply TyCase; eauto.\n apply Forall_map.\n eapply Forall_impl_in; eauto.\n intros. repeat nforall.\n eapply H; burn.\n rr. burn.\n repeat nforall. intros.\n have (In x (map dcOfAlt aa)).\n rr. auto.\n\n Case \"XUpdate\".\n have (DEFOK ds (DefData dc tsFields tcObj)).\n eapply TyUpdate; eauto.\n eapply Forall2_map_left.\n eapply Forall2_impl; eauto.\n eauto using kind_kienv_insert.\n rrwrite (TCon tcObj = liftTT 1 ix (TCon tcObj)). \n rewrite <- liftTT_makeTApps.\n eauto. \n rrwrite (ix = 0 + ix). \n rewrite substTTs_liftTT.\n rr. eauto.\n rr.\n rrwrite (length ts = length ks).\n repeat nforall. eauto.\n\n Case \"XAlt\".\n have (DEFOK ds (DefData dc tsFields tc)).\n\n rr.\n eapply TyAlt; eauto.\n eapply Forall2_map_left.\n eapply Forall2_impl; eauto.\n intros. eapply kind_kienv_insert. auto.\n\n assert ( map (liftTT 1 ix) (map (substTTs 0 tsParam) tsFields)\n = map (substTTs 0 (map (liftTT 1 ix) tsParam)) tsFields) as HXX.\n lists.\n erewrite map_ext_in; eauto.\n intros.\n rename a into t1.\n\n rrwrite (ix = ix + 0).\n rewrite liftTT_substTTs'.\n f_equal. \n nnat.\n\n have (wfT (length ks) t1).\n rw (length tsParam = length ks).\n auto.\n\n unfold liftTE in IHx1. \n unfold liftTE.\n rewrite <- HXX.\n rewrite <- map_app.\n burn.\nQed.\n\n\nLemma type_kienv_weaken1\n : forall ds ke te se x1 t1 k2\n , TYPE ds ke te se x1 t1\n -> TYPE ds (ke :> k2) (liftTE 0 te) (liftTE 0 se) (liftTX 0 x1) (liftTT 1 0 t1).\nProof.\n intros.\n assert (ke :> k2 = insert 0 k2 ke) as HI.\n simpl. destruct ke; auto.\n rewrite HI.\n eapply type_kienv_insert; auto.\nQed.\n\n\n(********************************************************************)\n(* Weakening Type Env in Type Judgement.\n We can insert a new type into the type environment, provided we\n lift existing references to types higher in the stack across\n the new one. *)\nLemma type_tyenv_insert\n : forall ds ke te se ix x t1 t2\n , TYPE ds ke te se x t1\n -> TYPE ds ke (insert ix t2 te) se (liftXX 1 ix x) t1.\nProof.\n intros. gen ix ds ke se te t1 t2.\n induction x using exp_mutind with \n (PA := fun a => forall ix ds ke se te t2 t3 t4\n , TYPEA ds ke te se a t3 t4 \n -> TYPEA ds ke (insert ix t2 te) se (liftXA 1 ix a) t3 t4)\n ; intros; inverts_type; simpl; eauto.\n\n Case \"XVar\".\n nnat; lift_cases; burn.\n\n Case \"XLAM\".\n apply TyLAM.\n assert ( liftTE 0 (insert ix t2 te)\n = insert ix (liftTT 1 0 t2) (liftTE 0 te)).\n unfold liftTE. rewrite map_insert. auto.\n burn.\n\n Case \"XLam\".\n apply TyLam; eauto.\n rewrite insert_rewind. auto.\n\n Case \"XCon\".\n eapply TyCon; eauto.\n nforall.\n apply (Forall2_map_left (TYPE ds ke (insert ix t2 te) se)).\n apply (Forall2_impl_in (TYPE ds ke te se)); eauto.\n\n Case \"XCase\".\n eapply TyCase; eauto.\n apply Forall_map.\n apply (Forall_impl_in \n (fun a => TYPEA ds ke te se a tObj t1)); eauto.\n repeat nforall. eauto.\n repeat nforall.\n intros. lists.\n rename x0 into d.\n eapply map_exists_in.\n have (In d (map dcOfAlt aa)). \n assert (exists a, dcOfAlt a = d /\\ In a aa).\n eapply map_in_exists. auto.\n shift a. rip.\n eapply dcOfAlt_liftXA.\n\n Case \"XAlt\".\n have (DEFOK ds (DefData dc tsFields tc)).\n destruct dc. inverts keep H.\n eapply TyAlt; eauto.\n rewrite insert_app.\n lists.\n eauto.\nQed. \n\n\n(* We can push a new type onto the environment stack provided\n we lift references to existing types across the new one. *)\nLemma type_tyenv_weaken1\n : forall ds ke te se x t1 t2\n , TYPE ds ke te se x t1\n -> TYPE ds ke (te :> t2) se (liftXX 1 0 x) t1.\nProof.\n intros.\n assert (te :> t2 = insert 0 t2 te) as HI.\n simpl. destruct te; auto.\n rewrite HI.\n apply type_tyenv_insert. auto.\nQed.\n\n\n(* We can several new types onto the environment stack provided\n we lift referenes to existing types across the new one. *)\nLemma type_tyenv_weaken_append\n : forall ds ke te te' se x t1\n , TYPE ds ke te se x t1\n -> TYPE ds ke (te >< te') se (liftXX (length te') 0 x) t1.\nProof.\n intros.\n induction te'; simpl.\n burn.\n\n rrwrite (S (length te') = length te' + 1).\n rrwrite (length te' + 1 = 1 + length te').\n rewrite <- liftXX_plus.\n eapply type_tyenv_weaken1.\n burn.\nQed.\n\n\n(********************************************************************)\n(* Weakening Store Typing in Type Judgement. *)\nLemma type_stenv_snoc \n : forall ds ke te se t2 x t1\n , closedT t2\n -> TYPE ds ke te se x t1\n -> TYPE ds ke te (t2 <: se) x t1.\nProof.\n intros. gen ds ke te se t1 t2.\n induction x using exp_mutind with \n (PA := fun a => forall ds ke te se t2 t3 t4\n , closedT t2\n -> TYPEA ds ke te se a t3 t4\n -> TYPEA ds ke te (t2 <: se) a t3 t4)\n ; intros; inverts_type; eauto.\n\n Case \"XLAM\".\n eapply TyLAM.\n unfold liftTE in *. rr.\n spec IHx H2. eauto.\n\n Case \"XCon\".\n eapply TyCon; eauto.\n eapply Forall2_impl_in with (R1 := TYPE ds ke te se); \n repeat nforall; eauto.\n\n Case \"XCase\".\n eapply TyCase; \n repeat nforall; eauto.\nQed.\nHint Resolve type_stenv_snoc.\n\n\nLemma type_stenv_weaken\n : forall ds ke te se1 se2 x t1\n , Forall closedT se2\n -> TYPE ds ke te se1 x t1\n -> TYPE ds ke te (se2 >< se1) x t1.\nProof.\n intros. gen ds ke te se1.\n induction se2; intros.\n rewrite app_nil_right. auto.\n rrwrite ((se2 :> a) >< se1 = se2 >< (a <: se1)). \n inverts H. eauto.\nQed.\nHint Resolve type_stenv_weaken.\n\n\nLemma type_stenv_extends\n : forall ds ke te se1 se2 x t1\n , Forall closedT se2\n -> extends se2 se1\n -> TYPE ds ke te se1 x t1\n -> TYPE ds ke te se2 x t1.\nProof.\n intros.\n unfold extends in *.\n destruct H0 as [se3]. subst.\n eapply type_stenv_weaken; auto.\n eauto.\nQed.\nHint Resolve type_stenv_extends.\n\n\nLemma typea_stenv_extends\n : forall ds ke te aa t1 t2 se1 se2\n , Forall closedT se2\n -> extends se2 se1\n -> TYPEA ds ke te se1 aa t1 t2\n -> TYPEA ds ke te se2 aa t1 t2.\nProof.\n intros.\n destruct aa.\n inverts H1.\n eauto.\nQed.\nHint Resolve typea_stenv_extends.\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Store/TyJudge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.25982564942392716, "lm_q1q2_score": 0.14406565247048386}} {"text": "From iris.algebra Require Import auth agree excl gmap gset frac.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Import adequacy.\nFrom cap_machine Require Import\n stdpp_extra iris_extra\n rules logrel fundamental.\nFrom cap_machine.examples Require Import addr_reg_sample malloc assert macros_new.\nFrom cap_machine.examples Require Export mkregion_helpers disjoint_regions_tactics.\nFrom cap_machine.examples Require Import template_adequacy.\n\nModule ocpl.\nInclude with_adv_and_link.\n\nRecord ocpl_library `{MachineParameters} := MkOcplLibrary {\n (* malloc library *)\n malloc_start : Addr;\n malloc_memptr : Addr;\n malloc_mem_start : Addr;\n malloc_end : Addr;\n\n malloc_code_size :\n (malloc_start + length malloc_subroutine_instrs)%a\n = Some malloc_memptr;\n\n malloc_memptr_size :\n (malloc_memptr + 1)%a = Some malloc_mem_start;\n\n malloc_mem_size :\n (malloc_mem_start <= malloc_end)%a;\n\n (* assert library *)\n assert_start : Addr;\n assert_cap : Addr;\n assert_flag : Addr;\n assert_end : Addr;\n\n assert_code_size :\n (assert_start + length assert_subroutine_instrs)%a = Some assert_cap;\n assert_cap_size :\n (assert_cap + 1)%a = Some assert_flag;\n assert_flag_size :\n (assert_flag + 1)%a = Some assert_end;\n\n (* disjointness of the two libraries *)\n libs_disjoint : ## [\n finz.seq_between assert_start assert_end;\n finz.seq_between malloc_mem_start malloc_end;\n [malloc_memptr];\n finz.seq_between malloc_start malloc_memptr\n ]\n}.\n\nDefinition malloc_library_content `{MachineParameters} (layout : ocpl_library) : gmap Addr Word :=\n (* code for the malloc subroutine *)\n mkregion (malloc_start layout) (malloc_memptr layout) malloc_subroutine_instrs\n (* Capability to malloc's memory pool, used by the malloc subroutine *)\n ∪ list_to_map [((malloc_memptr layout), WCap RWX (malloc_memptr layout) (malloc_end layout) (malloc_mem_start layout))]\n (* Malloc's memory pool, initialized to zero *)\n ∪ mkregion (malloc_mem_start layout) (malloc_end layout) (region_addrs_zeroes (malloc_mem_start layout) (malloc_end layout)).\n\nDefinition lib_entry_malloc `{MachineParameters} (layout : ocpl_library) : lib_entry :=\n {| lib_start := malloc_start layout;\n lib_end := malloc_end layout;\n lib_entrypoint := malloc_start layout;\n lib_full_content := malloc_library_content layout|}.\n\n(* assert library entry *)\nDefinition assert_library_content `{MachineParameters} (layout : ocpl_library) : gmap Addr Word :=\n (* code for the assert subroutine, followed by a capability to the assert flag\n and the flag itself, initialized to 0. *)\n mkregion (assert_start layout) (assert_cap layout) assert_subroutine_instrs\n ∪ list_to_map [(assert_cap layout, WCap RW (assert_flag layout) (assert_end layout) (assert_flag layout))]\n ∪ list_to_map [(assert_flag layout, WInt 0)] (* assert flag *).\n\nDefinition lib_entry_assert `{MachineParameters} (layout : ocpl_library) : lib_entry :=\n {| lib_start := assert_start layout;\n lib_end := assert_end layout;\n lib_entrypoint := assert_start layout;\n lib_full_content := assert_library_content layout |}.\n\n(* full library *)\nDefinition library `{MachineParameters} (layout : ocpl_library) : lib :=\n {| priv_libs := [lib_entry_assert layout] ;\n pub_libs := [lib_entry_malloc layout] |}.\n\nDefinition OK_invariant `{MachineParameters} (layout : ocpl_library) (m : gmap Addr Word) : Prop :=\n ∀ w, m !! (assert_flag layout) = Some w → w = WInt 0%Z.\n\nDefinition OK_dom `{MachineParameters} (layout : ocpl_library) : gset Addr := {[ assert_flag layout ]}.\n\nProgram Definition OK_dom_correct `{MachineParameters} (layout : ocpl_library) :\n ∀ m m',\n (∀ a, a ∈ OK_dom layout → ∃ x, m !! a = Some x ∧ m' !! a = Some x) →\n OK_invariant layout m ↔ OK_invariant layout m'.\nProof.\n intros m m' Hdom.\n destruct Hdom with (assert_flag layout) as [w [Hw1 Hw2] ]. rewrite /OK_dom. set_solver.\n split;intros HOK;intros w' Hw';simplify_eq;apply HOK;auto.\nDefined.\n\nDefinition flag_inv `{MachineParameters} (layout : ocpl_library) : memory_inv :=\n {| minv := OK_invariant layout;\n minv_dom := {[ assert_flag layout ]} ;\n minv_dom_correct := OK_dom_correct layout |}.\n\nLemma flag_inv_is_initial_memory `{MachineParameters} (layout : ocpl_library) trusted_prog adv_prog trusted_table adv_table m :\n is_initial_memory trusted_prog adv_prog (library layout) trusted_table adv_table m →\n minv (flag_inv layout) m.\nProof.\n intros Hinit. intros a Hin.\n destruct Hinit as (?&?&Hlibs&?&?&?&Hlibdisj).\n cbn in Hlibs. rewrite map_union_empty in Hlibs.\n assert ((assert_library_content layout) ⊆ m) as Hassert.\n { etrans;[|eauto]. apply map_union_subseteq_r. cbn in Hlibdisj.\n rewrite !map_union_empty in Hlibdisj. auto. }\n pose proof (assert_code_size layout). pose proof (assert_cap_size layout).\n pose proof (assert_flag_size layout).\n assert (list_to_map [(assert_flag layout, WInt 0)] ⊆ m) as Hassert_flag.\n { etrans;[|eauto]. eapply map_union_subseteq_r'. 2: done.\n pose proof (libs_disjoint layout) as Hdisjoint. disjoint_map_to_list.\n apply elem_of_disjoint. intro. rewrite elem_of_app !elem_of_finz_seq_between !elem_of_list_singleton.\n intros [ [? ?]|?] ->; solve_addr. }\n eapply (lookup_weaken _ _ (assert_flag layout) (WInt 0)) in Hassert_flag.\n by simplify_eq. by simplify_map_eq.\nQed.\n\nLemma flag_inv_sub `{MachineParameters} (layout : ocpl_library) :\n minv_dom (flag_inv layout) ⊆ dom (lib_region (priv_libs (library layout))).\nProof.\n cbn. rewrite map_union_empty.\n intros ? Hinit. rewrite elem_of_singleton in Hinit.\n rewrite /assert_library_content.\n pose proof (assert_code_size layout). pose proof (assert_cap_size layout).\n pose proof (assert_flag_size layout).\n rewrite /= dom_union_L. apply elem_of_union_r.\n rewrite dom_insert_L. set_solver.\nQed.\n\nDefinition assertInv `{memG Σ, regG Σ, MachineParameters} (layout : ocpl_library) :=\n assert_inv (assert_start layout) (assert_flag layout) (assert_end layout).\nDefinition mallocInv `{memG Σ, regG Σ, MachineParameters} (layout : ocpl_library) :=\n malloc_inv (malloc_start layout) (malloc_end layout).\n\nDefinition mallocN : namespace := nroot .@ \"pub\" .@ \"malloc\".\nDefinition assertN : namespace := nroot .@ \"priv\" .@ \"assert\".\n\nTheorem ocpl_template_adequacy `{MachineParameters} (Σ : gFunctors)\n (layout: ocpl_library)\n (P Adv: prog)\n (P_tbl : @tbl_priv P (library layout))\n (Adv_tbl : @tbl_pub Adv (library layout)) (r_adv : RegName)\n (m m': Mem) (reg reg': Reg) (es: list cap_lang.expr):\n is_initial_memory P Adv (library layout) P_tbl Adv_tbl m →\n is_initial_registers P Adv (library layout) P_tbl Adv_tbl reg r_adv →\n Forall (λ w, is_z w = true) (prog_instrs Adv) →\n\n let filtered_map := λ (m : gmap Addr Word), filter (fun '(a, _) => a ∉ minv_dom (flag_inv layout)) m in\n (∀ `{memG Σ', regG Σ', sealStoreG Σ', logrel_na_invs Σ', subG Σ Σ'} rmap,\n dom rmap = all_registers_s ∖ {[ PC; r_adv ]} →\n ⊢ inv invN (minv_sep (flag_inv layout))\n ∗ na_inv logrel_nais mallocN (mallocInv layout)\n ∗ na_inv logrel_nais assertN (assertInv layout)\n ∗ na_own logrel_nais ⊤\n ∗ PC ↦ᵣ WCap RWX (prog_lower_bound P_tbl) (prog_end P) (prog_start P)\n ∗ r_adv ↦ᵣ WCap RWX (prog_lower_bound Adv_tbl) (prog_end Adv) (prog_start Adv)\n ∗ ([∗ map] r↦w ∈ rmap, r ↦ᵣ w ∗ ⌜is_z w = true⌝)\n (* P program and table *)\n ∗ (prog_lower_bound P_tbl) ↦ₐ (WCap RO (tbl_start P_tbl) (tbl_end P_tbl) (tbl_start P_tbl))\n ∗ ([∗ map] a↦w ∈ (tbl_region P_tbl), a ↦ₐ w)\n ∗ ([∗ map] a↦w ∈ (prog_region P), a ↦ₐ w)\n (* Adv program and table *)\n ∗ (prog_lower_bound Adv_tbl) ↦ₐ (WCap RO (tbl_start Adv_tbl) (tbl_end Adv_tbl) (tbl_start Adv_tbl))\n ∗ ([∗ map] a↦w ∈ (tbl_region Adv_tbl), a ↦ₐ w)\n ∗ ([∗ map] a↦w ∈ (prog_region Adv), a ↦ₐ w)\n\n -∗ WP Seq (Instr Executable) {{ λ _, True }}) →\n\n rtc erased_step ([Seq (Instr Executable)], (reg, m)) (es, (reg', m')) →\n minv (flag_inv layout) m'.\nProof.\n intros ? ? ? ? Hspec.\n eapply (template_adequacy_no_seals Σ);[eauto..|]; (* rewrite /invGpreS. solve_inG. *)\n try typeclasses eauto.\n eapply flag_inv_is_initial_memory;eauto.\n eapply flag_inv_sub;eauto.\n intros. cbn.\n rewrite !map_union_empty.\n iIntros \"(#Hflag & Hown & HPC & Hr_adv & Hrmap & Htbl & Htbl_r\n & Hprog & Htbl_adv & Htbl_adv_r & Hprog_adv & Hmalloc & Hassert)\".\n\n (* allocate malloc invariant *)\n iMod (na_inv_alloc logrel_nais ⊤ mallocN (mallocInv layout)\n with \"[Hmalloc]\") as \"#Hinv_malloc\".\n { iNext. rewrite /mallocInv /malloc_inv. iExists (malloc_memptr layout), (malloc_mem_start layout).\n rewrite /malloc_library_content.\n iDestruct (big_sepM_union with \"Hmalloc\") as \"[Hpubs Hinit]\".\n { pose proof (libs_disjoint layout) as Hdisjoint.\n rewrite !disjoint_list_cons in Hdisjoint |- *.\n disjoint_map_to_list. set_solver + Hdisjoint. }\n iDestruct (big_sepM_union with \"Hpubs\") as \"[Hpubs Hmid]\".\n { pose proof (libs_disjoint layout) as Hdisjoint.\n rewrite !disjoint_list_cons in Hdisjoint |- *.\n disjoint_map_to_list. set_solver + Hdisjoint. }\n pose proof (malloc_code_size layout) as Hmalloc_size.\n pose proof (malloc_memptr_size layout) as Hmalloc_memptr_size.\n pose proof (malloc_mem_size layout) as Hmalloc_mem_size.\n iSplitL \"Hpubs\".\n iApply big_sepM_to_big_sepL2. apply finz_seq_between_NoDup.\n rewrite finz_seq_between_length /finz.dist.\n solve_addr +Hmalloc_size.\n assert (((malloc_start layout) ^+ length malloc_subroutine_instrs)%a = (malloc_memptr layout)) as ->\n ;[solve_addr+Hmalloc_size|iFrame].\n iSplit;[auto|]. iDestruct (big_sepM_insert with \"Hmid\") as \"[$ _]\";auto.\n iSplit;[|iPureIntro;solve_addr+Hmalloc_size Hmalloc_memptr_size Hmalloc_mem_size].\n iApply big_sepM_to_big_sepL2. apply finz_seq_between_NoDup.\n rewrite finz_seq_between_length replicate_length /finz.dist. solve_addr +Hmalloc_mem_size. iFrame. }\n\n (* allocate the flag invariant *)\n iMod (na_inv_alloc logrel_nais ⊤ assertN (assertInv layout)\n with \"[Hassert]\") as \"#Hinv_assert\".\n { iNext. rewrite /assertInv /assert_inv /assert_library_content.\n iExists (assert_cap layout).\n pose proof (assert_code_size layout). pose proof (assert_cap_size layout).\n pose proof (assert_flag_size layout).\n rewrite map_filter_union.\n 2: { disjoint_map_to_list. apply elem_of_disjoint. intro.\n rewrite elem_of_app elem_of_finz_seq_between !elem_of_list_singleton.\n intros [ [? ?]|?]; solve_addr. }\n iDestruct (big_sepM_union with \"Hassert\") as \"[Hassert _]\".\n { eapply map_disjoint_filter. disjoint_map_to_list.\n apply elem_of_disjoint. intro.\n rewrite elem_of_app elem_of_finz_seq_between !elem_of_list_singleton.\n intros [ [? ?]|?]; solve_addr. }\n rewrite map_filter_id.\n 2: { intros ? ? HH%elem_of_dom_2. rewrite !dom_union_L dom_mkregion_eq in HH.\n 2: solve_addr. apply elem_of_union in HH.\n rewrite elem_of_singleton. destruct HH as [HH|HH].\n rewrite -> elem_of_list_to_set, elem_of_finz_seq_between in HH; solve_addr.\n rewrite -> dom_list_to_map_singleton, elem_of_list_to_set, elem_of_list_singleton in HH; solve_addr. }\n iDestruct (big_sepM_union with \"Hassert\") as \"[Hassert Hcap]\".\n { disjoint_map_to_list. apply elem_of_disjoint. intro.\n rewrite elem_of_finz_seq_between !elem_of_list_singleton. solve_addr. }\n iDestruct (mkregion_sepM_to_sepL2 with \"Hassert\") as \"Hassert\". solve_addr.\n rewrite (_: assert_cap layout = assert_start layout ^+ length assert_subroutine_instrs)%a. 2: solve_addr.\n iFrame \"Hassert\". iDestruct (big_sepM_insert with \"Hcap\") as \"[Hcap _]\". done.\n iFrame \"Hcap\". iPureIntro. repeat split; solve_addr. }\n\n iApply Hspec; [exact|..|iFrame \"∗ #\"];auto.\nQed.\n\nEnd ocpl.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/examples/template_adequacy_ocpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2689414096510109, "lm_q1q2_score": 0.14391012569688172}} {"text": "Require Import Benchmarks.ProcessSchedulerSetup.\n\n(** This file demonstrates the extraction from a Fiat ADT to a Facade\n “CompileUnit”. For convenience, here is a copy of the Process Scheduler\n specs:\n\n Definition SchedulerSchema Def ADT Schema rep := QueryStructure Structure,\n\n relation \"Processes\" has schema\n <\"pid\" :: W, \"state\" :: State, \"cpu\" :: W>\n where (UniqueAttribute ``\"pid\")\n ] enforcing [].\n\n Definition SchedulerSpec : ADT _ :=\n Def ADT\n {\n rep := QueryStructure SchedulerSchema,\n\n Def Constructor0 \"Init\" : rep := empty,\n\n Def Method3 \"Spawn\" (r : rep) (new_pid cpu state : W) : rep * bool :=\n Insert (<\"pid\" :: new_pid, \"state\" :: state, \"cpu\" :: cpu> : RawTuple) into r!\"Processes\",\n\n Def Method1 \"Enumerate\" (r : rep) (state : State) : rep * list W :=\n procs <- For (p in r!\"Processes\")\n Where (p!\"state\" = state)\n Return (p!\"pid\");\n ret (r, procs),\n\n Def Method1 \"GetCPUTime\" (r : rep) (id : W) : rep * list W :=\n proc <- For (p in r!\"Processes\")\n Where (p!\"pid\" = id)\n Return (p!\"cpu\");\n ret (r, proc)\n }%methDefParsing.\n\n We have added the output of each of the three “Compute” calls below;\n running the example up to that point takes about 6 minutes on a modern machine. *)\n\nDefinition CUnit\n : { env : _ &\n BuildCompileUnit2TSpec\n env\n AbsR'\n (fun r => BagSanityConditions (prim_fst r))\n (DecomposeIndexedQueryStructure' QsADTs.ADTValue _ _)\n (DecomposeIndexedQueryStructurePre' QsADTs.ADTValue _ _ _)\n (DecomposeIndexedQueryStructurePost' QsADTs.ADTValue _ _ (Scheduler_RepWrapperT _))\n (QueryStructureSchema.numQSschemaSchemas SchedulerSchema)\n \"ProcessSchedulerAX\"\n \"ProcessSchedulerOP\"\n Scheduler_coDomainWrappers\n Scheduler_DomainWrappers\n (Scheduler_RepWrapperT _)\n (Scheduler_DecomposeRep_well_behaved QsADTs.ADTValue _ _ (Scheduler_RepWrapperT _))\n SharpenedRepImpl} .\nProof.\n Time _compile QSEnv_Ax. (* 228s *)\nTime Defined. (* 185s *)\n\nEval lazy in (methodBody \"Spawn\" CUnit).\n\n(*\n = Some\n (\"snd\" <- \"ADT\".\"Tuples2_findSecond\"(\"rep\", \"arg\");\n \"test\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n If Const (Word.natToWord 32 1) = Var \"test\" Then\n \"v1\" <- Var \"arg\";\n \"v2\" <- Var \"arg1\";\n \"v3\" <- Var \"arg0\";\n \"o1\" <- Const (Word.natToWord 32 0);\n \"o2\" <- Const (Word.natToWord 32 1);\n \"o3\" <- Const (Word.natToWord 32 2);\n \"vlen\" <- Const (Word.natToWord 32 3);\n \"tup\" <- \"ADT\".\"Tuple_new\"(\"vlen\");\n \"vtmp\" <- \"ADT\".\"Tuple_set\"(\"tup\", \"o1\", \"v1\");\n \"vtmp\" <- \"ADT\".\"Tuple_set\"(\"tup\", \"o2\", \"v2\");\n \"vtmp\" <- \"ADT\".\"Tuple_set\"(\"tup\", \"o3\", \"v3\");\n \"vtmp\" <- \"ADT\".\"Tuples2_insert\"(\"rep\", \"tup\");\n \"tmp\" <- Const (Word.natToWord 32 0);\n \"test0\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n While (Var \"test0\" = Const (Word.natToWord 32 0))\n \"head\" <- \"ADT\".\"TupleList_pop\"(\"snd\");\n \"size\" <- Const (Word.natToWord 32 3);\n \"tmp'\" <- \"ADT\".\"Tuple_delete\"(\"head\", \"size\");\n \"test0\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n \"test0\" <- \"ADT\".\"TupleList_delete\"(\"snd\");\n __;\n \"ret\" <- Const (Word.natToWord 32 1)\n Else\n \"tmp\" <- Const (Word.natToWord 32 0);\n \"test0\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n While (Var \"test0\" = Const (Word.natToWord 32 0))\n \"head\" <- \"ADT\".\"TupleList_pop\"(\"snd\");\n \"size\" <- Const (Word.natToWord 32 3);\n \"tmp'\" <- \"ADT\".\"Tuple_delete\"(\"head\", \"size\");\n \"test0\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n \"test0\" <- \"ADT\".\"TupleList_delete\"(\"snd\");\n __;\n \"ret\" <- Const (Word.natToWord 32 0)\n EndIf)%facade\n : option Stmt *)\n\nEval lazy in (methodBody \"Enumerate\" CUnit).\n\n(*\n = Some\n (\"snd\" <- \"ADT\".\"Tuples2_findFirst\"(\"rep\", \"arg\");\n \"ret\" <- \"ADT\".\"WordList_new\"();\n \"test\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n While (Var \"test\" = Const (Word.natToWord 32 0))\n \"head\" <- \"ADT\".\"TupleList_pop\"(\"snd\");\n \"pos\" <- Const (Word.natToWord 32 0);\n \"head'\" <- \"ADT\".\"Tuple_get\"(\"head\", \"pos\");\n \"size\" <- Const (Word.natToWord 32 3);\n \"tmp\" <- \"ADT\".\"Tuple_delete\"(\"head\", \"size\");\n \"tmp\" <- \"ADT\".\"WordList_push\"(\"ret\", \"head'\");\n \"test\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n \"test\" <- \"ADT\".\"TupleList_delete\"(\"snd\");\n __)%facade\n : option Stmt *)\n\nEval lazy in (methodBody \"GetCPUTime\" CUnit).\n\n(*\n = Some\n (\"snd\" <- \"ADT\".\"Tuples2_findSecond\"(\"rep\", \"arg\");\n \"ret\" <- \"ADT\".\"WordList_new\"();\n \"test\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n While (Var \"test\" = Const (Word.natToWord 32 0))\n \"head\" <- \"ADT\".\"TupleList_pop\"(\"snd\");\n \"pos\" <- Const (Word.natToWord 32 2);\n \"head'\" <- \"ADT\".\"Tuple_get\"(\"head\", \"pos\");\n \"size\" <- Const (Word.natToWord 32 3);\n \"tmp\" <- \"ADT\".\"Tuple_delete\"(\"head\", \"size\");\n \"tmp\" <- \"ADT\".\"WordList_push\"(\"ret\", \"head'\");\n \"test\" <- \"ADT\".\"TupleList_empty\"(\"snd\");\n \"test\" <- \"ADT\".\"TupleList_delete\"(\"snd\");\n __)%facade\n : option Stmt *)\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/Benchmarks/ProcessScheduler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.14347475069036472}} {"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import ReorderStep.\nRequire Import ReorderLoad.\nRequire Import ReorderStore.\nRequire Import ReorderUpdate.\nRequire Import ReorderFence.\nRequire Import ReorderAbort.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\nInductive reorder: forall (i1 i2:Instr.t), Prop :=\n| reorder_intro_load\n r1 l1 o1 i2\n (REORDER: reorder_load r1 l1 o1 i2):\n reorder (Instr.load r1 l1 o1) i2\n| reorder_intro_store\n l1 v1 o1 i2\n (REORDER: reorder_store l1 v1 o1 i2):\n reorder (Instr.store l1 v1 o1) i2\n| reorder_intro_update\n l1 v1 rmw1 or1 ow1 i2\n (REORDER: reorder_update l1 v1 rmw1 or1 ow1 i2):\n reorder (Instr.update l1 v1 rmw1 or1 ow1) i2\n| reorder_intro_fence\n or1 ow1 i2\n (REORDER: reorder_fence or1 ow1 i2):\n reorder (Instr.fence or1 ow1) i2\n| reorder_intro_abort\n i2\n (REORDER: reorder_abort i2):\n reorder Instr.abort i2\n.\n\nLemma reorder_sim_stmts\n i1 i2 (REORDER: reorder i1 i2):\n sim_stmts eq\n [Stmt.instr i2; Stmt.instr i1]\n [Stmt.instr i1; Stmt.instr i2]\n eq.\nProof.\n pcofix CIH. ii. subst. pfold. ii. splits; ii.\n { inv TERMINAL_TGT. }\n { exploit SimPromises.cap; try eapply LOCAL; eauto. }\n { right. esplits; eauto.\n inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n }\n inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n try (inv STATE; inv INSTR; inv REORDER); ss.\n - (* promise *)\n right.\n exploit sim_local_promise; eauto. i. des.\n esplits; try apply SC; eauto; ss.\n econs 2. econs 1; eauto. econs; eauto. eauto.\n - (* load *)\n right.\n exploit sim_local_read; eauto; try refl. i. des.\n esplits; try apply SC; eauto; ss.\n + econs 1.\n + auto.\n + left. eapply paco9_mon; [apply sim_load_sim_thread|]; ss.\n econs; eauto.\n eapply Local.read_step_future; eauto.\n - (* update-load *)\n right.\n exploit sim_local_read; eauto; try refl. i. des.\n esplits; try apply SC; eauto; ss.\n + econs 1.\n + auto.\n + left. eapply paco9_mon; [apply sim_update_sim_thread|]; ss.\n econs; [eauto|..]; s; eauto.\n eapply Local.read_step_future; eauto.\n - (* store *)\n right.\n exploit Local.write_step_future; eauto; try by viewtac. i. des.\n hexploit sim_local_write_bot; try exact LOCAL1; try exact SC;\n try exact WF_SRC; try refl; viewtac. i. des.\n exploit write_promise_fulfill; eauto; try by viewtac. i. des.\n exploit Local.promise_step_future; eauto. i. des.\n esplits.\n + ss.\n + eauto.\n + econs 2. econs 1. econs; eauto.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco9_mon; [apply sim_store_sim_thread|done].\n econs; eauto.\n - (* update *)\n right.\n exploit Local.read_step_future; eauto. i. des.\n exploit Local.write_step_future; eauto. i. des.\n exploit sim_local_read; eauto; try refl. i. des.\n exploit Local.read_step_future; eauto. i. des.\n hexploit sim_local_write_bot; try apply LOCAL2; try apply LOCAL0; try apply SC; eauto; try refl; try by viewtac. i. des.\n exploit write_promise_fulfill; eauto; try by viewtac. i. des.\n exploit Local.promise_step_future; eauto. i. des.\n exploit reorder_read_promise; try exact STEP_SRC; try exact STEP1; eauto. i. des.\n exploit Local.promise_step_future; eauto. i. des.\n exploit Local.read_step_future; eauto. i. des.\n exploit sim_local_fulfill_bot; try exact STEP2; try exact LOCAL4; try exact REL1;\n try exact WF3; try refl; eauto; try by viewtac. i. des.\n esplits.\n + ss.\n + eauto.\n + econs 2. econs 1. econs; eauto.\n + auto.\n + etrans; eauto.\n + auto.\n + left. eapply paco9_mon; [apply sim_update_sim_thread|done].\n econs; [eauto|..]; s; eauto.\n etrans; eauto.\n - (* fence *)\n right.\n exploit sim_local_fence; try apply SC; eauto; try refl. i. des.\n esplits.\n + ss.\n + eauto.\n + econs 1.\n + auto.\n + etrans; [|eauto]. inv STEP_SRC. apply TViewFacts.write_fence_sc_incr.\n + auto.\n + left. eapply paco9_mon; [apply sim_fence_sim_thread|]; ss.\n econs; eauto.\n - (* abort *)\n left.\n eapply sim_abort_steps_failure. econs; eauto.\n eapply sim_local_failure; eauto.\nUnshelve.\n { econs. econs 3. }\n { econs 2. }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/opt/Reorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14347474143210134}} {"text": "(* Well-scopedness definition for LambdaANF. Part of the CertiCoq project.\n * Author: Anonymized, 2016\n *)\n\nRequire Import LambdaANF.set_util LambdaANF.cps LambdaANF.eval LambdaANF.cps_util LambdaANF.ctx LambdaANF.identifiers.\nRequire Import Coq.MSets.MSetRBT Coq.Lists.List.\nRequire Import compcert.lib.Coqlib.\n\n\nImport PS.\n\nDefinition env_subset (rho1 rho2 : env) :=\n forall x v, M.get x rho1 = Some v -> M.get x rho2 = Some v.\n\n(** An expression is well scoped in an environment: [Γ |- e] *) \nInductive well_scoped_exp : env -> exp -> Prop :=\n| WS_constr :\n forall x t ys vs e Γ,\n get_list ys Γ = Some vs ->\n (forall v, well_scoped_exp (M.set x v Γ) e) ->\n well_scoped_exp Γ (Econstr x t ys e)\n| WS_case :\n forall x v te Γ,\n M.get x Γ = Some v ->\n Forall (fun p => well_scoped_exp Γ (snd p)) te ->\n well_scoped_exp Γ (Ecase x te)\n| WSproj :\n forall x tau N y v e Γ,\n M.get y Γ = Some v ->\n (forall v, well_scoped_exp (M.set x v Γ) e) ->\n well_scoped_exp Γ (Eproj x tau N y e)\n| WSletapp :\n forall x tau f ys v e Γ,\n get_list ys Γ = Some v ->\n (forall v, well_scoped_exp (M.set x v Γ) e) ->\n well_scoped_exp Γ (Eletapp x f tau ys e)\n| WS_app :\n forall x v ys vs ft Γ,\n get_list ys Γ = Some vs ->\n M.get x Γ = Some v ->\n well_scoped_exp Γ (Eapp x ft ys)\n| WS_prim :\n forall x f ys vs e Γ,\n get_list ys Γ = Some vs ->\n (forall v, well_scoped_exp (M.set x v Γ) e) ->\n well_scoped_exp Γ (Eprim x f ys e)\n| WS_halt :\n forall x v Γ,\n M.get x Γ = Some v ->\n well_scoped_exp Γ (Ehalt x)\n| WS_fun :\n forall defs e Γ,\n well_scoped_fundefs Γ defs ->\n (forall vs Γ',\n set_lists (elements (fundefs_names defs)) vs Γ = Some Γ' ->\n well_scoped_exp Γ' e) ->\n well_scoped_exp Γ (Efun defs e)\nwith well_scoped_fundefs : env -> fundefs -> Prop :=\n| WS_fcons :\n forall f tau xs e defs Γ,\n (forall vs vs' Γ' Γ'',\n set_lists (elements (fundefs_names defs)) vs' Γ = Some Γ' ->\n set_lists xs vs Γ' = Some Γ'' ->\n well_scoped_exp Γ'' e) ->\n (forall v, well_scoped_fundefs (M.set f v Γ) defs) ->\n well_scoped_fundefs Γ (Fcons f tau xs e defs)\n| WS_fnil :\n forall Γ,\n well_scoped_fundefs Γ Fnil.\n\nFixpoint fundefs_ctx_names (cdefs : fundefs_ctx) : FVSet :=\n match cdefs with\n | Fcons1_c f _ _ _ defs => add f (fundefs_names defs) \n | Fcons2_c f _ _ _ cdefs' => add f (fundefs_ctx_names cdefs') \n end.\n \n(** [Γ {[Γ']} |- c ]: A context is well scoped in an environment Γ, given that \n the expression we put in the hole is well scoped in the environment Γ' *)\nInductive well_scoped_exp_ctx : env -> exp_ctx -> env -> Prop :=\n| WSCtx_hole :\n forall Γ Γ',\n env_subset Γ' Γ ->\n well_scoped_exp_ctx Γ Hole_c Γ'\n| WSCtx_constr :\n forall x t ys vs c Γ Γ',\n get_list ys Γ = Some vs ->\n (forall v, well_scoped_exp_ctx (M.set x v Γ) c Γ') ->\n well_scoped_exp_ctx Γ (Econstr_c x t ys c) Γ'\n| WSCtx_proj :\n forall x tau N y v c Γ Γ',\n M.get y Γ = Some v ->\n (forall v, well_scoped_exp_ctx (M.set x v Γ) c Γ') ->\n well_scoped_exp_ctx Γ (Eproj_c x tau N y c) Γ'\n| WSCtx_letapp :\n forall x tau f ys vs c Γ Γ',\n get_list ys Γ = Some vs->\n (forall v, well_scoped_exp_ctx (M.set x v Γ) c Γ') ->\n well_scoped_exp_ctx Γ (Eletapp_c x f tau ys c) Γ'\n| WSCtx_prim :\n forall x f ys vs c Γ Γ',\n get_list ys Γ = Some vs ->\n (forall v, well_scoped_exp_ctx (M.set x v Γ) c Γ') ->\n well_scoped_exp_ctx Γ (Eprim_c x f ys c) Γ'\n| WSCtx_fun1 :\n forall defs c Γ Γ',\n well_scoped_fundefs Γ defs ->\n (forall vs Γ'',\n set_lists (elements (fundefs_names defs)) vs Γ = Some Γ'' ->\n well_scoped_exp_ctx Γ'' c Γ') ->\n well_scoped_exp_ctx Γ (Efun1_c defs c) Γ'\n| WSCtx_fun2 :\n forall cdefs e Γ Γ',\n well_scoped_fundefs_ctx Γ cdefs Γ' ->\n (forall vs Γ'',\n set_lists (elements (fundefs_ctx_names cdefs)) vs Γ = Some Γ'' ->\n well_scoped_exp Γ'' e) ->\n well_scoped_exp_ctx Γ (Efun2_c cdefs e) Γ'\nwith well_scoped_fundefs_ctx : env -> fundefs_ctx -> env -> Prop :=\n| WS_fcons1 :\n forall f tau xs c defs Γ Γ',\n (forall vs vs' Γ'' Γ''',\n set_lists (elements (fundefs_names defs)) vs' Γ = Some Γ''->\n set_lists xs vs Γ'' = Some Γ''' ->\n well_scoped_exp_ctx Γ''' c Γ') ->\n (forall v, well_scoped_fundefs (M.set f v Γ) defs) ->\n well_scoped_fundefs_ctx Γ (Fcons1_c f tau xs c defs) Γ'\n| WS_fcons2 :\n forall f tau xs e cdefs Γ Γ',\n (forall vs vs' Γ'' Γ''',\n set_lists (elements (fundefs_ctx_names cdefs)) vs' Γ = Some Γ''->\n set_lists xs vs Γ'' = Some Γ''' ->\n well_scoped_exp Γ''' e) ->\n (forall v, well_scoped_fundefs_ctx (M.set f v Γ) cdefs Γ') ->\n well_scoped_fundefs_ctx Γ (Fcons2_c f tau xs e cdefs) Γ'.\n\nDeclare Scope env_scope.\n\nNotation \"Γ '⊢' e\" := (well_scoped_exp Γ e) (at level 30, no associativity)\n : env_scope.\nNotation \"Γ '{[' Γ' ']}' '⊢' e \" := (well_scoped_exp_ctx Γ e Γ')\n (at level 30, no associativity)\n : env_scope.\nNotation \"Γ '⊢*' f\" := (well_scoped_fundefs Γ f) (at level 30, no associativity)\n : env_scope.\nNotation \"Γ '{[' Γ' ']}' '⊢*' f \" := (well_scoped_fundefs_ctx Γ f Γ')\n (at level 30, no associativity)\n : env_scope.\n\n\nOpen Scope env_scope.\nOpen Scope ctx_scope.\n\n \n\nLemma env_subset_set Γ Γ' x v :\n env_subset Γ Γ' ->\n env_subset (M.set x v Γ) (M.set x v Γ')\n.\nProof.\n intros Hsub x' v' Hget. rewrite M.gsspec in *.\n destruct (peq x' x); eauto.\nQed.\n\nLemma env_subset_set_lists Γ1 Γ2 Γ1' xs vs :\n env_subset Γ2 Γ1 ->\n Some Γ1' = set_lists xs vs Γ1 ->\n exists Γ2', Some Γ2' = set_lists xs vs Γ2 /\\ env_subset Γ2' Γ1'.\nProof.\n revert vs Γ1'.\n induction xs; simpl; intros vs Γ1' Hsub Hset1;\n destruct vs; try discriminate.\n - inv Hset1; eexists; eauto.\n - destruct (set_lists xs vs Γ1) as [Γ1'' | ] eqn:Heq; try discriminate.\n edestruct (IHxs vs Γ1'' Hsub) as [Γ2' [Heq' Ηsub]]; eauto. inv Hset1.\n exists (M.set a v Γ2'). split. rewrite <- Heq'. eauto.\n eapply env_subset_set. eauto.\nQed.\n\nLemma env_subset_get_list Γ1 Γ2 xs vs :\n env_subset Γ1 Γ2 ->\n get_list xs Γ1 = Some vs ->\n get_list xs Γ2 = Some vs.\nProof.\n revert vs.\n induction xs; simpl; intros vs Hsub Hget; eauto.\n destruct (M.get a Γ1) eqn:Heq; try discriminate.\n destruct (get_list xs Γ1) eqn:Heq'; try discriminate.\n eapply Hsub in Heq. rewrite Heq. inv Hget.\n erewrite IHxs; eauto.\nQed.\n\nLemma env_subset_get Γ1 Γ2 x v :\n env_subset Γ1 Γ2 ->\n M.get x Γ1 = Some v ->\n M.get x Γ2 = Some v.\nProof.\n intros Henv Hget. eauto.\nQed.\n\n\nLemma well_scoped_exp_fundefs_weakening :\n (forall e Γ Γ',\n Γ ⊢ e -> env_subset Γ Γ' -> Γ' ⊢ e) /\\\n (forall defs Γ Γ',\n Γ ⊢* defs -> env_subset Γ Γ' -> Γ' ⊢* defs).\nProof.\n exp_defs_induction IHc IHl IHfc; intros Γ Γ' Hws Hsub;\n try (now inv Hws; econstructor; eauto using env_subset_get_list, env_subset_get;\n intros; eapply IHc; eauto using env_subset_set).\n - inv Hws; econstructor; eauto.\n inv H3. constructor; eauto.\n assert (Hsuf : Γ' ⊢ Ecase v l)\n by (eapply IHl; eauto; econstructor; eauto).\n inv Hsuf; eauto.\n - inv Hws. constructor; eauto.\n intros. edestruct env_subset_set_lists as [Γ2 [Hset2 Hsub2]]; eauto.\n - inv Hws. constructor; eauto.\n intros. edestruct env_subset_set_lists as [Γ2 [Hset2 Hsub2]]; eauto.\n edestruct env_subset_set_lists as [Γ3 [Hset3 Hsub3]]; eauto.\n intros. eapply IHfc; eauto using env_subset_set.\nQed.\n\nLemma fundefs_names_eq fc e :\n eq (fundefs_ctx_names fc) (fundefs_names (fc <[ e ]>)).\nProof.\n induction fc; simpl; intros x; split; intros HIn; eauto;\n eapply add_spec in HIn; inv HIn; eapply add_spec; eauto;\n right; eapply IHfc; eauto.\nQed.\n\nLemma fundefs_names_elem fc e :\n eq (fundefs_ctx_names fc) (fundefs_names (fc <[ e ]>)).\nProof.\n induction fc; simpl; eauto;\n intros x; split; intros HIn; eauto;\n eapply add_spec in HIn; inv HIn; eapply add_spec; eauto;\n right; eapply IHfc; eauto.\nQed. \n\nLemma well_scoped_ctx_app :\n (forall c e Γ Γ',\n Γ {[ Γ' ]} ⊢ c -> Γ' ⊢ e -> Γ ⊢ c |[ e ]| ) /\\\n (forall fc e Γ Γ',\n Γ {[ Γ' ]} ⊢* fc -> Γ' ⊢ e -> Γ ⊢* fc <[ e ]>).\nProof.\n exp_fundefs_ctx_induction IHc IHfc;\n try (now intros e' Γ Γ' Hws1 Hws2; inv Hws1;\n simpl; econstructor; eauto).\n - intros e' Γ Γ' Hws1 Hws2. inv Hws1. simpl.\n eapply well_scoped_exp_fundefs_weakening; eauto.\n - intros te e' Γ Γ' Hws1 Hws2. inv Hws1.\n - intros e' Γ Γ' Hws1 Hws2. inv Hws1.\n simpl. econstructor; eauto. intros.\n eapply H4. erewrite elements_eq; eauto.\n apply fundefs_names_eq.\n - intros e' Γ Γ' Hws1 Hws2. inv Hws1.\n simpl. econstructor; eauto. intros.\n eapply H6. erewrite elements_eq; eauto.\n apply fundefs_names_eq. eauto.\nQed.\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/LambdaANF/env.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.14339960756668296}} {"text": "Require Import Eqdep Lia Framework FSParameters FileDiskLayer. (* LoggedDiskLayer TransactionCacheLayer TransactionalDiskLayer. *)\nRequire Import FileDiskNoninterference FileDiskRefinement.\nRequire Import ATCDLayer FileDisk.TransferProofs ATCD_Simulation ATCD_AOE.\nRequire Import Not_Init HSS ATCD_ORS ATCD_TS_Common ATCD_TS_Recovery ATCD_TS_Transaction.\n\nImport FileDiskLayer.\nSet Nested Proofs Allowed.\n\nOpaque File.recover.\nLemma ATCD_TS_InodeAllocator_read:\nforall n inum u u' txns1 txns2 hdr1 hdr2,\nTermination_Sensitive u\n(Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n(@lift_L2 AuthenticationOperation _ TD _\n (Inode.InodeAllocator.read inum))))\n(Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n(@lift_L2 AuthenticationOperation _ TD _\n (Inode.InodeAllocator.read inum))))\n(Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n (Simulation.Definitions.compile\n FD.refinement\n (| Recover |))))\n(refines_valid ATCD_Refinement\n (refines_valid ATC_Refinement\n AD_valid_state))\n(fun s1 s2 => \nrefines_related ATCD_Refinement \n(fun s1 s2 => refines_related ATC_Refinement\n (fun s1 s2 => exists s1a s2a, \n File.files_inner_rep s1a (fst (snd (snd s1))) /\\ \n File.files_inner_rep s2a (fst (snd (snd s2))) /\\ \n FD_related_states u' None s1a s2a) s1 s2 /\\\n(forall a, \n Transaction.get_first (fst (snd s1)) a = None <-> \n Transaction.get_first (fst (snd s2)) a = None)) s1 s2 /\\\n equivalent_for_recovery txns1 txns2 Log.Current_Part hdr1 hdr2 s1 s2 /\\\n (forall a, \n fst (snd (snd s1)) a = None <->\n fst (snd (snd s2)) a = None) /\\\n fst (snd (snd s1)) =\nMem.list_upd_batch empty_mem\n (map Log.addr_list txns1)\n (map Log.data_blocks txns1) /\\\nfst (snd (snd s2)) =\nMem.list_upd_batch empty_mem\n (map Log.addr_list txns2)\n (map Log.data_blocks txns2))\n(ATCD_reboot_list n).\nProof.\nTransparent Inode.InodeAllocator.read.\nunfold Inode.InodeAllocator.read; simpl; intros.\ndestruct (Compare_dec.lt_dec inum\nInode.InodeAllocatorParams.num_of_blocks).\n2: {\n intros; eapply TS_eqv_impl.\n apply ATCD_TS_ret.\n simpl; intuition eauto.\n}\n{\n eapply ATCD_TS_compositional; simpl.\n intros; eapply TS_eqv_impl.\n unfold Inode.InodeAllocatorParams.bitmap_addr in *.\n pose proof Inode.InodeAllocatorParams.blocks_fit_in_disk.\n intros; eapply ATCD_TS_Transaction_read.\n lia.\n simpl; intros; cleanup; eauto.\n {\n intros.\n unfold refines_related in *; cleanup.\n simpl in *; unfold HC_refines in *; cleanup.\n simpl in *; unfold HC_refines in *; cleanup.\n\n simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines in *.\n unfold Definitions.refines in *; simpl in *.\n rewrite H13, H14.\n unfold LogCache.cached_log_rep in *; cleanup.\n repeat (split; eauto).\n }\n {\n simpl; intros.\n\n\n unfold refines_related in *; cleanup.\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H0.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n\n edestruct ATCD_simulation.\n 2: apply H13.\n all: eauto.\n 2: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n\n edestruct ATCD_simulation.\n 2: apply H14.\n all: eauto.\n 2: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n\n simpl in *; cleanup; repeat invert_exec.\n\n eapply_fresh lift2_invert_exec in H30;\n eapply_fresh lift2_invert_exec in H31; cleanup.\n \n unfold refines_related in *; cleanup.\n simpl in *; unfold HC_refines in *; cleanup.\n simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines in *.\n\n eapply Transaction.read_finished in H26; eauto.\n eapply Transaction.read_finished in H24; eauto.\n\n unfold Inode.InodeAllocatorParams.bitmap_addr in *.\n cleanup; repeat split_ors; cleanup; try lia.\n erewrite InodeTS.inode_allocations_are_same with (s2:= fst (snd (snd x2))); eauto.\n destruct_fresh (nth_error\n (value_to_bits\n (fst (snd (snd x2)) Inode.InodeAllocatorParams.bitmap_addr)) inum);\n setoid_rewrite D; simpl.\n 2: {\n eapply TS_eqv_impl.\n apply ATCD_TS_ret.\n shelve.\n }\n destruct b; simpl.\n 2: {\n eapply TS_eqv_impl.\n apply ATCD_TS_ret.\n shelve.\n }\n eapply ATCD_TS_compositional; simpl.\n 2: intros; apply ATCD_TS_ret.\n intros; eapply TS_eqv_impl.\n eapply ATCD_TS_Transaction_read.\n lia.\n shelve.\n intros; shelve.\n\n destruct (block_allocator_empty inum); \n rewrite H18;\n eapply TS_eqv_impl;\n try apply ATCD_TS_ret.\n shelve.\n shelve.\n }\n {\n simpl; intros; cleanup; eauto.\n unfold refines_related in *; cleanup.\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H0.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n\n edestruct ATCD_simulation.\n 2: apply H13.\n all: eauto.\n 2: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n\n edestruct ATCD_simulation.\n 2: apply H14.\n all: eauto.\n 2: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n\n simpl in *; cleanup; repeat invert_exec.\n\n eapply_fresh lift2_invert_exec in H30;\n eapply_fresh lift2_invert_exec in H31; cleanup.\n\n simpl in *; unfold HC_refines in *; cleanup.\n simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines in *.\n\n eapply Transaction.read_finished in H26; eauto.\n eapply Transaction.read_finished in H24; eauto.\n\n unfold Inode.InodeAllocatorParams.bitmap_addr in *.\n pose proof Inode.InodeAllocatorParams.blocks_fit_in_disk.\n cleanup; repeat split_ors; cleanup; try lia; eauto.\n \n shelve.\n }\n}\nUnshelve.\nall: \ntry match goal with\n| [|- not_init _ ] =>\n unfold Transaction.read;\n destruct (Compare_dec.lt_dec Inode.InodeAllocatorParams.bitmap_addr\n data_length); simpl; intuition eauto;\n try destruct (Transaction.get_first t Inode.InodeAllocatorParams.bitmap_addr); \n simpl; intuition eauto; \n try match goal with\n | [H: eq_dep _ _ _ _ _ _ |- _] =>\n inversion H\n end\nend.\n5: instantiate (5 := fun _ _ s0 s3 => \nequivalent_for_recovery txns1 txns2 Log.Current_Part hdr1 hdr2 s0 s3 /\\\n(Transaction.get_first (fst (snd s0)) (inode_blocks_start + S inum) = None <->\n Transaction.get_first (fst (snd s3)) (inode_blocks_start + S inum) = None) /\\\n(fst (snd (snd s0)) (data_start + (inode_blocks_start + S inum)) = None <->\n fst (snd (snd s3)) (data_start + (inode_blocks_start + S inum)) = None) /\\\nfst (snd (snd s0)) =\nMem.list_upd_batch empty_mem (map Log.addr_list txns1)\n (map Log.data_blocks txns1) /\\\nfst (snd (snd s3)) =\nMem.list_upd_batch empty_mem (map Log.addr_list txns2)\n (map Log.data_blocks txns2)); simpl; intuition eauto.\n5: simpl; intuition eauto.\n9: simpl; intuition eauto.\n5: simpl; intuition eauto.\n14: simpl; intuition eauto.\n10: simpl; intuition eauto.\n5: {\n (*\n instantiate (1:= hdr2).\n instantiate (1:= hdr1).\n instantiate (1:= txns2).\n instantiate (1:= txns1).\n *)\n simpl; intuition eauto.\n simpl in *.\n\n simpl; intros; cleanup; eauto.\n unfold refines_related in *; cleanup.\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H18.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n simpl.\n unfold HC_refines; simpl.\n unfold HC_refines; simpl.\n unfold Definitions.refines, LogCache.cached_log_rep.\n unfold Log.log_rep, Log.log_header_rep, Log.log_rep_general.\n unfold equivalent_for_recovery in *; cleanup.\n eexists (_, (_, _)); simpl; intuition eauto.\n eexists; simpl; intuition eauto.\n\n edestruct ATCD_AOE.\n 4: {\n instantiate (1:= RFinished _ _).\n instantiate (6:= []). \n unfold ATCD_reboot_list; simpl.\n econstructor.\n apply H26.\n }\n all: try solve [simpl in *; eauto].\n shelve.\n simpl.\n unfold HC_refines; simpl.\n unfold HC_refines; simpl.\n unfold Definitions.refines, LogCache.cached_log_rep.\n unfold Log.log_rep, Log.log_header_rep, Log.log_rep_general.\n unfold equivalent_for_recovery in *; cleanup.\n eexists (_, (_, _)); simpl; intuition eauto.\n eexists; simpl; intuition eauto.\n\n unfold equivalent_for_recovery in *; cleanup.\n edestruct ATCD_simulation.\n 2: apply H35.\n all: eauto.\n 3: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n unfold Simulation.Definitions.refines; simpl.\n unfold HC_refines; simpl.\n unfold HC_refines; simpl.\n unfold Definitions.refines, LogCache.cached_log_rep.\n unfold Log.log_rep, Log.log_header_rep, Log.log_rep_general.\n instantiate (1:= (_, (_, _))); simpl; intuition eauto.\n eexists; simpl; intuition eauto.\n\n edestruct ATCD_simulation.\n 2: apply H44.\n all: eauto.\n 3: unfold ATCD_reboot_list; simpl; econstructor; eauto.\n shelve.\n unfold Simulation.Definitions.refines; simpl.\n unfold HC_refines; simpl.\n unfold HC_refines; simpl.\n unfold Definitions.refines, LogCache.cached_log_rep.\n unfold Log.log_rep, Log.log_header_rep, Log.log_rep_general.\n instantiate (1:= (_, (_, _))); simpl; intuition eauto.\n eexists; simpl; intuition eauto.\n\n simpl in *; cleanup_no_match; repeat invert_exec.\n\n repeat invert_lift2.\n simpl in *; unfold HC_refines in *; cleanup.\n simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines in *.\n\n repeat cleanup_pairs.\n (*\n eapply Transaction.read_finished in H80; eauto.\n eapply Transaction.read_finished in H81; eauto.\n\n cleanup; repeat cleanup_pairs.\n \n repeat match goal with\n |[H: _ \\/ _|- _] =>\n clear H\n end.\n\n unfold HC_refines in *; simpl in *; cleanup.\n unfold Definitions.refines, LogCache.cached_log_rep in *.\n unfold Log.log_rep, Log.log_header_rep, Log.log_rep_general in *.\n cleanup.\n\n eexists (_, (_, _)), (_, (_, _)); simpl; split.\n intuition eauto.\n do 2 eexists; split.\n eauto.\n *)\n admit.\n}\nAdmitted.\n\n\nLemma ATCD_TS_DiskAllocator_read:\n forall n a1 a2 u u' txns1 txns2 hdr1 hdr2,\n (a1 < File.DiskAllocatorParams.num_of_blocks <-> a2 < File.DiskAllocatorParams.num_of_blocks) ->\n (File.DiskAllocatorParams.bitmap_addr + S a1 <\n data_length <->\n File.DiskAllocatorParams.bitmap_addr + S a2 <\n data_length) ->\n Termination_Sensitive u\n (Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n (@lift_L2 AuthenticationOperation _ TD _\n (File.DiskAllocator.read a1))))\n (Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n (@lift_L2 AuthenticationOperation _ TD _\n (File.DiskAllocator.read a2))))\n (Simulation.Definitions.compile\n ATCD_Refinement\n (Simulation.Definitions.compile\n ATC_Refinement\n (Simulation.Definitions.compile\n FD.refinement\n (| Recover |))))\n (refines_valid ATCD_Refinement\n (refines_valid ATC_Refinement\n AD_valid_state))\n (fun s1 s2 => equivalent_for_recovery txns1 txns2 Log.Current_Part hdr1 hdr2 s1 s2 /\\\n refines_related ATCD_Refinement (fun s1 s2 => refines_related ATC_Refinement\n (fun s1 s2 => exists s1a s2a, \n File.files_inner_rep s1a (fst (snd (snd s1))) /\\ \n File.files_inner_rep s2a (fst (snd (snd s2))) /\\ \n FD_related_states u' None s1a s2a) s1 s2 /\\\n (forall a, \n Transaction.get_first (fst (snd s1)) a = None <-> \n Transaction.get_first (fst (snd s2)) a = None) /\\\n (Transaction.get_first (fst (snd s1)) (File.DiskAllocatorParams.bitmap_addr + S a1) = None <-> \n Transaction.get_first (fst (snd s2)) (File.DiskAllocatorParams.bitmap_addr + S a2) = None) /\\\n nth_error\n (value_to_bits\n (upd_batch (snd (snd s1)) (rev (map fst (fst (snd s1))))\n (rev (map snd (fst (snd s1)))) File.DiskAllocatorParams.bitmap_addr)) a1 =\n nth_error\n (value_to_bits\n (upd_batch (snd (snd s2)) (rev (map fst (fst (snd s2))))\n (rev (map snd (fst (snd s2)))) File.DiskAllocatorParams.bitmap_addr)) a2) s1 s2)\n (ATCD_reboot_list n).\n Proof.\n unfold File.DiskAllocator.read; intros.\n destruct (Compare_dec.lt_dec a1 File.DiskAllocatorParams.num_of_blocks);\n destruct (Compare_dec.lt_dec a2 File.DiskAllocatorParams.num_of_blocks);\n try lia.\n 2: intros; eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve].\n simpl.\n eapply ATCD_TS_compositional.\n\n intros; eapply TS_eqv_impl.\n eapply ATCD_TS_Transaction_read.\n shelve.\n shelve.\n intros; cleanup; eauto.\n 2: shelve.\n intros.\n\n intros; unfold refines_related in *; cleanup.\n intros; unfold refines_related in *; cleanup.\n eapply_fresh ATCD_oracle_refines_finished in H1; eauto.\n eapply_fresh ATCD_oracle_refines_finished in H2; eauto.\n cleanup.\n\n eapply_fresh ATCD_exec_lift_finished in H1; eauto;\n try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n cleanup.\n eapply_fresh ATCD_exec_lift_finished in H2; eauto;\n try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n cleanup.\n simpl in *.\n eapply_fresh ATCD_oracle_refines_impl_eq in H14; eauto.\n 2: shelve. (* eapply have_same_structure_get_owner; eauto. *)\n 2: apply TC_oracle_refines_operation_eq.\n cleanup.\n\n clear H1 H2.\n repeat invert_lift2; cleanup.\n apply HC_map_ext_eq in H1; subst.\n unfold HC_refines in *; simpl in *; cleanup.\n\n unfold TransactionToTransactionalDisk.Definitions.refines in *.\n eapply Transaction.read_finished in H18; eauto.\n eapply Transaction.read_finished in H21; eauto.\n cleanup; repeat split_ors; cleanup; try lia.\n unfold Transaction.transaction_rep in *; cleanup.\n setoid_rewrite H9.\n destruct_fresh (nth_error\n (value_to_bits\n (upd_batch (snd (snd x0)) (rev (map fst (fst (snd x0))))\n (rev (map snd (fst (snd x0))))\n File.DiskAllocatorParams.bitmap_addr)) a2); setoid_rewrite D.\n 2: intros; eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve].\n {\n destruct b.\n 2: intros; eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve].\n eapply ATCD_TS_compositional.\n 2: intros; eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve].\n intros; simpl; \n eapply TS_eqv_impl; [apply ATCD_TS_Transaction_read; eauto | shelve].\n shelve.\n }\n {\n edestruct (block_allocator_empty a1);\n edestruct (block_allocator_empty a2);\n cleanup; (eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve]).\n }\n Admitted.", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/Storage/TerminationSensivitiy/ATCD_TS/ATCD_TS_Allocator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.14330511684460068}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of PM: Refinement Proof for PThreadIntro *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between PKContextNew layer and PThreadIntro layer*)\nRequire Import ShareIntroGenDef.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n Context `{real_params: RealParams}.\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n Proof.\n accessor_prop_tac.\n - eapply flatmem_store_exists; eauto.\n - eapply flatmem_store_match; eauto.\n Qed.\n\n Lemma passthrough_correct:\n sim (crel HDATA LDATA) mshareintro_passthrough mptnew.\n Proof.\n sim_oplus.\n - apply fload_sim.\n - apply fstore_sim.\n - apply flatmem_copy_sim.\n - apply vmxinfo_get_sim.\n - apply device_output_sim.\n - apply pfree_sim.\n - apply setPT_sim.\n - apply ptRead_sim. \n - apply ptResv_sim.\n - apply ptResv2_sim.\n - apply pt_new_sim.\n - apply pmap_init_sim.\n - apply ptin_sim.\n - apply ptout_sim.\n - apply clearCR2_sim.\n - apply container_get_nchildren_sim.\n - apply container_get_quota_sim.\n - apply container_get_usage_sim.\n - apply container_can_consume_sim.\n - apply alloc_sim.\n - apply trapin_sim.\n - apply trapout_sim.\n - apply hostin_sim.\n - apply hostout_sim.\n - apply trap_info_get_sim.\n - apply trap_info_ret_sim.\n - layer_sim_simpl.\n + eapply load_correct2.\n + eapply store_correct2.\n Qed.\n\n End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/ShareIntroGenPassthrough.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.14330511057400833}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of VMM *)\n(* *)\n(* Refinement proof for MALInit layer *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MBoot layer and MALInit layer*)\nRequire Import ALInitGenDef.\n\n(** * Definition of the refinement relation*)\nSection Refinement. \n\n Context `{real_params: RealParams}.\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** ** The low level specifications exist*)\n Section Exists.\n\n Lemma setPG_exist:\n forall habd habd' labd f,\n setPG0_spec habd = Some habd'\n -> relate_RData f habd labd\n -> exists labd', setPG_spec labd = Some labd' /\\ relate_RData f habd' labd'\n /\\ AT habd' = AT habd /\\ nps habd' = nps habd.\n Proof.\n unfold setPG0_spec, setPG_spec; intros until f; exist_simpl.\n Qed.\n\n Lemma setCR3_exist:\n forall habd habd' labd id ofs f,\n setCR30_spec habd (GLOBP id ofs) = Some habd'\n -> relate_RData f habd labd\n -> exists labd', setCR3_spec labd (GLOBP id ofs) = Some labd' /\\ relate_RData f habd' labd'\n /\\ AT habd' = AT habd /\\ nps habd' = nps habd.\n Proof.\n unfold setCR30_spec, setCR3_spec; intros until f; exist_simpl.\n Qed.\n\n Lemma trapout_exist:\n forall habd habd' labd f,\n trapout0_spec habd = Some habd'\n -> relate_RData f habd labd\n -> exists labd', trapout'_spec labd = Some labd' /\\ relate_RData f habd' labd'\n /\\ AT habd' = AT habd /\\ nps habd' = nps habd.\n Proof.\n unfold trapout0_spec, trapout'_spec; intros until f; exist_simpl.\n Qed.\n\n Lemma hostout_exist:\n forall habd habd' labd f,\n hostout_spec habd = Some habd'\n -> relate_RData f habd labd\n -> exists labd', hostout'_spec labd = Some labd' /\\ relate_RData f habd' labd'\n /\\ AT habd' = AT habd /\\ nps habd' = nps habd.\n Proof.\n unfold hostout_spec, hostout'_spec; intros until f; exist_simpl.\n Qed.\n\n End Exists.\n\n Ltac pattern2_refinement_simpl:= \n pattern2_refinement_simpl' (@relate_AbData).\n\n Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store') (lflatmem_store:= flatmem_store')).\n Proof.\n accessor_prop_tac.\n - eapply flatmem_store'_exists; eauto.\n Qed. \n\n Lemma passthrough_correct:\n sim (crel HDATA LDATA) malinit_passthrough mboot.\n Proof.\n sim_oplus.\n - apply fload'_sim.\n - apply fstore'_sim.\n - apply flatmem_copy'_sim.\n - apply vmxinfo_get_sim.\n - apply device_output_sim.\n - apply get_size_sim.\n - apply is_mm_usable_sim.\n - apply get_mm_s_sim.\n - apply get_mm_l_sim.\n - apply bootloader0_sim.\n - (* set_PG *)\n layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n exploit setPG_exist; eauto 1; intros [labd' [HP [HM[HAT HN]]]].\n match_external_states_simpl. congruence.\n - apply clearCR2_sim.\n - (* set_CR3 *)\n layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n inv_val_inject.\n eapply inject_forward_equal' in H8; eauto 1. inv H8.\n exploit setCR3_exist; eauto 1; intros [labd' [HP [HM[HAT HN]]]].\n match_external_states_simpl. \n rewrite Int.add_zero; eauto. congruence.\n - apply trapin_sim.\n - (* trapout *)\n layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n inv H4. inv match_extcall_states.\n exploit trapout_exist; eauto 1; intros [labd' [HP [HM[HAT HN]]]]. \n inv match_match. match_external_states_simpl. congruence.\n - apply hostin_sim.\n - (* hostout *)\n layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n inv H4. inv match_extcall_states.\n exploit hostout_exist; eauto 1; intros [labd' [HP [HM[HAT HN]]]]. \n inv match_match. match_external_states_simpl. congruence.\n - apply trap_info_get_sim.\n - apply trap_info_ret_sim.\n - layer_sim_simpl.\n + eapply load_correct1.\n + eapply store_correct1.\n Qed.\n\n End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/ALInitGenPassthrough.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.27512973571032984, "lm_q1q2_score": 0.1429357640045605}} {"text": "Require Import Setoid.\nFrom hahn Require Import Hahn.\nFrom imm Require Import AuxDef Events Execution Execution_eco\n imm_bob imm_s_ppo imm_s imm_s_hb CombRelations AuxRel2.\nFrom imm Require Import TraversalConfig Traversal.\nRequire Import AuxRel.\nRequire Export ExtTravRelations.\nFrom imm Require Import TraversalProperties.\n\nSet Implicit Arguments.\n\nSection ExtTraversalConfig.\nVariable G : execution.\nVariable sc : relation actid.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'rmw_dep'\" := G.(rmw_dep).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'coe'\" := G.(coe).\nNotation \"'fr'\" := G.(fr).\n\nNotation \"'eco'\" := G.(eco).\n\nNotation \"'bob'\" := G.(bob).\nNotation \"'fwbob'\" := G.(fwbob).\nNotation \"'ppo'\" := G.(ppo).\nNotation \"'rppo'\" := G.(rppo).\nNotation \"'fre'\" := G.(fre).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'deps'\" := G.(deps).\nNotation \"'detour'\" := G.(detour).\nNotation \"'release'\" := G.(release).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\n\nNotation \"'urr'\" := (urr G sc).\nNotation \"'c_acq'\" := (c_acq G sc).\nNotation \"'c_cur'\" := (c_cur G sc).\nNotation \"'c_rel'\" := (c_rel G sc).\nNotation \"'t_acq'\" := (t_acq G sc).\nNotation \"'t_cur'\" := (t_cur G sc).\nNotation \"'t_rel'\" := (t_rel G sc).\nNotation \"'S_tm'\" := G.(S_tm).\nNotation \"'S_tmr'\" := G.(S_tmr).\nNotation \"'msg_rel'\" := (msg_rel G sc).\n\nNotation \"'lab'\" := G.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (Events.mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun x => is_true (is_r lab x)).\nNotation \"'W'\" := (fun x => is_true (is_w lab x)).\nNotation \"'F'\" := (fun x => is_true (is_f lab x)).\nNotation \"'RW'\" := (R ∪₁ W).\nNotation \"'FR'\" := (F ∪₁ R).\nNotation \"'FW'\" := (F ∪₁ W).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Init'\" := (fun a => is_true (is_init a)).\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_' l\" := (W ∩₁ Loc_ l) (at level 1).\n\nNotation \"'Pln'\" := (fun x => is_true (is_only_pln lab x)).\nNotation \"'Rlx'\" := (fun x => is_true (is_rlx lab x)).\nNotation \"'Rel'\" := (fun x => is_true (is_rel lab x)).\nNotation \"'Acq'\" := (fun x => is_true (is_acq lab x)).\nNotation \"'Acqrel'\" := (fun x => is_true (is_acqrel lab x)).\nNotation \"'Sc'\" := (fun x => is_true (is_sc lab x)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\n\n(******************************************************************************)\n(** ** *)\n(******************************************************************************)\n\nRecord ext_trav_config :=\n mkETC { etc_TC : trav_config; reserved : actid -> Prop; }.\n\nDefinition eissued T := issued (etc_TC T).\nDefinition ecovered T := covered (etc_TC T).\n\nDefinition dom_sb_S_rfrmw T rrf P :=\n dom_rel (sb ⨾ ⦗reserved T⦘) ∩₁ codom_rel (⦗P⦘ ⨾ rrf ⨾ rmw).\n\nRecord etc_coherent (T : ext_trav_config) :=\n mkETCC {\n etc_tccoh : tc_coherent G sc (etc_TC T);\n etc_S_in_E : reserved T ⊆₁ E;\n etc_I_in_S : eissued T ⊆₁ reserved T;\n etc_S_I_in_W_ex : reserved T \\₁ eissued T ⊆₁ W_ex;\n etc_F_sb_S : dom_rel (⦗F∩₁Acq/Rel⦘ ⨾ sb ⨾ ⦗reserved T⦘) ⊆₁ ecovered T ;\n etc_dr_R_acq_I : dom_rel ((detour ∪ rfe) ⨾ (rmw ⨾ rfi)* ⨾ ⦗R∩₁Acq⦘ ⨾ sb ⨾ ⦗reserved T⦘) ⊆₁ eissued T ;\n etc_W_ex_sb_I : dom_rel (⦗W_ex_acq⦘ ⨾ sb ⨾ ⦗reserved T⦘) ⊆₁ eissued T ;\n etc_sb_S : dom_sb_S_rfrmw T (rf ⨾ ⦗R_ex⦘) (eissued T) ⊆₁ reserved T;\n (* TODO: uncomment the next property for handling FADDs. *)\n (* etc_sb_Acq_S : dom_rel ((rmw ⨾ rfi)* ⨾ ⦗R∩₁Acq⦘ ⨾ sb ⨾ ⦗reserved T⦘) ∩₁ codom_rel (⦗eissued T⦘ ⨾ rf ⨾ rmw); *)\n etc_rppo_S : dom_rel ((detour ∪ rfe) ⨾ (data ∪ rfi ∪ rmw)* ⨾ rppo ⨾ ⦗ reserved T ⦘) ⊆₁ eissued T;\n etc_d_rmw_S : dom_rel (detour ⨾ rmw ⨾ ⦗ reserved T ⦘) ⊆₁ eissued T;\n etc_S_W_ex_rfrmw_I : reserved T ∩₁ W_ex ⊆₁ codom_rel (⦗eissued T⦘ ⨾ rf ⨾ rmw);\n }.\n\nSection Props.\n\nVariable WF : Wf G.\nVariable T : ext_trav_config.\nVariable ETCCOH : etc_coherent T.\n\nLemma etc_rmw_S : dom_rel ((detour ∪ rfe) ⨾ rmw ⨾ ⦗ reserved T ⦘) ⊆₁ eissued T.\nProof using WF ETCCOH.\n rewrite !seq_union_l, dom_union. unionL; [by apply ETCCOH|].\n rewrite rmw_W_ex, !seqA. rewrite <- id_inter. rewrite set_interC.\n rewrite etc_S_W_ex_rfrmw_I; auto. rewrite rfe_in_rf.\n remember (rf ⨾ rmw) as X.\n arewrite (rf ⨾ rmw ⊆ X) by subst.\n unfolder. ins. desf.\n assert (x = z); subst; auto.\n eapply wf_rfrmwf; eauto.\nQed.\n\nLemma eissuedW : eissued T ⊆₁ W.\nProof using ETCCOH. unfold eissued. eapply issuedW. apply ETCCOH. Qed.\n\nLemma reservedW : reserved T ⊆₁ W.\nProof using WF ETCCOH.\n arewrite (reserved T ⊆₁ reserved T \\₁ eissued T ∪₁ reserved T ∩₁ eissued T).\n 2: { rewrite eissuedW at 2; auto. rewrite etc_S_I_in_W_ex; auto.\n rewrite W_ex_in_W; auto. basic_solver. }\n unfolder. ins.\n destruct (classic (eissued T x)); eauto.\nQed.\n\nEnd Props.\nEnd ExtTraversalConfig.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/ext_traversal/ExtTraversalConfig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.27512973571032984, "lm_q1q2_score": 0.14293576400456048}} {"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.nested_field_lemmas.\nRequire Import VST.floyd.efield_lemmas.\nRequire Import VST.floyd.mapsto_memory_block.\nRequire Import VST.floyd.reptype_lemmas.\nRequire Import VST.floyd.data_at_rec_lemmas.\nRequire Import VST.floyd.field_at.\nRequire Import VST.floyd.stronger.\nRequire Import VST.floyd.entailer.\nRequire Import VST.floyd.closed_lemmas.\nRequire Import VST.floyd.proj_reptype_lemmas.\nRequire Import VST.floyd.replace_refill_reptype_lemmas.\nRequire Import VST.floyd.loadstore_field_at.\nRequire Import VST.floyd.nested_loadstore.\n\nLocal Open Scope logic.\n\nDefinition array_with_hole {cs: compspecs} sh (t: type) lo hi n (al': list (reptype t)) p :=\n!! field_compatible (tarray t n) nil p &&\n(ALL cl: list (reptype t),\n(data_at sh (tarray t (hi-lo)) cl (field_address0 (tarray t n) (ArraySubsc lo :: nil) p)\n-* data_at sh (tarray t n) (sublist 0 lo al' ++ cl ++ sublist hi n al') p)).\n\nLemma array_with_hole_local_facts {cs: compspecs}: forall sh t lo hi n (al': list (reptype t)) p,\narray_with_hole sh t lo hi n al' p |-- \n!! (field_compatible (tarray t n) nil p).\nProof.\nintros.\nunfold array_with_hole. entailer!.\nQed.\n#[export] Hint Resolve array_with_hole_local_facts : saturate_local.\n\nLemma wand_slice_array:\nforall {cs: compspecs} lo hi n sh t (al: list (reptype t)) p,\n0 <= lo <= hi ->\nhi <= n ->\nZlength al = n ->\ndata_at sh (tarray t n) al p =\n!! (field_compatible (tarray t n) nil p) &&\ndata_at sh (tarray t (hi-lo)) (sublist lo hi al) (field_address0 (tarray t n) (ArraySubsc lo :: nil) p) *\narray_with_hole sh t lo hi n al p.\nProof.\n intros until p.\n intros H H0 H1.\n unfold data_at, array_with_hole.\n assert (forall n, reptype (tarray t n) = list (reptype t)).\n {\n intros.\n rewrite reptype_eq.\n auto.\n }\n apply pred_ext.\n + rewrite (add_andp _ _ (field_at_local_facts _ _ _ _ _)).\n normalize.\n rename H3 into H7, H4 into H8.\n erewrite field_at_Tarray.\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at' _ _ _ 0 lo hi n); try lia.\n 2:etransitivity; [exact H1 | lia].\n unfold data_at.\n rewrite (sepcon_comm (array_at _ _ _ _ _ _ _)), sepcon_assoc.\n apply sepcon_derives.\n - apply derives_refl'.\n f_equal.\n rewrite !Z.sub_0_r.\n auto.\n - apply allp_right; intros v. change (list (reptype t)) in v.\n * apply -> wand_sepcon_adjoint.\n rewrite (add_andp _ _ (field_at_local_facts _ _ _ _ _)).\n normalize.\n rewrite value_fits_eq in H4; simpl in H4.\n destruct H4.\n rewrite Z.max_r in H4 by lia.\n change (@Zlength (reptype t) v = hi - lo) in H4.\n erewrite (field_at_Tarray _ (tarray t n)).\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at' _ _ _ 0 lo hi n); try lia.\n 2:{\n change (Zlength (sublist 0 lo al ++ v ++ sublist hi n al) = n - 0).\n autorewrite with sublist.\n lia.\n }\n autorewrite with norm.\n change (array_at sh (tarray t n) nil 0 lo (sublist 0 lo al) p *\n array_at sh (tarray t n) nil hi n (sublist hi n al) p *\n field_at sh (tarray t (hi - lo)) nil v (field_address0 (tarray t n) (SUB lo) p)\n |-- array_at sh (tarray t n) nil 0 lo\n (sublist 0 lo (sublist 0 lo al ++ v ++ sublist hi n al)) p *\n data_at sh (nested_field_array_type (tarray t n) nil lo hi)\n (sublist lo hi (sublist 0 lo al ++ v ++ sublist hi n al))\n (field_address0 (tarray t n) (SUB lo) p) *\n array_at sh (tarray t n) nil hi n\n (sublist hi n (sublist 0 lo al ++ v ++ sublist hi n al)) p).\n unfold tarray; autorewrite with sublist.\n rewrite H4.\n replace (hi - lo - (hi - lo) + hi) with hi by lia.\n replace (n - lo - (hi - lo) + hi) with n by lia.\n rewrite !sepcon_assoc.\n apply sepcon_derives; [apply derives_refl |].\n rewrite sepcon_comm.\n apply sepcon_derives; [| apply derives_refl].\n autorewrite with sublist.\n apply derives_refl.\n + normalize.\n clear H2.\n rewrite sepcon_comm.\n apply wand_sepcon_adjoint.\n apply (allp_left _ (sublist lo hi al)); intros.\n apply wand_derives; [apply derives_refl |].\n unfold data_at.\n apply derives_refl'.\n f_equal.\n autorewrite with sublist.\n auto.\nQed.\n\nModule SingletonHole.\n\nDefinition array_with_hole {cs: compspecs} sh (t: type) i n (al': list (reptype t)) p :=\nALL v:reptype t,\n (data_at sh t v (field_address (tarray t n) (ArraySubsc i :: nil) p) -* data_at sh (tarray t n) (upd_Znth i al' v) p).\n\nLemma array_with_hole_intro {cs: compspecs} sh: forall t i n (al: list (reptype t)) p,\n 0 <= i < n ->\n data_at sh (tarray t n) al p |--\n data_at sh t (Znth i al) (field_address (tarray t n) (ArraySubsc i :: nil) p) *\n array_with_hole sh t i n al p.\nProof.\n intros.\n unfold data_at, array_with_hole.\n assert (forall n, reptype (tarray t n) = list (reptype t)).\n {\n intros.\n rewrite reptype_eq.\n auto.\n }\n saturate_local.\n assert (Zlength al = n).\n {\n destruct H2 as [? _].\n rewrite Z.max_r in H2 by lia.\n rewrite <- H2.\n reflexivity.\n }\n clear H2.\n erewrite field_at_Tarray.\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at _ _ _ 0 i (i+1) n); try lia.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n autorewrite with sublist.\n rewrite sublist_len_1.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n erewrite array_at_len_1.\n 2: apply JMeq_refl.\n rewrite field_at_data_at.\n change ((nested_field_type (tarray t n) (ArraySubsc i :: nil))) with t.\n cancel.\n apply allp_right; intros v.\n apply -> wand_sepcon_adjoint.\n \n unfold data_at at 2.\n erewrite field_at_Tarray.\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at _ _ _ 0 i (i+1) n); try lia.\n 2: autorewrite with sublist; change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n autorewrite with sublist.\n rewrite sublist_len_1.\n 2: autorewrite with sublist; change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n erewrite array_at_len_1.\n 2: apply JMeq_refl.\n rewrite field_at_data_at.\n change ((nested_field_type (tarray t n) (ArraySubsc i :: nil))) with t.\n rewrite upd_Znth_same.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n rewrite sublist_upd_Znth_l; try lia.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n rewrite sublist_upd_Znth_r; try lia.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n cancel.\nQed.\n\nLemma array_with_hole_elim {cs: compspecs} sh: forall t i n (a: reptype t) (al: list (reptype t)) p,\n data_at sh t a (field_address (tarray t n) (ArraySubsc i :: nil) p) *\n array_with_hole sh t i n al p |--\n data_at sh (tarray t n) (upd_Znth i al a) p.\nProof.\n intros.\n rewrite sepcon_comm.\n apply wand_sepcon_adjoint.\n apply (allp_left _ a).\n auto.\nQed.\n\nEnd SingletonHole.\n\nDefinition splice_into_list {A} (lo hi: Z) (source target : list A) : list A :=\n sublist 0 lo target\n ++ source \n ++ sublist hi (Zlength target) target.\n\nModule SegmentHole.\n\nDefinition array_with_hole {cs: compspecs} sh (t: type) lo hi n (al': list (reptype t)) p :=\nALL v: list (reptype t),\n (data_at sh (tarray t (hi - lo)) v (field_address0 (tarray t n) (ArraySubsc lo :: nil) p) -* data_at sh (tarray t n) (splice_into_list lo hi v al') p).\n\nLemma array_with_hole_intro {cs: compspecs} sh: forall t lo hi n (al: list (reptype t)) p,\n 0 <= lo <= hi ->\n hi <= n ->\n data_at sh (tarray t n) al p |--\n data_at sh (tarray t (hi - lo)) (sublist lo hi al) (field_address0 (tarray t n) (ArraySubsc lo :: nil) p) *\n array_with_hole sh t lo hi n al p.\nProof.\n intros.\n unfold data_at at 1, array_with_hole.\n assert (forall n, reptype (tarray t n) = list (reptype t)).\n {\n intros.\n rewrite reptype_eq.\n auto.\n }\n saturate_local.\n assert (Zlength al = n).\n {\n destruct H3 as [? _].\n rewrite Z.max_r in H3 by lia.\n rewrite <- H3.\n reflexivity.\n }\n clear H3.\n erewrite field_at_Tarray.\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at _ _ _ 0 lo hi n); try lia.\n 2: change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n autorewrite with sublist.\n change (tarray t (hi - lo)) with (nested_field_array_type (tarray t n) nil lo hi).\n erewrite <- array_at_data_at''' by first [reflexivity | lia].\n cancel.\n apply allp_right; intros v.\n apply -> wand_sepcon_adjoint.\n \n unfold data_at at 2.\n assert_PROP (Zlength v = hi - lo).\n {\n saturate_local.\n destruct H13.\n clear - H H13.\n apply prop_right.\n rewrite Z.max_r in H13 by lia.\n exact H13.\n }\n erewrite field_at_Tarray.\n 2: constructor.\n 2: reflexivity.\n 2: lia.\n 2: apply JMeq_refl.\n erewrite (split3seg_array_at _ _ _ 0 lo hi n); try lia.\n 2: unfold splice_into_list; autorewrite with sublist; change (nested_field_type (tarray t n) (ArraySubsc 0 :: nil)) with t; lia.\n erewrite <- array_at_data_at''' by first [reflexivity | lia].\n cancel.\n unfold splice_into_list.\n autorewrite with sublist.\n replace (hi - lo - Zlength v + hi) with hi by lia.\n replace (n - lo - Zlength v + hi) with n by lia.\n cancel.\n autorewrite with sublist.\n cancel.\nQed.\n\nLemma array_with_hole_elim {cs: compspecs} sh: forall t lo hi n (a: list (reptype t)) (al: list (reptype t)) p,\n data_at sh (tarray t (hi - lo)) a (field_address0 (tarray t n) (ArraySubsc lo :: nil) p) *\n array_with_hole sh t lo hi n al p |--\n data_at sh (tarray t n) (splice_into_list lo hi a al) p.\nProof.\n intros.\n rewrite sepcon_comm.\n apply wand_sepcon_adjoint.\n apply (allp_left _ a).\n auto.\nQed.\n\nEnd SegmentHole.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/field_at_wand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.14286421014543693}} {"text": "Require Import String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Utility.Utility.\nRequire Import coqutil.Word.LittleEndian.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.Machine.\nRequire riscv.Platform.Memory.\nRequire Import riscv.Spec.PseudoInstructions.\nRequire Import riscv.Proofs.EncodeBound.\nRequire Import riscv.Proofs.DecodeEncode.\nRequire Import riscv.Platform.Run.\nRequire Import riscv.Utility.MkMachineWidth.\nRequire Import riscv.Utility.Monads. Import MonadNotations.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import compiler.RunInstruction.\nRequire Import compiler.RiscvEventLoop.\nRequire Import compiler.ForeverSafe.\nRequire Import compiler.GoFlatToRiscv.\nRequire Import coqutil.Tactics.Simp.\nRequire Import processor.KamiWord.\nRequire Import processor.KamiRiscvStep.\nRequire Import processor.KamiRiscv.\nRequire Import bedrock2.Syntax bedrock2.Semantics.\nRequire Import compiler.Pipeline.\nRequire Import compilerExamples.MMIO.\nRequire Import riscv.Platform.FE310ExtSpec.\nRequire Import compiler.FlatToRiscvDef.\nRequire Import coqutil.Tactics.rdelta.\nRequire Import end2end.KamiRiscvWordProperties.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import compiler.SeparationLogic.\nRequire Import compiler.ToplevelLoop.\nRequire Import compiler.CompilerInvariant.\nRequire Import compiler.ExprImpEventLoopSpec.\n\nLocal Open Scope Z_scope.\n\nRequire Import Coq.Classes.Morphisms.\n\n#[global] Instance word_riscv_ok: @RiscvWordProperties.word.riscv_ok 32 KamiWord.wordW.\nrefine (@KamiRiscvWordProperties.kami_word_riscv_ok 5 _ _).\nall: cbv; congruence.\nQed.\n\n#[global] Existing Instance SortedListString.map.\n#[global] Existing Instance SortedListString.ok.\n\n(* TODO these definitions should be in KamiRiscv.v: *)\n\nDefinition get_kamiMemInit{memSizeLg: Z}\n (memInit: Syntax.Vec (Syntax.ConstT (Syntax.Bit MemTypes.BitsPerByte)) (Z.to_nat memSizeLg))\n (n: nat): Byte.byte :=\n byte.of_Z (Kami.Lib.Word.uwordToZ\n (Kami.Semantics.evalConstT (kamiMemInit _ memInit) (Kami.Lib.Word.natToWord _ n))).\n\nDefinition kami_mem_contains_bytes(bs: list Coq.Init.Byte.byte){memSizeLg}(from: KamiWord.word 32)\n (mem: Syntax.Vec (Syntax.ConstT (Syntax.Bit MemTypes.BitsPerByte)) (Z.to_nat memSizeLg)): Prop :=\n List.map (get_kamiMemInit mem) (seq 0 (List.length bs)) = bs.\n\nSection Connect.\n\n Context (instrMemSizeLg memSizeLg stack_size_in_bytes: Z).\n\n Context {Registers: map.map Register (KamiWord.word 32)}\n {Registers_ok: map.ok Registers}\n {mem: map.map (KamiWord.word 32) byte}\n {mem_ok: map.ok mem}.\n\n Let instrMemSizeBytes: Z := 2 ^ (2 + instrMemSizeLg).\n\n Definition ml: MemoryLayout (width := 32) := {|\n code_start := word.of_Z 0;\n code_pastend := word.of_Z instrMemSizeBytes;\n heap_start := word.of_Z instrMemSizeBytes;\n heap_pastend := word.of_Z (2 ^ memSizeLg - stack_size_in_bytes);\n stack_start := word.of_Z (2 ^ memSizeLg - stack_size_in_bytes);\n stack_pastend := word.of_Z (2 ^ memSizeLg);\n |}.\n\n Context (memInit: Syntax.Vec (Syntax.ConstT (Syntax.Bit MemTypes.BitsPerByte))\n (Z.to_nat memSizeLg)).\n\n Hypotheses (instrMemSizeLg_bounds: 3 <= instrMemSizeLg <= 30)\n (Hkmem: 2 + instrMemSizeLg < memSizeLg <= 16).\n\n Lemma memSizeLg_width_trivial: memSizeLg <= 32. Proof. blia. Qed.\n\n Definition p4mm: Kami.Syntax.Modules :=\n KamiRiscv.p4mm instrMemSizeLg memSizeLg (proj1 instrMemSizeLg_bounds)\n (proj2 instrMemSizeLg_bounds)\n memInit.\n\n Add Ring wring : (word.ring_theory (word := Consistency.word))\n (preprocess [autorewrite with rew_word_morphism],\n morphism (word.ring_morph (word := Consistency.word)),\n constants [word_cst]).\n\n Goal True.\n epose (_ : PrimitivesParams (FreeMonad.free MetricMinimalMMIO.action MetricMinimalMMIO.result)\n MetricRiscvMachine).\n Abort.\n\n Existing Instance MetricMinimalMMIO.MetricMinimalMMIOSatisfiesPrimitives.\n\n Definition states_related :=\n states_related instrMemSizeLg memSizeLg (proj1 instrMemSizeLg_bounds) (proj2 instrMemSizeLg_bounds).\n\n Lemma split_ll_trace: forall {t2' t1' t},\n traces_related t (t2' ++ t1') ->\n exists t1 t2, t = t2 ++ t1 /\\ traces_related t1 t1' /\\ traces_related t2 t2'.\n Proof.\n induction t2'; intros.\n - exists t, nil. simpl in *. repeat constructor. assumption.\n - simpl in H. simp. specialize IHt2' with (1 := H4).\n destruct IHt2' as (t1 & t2 & E & R1 & R2). subst.\n exists t1. exists (e :: t2). simpl. repeat constructor; assumption.\n Qed.\n\n Lemma states_related_to_traces_related: forall m m' t,\n states_related (m, t) m' -> traces_related t m'.(getLog).\n Proof. intros. inversion H. simpl. assumption. Qed.\n\n (* for debugging f_equal *)\n Lemma cong_app: forall {A B: Type} (f f': A -> B) (a a': A),\n f = f' ->\n a = a' ->\n f a = f' a'.\n Proof. intros. congruence. Qed.\n\n Context (spec: ProgramSpec)\n (funimplsList: list (string * (list string * list string * cmd))).\n\n Hypothesis heap_start_agree: spec.(datamem_start) = ml.(heap_start).\n Hypothesis heap_pastend_agree: spec.(datamem_pastend) = ml.(heap_pastend).\n Hypothesis stack_size_div: stack_size_in_bytes mod bytes_per_word = 0.\n Hypothesis stack_size_bounds: 0 <= stack_size_in_bytes <= 2 ^ memSizeLg - instrMemSizeBytes.\n\n Lemma mlOk: MemoryLayoutOk ml.\n Proof.\n constructor;\n unfold ml, code_start, code_pastend, heap_start, heap_pastend, stack_start, stack_pastend.\n - reflexivity.\n - rewrite word.unsigned_of_Z.\n unfold word.wrap.\n etransitivity.\n 1: exact (ToplevelLoop.mod_2width_mod_bytes_per_word (2 ^ memSizeLg - stack_size_in_bytes)).\n change bytes_per_word with 4.\n apply mod4_0.mod4_0_sub.\n + replace memSizeLg with (memSizeLg - 2 + 2) by blia.\n rewrite Z.pow_add_r by blia.\n apply mod4_0.mod4_mul4_r.\n + exact stack_size_div.\n - rewrite word.unsigned_of_Z.\n unfold word.wrap.\n etransitivity.\n 1: exact (ToplevelLoop.mod_2width_mod_bytes_per_word (2 ^ memSizeLg)).\n replace memSizeLg with (memSizeLg - 2 + 2) by blia.\n rewrite Z.pow_add_r by blia.\n apply mod4_0.mod4_mul4_r.\n - rewrite word.unsigned_of_Z. change (word.wrap 0) with 0.\n eapply proj1. eapply word.unsigned_range.\n - reflexivity.\n - rewrite ?word.unsigned_of_Z. unfold word.wrap.\n pose proof (Z.pow_nonneg 2 (2 + instrMemSizeLg)).\n change width with 32 in *.\n assert (2 ^ memSizeLg < 2 ^ 32). {\n apply Z.pow_lt_mono_r; blia.\n }\n rewrite ?Z.mod_small; try split; try apply Z.pow_nonneg; try blia.\n - reflexivity.\n - rewrite ?word.unsigned_of_Z. unfold word.wrap.\n pose proof (Z.pow_nonneg 2 (2 + instrMemSizeLg)).\n change width with 32 in *.\n assert (2 ^ memSizeLg < 2 ^ 32). {\n apply Z.pow_lt_mono_r; blia.\n }\n rewrite ?Z.mod_small; try split; try apply Z.pow_nonneg; try blia.\n Qed.\n\n Hypothesis funimplsList_NoDup: NoDup (List.map fst funimplsList).\n\n (* goodTrace in terms of \"exchange format\" (list Event).\n Only holds at the beginning/end of each loop iteration,\n will be transformed into \"exists suffix, ...\" form later *)\n Definition goodTraceE(t: list Event): Prop :=\n exists bedrockTrace, traces_related t bedrockTrace /\\ spec.(goodTrace) bedrockTrace.\n\n Definition bedrock2Inv := (fun t m l => forall mc, hl_inv spec t m l mc).\n\n Let funspecs := WeakestPrecondition.call funimplsList.\n\n Hypothesis goodTrace_implies_related_to_Events: forall (t: list LogItem),\n spec.(goodTrace) t -> exists t': list Event, traces_related t' t.\n\n Definition riscvMemInit_all_values: list byte :=\n List.map (get_kamiMemInit memInit) (seq 0 (Z.to_nat (2 ^ memSizeLg))).\n\n Definition riscvMemInit_values(from len: nat): list byte :=\n List.firstn len (List.skipn from riscvMemInit_all_values).\n\n Lemma riscvMemInit_to_seplog_aux: forall len from,\n Z.of_nat from + Z.of_nat len <= 2 ^ memSizeLg ->\n LowerPipeline.ptsto_bytes\n (word.of_Z (width := width) (Z.of_nat from))\n (map (get_kamiMemInit memInit) (seq from len))\n (map.of_list (map\n (fun i => (word.of_Z (BinIntDef.Z.of_nat i),\n byte.of_Z (Word.uwordToZ (Semantics.evalConstT (kamiMemInit memSizeLg memInit)\n (Word.natToWord (BinIntDef.Z.to_nat memSizeLg) i)))))\n (seq from len))).\n Proof.\n induction len; intros.\n - cbv. auto.\n - unfold LowerPipeline.ptsto_bytes, riscvMemInit_values in *.\n cbn [seq map array map.of_list].\n match goal with\n | |- context [map.put ?m ?k ?v] => pose proof map.put_putmany_commute k v m map.empty as P\n end.\n rewrite map.putmany_empty_r in P.\n rewrite P. clear P.\n eapply sep_comm.\n unfold sep.\n do 2 eexists.\n ssplit; cycle 1.\n + specialize (IHlen (S from)).\n replace (Z.of_nat (S from)) with (Z.of_nat from + 1) in IHlen by blia.\n rewrite word.ring_morph_add in IHlen.\n apply IHlen. blia.\n + unfold ptsto. reflexivity.\n + unfold map.split, map.disjoint. split; [reflexivity|].\n intros.\n rewrite map.get_put_dec in H1.\n destruct_one_match_hyp. 2: {\n rewrite map.get_empty in H1. discriminate.\n }\n subst.\n rewrite get_of_list_not_In in H0.\n * discriminate.\n * simpl. apply Word.weq.\n * exact mem_ok.\n * intro C.\n rewrite map_map in C.\n unfold fst in C.\n apply in_map_iff in C.\n destruct C as [ from' [E C] ].\n apply (f_equal word.unsigned) in E.\n do 2 rewrite word.unsigned_of_Z in E.\n unfold word.wrap in E.\n change width with 32 in *.\n rewrite (Z.mod_small (Z.of_nat from)) in E. 2: {\n split; [blia|].\n eapply Z.le_lt_trans with (m := 2 ^ memSizeLg). 1: blia.\n eapply Z.pow_lt_mono_r; blia.\n }\n apply in_seq in C.\n rewrite (Z.mod_small (Z.of_nat from')) in E. 2: {\n split; [blia|].\n eapply Z.le_lt_trans with (m := 2 ^ memSizeLg). 1: blia.\n eapply Z.pow_lt_mono_r; blia.\n }\n blia.\n Qed.\n\n Lemma riscvMemInit_to_seplog:\n (LowerPipeline.ptsto_bytes (word.of_Z 0) riscvMemInit_all_values)\n (riscvMemInit memSizeLg memInit).\n Proof.\n intros.\n unfold riscvMemInit_all_values, riscvMemInit.\n pose proof (riscvMemInit_to_seplog_aux (Z.to_nat (2 ^ memSizeLg)) 0) as P.\n change (Z.of_nat 0) with 0 in *.\n (* TODO could adapt riscvMemInit definition to make this not needed *)\n replace (2 ^ BinIntDef.Z.to_nat memSizeLg)%nat with (Z.to_nat (2 ^ memSizeLg)).\n 1: eapply P.\n - rewrite Z2Nat.id. 1: blia.\n apply Z.pow_nonneg. blia.\n - rewrite N_Z_nat_conversions.Z2Nat.inj_pow; try blia. reflexivity.\n Qed.\n\n (* end to end, but still generic over the program *)\n Lemma end2end:\n (* Assumptions on the program logic level: *)\n forall init_code loop_body,\n map.get (map.of_list funimplsList) \"init\"%string = Some ([], [], init_code) ->\n (forall m, LowerPipeline.mem_available ml.(heap_start) ml.(heap_pastend) m ->\n WeakestPrecondition.cmd funspecs init_code [] m map.empty bedrock2Inv) ->\n map.get (map.of_list funimplsList) \"loop\"%string = Some ([], [], loop_body) ->\n (forall t m l, bedrock2Inv t m l ->\n WeakestPrecondition.cmd funspecs loop_body t m l bedrock2Inv) ->\n (* Assumptions on the compiler level: *)\n forall (instrs: list Instruction) positions (required_stack_space: Z),\n compile_prog compile_ext_call ml (map.of_list funimplsList) = Success (instrs, positions, required_stack_space) ->\n required_stack_space <= word.unsigned (word.sub (stack_pastend ml) (stack_start ml)) / bytes_per_word ->\n word.unsigned (code_start ml) + Z.of_nat (Datatypes.length (instrencode instrs)) <=\n word.unsigned (code_pastend ml) ->\n Forall (fun i : Instruction => verify i iset) instrs ->\n ExprImp.valid_funs (map.of_list funimplsList) ->\n (* Assumptions on the Kami level: *)\n kami_mem_contains_bytes (instrencode instrs) ml.(code_start) memInit ->\n forall (t: Kami.Semantics.LabelSeqT) (mFinal: KamiImplMachine),\n (* IF the 4-stage pipelined processor steps to some final state mFinal, producing trace t,*)\n Kami.Semantics.Behavior p4mm mFinal t ->\n (* THEN the trace produced by the kami implementation can be mapped to an MMIO trace\n (this guarantees that the only external behavior of the kami implementation is MMIO)\n and moreover, this MMIO trace satisfies \"not yet bad\", as in, there exists at\n least one way to complete it to a good trace *)\n exists (t': list Event), KamiLabelSeqR t t' /\\\n exists (suffix: list Event), goodTraceE (suffix ++ t').\n Proof.\n intros *. intros GetInit Establish GetLoop Preserve. intros *. intros C RS L F V M. intros *. intros B.\n\n set (traceProp := fun (t: list Event) =>\n exists (suffix: list Event), goodTraceE (suffix ++ t)).\n change (exists t' : list Event,\n KamiLabelSeqR t t' /\\ traceProp t').\n\n (* stack of proofs, bottom-up: *)\n\n (* 1) Kami pipelined processor to riscv-coq *)\n pose proof @riscv_to_kamiImplProcessor as P1.\n specialize_first P1 traceProp.\n specialize_first P1 (ll_inv compile_ext_call ml spec).\n specialize_first P1 B.\n specialize_first P1 (proj1 Hkmem).\n specialize_first P1 memSizeLg_width_trivial.\n specialize_first P1 (proj2 Hkmem).\n (* destruct spec. TODO why \"Error: sat is already used.\" ?? *)\n\n (* 2) riscv-coq to bedrock2 semantics *)\n pose proof compiler_invariant_proofs compile_ext_call compile_ext_call_correct as P2.\n specialize_first P2 spec.\n specialize_first P2 ml.\n specialize_first P2 mlOk.\n destruct P2 as [ P2establish [P2preserve P2use] ]. {\n intros. reflexivity.\n }\n eapply P1; clear P1.\n - assumption.\n - assumption.\n - (* establish *)\n intros.\n eapply P2establish.\n unfold initial_conditions.\n exists (map.of_list funimplsList), instrs, positions, required_stack_space.\n destr_RiscvMachine m0RV.\n subst.\n ssplit.\n + (* 3) bedrock2 semantics to bedrock2 program logic *)\n econstructor.\n * exact V.\n * exact GetInit.\n * intros.\n eapply ExprImp.weaken_exec.\n -- match goal with\n | H: LowerPipeline.mem_available ?from ?to _ |- _ =>\n rewrite heap_start_agree in H;\n rewrite heap_pastend_agree in H\n end.\n refine (WeakestPreconditionProperties.sound_cmd _ _ _ _ _ _ _ _ _); eauto.\n -- simpl. clear. intros. unfold bedrock2Inv in *. eauto.\n * exact GetLoop.\n * intros. unfold bedrock2Inv in *.\n eapply ExprImp.weaken_exec.\n -- refine (WeakestPreconditionProperties.sound_cmd _ _ _ _ _ _ _ _ _); eauto.\n -- simpl. clear. intros. eauto.\n + assumption.\n + assumption.\n + assumption.\n + assumption.\n + assumption.\n + assumption.\n + pose proof word.eqb_spec.\n cbv [imem LowerPipeline.mem_available].\n unfold code_start, code_pastend, heap_start, heap_pastend, stack_start, stack_pastend, ml in *.\n assert (Bounds_instrs: 0 <= Z.of_nat (Datatypes.length (instrencode instrs))) by blia.\n assert (Bounds_unused_imem: Z.of_nat (Datatypes.length (instrencode instrs)) <= instrMemSizeBytes). {\n move L at bottom.\n rewrite ?word.unsigned_of_Z in L.\n change (word.wrap 0) with 0 in L.\n unfold word.wrap in L.\n rewrite (Z.mod_small instrMemSizeBytes) in L. 1: blia.\n split.\n - apply Z.pow_nonneg. blia.\n - change width with 32. apply Z.pow_lt_mono_r; blia.\n }\n assert (Bounds_heap: instrMemSizeBytes <= 2 ^ memSizeLg - stack_size_in_bytes) by blia.\n assert (Bounds_stack: 2 ^ memSizeLg - stack_size_in_bytes <= 2 ^ memSizeLg) by blia.\n assert (Bounds_unmapped: 2 ^ memSizeLg < 2 ^ width). {\n change width with 32.\n apply Z.pow_lt_mono_r; try blia.\n }\n assert (Datatypes.length riscvMemInit_all_values = Z.to_nat (2 ^ memSizeLg)). {\n unfold riscvMemInit_all_values.\n rewrite map_length. rewrite seq_length.\n blia.\n }\n clear P2establish P2preserve P2use.\n eapply Proper_iff1_iff1; [|reflexivity..|].\n { progress repeat rewrite ?sep_ex1_r, ?sep_ex1_l; reflexivity. }\n eexists ?[stack].\n eapply Proper_iff1_iff1; [|reflexivity..|].\n { progress repeat rewrite ?sep_ex1_r, ?sep_ex1_l; reflexivity. }\n eexists ?[heap].\n eapply Proper_iff1_iff1; [|reflexivity..|].\n { progress repeat rewrite ?sep_ex1_r, ?sep_ex1_l; reflexivity. }\n eexists ?[unused_imem].\n eapply Proper_iff1_iff1; [|reflexivity..|].\n { progress repeat rewrite ?sep_emp_2, ?sep_emp_l, ?sep_emp_r; reflexivity. }\n eapply sep_emp_l; split.\n 2: eapply sep_assoc; eapply sep_emp_l; split.\n 3: eapply Proper_iff1_iff1; [|reflexivity..|].\n 3: { progress repeat rewrite ?sep_assoc, ?sep_emp_2, ?sep_emp_l, ?sep_emp_r; reflexivity. }\n 3: eapply sep_emp_l; split.\n\n all : cycle 3.\n Unshelve. {\n pose proof riscvMemInit_to_seplog as P.\n unfold LowerPipeline.ptsto_bytes in *.\n remember riscvMemInit_all_values as l. symmetry in Heql. pose proof Heql as E.\n (* 1) chop off instructions *)\n rewrite <- (firstn_skipn (Datatypes.length (instrencode instrs)) l) in E. subst l.\n match type of E with\n | _ = _ ++ ?L => remember L as l\n end.\n (* 2) chop off unused instruction memory *)\n rewrite <- (firstn_skipn (Z.to_nat instrMemSizeBytes - Datatypes.length (instrencode instrs))\n l) in E. subst l.\n rewrite List.app_assoc in E.\n match type of E with\n | _ = _ ++ ?L => remember L as l\n end.\n (* 3 chop off heap *)\n rewrite <- (firstn_skipn (Z.to_nat (2 ^ memSizeLg - instrMemSizeBytes - stack_size_in_bytes))\n l) in E. subst l.\n rewrite List.app_assoc in E.\n rewrite E in P; clear E.\n use_sep_assumption.\n wseplog_pre.\n simpl_addrs.\n unfold code_start, code_pastend, heap_start, heap_pastend, stack_start, stack_pastend, ml.\n replace (firstn (Datatypes.length (instrencode instrs)) riscvMemInit_all_values)\n with (instrencode instrs). 2: {\n unfold riscvMemInit_all_values.\n rewrite List.firstn_map.\n rewrite List.firstn_seq.\n rewrite Nat.min_l by blia.\n symmetry.\n exact M.\n }\n cancel.\n cancel_seps_at_indices 0%nat 0%nat. {\n f_equal.\n ring.\n }\n cancel_seps_at_indices 0%nat 0%nat. {\n f_equal.\n rewrite firstn_length.\n rewrite skipn_length.\n let word_ok := constr:(_ : word.ok _) in simpl_word_exprs word_ok.\n f_equal.\n blia.\n }\n cancel_seps_at_indices 0%nat 0%nat. {\n f_equal.\n rewrite ?firstn_length.\n rewrite ?skipn_length.\n let word_ok := constr:(_ : word.ok _) in simpl_word_exprs word_ok.\n f_equal.\n blia.\n }\n cbn [seps]. reflexivity.\n }\n all: repeat rewrite ?word.unsigned_sub, ?word.unsigned_add,\n ?firstn_length, ?skipn_length, ?word.unsigned_of_Z;\n unfold word.wrap;\n change width with 32 in *.\n all: try (\n Z.div_mod_to_equations;\n (* COQBUG (performance) https://github.com/coq/coq/issues/10743#issuecomment-530673037\n cond_hyp_factor: *)\n repeat match goal with\n | H : ?x -> _, H' : ?x -> _ |- _ =>\n pose proof (fun u : x => conj (H u) (H' u)); clear H H'\n end;\n blia).\n + change (word.unsigned (code_start ml)) with 0.\n assert (Hend: code_pastend ml = word.of_Z instrMemSizeBytes) by reflexivity.\n setoid_rewrite Hend.\n rewrite word.unsigned_of_Z.\n cbv [word.wrap].\n rewrite Z.mod_small. 2: {\n split.\n - apply Z.pow_nonneg; blia.\n - apply Z.pow_lt_mono_r; blia.\n }\n assumption.\n + reflexivity.\n + reflexivity.\n + unfold regs_initialized.regs_initialized. intros.\n match goal with\n | |- exists _, ?x = Some _ => destr x; [eauto|exfalso]\n end.\n match goal with\n | H: forall _, _ -> _ <> None |- _ => eapply H; eauto\n end.\n + reflexivity.\n + simpl. split.\n * apply @riscv_init_memory_undef_on_MMIO with (instrMemSizeLg:= instrMemSizeLg).\n { apply instrMemSizeLg_bounds. }\n { apply Hkmem. }\n { cbv [KamiProc.width]; blia. }\n { apply Hkmem. }\n { assumption. }\n * assumption.\n - (* preserve *)\n intros.\n refine (P2preserve _ _). assumption.\n - (* use *)\n intros *. intro Inv.\n subst traceProp. simpl.\n specialize_first P2use Inv.\n destruct P2use as [suff Good].\n unfold goodTraceE.\n pose proof (goodTrace_implies_related_to_Events _ Good) as G.\n destruct G as [t' R].\n pose proof (split_ll_trace R). simp.\n eauto 10.\n Qed.\n\nEnd Connect.\n", "meta": {"author": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/rupicola/bedrock2/end2end/src/end2end/End2EndPipeline.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.14286420703281966}} {"text": "Require Import Verdi.GhostSimulations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.NoAppendEntriesToSelfInterface.\nRequire Import VerdiRaft.OneLeaderLogPerTermInterface.\nRequire Import VerdiRaft.AppendEntriesRequestsCameFromLeadersInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsInterface.\n\nRequire Import VerdiRaft.NoAppendEntriesToLeaderInterface.\n\nSection NoAppendEntriesToLeader.\n Context {orig_base_params : BaseParams}.\n Context {one_node_params : OneNodeParams orig_base_params}.\n Context {raft_params : RaftParams orig_base_params}.\n\n Context {rri : raft_refinement_interface}.\n Context {naetsi : no_append_entries_to_self_interface}.\n Context {ollpti : one_leaderLog_per_term_interface}.\n Context {aercfli : append_entries_came_from_leaders_interface}.\n Context {lhlli : leaders_have_leaderLogs_interface}.\n\n Definition no_append_entries_to_leader' (net : network) : Prop :=\n forall p t n pli plt es ci,\n In p (nwPackets net) ->\n pBody p = AppendEntries t n pli plt es ci ->\n type (snd (nwState net (pDst p))) = Leader ->\n currentTerm (snd (nwState net (pDst p))) = t ->\n False.\n\n\n Definition no_append_entries_to_self' (net : network) : Prop :=\n forall p t n pli plt es ci,\n In p (nwPackets net) ->\n pBody p = AppendEntries t n pli plt es ci ->\n pDst p = pSrc p ->\n False.\n \n Theorem lift_no_append_entries_to_self :\n forall net,\n refined_raft_intermediate_reachable net ->\n no_append_entries_to_self (deghost net).\n Proof using naetsi rri. \n intros.\n eapply lift_prop; eauto using no_append_entries_to_self_invariant.\n Qed.\n\n Lemma ghost_packet :\n forall (net : network (params := raft_refined_multi_params)) p,\n In p (nwPackets net) ->\n In (deghost_packet p) (nwPackets (deghost net)).\n Proof using. \n unfold deghost.\n simpl. intuition.\n apply in_map_iff.\n eexists; eauto.\n Qed.\n\n Theorem no_append_entries_to_self'_invariant :\n forall net,\n refined_raft_intermediate_reachable net ->\n no_append_entries_to_self' net.\n Proof using naetsi rri. \n unfold no_append_entries_to_self'. intros.\n find_apply_lem_hyp ghost_packet.\n find_eapply_lem_hyp lift_no_append_entries_to_self; auto.\n simpl in *. eauto.\n Qed.\n \n Lemma no_append_entries_to_leader_invariant' :\n forall net,\n refined_raft_intermediate_reachable net ->\n no_append_entries_to_leader' net.\n Proof using lhlli aercfli ollpti naetsi rri. \n unfold no_append_entries_to_leader'. intros. subst.\n find_copy_eapply_lem_hyp no_append_entries_to_self'_invariant; eauto.\n find_false.\n find_eapply_lem_hyp leaders_have_leaderLogs_invariant; eauto.\n break_exists.\n find_eapply_lem_hyp append_entries_came_from_leaders_invariant; eauto.\n break_exists.\n eapply one_leaderLog_per_term_host_invariant; eauto.\n Qed.\n \n Lemma deghost_packet_exists :\n forall net p,\n In p (nwPackets (deghost net)) ->\n exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n In q (nwPackets net) /\\ p = deghost_packet q.\n Proof using. \n unfold deghost.\n simpl.\n intros.\n do_in_map.\n eauto.\n Qed.\n \n Instance noaetli : no_append_entries_to_leader_interface.\n split. intros.\n apply lower_prop; auto.\n intros.\n find_apply_lem_hyp no_append_entries_to_leader_invariant'.\n unfold no_append_entries_to_leader', no_append_entries_to_leader in *.\n intros.\n find_apply_lem_hyp deghost_packet_exists. break_exists. intuition. subst.\n simpl in *. repeat break_match; simpl in *. subst.\n match goal with\n | H : nwState ?h = (?gd, ?d) |- _ =>\n replace gd with (fst (nwState h)) in * by (rewrite H; reflexivity);\n replace d with (snd (nwState h)) in * by (rewrite H; reflexivity);\n clear H\n end. eauto.\n Qed.\nEnd NoAppendEntriesToLeader.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/NoAppendEntriesToLeaderProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.14286420615351103}} {"text": "From ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution.Test Require Import QCTest.\nFrom ConCert.Examples.BAT Require Import BATCommon.\nFrom ConCert.Examples.BAT Require Import BATPrinters.\nFrom ConCert.Examples.EIP20 Require Import EIP20TokenGens.\nFrom Coq Require Import List.\nFrom Coq Require Import ZArith.\nImport ListNotations.\nImport MonadNotation.\n\n\nModule Type BATGensInfo.\n Parameter trace_length : nat.\n Parameter gAccount : G Address.\n Parameter contract_addr : Address.\n Parameter accounts : list Address.\n Parameter accounts_total_balance : Z.\n Parameter bat_addr : Address.\n Parameter fund_addr : Address.\n Parameter bat_addr_refundable : bool.\n Parameter bat_addr_fundable : bool.\n Parameter eip20_transactions_before_finalized : bool.\nEnd BATGensInfo.\n\nModule BATGens (Info : BATGensInfo).\n Import Info.\n Arguments SerializedValue : clear implicits.\n Arguments deserialize : clear implicits.\n Arguments serialize : clear implicits.\n\n Definition account_balance (env : Environment) (addr : Address) : Amount :=\n (env_account_balances env) addr.\n\n Definition get_refundable_accounts state : list (G (option Address)) :=\n let balances_list := FMap.elements (balances state) in\n let filtered_balances := filter (fun x => (bat_addr_refundable || (address_neqb bat_addr (fst x))) && (0 (if bat_addr_fundable || (address_neqb addr bat_addr) then Z.to_nat (account_balance env addr) else 0, returnGenSome addr)) accounts in\n freq_ (returnGen None) freq_accounts.\n\n Definition gFund_amount env state addr : G Z :=\n (choose (1, Z.min (account_balance env addr) (Z.of_N ((state.(tokenCreationCap) - (total_supply state)) / state.(tokenExchangeRate)))))%Z.\n\n Definition gCreateTokens (env : Environment) (state : BATCommon.State) : GOpt (Address * Amount * Msg) :=\n let current_slot := S (current_slot (env_chain env)) in\n if (state.(isFinalized)\n || (Nat.ltb current_slot state.(fundingStart))\n || (Nat.ltb state.(fundingEnd) current_slot) (* Funding can only happen in funding period *)\n || (N.ltb (state.(tokenCreationCap) - (total_supply state)) state.(tokenExchangeRate))) (* No funding if cap was hit or if we are too close to it *)\n then\n returnGen None\n else\n from_addr <- get_fundable_accounts env ;;\n value <- bindGen (gFund_amount env state from_addr) returnGenSome ;;\n returnGenSome (from_addr, value, create_tokens).\n\n Definition gCreateTokensInvalid (env : Environment) (state : BATCommon.State) : GOpt (Address * Amount * Msg) :=\n from_addr <- get_fundable_accounts env ;;\n value <- bindGen (choose (1, account_balance env from_addr)%Z) returnGenSome ;;\n returnGenSome (from_addr, value, create_tokens).\n\n Definition gRefund (env : Environment) (state : BATCommon.State) : GOpt (Address * Msg) :=\n let current_slot := S (current_slot (env_chain env)) in\n let accounts := get_refundable_accounts state in\n if ((state.(isFinalized)\n || (Nat.leb current_slot state.(fundingEnd))\n || (state.(tokenCreationMin) <=? (total_supply state))%N))\n then\n returnGen None\n else\n from_addr <- oneOf_ (returnGen None) accounts ;;\n returnGenSome (from_addr, refund).\n\n Definition gRefundInvalid (env : Environment) (state : BATCommon.State) : G (Address * Msg) :=\n from_addr <- gAccount ;;\n returnGen (from_addr, refund).\n\n Definition gFinalize (env : Environment) (state : BATCommon.State) : GOpt (Address * Msg) :=\n let current_slot := S (current_slot (env_chain env)) in\n if (state.(isFinalized)\n || ((total_supply state) returnGenSome (caller, tokenMsg msg))\n else\n returnGen None.\n\n Definition gTransfer_from (state : BATCommon.State) : GOpt (Address * Msg) :=\n if eip20_transactions_before_finalized || state.(isFinalized)\n then\n bindGenOpt (EIP20.gTransfer_from (token_state state))\n (fun '(caller, msg) => returnGenSome (caller, tokenMsg msg))\n else\n returnGen None.\n\n (* BAT valid call generator.\n Generator that will always return BAToken contract calls that are valid on their own,\n i.e. guaranteed to be valid if it is the first action executed in the block.\n *)\n Definition gBATActionValid (env : Environment) : GOpt Action :=\n let call contract_addr caller_addr value msg :=\n returnGenSome (build_call caller_addr contract_addr value msg) in\n state <- returnGen (get_contract_state BATCommon.State env contract_addr) ;;\n backtrack [\n (* transfer *)\n (1, bindGenOpt (gTransfer env state)\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) msg\n )\n );\n (* transfer_from *)\n (2, bindGenOpt (gTransfer_from state)\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) msg\n )\n );\n (* approve *)\n (1, bindGenOpt (gApprove state)\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) msg\n )\n );\n (* create_tokens *)\n (5, bindGenOpt (gCreateTokens env state)\n (fun '(caller, value, msg) =>\n call contract_addr caller value msg\n )\n );\n (* refund *)\n (10, bindGenOpt (gRefund env state)\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) msg\n )\n );\n (* finalize *)\n (10, bindGenOpt (gFinalize env state)\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) msg\n )\n )\n ].\n\n (* BAT invalid call generator.\n Generator likely to generate invalid BAToken contract calls.\n It treats the BAToken code mostly as blackbox and only know the expected types of input\n but does not make any assumptions/checks on which values will result in valid or invalid calls\n *)\n Definition gBATActionInvalid (env : Environment) : GOpt Action :=\n let call contract_addr caller_addr value msg :=\n returnGenSome (build_call caller_addr contract_addr value msg) in\n state <- returnGen (get_contract_state BATCommon.State env contract_addr) ;;\n backtrack [\n (* transfer *)\n (1, '(caller, msg) <- EIP20.gTransfer env (token_state state) ;;\n call contract_addr caller (0%Z) (tokenMsg msg)\n ) ;\n (* transfer_from *)\n (2, bindGenOpt (EIP20.gTransfer_from (token_state state))\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) (tokenMsg msg)\n )\n );\n (* approve *)\n (1, bindGenOpt (EIP20.gApprove (token_state state))\n (fun '(caller, msg) =>\n call contract_addr caller (0%Z) (tokenMsg msg)\n )\n );\n (* create_tokens *)\n (5, bindGenOpt (gCreateTokensInvalid env state)\n (fun '(caller, value, msg) =>\n call contract_addr caller value msg\n )\n );\n (* refund *)\n (1, '(caller, msg) <- gRefundInvalid env state ;;\n call contract_addr caller (0%Z) msg\n );\n (* finalize *)\n (1, '(caller, msg) <- gFinalizeInvalid env state ;;\n call contract_addr caller (0%Z) msg\n )\n ].\n\n (* BAT call generator\n Has a 7% chance to attempt to generate an invalid contract call\n More specifically it has:\n - 0.5% chance of generating a valid call and then replacing the amount of money sent with that call.\n For BAT contract this is likely to result in an invalid call as most contract calls on BAToken are\n not allowed to include money in them.\n - 6.5% chance of using the invalid action generator. This generator is likely to generate an invalid call\n since it treats the contract as a black box and thus does not check any of the expected requirements for\n a contract call to be valid.\n The remaining 90% of the time it will generate a call that is guaranteed to be valid (only guaranteed to\n be valid on its own, since the generator cannot know what other calls may be included in the same block and\n which order they will be executed in)\n *)\n Definition gBATAction (env : Environment) : GOpt Action :=\n state <- returnGen (get_contract_state BATCommon.State env contract_addr) ;;\n freq [\n (5, bindGenOpt (gBATActionValid env)\n (fun '(action) =>\n match action.(act_body) with\n | act_transfer _ _ => returnGen None\n | act_deploy _ _ _ => returnGen None\n | act_call to _ msg =>\n amount <- choose (0, account_balance env action.(act_from))%Z ;;\n returnGenSome (build_call action.(act_from) to amount msg)\n end\n ));\n (65, gBATActionInvalid env);\n (930, gBATActionValid env)\n ].\n\n Definition gBATSetup : G Setup :=\n fundingStart <- choose (0, (trace_length - 1)) ;;\n fundingEnd <- choose (0, (trace_length - 1)) ;;\n exchangeRate <- choose (0, Z.to_N accounts_total_balance)%N ;;\n initSupply <- choose (0, Z.to_N accounts_total_balance)%N ;;\n tokenMin <- choose (0, Z.to_N accounts_total_balance)%N ;;\n tokenCap <- choose (0, Z.to_N accounts_total_balance)%N ;;\n returnGen (BATCommon.build_setup initSupply\n fund_addr\n bat_addr\n fundingStart\n fundingEnd\n exchangeRate\n tokenCap\n tokenMin).\n\nEnd BATGens.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/bat/BATGens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.14268718981305}} {"text": "Require Import Relations.\nRequire Import Permutation.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nRequire Import sflib.\nRequire Import PacoNotation.\nRequire Import HahnRelationsBasic.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.HahnRelationsMore.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\nRequire Import PromisingArch.promising.TsoPromising.\nRequire Import PromisingArch.promising.CommonPromising.\nRequire Import PromisingArch.promising.TsoStateExecFacts.\nRequire Import PromisingArch.axiomatic.TsoAxiomatic.\nRequire Import PromisingArch.equiv.TsoSimLocal.\n\nSet Implicit Arguments.\n\n\nInductive sim_trace (p: program) (mem: Memory.t) (tid: Id.t):\n forall (tr: list (ExecUnit.t)) (atr: list AExecUnit.t)\n (wl: list (nat -> option (Loc.t * Time.t))) (rl: list (nat -> option (Loc.t * Time.t))) (fl: list (nat -> option (Loc.t * Time.t)))\n (cov: list (nat -> Time.t)) (vext: list (nat -> Time.t)), Prop :=\n| sim_trace_init\n st lc stmts\n (FIND: IdMap.find tid (Machine.init_with_promises p mem).(Machine.tpool) = Some (st, lc))\n (STMT: IdMap.find tid p = Some stmts):\n sim_trace p mem tid [ExecUnit.mk st lc mem] [AExecUnit.mk (State.init stmts) ALocal.init]\n [fun _ => None] [fun _ => None] [fun _ => None] [fun _ => Time.bot] [fun _ => Time.bot]\n| sim_trace_step\n e ae tr eu1 eu2 atr aeu1 aeu2 rl r1 r2 wl w1 w2 fl f1 f2 covl cov1 cov2 vextl vext1 vext2\n (STEP: ExecUnit.state_step0 tid e e eu1 eu2)\n (ASTATE_STEP: State.step ae aeu1.(AExecUnit.state) aeu2.(AExecUnit.state))\n (ALOCAL_STEP: ALocal.step ae aeu1.(AExecUnit.local) aeu2.(AExecUnit.local))\n (EVENT: sim_event e ae)\n (STATE: sim_state_weak eu2.(ExecUnit.state) aeu2.(AExecUnit.state))\n (W: w2 = match e with\n | Event.write _ _ vloc _ (ValA.mk _ 0 _)\n | Event.rmw _ _ vloc _ _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts))\n else w1 eid)\n | _ => w1\n end)\n (R: r2 = match e with\n | Event.read _ _ _ vloc _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts))\n else r1 eid)\n | Event.rmw _ _ vloc _ _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n Memory.latest_ts\n vloc.(ValA.val)\n (pred ((eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)))\n mem)\n else r1 eid)\n | _ => r1\n end)\n (F: f2 = match e with\n | Event.flush vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n (eu2.(ExecUnit.local).(Local.vpc) vloc.(ValA.val)).(View.ts))\n else f1 eid)\n | Event.flushopt vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then Some (vloc.(ValA.val),\n (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts))\n else f1 eid)\n | _ => f1\n end)\n (COV: cov2 = match e with\n | Event.read _ _ _ vloc _\n | Event.write _ _ vloc _ (ValA.mk _ 0 _)\n | Event.rmw _ _ vloc _ _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n else cov1 eid)\n | Event.flush vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.vpc) vloc.(ValA.val)).(View.ts)\n else cov1 eid)\n | Event.flushopt vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts)\n else cov1 eid)\n | _ => cov1\n end)\n (VEXT: vext2 = match e with\n | Event.read _ _ _ vloc _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.vrn).(View.ts))\n else vext1 eid)\n | Event.write _ _ vloc _ (ValA.mk _ 0 _)\n | Event.rmw _ _ vloc _ _ =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n else vext1 eid)\n | Event.flush vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.vpc) vloc.(ValA.val)).(View.ts)\n else vext1 eid)\n | Event.flushopt vloc =>\n (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n then (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts)\n else vext1 eid)\n | _ => vext1\n end)\n (TRACE: sim_trace p mem tid (eu1::tr) (aeu1::atr) (w1::wl) (r1::rl) (f1::fl) (cov1::covl) (vext1::vextl)):\n sim_trace p mem tid (eu2::eu1::tr) (aeu2::aeu1::atr) (w2::w1::wl) (r2::r1::rl) (f2::f1::fl) (cov2::cov1::covl) (vext2::vext1::vextl)\n.\n\nDefinition sim_traces\n (p: program) (mem: Memory.t)\n (trs: IdMap.t (list (ExecUnit.t)))\n (atrs: IdMap.t (list AExecUnit.t))\n (ws: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n (rs: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n (fs: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n (covs: IdMap.t (list (nat -> Time.t)))\n (vexts: IdMap.t (list (nat -> Time.t)))\n : Prop :=\n IdMap.Forall7 (sim_trace p mem) trs atrs ws rs fs covs vexts.\n\nLemma sim_trace_last\n p mem tid tr atr wl rl fl covl vextl\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n exists eu tr' aeu atr' w wl' r rl' f fl' cov covl' vext vextl',\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n inv SIM; esplits; eauto.\nQed.\n\nLemma sim_trace_length\n p mem tid tr atr wl rl fl covl vextl\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n induction SIM; ss. des. splits; congr.\nQed.\n\nLemma sim_trace_memory\n p mem tid tr atr wl rl fl covl vextl\n eu tr'\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n (EU: tr = eu :: tr'):\n mem = eu.(ExecUnit.mem).\nProof.\n revert eu tr' EU.\n induction SIM.\n - ii. inv EU. ss.\n - ii. inv EU. exploit IHSIM; try refl. i.\n inv STEP. ss.\nQed.\n\nLemma sim_traces_memory\n p trs atrs ws rs fs covs vexts\n m\n ts loc val tid\n (STEP: Machine.pf_exec p m)\n (SIM: sim_traces p m.(Machine.mem) trs atrs ws rs fs covs vexts)\n (TR: IdMap.Forall2\n (fun tid tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n trs m.(Machine.tpool))\n (GET: Memory.get_msg ts m.(Machine.mem) = Some (Msg.mk loc val tid)):\n exists eu, IdMap.find tid trs = Some eu.\nProof.\n generalize (SIM tid). intro X. inv X; eauto.\n generalize (TR tid). rewrite <- H0. intro X. inv X.\n inv STEP. hexploit state_exec_rtc_state_step; [by eauto|]. i. des.\n exploit Machine.step_get_msg_tpool.\n - etrans.\n + eapply Machine.rtc_step_mon; [|by eauto]. right. ss.\n + eapply Machine.rtc_step_mon; [|by eauto]. left. ss.\n - inv EQUIV. rewrite <- MEM. eauto.\n - s. i. des. inv EQUIV. generalize (TPOOL tid). congr.\nQed.\n\nLtac simplify :=\n repeat\n (try match goal with\n | [H1: _ = IdMap.find ?id ?m, H2: _ = IdMap.find ?id ?m |- _] =>\n rewrite <- H1 in H2; inv H2\n | [H1: IdMap.find ?id ?m = _, H2: IdMap.find ?id ?m = _ |- _] =>\n rewrite H1 in H2; inv H2\n | [H1: IdMap.find ?id ?m = _, H2: _ = IdMap.find ?id ?m |- _] =>\n rewrite H1 in H2; inv H2\n | [H: Some _ = Some _ |- _] => inv H\n | [H: _::_ = _::_ |- _] => inv H\n end).\n\nLemma promising_pf_sim_step\n tid e (eu1 eu2:ExecUnit.t) aeu1\n (STATE1: sim_state_weak eu1.(ExecUnit.state) aeu1.(AExecUnit.state))\n (STEP: ExecUnit.state_step0 tid e e eu1 eu2):\n exists ae aeu2,\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n destruct eu1 as [st1 lc1 mem1].\n destruct eu2 as [st2 lc2 mem2].\n destruct aeu1 as [[astmt1 armap1] alc1].\n inv STATE1. inv STEP. ss. subst. inv STATE; inv LOCAL; inv EVENT; ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 1.\n + econs; ss.\n + ss.\n + ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 2. ss.\n + econs; ss.\n + econs; ss.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 3; ss.\n + econs 2; ss.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 4; ss.\n + econs 3; ss.\n + econs; ss.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 5; ss. eapply sim_rmap_weak_sem_rmw; eauto.\n + econs 4; ss.\n + econs; ss.\n eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 6; ss. inv RMW. econs; eauto.\n + econs 2; ss.\n + econs; ss.\n eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n + econs; ss.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 7; ss.\n + econs 5; ss.\n + econs; ss.\n + econs; ss.\n - inv STEP.\n eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 7; ss.\n + econs 6; ss.\n + econs; ss.\n + econs; ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 9. ss.\n + econs; ss.\n + ss.\n + ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 10. ss.\n + econs 8; ss.\n + econs. eauto using sim_rmap_weak_expr.\n + ss.\n - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n + econs 11. ss.\n + econs 7; ss.\n + econs. eauto using sim_rmap_weak_expr.\n + ss.\nQed.\n\nLemma promising_pf_sim_traces\n p m\n (STEP: Machine.pf_exec p m):\n exists trs atrs ws rs fs covs vexts ex (PRE: Valid.pre_ex p ex),\n <> /\\\n < exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n trs m.(Machine.tpool)>> /\\\n < exists l, atr = aeu :: l)\n atrs PRE.(Valid.aeus)>>.\nProof.\n inv STEP. exploit state_exec_rtc_state_step; eauto. i. des.\n eapply Machine.equiv_no_promise in NOPROMISE; eauto. revert NOPROMISE.\n cut (exists trs atrs ws rs fs covs vexts ex (PRE: Valid.pre_ex p ex),\n <> /\\\n < exists l, tr = (ExecUnit.mk (fst sl) (snd sl) (Machine.mem m2')) :: l)\n (IdMap.find tid trs)\n (IdMap.find tid (Machine.tpool m2'))>> /\\\n < exists l, atr = aeu :: l)\n atrs PRE.(Valid.aeus)>>).\n { inv EQUIV. rewrite MEM. i. des. esplits; eauto. ii. rewrite TPOOL. ss. }\n clear m STEP2 EQUIV.\n apply clos_rt_rt1n_iff, clos_rt_rtn1_iff in EXEC. induction EXEC.\n { eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n eexists (IdMap.mapi (fun _ _ => [bot]) p).\n eexists (IdMap.mapi (fun _ _ => [bot]) p).\n eexists (Execution.mk (IdMap.mapi (fun _ _ => _) p) bot bot bot).\n eexists (@Valid.mk_pre_ex _ _ (IdMap.mapi (fun tid stmts => AExecUnit.mk (State.init stmts) ALocal.init) p) _ _).\n hexploit Machine.rtc_promise_step_spec; eauto. s. intro X.\n s. splits; cycle 1.\n - i. specialize (X tid). rewrite ? IdMap.map_spec, ? IdMap.mapi_spec in *.\n rewrite X. destruct (IdMap.find tid p); ss. econs. eauto.\n - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p); ss. eauto.\n - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p) eqn:STMTS; ss. econs.\n econs 1; ss. rewrite IdMap.mapi_spec, STMTS. s. ss.\n }\n des.\n destruct y as [tpool1 mem1].\n destruct z as [tpool2 mem2].\n ss. inv H. ss. subst. inv STEP. inv STEP0. ss. subst.\n generalize (TR tid). rewrite FIND. intro Y. inv Y. des. subst. rename H0 into TRS. symmetry in TRS.\n generalize (SIM tid). intro Y. inv Y; [congr|]. rewrite TRS in H0. inv H0.\n hexploit sim_trace_last; eauto. i. des. subst. simplify.\n exploit promising_pf_sim_step; eauto.\n { inv REL7; eauto. s.\n unfold Machine.init_with_promises in FIND0. ss.\n rewrite IdMap.mapi_spec, STMT in *. inv FIND0.\n apply sim_state_weak_init.\n }\n { instantiate (1 := ExecUnit.mk _ _ _). econs; ss; eauto. }\n i. des.\n\n eexists (IdMap.add tid _ trs).\n eexists (IdMap.add tid _ atrs).\n eexists (IdMap.add tid _ ws).\n eexists (IdMap.add tid _ rs).\n eexists (IdMap.add tid _ fs).\n eexists (IdMap.add tid _ covs).\n eexists (IdMap.add tid _ vexts).\n eexists (Execution.mk _ _ _ _).\n eexists (@Valid.mk_pre_ex _ _ (IdMap.add tid _ PRE.(Valid.aeus)) _ _).\n s. splits; cycle 1.\n - i. rewrite ? IdMap.add_spec. condtac; eauto.\n - ii. rewrite ? IdMap.add_spec. condtac; eauto.\n - s. ii. rewrite ? IdMap.add_spec. condtac; eauto. inversion e0. subst. clear e0 X. econs.\n econs 2; eauto. econs; eauto.\nGrab Existential Variables.\nall: ss.\n1: { ii. generalize (PRE.(Valid.AEUS) id). intro X.\n rewrite IdMap.add_spec. condtac; ss. inversion e0. subst. clear e0 X0.\n generalize (ATR tid). rewrite <- H. intro Y. inv Y. des. inv REL.\n rewrite <- H7 in X. inv X. econs. etrans; eauto with tso.\n}\n5: { ii. rewrite IdMap.mapi_spec. destruct (IdMap.find id p); ss. econs. refl. }\n4: { unfold IdMap.map. rewrite IdMap.mapi_mapi. f_equal. }\n1: { apply bot. (* it's ex's co. *) }\n1: { apply bot. (* it's ex's rf. *) }\n1: { apply bot. (* it's ex's pf. *) }\nQed.\n\nInductive sim_th\n (p:program) (mem:Memory.t) (tid:Id.t)\n (eu:ExecUnit.t)\n (aeu:AExecUnit.t)\n (w: nat -> option (Loc.t * Time.t))\n (r: nat -> option (Loc.t * Time.t))\n (f: nat -> option (Loc.t * Time.t))\n (cov: nat -> Time.t)\n (vext: nat -> Time.t): Prop := mk {\n WPROP1:\n forall ts loc val\n (GET: Memory.get_msg ts mem = Some (Msg.mk loc val tid)),\n ((Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = true /\\\n forall eid, w eid <> Some (loc, ts)) \\/\n (Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = false /\\\n exists eid l,\n w eid = Some (loc, ts) /\\\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_writing_val loc val l));\n WPROP2:\n forall eid loc val l\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_writing_val loc val l),\n exists ts,\n w eid = Some (loc, ts) /\\\n Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n WPROP2':\n forall eid loc l\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_writing loc l),\n exists ts val,\n w eid = Some (loc, ts) /\\\n Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n WPROP3:\n forall eid loc ts (GET: w eid = Some (loc, ts)),\n Time.lt Time.bot ts /\\\n cov eid = ts /\\\n vext eid = ts /\\\n ts <= (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n exists val l,\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_writing_val loc val l /\\\n Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n WPROP4:\n forall eid1 loc1 eid2 loc2 ts (W1: w eid1 = Some (loc1, ts)) (W2: w eid2 = Some (loc2, ts)),\n eid1 = eid2;\n RPROP1:\n forall eid loc val l\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_reading_val loc val l),\n exists ts tid',\n r eid = Some (loc, ts) /\\\n <>;\n RPROP2:\n forall eid loc ts (GET: r eid = Some (loc, ts)),\n (cov eid = ts /\\\n ts <= (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n exists l val tid',\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_reading_val loc val l /\\\n <>) \\/\n (cov eid > ts /\\\n ts <= (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n exists l vold tid',\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_kinda_reading_val loc vold l /\\\n Label.is_kinda_write l /\\\n <>);\n UPROP:\n forall eid loc old_ts ts\n (R: r eid = Some (loc, old_ts))\n (W: w eid = Some (loc, ts)),\n old_ts < ts /\\\n Memory.latest loc old_ts (pred ts) mem;\n FPROP1:\n forall eid loc1 l\n (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_persisting loc1 l),\n exists perv,\n <> /\\\n <>>>;\n FPROP2:\n forall eid loc1 perv\n (GET: f eid = Some (loc1, perv)),\n <> /\\\n <> /\\\n exists l,\n List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some l /\\\n Label.is_persisting loc1 l /\\\n <>>>;\n COVPROP:\n forall eid (COV: cov eid > 0),\n AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access_persist eid;\n VEXTPROP:\n forall eid (VEXT: vext eid > 0),\n AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access_persist eid;\n\n PO: forall iid1 iid2 label1 label2\n (PO: iid1 < iid2)\n (LABEL1: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid1 = Some label1)\n (LABEL2: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid2 = Some label2)\n (REL: Execution.label_loc label1 label2),\n <\n cov iid1 < cov iid2>> /\\\n <\n cov iid1 <= cov iid2>>;\n PO_FL: forall iid1 iid2 label1 label2\n (PO: iid1 < iid2)\n (LABEL1: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid1 = Some label1)\n (LABEL2: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid2 = Some label2)\n (WR: Label.is_write label1)\n (FL: Label.is_flush label2),\n vext iid1 <= vext iid2;\n EU_WF: ExecUnit.wf tid eu;\n AEU_WF: AExecUnit.wf aeu;\n MEM: eu.(ExecUnit.mem) = mem;\n}.\n\nLemma sim_trace_sim_state_weak\n p mem tid\n tr eu tr'\n atr aeu atr'\n wl w wl'\n rl r rl'\n fl f fl'\n covl cov covl'\n vextl vext vextl'\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n (EU: tr = eu :: tr')\n (AEU: atr = aeu :: atr')\n (WL: wl = w :: wl')\n (RL: rl = r :: rl')\n (FL: fl = f :: fl')\n (COV: covl = cov :: covl')\n (VEXT: vextl = vext :: vextl'):\n sim_state_weak eu.(ExecUnit.state) aeu.(AExecUnit.state).\nProof.\n subst. inv SIM; ss.\n rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n eapply sim_state_weak_init.\nQed.\n\nLemma sim_trace_lastn\n p mem tid tr atr wl rl fl covl vextl\n n\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n sim_trace p mem tid\n (lastn (S n) tr) (lastn (S n) atr) (lastn (S n) wl) (lastn (S n) rl)\n (lastn (S n) fl) (lastn (S n) covl) (lastn (S n) vextl).\nProof.\n revert n atr wl rl fl covl vextl SIM. induction tr; i; [by inv SIM|].\n exploit sim_trace_length; eauto. s. i. des.\n destruct (le_lt_dec (length tr) n).\n { rewrite ? lastn_all in *; ss; try lia. }\n exploit sim_trace_last; eauto. i. des. simplify. ss.\n rewrite ? lastn_cons; try lia. eapply IHtr.\n inv SIM; ss. lia.\nQed.\n\nLemma sim_trace_lastn_rtc_step\n p mem tid tr atr wl rl fl covl vextl\n n k\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n (SIM_N: sim_trace p mem tid\n (lastn (S n) tr) (lastn (S n) atr) (lastn (S n) wl) (lastn (S n) rl)\n (lastn (S n) fl) (lastn (S n) covl) (lastn (S n) vextl))\n (SIM_NK: sim_trace p mem tid\n (lastn ((S n) + k) tr) (lastn ((S n) + k) atr) (lastn ((S n) + k) wl) (lastn ((S n) + k) rl)\n (lastn ((S n) + k) fl) (lastn ((S n) + k) covl) (lastn ((S n) + k) vextl)):\n forall eu1 eu2 l l'\n (TR: lastn (S n) tr = eu1 :: l)\n (TR2: lastn ((S n) + k) tr = eu2 :: l'),\n rtc (ExecUnit.state_step tid) eu1 eu2.\nProof.\n induction k; ss.\n - ii. rewrite plus_comm in TR2. ss.\n rewrite TR in TR2. inv TR2. auto.\n - ii. rewrite <- plus_Sn_m in *. rewrite <- plus_n_Sm in *. ss.\n exploit sim_trace_length; try exact SIM; eauto. intro X. des.\n destruct (le_lt_dec (length tr) (S (n + k))).\n + assert (EQ_S:\n lastn (S (S (n + k))) tr = lastn (S (n + k)) tr /\\\n lastn (S (S (n + k))) atr = lastn (S (n + k)) atr /\\\n lastn (S (S (n + k))) wl = lastn (S (n + k)) wl /\\\n lastn (S (S (n + k))) rl = lastn (S (n + k)) rl /\\\n lastn (S (S (n + k))) fl = lastn (S (n + k)) fl /\\\n lastn (S (S (n + k))) covl = lastn (S (n + k)) covl /\\\n lastn (S (S (n + k))) vextl = lastn (S (n + k)) vextl).\n { repeat rewrite lastn_all; ss; try lia. splits; ss. }\n des. rewrite EQ_S, EQ_S0, EQ_S1, EQ_S2, EQ_S3, EQ_S4, EQ_S5 in SIM_NK.\n eapply IHk; eauto. rewrite <- EQ_S. eauto.\n + inversion SIM_NK.\n * exploit lastn_length_incr; eauto. intro LT_NK.\n rewrite <- Nat.add_1_r in H0. rewrite <- H0 in LT_NK. ss.\n assert (1 <= length (lastn (S n) tr)).\n { rewrite TR. ss. lia. }\n destruct k.\n { rewrite plus_comm in LT_NK. ss. lia. }\n exploit lastn_length_incr.\n { instantiate (1 := tr). instantiate (1 := S n). lia. }\n rewrite plus_Sn_m. rewrite LT_NK. lia.\n * clear W R COV VEXT.\n rewrite <- H0 in TR2. inversion TR2. rewrite H7 in *. clear H7 H8.\n symmetry in H0. eapply lastn_S1 in H0; ss. rewrite <- H0 in TRACE.\n symmetry in H. eapply lastn_S1 in H; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H in TRACE.\n symmetry in H2. eapply lastn_S1 in H2; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H2 in TRACE.\n symmetry in H3. eapply lastn_S1 in H3; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H3 in TRACE.\n symmetry in H4. eapply lastn_S1 in H4; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H4 in TRACE.\n symmetry in H5. eapply lastn_S1 in H5; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H5 in TRACE.\n symmetry in H6. eapply lastn_S1 in H6; [| eapply lt_le_trans]; eauto; try lia. rewrite <- H6 in TRACE.\n etrans; cycle 1.\n { econs 2; eauto. econs; eauto. }\n eapply IHk; eauto.\nQed.\n\nLemma sim_trace_rtc_step\n p mem tid tr atr wl rl fl covl vextl\n n\n (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n forall eu_to l eu_from l'\n (TR: tr = eu_to :: l)\n (TR_N: lastn (S n) tr = eu_from :: l'),\n rtc (ExecUnit.state_step tid) eu_from eu_to.\nProof.\n exploit sim_trace_length; eauto. i. des.\n exploit sim_trace_lastn; eauto. instantiate (1 := n). intro SIM_N.\n destruct (le_lt_dec (length tr) (S n)).\n { exploit sim_trace_length; try exact SIM; eauto. intro X. des.\n rewrite ? lastn_all in *; try lia. ii. rewrite TR in TR_N. inv TR_N. eauto. }\n assert (exists k, S n + k = length tr).\n { exists (((length tr) - (S n))). lia. }\n des.\n exploit lastn_all.\n { instantiate (1 := tr). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := atr). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := wl). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := rl). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := fl). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := covl). instantiate (1 := S n + k). lia. }\n exploit lastn_all.\n { instantiate (1 := vextl). instantiate (1 := S n + k). lia. }\n i.\n generalize SIM. intro SIM_NK.\n rewrite <- x0 in SIM_NK.\n rewrite <- x1 in SIM_NK.\n rewrite <- x2 in SIM_NK.\n rewrite <- x3 in SIM_NK.\n rewrite <- x4 in SIM_NK.\n rewrite <- x5 in SIM_NK.\n rewrite <- x6 in SIM_NK.\n rewrite <- x6 in TR.\n eapply sim_trace_lastn_rtc_step.\n 3: exact SIM_NK.\n all: eauto.\nQed.\n\nLemma sim_trace_sim_th\n p m tid\n trs tr eu tr' trt\n atrs atr aeu atr'\n ws wl w wl'\n rs rl r rl'\n fs fl f fl'\n covs covl cov covl'\n vexts vextl vext vextl'\n (PF: Machine.pf_exec p m)\n (SIM: sim_trace p m.(Machine.mem) tid tr atr wl rl fl covl vextl)\n (SIMS: sim_traces p m.(Machine.mem) trs atrs ws rs fs covs vexts)\n (TR: IdMap.Forall2\n (fun _ tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n trs m.(Machine.tpool))\n (TRS: Some trt = IdMap.find tid trs)\n (EU: tr = eu :: tr')\n (AEU: atr = aeu :: atr')\n (WL: wl = w :: wl')\n (RL: rl = r :: rl')\n (FL: fl = f :: fl')\n (COV: covl = cov :: covl')\n (VEXT: vextl = vext :: vextl'):\n forall trt' (TRT: trt = trt' ++ tr),\n sim_th p m.(Machine.mem) tid eu aeu w r f cov vext.\nProof.\n revert f fl' r rl' r rl' w wl' eu tr' aeu atr' cov covl' vext vextl' FL RL WL EU AEU COV VEXT. induction SIM.\n { i. simplify. ss. econs; ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n left. splits; ss. destruct ts; ss.\n eapply Promises.promises_from_mem_lookup. eauto.\n - i. des. destruct eid; ss.\n - i. des. destruct eid; ss.\n - i. des. destruct eid; ss.\n - i. des. destruct eid; ss.\n - unfold Time.bot. i. lia.\n - unfold Time.bot. i. lia.\n - i. destruct iid1; ss.\n - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n econs; ss.\n econs; ss; i; try by apply bot_spec.\n + econs; esplits; ss.\n + destruct ts; ss.\n rewrite Promises.promises_from_mem_spec in IN. des.\n apply lt_le_S. rewrite <- List.nth_error_Some. ii. congr.\n + destruct ts; ss.\n unfold Memory.get_msg in *. ss. destruct msg.\n exploit Promises.promises_from_mem_lookup; eauto. ss. subst. ss.\n + econs; viewtac; try by i; apply bot_spec.\n econs; ss. instantiate (1 := Loc.default). econs; ss.\n + rewrite TS. ss.\n + left. apply bot_spec.\n }\n i. simplify.\n destruct eu1 as [st1 lc1 mem1] eqn: EU1. guardH EU1.\n destruct eu as [st2 lc2 mem2] eqn: EU. guardH EU.\n destruct aeu1 as [ast1 alc1].\n destruct aeu as [ast2 alc2].\n assert (mem1 = m.(Machine.mem)); subst.\n { exploit sim_trace_memory; eauto. }\n ss. exploit IHSIM; eauto.\n { instantiate (1 := trt' ++ [eu]). rewrite <- List.app_assoc. rewrite EU. ss. }\n i. rename x into IH.\n assert (EU_WF2: ExecUnit.wf tid (ExecUnit.mk st2 lc2 mem2)).\n { destruct IH.\n eapply ExecUnit.state_step_wf; eauto. econs; eauto. }\n assert (AEU_WF2: AExecUnit.wf (AExecUnit.mk ast2 alc2)).\n { destruct IH.\n eapply AExecUnit.step_future; eauto with tso. }\n inv STEP. inv ALOCAL_STEP; inv EVENT; ss; eauto.\n { (* internal *)\n inv LOCAL; ss. inv EVENT. econs; ss; try by apply IH.\n }\n { (* read *)\n inv LOCAL; ss.\n { (* pure read *)\n generalize IH.(EU_WF). i. inv H.\n specialize (Local.read_spec LOCAL STEP). intro READ_SPEC. guardH READ_SPEC.\n inv STEP. inv STATE0; inv EVENT; ss.\n exploit sim_trace_sim_state_weak; eauto. s. intro Y. inv Y. ss. inv STMTS.\n exploit sim_rmap_weak_expr; eauto. intro Y. inv Y.\n inv ASTATE_STEP.\n all: econs; ss.\n clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto. des.\n apply nth_error_snoc_inv in GET. des; eauto. split; ss. destruct l; ss.\n - i. exploit IH.(WPROP2'); eauto. des.\n apply nth_error_snoc_inv in GET. des; eauto. split; ss. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n { exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n }\n esplits; eauto.\n + rewrite fun_add_spec. des_ifs; eauto. inv e.\n ss. etrans; eauto.\n + eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(RPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n ss. eqvtac. rewrite fun_add_spec in *. condtac; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move READ_SPEC at bottom. desH READ_SPEC.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n - i. des_ifs.\n + left. apply Nat.eqb_eq in Heq. subst.\n rewrite fun_add_spec in *. des_ifs; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move READ_SPEC at bottom. desH READ_SPEC.\n exploit Memory.read_get_msg; eauto. i. des; esplits; ss; eauto with tso.\n all: try by rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss; eauto with tso.\n + exploit IH.(RPROP2); eauto. s. i. des; [left|right]; esplits; eauto with tso.\n all: try by eapply nth_error_app_mon; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto.\n - i. eapply IH.(UPROP); eauto. des_ifs.\n exploit IH.(WPROP3); eauto. i. des.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *. ss.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + unfold le in *.\n subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. destruct label1; ss; eqvtac.\n * exploit IH.(RPROP1); eauto with tso. i. des.\n exploit IH.(RPROP2); eauto. s. i.\n exploit sim_rmap_weak_expr; eauto. i. inv x2. rewrite VAL1 in *.\n des; cycle 1.\n { rewrite LABEL3 in x3. destruct l; ss. }\n subst. desH READ_TS_SPEC.\n { rewrite READ_TS_SPEC. apply bot_spec. }\n lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n - i. i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n { (* rmw_fail *)\n generalize IH.(EU_WF). i. inv H.\n specialize (Local.rmw_failure_spec LOCAL STEP). intro RMW_FAILURE_SPEC. guardH RMW_FAILURE_SPEC.\n inv STEP. inv STATE0; inv EVENT; ss.\n exploit sim_trace_sim_state_weak; eauto. s. intro Y. inv Y. ss. inv STMTS.\n exploit sim_rmap_weak_expr; eauto. intro Y. inv Y.\n inv ASTATE_STEP.\n all: econs; ss.\n clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. exploit IH.(WPROP2); eauto. des.\n apply nth_error_snoc_inv in GET. des; eauto. split; ss. destruct l; ss.\n - i. exploit IH.(WPROP2'); eauto. des.\n apply nth_error_snoc_inv in GET. des; eauto. split; ss. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n { exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n }\n esplits; eauto.\n + rewrite fun_add_spec. des_ifs; eauto. inv e.\n ss. etrans; eauto.\n + eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(RPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n ss. eqvtac. rewrite fun_add_spec in *. condtac; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move RMW_FAILURE_SPEC at bottom. desH RMW_FAILURE_SPEC.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n - i. des_ifs.\n + left. apply Nat.eqb_eq in Heq. subst.\n rewrite fun_add_spec in *. des_ifs; [|congr].\n inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n move RMW_FAILURE_SPEC at bottom. desH RMW_FAILURE_SPEC.\n exploit Memory.read_get_msg; eauto. i. des; esplits; ss; eauto with tso.\n all: try by rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss; eauto with tso.\n + exploit IH.(RPROP2); eauto. s. i. des; [left|right]; esplits; eauto with tso.\n all: try by eapply nth_error_app_mon; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto.\n - i. eapply IH.(UPROP); eauto. des_ifs.\n exploit IH.(WPROP3); eauto. i. des.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *. ss.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + unfold le in *.\n subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. destruct label1; ss; eqvtac.\n * exploit IH.(RPROP1); eauto with tso. i. des.\n exploit IH.(RPROP2); eauto. s. i.\n exploit sim_rmap_weak_expr; eauto. i. inv x2. rewrite VAL1 in *.\n des; cycle 1.\n { rewrite LABEL3 in x3. destruct l; ss. }\n subst. desH READ_TS_SPEC.\n { rewrite READ_TS_SPEC. apply bot_spec. }\n lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n }\n { (* write *)\n inv LOCAL; ss; inv EVENT; inv RES; inv STEP; ss. inv STATE. ss.\n destruct IH.(EU_WF).\n econs; ss; clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. rewrite Promises.unset_o. des_ifs.\n { inv e. right. rewrite MSG in GET. inv GET. esplits; ss.\n - instantiate (1 := ALocal.next_eid alc1). des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. congr. }\n rewrite fun_add_spec. des_ifs; ss; try congr.\n - rewrite List.nth_error_app2, Nat.sub_diag; ss.\n - inv VLOC. inv VVAL. rewrite VAL0, VAL1. eauto with tso.\n }\n des; [left|right]; splits; ss.\n + i. des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. ii. inv H.\n rewrite fun_add_spec in *. des_ifs; [|congr]. ss. apply c. ss.\n + esplits; eauto.\n * des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon. eauto.\n - i. des. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n + des_ifs.\n { apply Nat.eqb_eq in Heq. subst. lia. }\n eapply IH.(WPROP2); eauto.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. lia. }\n ss. eqvtac. esplits; eauto.\n * inv VLOC. rewrite VAL. eauto.\n * rewrite fun_add_spec in *. des_ifs; [|congr]. ss.\n inv VLOC. inv VVAL. rewrite <- VAL, <- VAL0. ss.\n - i. des. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n + des_ifs.\n { apply Nat.eqb_eq in Heq. subst. lia. }\n eapply IH.(WPROP2'); eauto.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. lia. }\n ss. eqvtac. esplits; eauto.\n * inv VLOC. rewrite VAL. eauto.\n * rewrite fun_add_spec in *. des_ifs; [|congr]. ss.\n inv VLOC. inv VVAL. rewrite <- VAL. eauto.\n - i. unfold ALocal.next_eid in *. des_ifs.\n + apply Nat.eqb_eq in Heq. subst. rewrite fun_add_spec. des_ifs; [|congr]. inv e.\n destruct ts; ss. esplits; eauto using Label.write_is_kinda_writing_val; ss.\n { unfold Time.lt, Time.bot. lia. }\n rewrite List.nth_error_app2, Nat.sub_diag; ss.\n inv VLOC. inv VVAL. rewrite <- VAL0, <-VAL1. eauto.\n + exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. inv COHMAX. s.\n exploit MAX. intro X. inv X. unfold le in *.\n rewrite TS. lia.\n * eapply nth_error_app_mon. eauto.\n - i. unfold ALocal.next_eid in *.\n des_ifs.\n + apply Nat.eqb_eq in Heq. apply Nat.eqb_eq in Heq0. subst. ss.\n + clear Heq0. rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite PROMISE. i. des; ss.\n rewrite MSG in x6. inv x6. inv WRITABLE.\n inv COHMAX. specialize (MAX (ValA.val vloc0)). inv MAX.\n unfold le in *. lia.\n + rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite PROMISE. i. des; ss.\n rewrite MSG in x6. inv x6. inv WRITABLE.\n inv COHMAX. specialize (MAX (ValA.val vloc0)). inv MAX.\n unfold le in *. lia.\n + eapply IH.(WPROP4); eauto.\n - i. des. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; esplits; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(RPROP2); eauto. s. i. des; [left|right].\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. inv COHMAX. s.\n exploit MAX. intro X. inv X. unfold le in *.\n rewrite TS. lia.\n * eapply nth_error_app_mon in x2. eauto.\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. inv COHMAX. s.\n exploit MAX. intro X. inv X. unfold le in *.\n rewrite TS. lia.\n * eapply nth_error_app_mon in x2. eauto.\n - i. eapply IH.(UPROP); eauto. des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *. ss.\n exploit IH.(RPROP2); eauto. i. des; ss.\n + assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n + assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - inv ASTATE_STEP; ss; eauto. subst.\n inv VLOC. inv VVAL. rewrite VAL0, VAL1 in *. unfold ALocal.next_eid in *.\n i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n splits; ss.\n rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. destruct label1; ss; eqvtac.\n * exploit IH.(RPROP1); eauto with tso. i. des.\n exploit IH.(RPROP2); eauto. s. i. des; cycle 1.\n { rewrite LABEL3 in x3. destruct l; ss. }\n inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap eloc))). inv MAX.\n unfold le in *. lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap eloc))). inv MAX.\n unfold le in *. lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap eloc))). inv MAX.\n unfold le in *. lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n { (* rmw *)\n inv LOCAL; ss.\n generalize IH.(EU_WF). i. inv H.\n inversion STEP. guardH LC2.\n inv STATE0; inv EVENT; ss.\n inv ASTATE_STEP.\n exploit sim_trace_sim_state_weak; eauto. s. intro Y. inv Y. ss. inv STMTS.\n exploit sim_rmap_weak_expr; eauto. intro Y. inv Y.\n inv VLOC. rewrite VAL0 in *. clear VAL.\n\n assert (PRED: old_ts = Memory.latest_ts (ValA.val (sem_expr rmap0 eloc0)) (Init.Nat.pred ts) m.(Machine.mem)).\n { generalize (SIMS tid). intro SIM_TID. inv SIM_TID; try congr. simplify.\n generalize (TR tid). intro TR_TID. inv TR_TID; try congr. simplify.\n rewrite <- EU1 in *. rewrite <- EU in *.\n exploit lastn_sub_S; ss.\n { instantiate (1 := eu :: eu1 :: tr). ss. lia. }\n instantiate (1 := trt'). i. des.\n exploit sim_trace_rtc_step; try exact REL6; eauto. intro RTC_STEP.\n replace (m.(Machine.mem)) with (ExecUnit.mem eu1); cycle 1.\n { rewrite EU1. ss. }\n rewrite <- VAL0.\n eapply ExecUnit.no_promise_rmw_spec; try exact RTC_STEP; try rewrite EU1; try rewrite EU; eauto.\n inv PF. inv NOPROMISE. rename H7 into PROMBOT.\n symmetry in PROMBOT. destruct b0. eapply PROMISES in PROMBOT. ss.\n }\n unguardH LC2. inv LC2.\n\n econs; ss; clear EU_WF2 AEU_WF2.\n - i. exploit IH.(WPROP1); eauto. s. i. rewrite Promises.unset_o. des_ifs.\n { inv e. right. rewrite MSG in GET. inv GET. esplits; ss.\n - instantiate (1 := ALocal.next_eid alc1). des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. congr. }\n rewrite fun_add_spec. des_ifs; ss; try congr.\n - rewrite List.nth_error_app2, Nat.sub_diag; ss.\n - inv NEW. rewrite VAL. eauto with tso.\n }\n des; [left|right]; splits; ss.\n + i. des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. ii. inv H.\n rewrite fun_add_spec in *. des_ifs; [|congr]. ss. apply c.\n specialize (Memory.latest_ts_spec (ValA.val (sem_expr rmap eloc0)) ts m.(Machine.mem)). i. des.\n destruct ts; ss.\n + esplits; eauto.\n * des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon. eauto.\n - i. des. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n + des_ifs.\n { apply Nat.eqb_eq in Heq. subst. lia. }\n eapply IH.(WPROP2); eauto.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. lia. }\n ss. eqvtac. esplits; eauto.\n rewrite fun_add_spec in *. des_ifs; try congr. ss.\n inv NEW. rewrite <- VAL. ss.\n - i. des. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n + des_ifs.\n { apply Nat.eqb_eq in Heq. subst. lia. }\n eapply IH.(WPROP2'); eauto.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. lia. }\n inv GET0. eqvtac.\n rewrite fun_add_spec in *. des_ifs; try congr. ss. esplits; eauto.\n - i. unfold ALocal.next_eid in *. des_ifs.\n + apply Nat.eqb_eq in Heq. subst. rewrite fun_add_spec. des_ifs; [|congr]. inv e.\n destruct ts; ss. esplits; eauto using Label.update_is_kinda_writing_val.\n * unfold Time.lt, Time.bot. lia.\n * rewrite List.nth_error_app2, Nat.sub_diag; ss.\n inv NEW. rewrite <- VAL. ss.\n + exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n inv WRITABLE. inv COHMAX. s.\n exploit MAX. intro X. inv X. unfold le in *.\n rewrite TS. lia.\n * eapply nth_error_app_mon. eauto.\n - i. unfold ALocal.next_eid in *.\n des_ifs.\n + apply Nat.eqb_eq in Heq. apply Nat.eqb_eq in Heq0. subst. ss.\n + clear Heq0. rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite PROMISE. i. des; ss.\n rewrite MSG in x6. inv x6. inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n + rewrite fun_add_spec in *. des_ifs; [|congr].\n exploit IH.(WPROP3); eauto. s. i. des.\n exploit IH.(WPROP1); eauto. s. rewrite PROMISE. i. des; ss.\n rewrite MSG in x6. inv x6. inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n + eapply IH.(WPROP4); eauto.\n - i. des. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(RPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n rewrite fun_add_spec in *. condtac; [|congr].\n inv OLD. ss. eqvtac. rewrite <- VAL.\n exploit Memory.read_get_msg; eauto. i. unguard. des; esplits; eauto.\n - i. des_ifs.\n + right. apply Nat.eqb_eq in Heq. subst.\n rewrite fun_add_spec in *. des_ifs; [|congr].\n inv VAL0. ss. subst. rewrite H0 in *.\n splits; try lia.\n inv OLD. rewrite VAL in *.\n exploit Memory.read_get_msg; eauto. i.\n assert (TS_GT: lt (Memory.latest_ts (ValA.val (sem_expr rmap0 eloc0)) (Init.Nat.pred ts) m.(Machine.mem)) ts).\n { eapply le_lt_trans with (Init.Nat.pred ts); [apply Memory.latest_ts_spec | lia]. }\n des.\n * esplits.\n { rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss. }\n all: eauto with tso.\n left. rewrite x0, x1. ss.\n * esplits.\n { rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss. }\n all: eauto with tso.\n right. eauto.\n + inv WRITABLE.\n exploit sim_rmap_weak_expr; eauto. intro Y. inv Y. rewrite VAL in *.\n exploit IH.(RPROP2); eauto. s. i. des; [left|right]; esplits; eauto with tso.\n all: try by eapply nth_error_app_mon; eauto.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto. s. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n * rewrite fun_add_spec. des_ifs; eauto.\n inv e. etrans; eauto. ss. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n - i. des_ifs; cycle 1.\n { exploit IH.(UPROP); eauto. }\n rewrite fun_add_spec. condtac; ss; try congr.\n split; ss. eapply Memory.latest_ts_latest. ss.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - inv NEW. rewrite VAL in *. unfold ALocal.next_eid in *.\n i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_neq in X0; ss; try lia.\n rewrite fun_add_spec. des_ifs; [|congr].\n inv REL. ss. split; ss. ii.\n destruct label1; ss; eqvtac.\n * exploit IH.(RPROP1); eauto with tso. i. des.\n exploit IH.(RPROP2); eauto. s. i. des; cycle 1.\n { rewrite LABEL3 in x3. destruct l; ss. }\n subst. inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des.\n subst. inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n * exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des.\n subst. inv WRITABLE. inv COHMAX.\n specialize (MAX (ValA.val (sem_expr rmap0 eloc0))). inv MAX.\n unfold le in *. lia.\n + subst. repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; try lia.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n { (* mfence *)\n inv LOCAL; ss; cycle 1.\n { destruct b; destruct b0; ss. inv EVENT. destruct wr0; destruct ww0; ss. }\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. des. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. des. exploit IH.(WPROP2'); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des.\n + esplits; eauto.\n + rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(RPROP2); eauto. s. i. des; [left|right]; esplits; eauto.\n all: eapply nth_error_app_mon; eauto.\n - i. eapply IH.(UPROP); eauto.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des; esplits; eauto.\n eapply nth_error_app_mon; eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n { subst. inv REL. inv X. }\n apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n { subst. inv REL. inv Y. }\n eapply IH.(PO); eauto.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n { (* sfence *)\n inv LOCAL; ss.\n { destruct b; destruct b0; ss. inv EVENT. destruct wr0; destruct ww0; ss. }\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. des. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. des. exploit IH.(WPROP2'); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des.\n + esplits; eauto.\n + rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(RPROP2); eauto. s. i. des; [left|right]; esplits; eauto.\n all: eapply nth_error_app_mon; eauto.\n - i. eapply IH.(UPROP); eauto.\n - i. des. exploit IH.(FPROP1); eauto.\n apply nth_error_snoc_inv in GET. des; eauto.\n rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(FPROP2); eauto. s. i. des; esplits; eauto.\n eapply nth_error_app_mon; eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n { subst. inv REL. inv X. }\n apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n { subst. inv REL. inv Y. }\n eapply IH.(PO); eauto.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n { (* flush *)\n inv LOCAL; ss.\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. des. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. des. exploit IH.(WPROP2'); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n { exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n }\n esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des.\n + esplits; eauto.\n + rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(RPROP2); eauto. s. i. des; [left|right].\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon in x2. eauto.\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon in x2. eauto.\n - i. eapply IH.(UPROP); eauto.\n - i. des. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(FPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n ss. eqvtac. inv VLOC. inv VAL.\n esplits; eauto. i.\n exploit Memory.latest_ts_spec. i. des.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto; [left|right]; eauto.\n - i. des_ifs.\n + split; ss.\n apply Nat.eqb_eq in Heq. subst.\n inv VLOC. inv VAL. ss.\n esplits; cycle 1.\n { rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss; eauto with tso. }\n all: eauto with tso.\n i.\n exploit Memory.latest_ts_spec. i. des.\n exploit Memory.read_get_msg; eauto. i. des; esplits; ss; [left | right]; eauto.\n + exploit IH.(FPROP2); eauto. s. i. des; esplits; eauto with tso.\n eapply nth_error_app_mon; eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - unfold ALocal.next_eid in *.\n i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n + subst. repeat condtac; ss.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. condtac.\n { apply Nat.eqb_eq in X. lia. }\n condtac; cycle 1.\n { assert (length (ALocal.labels alc1) =? length (ALocal.labels alc1)); try apply Nat.eqb_eq; ss.\n rewrite H in *. ss.\n }\n destruct label1; ss.\n exploit IH.(WPROP2); eauto with tso. i. des.\n exploit IH.(WPROP3); eauto. s. i. des. subst.\n rewrite x4. etrans; eauto.\n rewrite <- join_r. rewrite Loc.cl_refl. s.\n inv COHMAX. specialize (MAX loc). inv MAX. unfold le in *. ss.\n + subst. lia.\n }\n { (* flushopt *)\n inv LOCAL; ss.\n inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - i. des. exploit IH.(WPROP2); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. des. exploit IH.(WPROP2'); eauto.\n apply nth_error_snoc_inv in GET. des; eauto. destruct l; ss.\n - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n { exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n }\n esplits; eauto.\n eapply nth_error_app_mon. eauto.\n - eapply IH.(WPROP4).\n - i. des. exploit IH.(RPROP1); eauto.\n apply nth_error_snoc_inv in GET. des.\n + esplits; eauto.\n + rewrite <- GET1 in GET0. ss.\n - i. exploit IH.(RPROP2); eauto. s. i. des; [left|right].\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon in x2. eauto.\n + esplits; eauto.\n * des_ifs.\n exfalso. apply Nat.eqb_eq in Heq. subst.\n unfold ALocal.next_eid in *.\n assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n apply List.nth_error_Some in H. lia.\n * eapply nth_error_app_mon in x2. eauto.\n - i. eapply IH.(UPROP); eauto.\n - i. des. apply nth_error_snoc_inv in GET. des.\n + exploit IH.(FPROP1); eauto. i. des. esplits; eauto.\n des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n + des_ifs; cycle 1.\n { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n ss. eqvtac. inv VLOC. inv VAL.\n esplits; eauto. i.\n exploit Memory.latest_ts_spec. i. des.\n exploit Memory.read_get_msg; eauto. i. des; esplits; eauto; [left|right]; eauto.\n - i. des_ifs.\n + split; ss.\n apply Nat.eqb_eq in Heq. subst.\n inv VLOC. inv VAL. ss.\n esplits; cycle 1.\n { rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss; eauto with tso. }\n all: eauto with tso.\n i.\n exploit Memory.latest_ts_spec. i. des.\n exploit Memory.read_get_msg; eauto. i. des; esplits; ss; [left | right]; eauto.\n + exploit IH.(FPROP2); eauto. s. i. des; esplits; eauto with tso.\n eapply nth_error_app_mon; eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n - unfold ALocal.next_eid in *. s. i. des_ifs.\n { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n - econs; ss.\n }\n apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n - unfold ALocal.next_eid in *.\n i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac; ss.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO); eauto.\n + lia.\n + subst. repeat condtac; ss.\n + subst. repeat condtac; ss.\n - i. unfold ALocal.next_eid in *.\n apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n + repeat condtac.\n all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n eapply IH.(PO_FL); eauto.\n + lia.\n + subst. ss.\n + subst. ss.\n }\n\n Grab Existential Variables.\n all: auto. (* tid *)\nQed.\n", "meta": {"author": "kaist-cp", "repo": "view-hw", "sha": "e41c8ab30119acd73b6b47cf95584f966ccb8e62", "save_path": "github-repos/coq/kaist-cp-view-hw", "path": "github-repos/coq/kaist-cp-view-hw/view-hw-e41c8ab30119acd73b6b47cf95584f966ccb8e62/src/equiv/TsoPFtoA1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.26284183737131667, "lm_q1q2_score": 0.14268718279048664}} {"text": "Require Import RelationClasses.\nRequire Import List.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import LibTactics.\nRequire Import Integers.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\n\nRequire Import Kildall.\nRequire Import CorrectOpt.\nRequire Import ValAnalysis.\nRequire Import ConstProp.\nRequire Import CSEProofMState.\n\nRequire Import Language.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import LocalSim.\n\n(** ** Invariant in ConstProp proof *) \nDefinition I_cp (lo: Ordering.LocOrdMap) (inj: Mapping) (S: Rss) :=\n <> /\\\n <> /\\ <>.\n\n(** ** Match state in ConstProp proof *) \n(** Interpretation/semantics of the result of the value analysis at each program point. *)\nDefinition sem_val_reg (R_src: RegFile.t) (aregs: vreg) :=\n forall r, match (VALSET.get r aregs) with\n | LVal.VAL v => RegFun.find r R_src = v\n | LVal.vtop => True\n | LVal.vbot => False\n end.\n\nDefinition sem_val_loc (tview_src: TView.t) (mem_src: Memory.t) (amem: vmem) (lo: Ordering.LocOrdMap) :=\n forall loc,\n match (VALSET.get loc amem) with\n | LVal.VAL v => exists from R, Memory.get loc (View.pln (TView.cur tview_src) loc) mem_src =\n Some (from, Message.concrete v R) /\\\n lo loc = Ordering.nonatomic\n | LVal.vtop => True\n | LVal.vbot => False\n end.\n\nDefinition val_interp (R_src: RegFile.t) (tview_src: TView.t) (mem_src: Memory.t)\n (ae: ValLat.t) (lo: Ordering.LocOrdMap) :=\n sem_val_reg R_src (fst ae) /\\ sem_val_loc tview_src mem_src (snd ae) lo.\n\n(** Match state for current stack frame *) \nInductive match_state_cur_stkframe:\n Ordering.LocOrdMap -> TView.t -> Memory.t ->\n (RegFile.t * BBlock.t * CodeHeap) ->\n (RegFile.t * BBlock.t * CodeHeap) -> Prop :=\n| match_state_cur_stkframe_intro\n lo R_tgt BB_tgt C_tgt R_src BB_src C_src tview_src mem_src\n afunc ep ae fid\n (* function analysis *)\n (FUNC_ANALYSIS: ValDS.analyze_func (C_src, fid) succ ep transf_blk = Some afunc)\n (* transformation code heap *)\n (FUNC_TRANS: transform_cdhp C_src afunc = C_tgt)\n (* current source and target blocks transformation *)\n (TRANS_PBLK: transform_blk (transf_blk ae BB_src) BB_src = BB_tgt)\n (* current ai interpretation *)\n (AI_INTERP: val_interp R_src tview_src mem_src ae lo)\n (* RegFile eq *)\n (REGS_EQ: R_tgt = R_src)\n (* link *)\n (LINK: forall s BB_src',\n In s (succ BB_src) -> C_src ! s = Some BB_src' ->\n ValDS.L.ge (ValDS.AI.getFirst (afunc !! s)) (ValDS.AI.getLast (transf_blk ae BB_src))):\n match_state_cur_stkframe lo tview_src mem_src (R_tgt, BB_tgt, C_tgt) (R_src, BB_src, C_src).\n\n(** Match state for stack frames. *) \nInductive match_state_stkframes:\n Ordering.LocOrdMap ->\n Continuation.t -> Continuation.t -> Prop :=\n| match_state_stkframes_done\n lo:\n match_state_stkframes lo Continuation.done Continuation.done\n| match_state_stkframes_cont\n lo\n R_tgt BB_tgt C_tgt cont_tgt \n R_src BB_src C_src cont_src\n (CUR_MATCH: \n forall tview_src mem_src, \n match_state_cur_stkframe lo tview_src mem_src\n (R_tgt, BB_tgt, C_tgt) (R_src, BB_src, C_src)\n )\n (CONT_MATCH: match_state_stkframes lo cont_tgt cont_src):\n match_state_stkframes lo\n (Continuation.stack R_tgt BB_tgt C_tgt cont_tgt)\n (Continuation.stack R_src BB_src C_src cont_src).\n\n(** Match state for the thread-local state *)\nInductive match_state_tlocal:\n Mapping -> Ordering.LocOrdMap -> Memory.t ->\n (State.t * TView.t * Memory.t) -> (State.t * TView.t * Memory.t) -> Prop :=\n| match_state_tlocal_intro\n inj lo mem_src\n R_tgt BB_tgt C_tgt cont_tgt Prog_tgt tview_tgt prm_tgt\n R_src BB_src C_src cont_src Prog_src tview_src prm_src\n (PROG_TRANS: transform_prog Prog_src = Some Prog_tgt)\n (CUR_STK_FRAME: match_state_cur_stkframe lo tview_src mem_src\n (R_tgt, BB_tgt, C_tgt)\n (R_src, BB_src, C_src))\n (STK_FRAMES: match_state_stkframes lo cont_tgt cont_src)\n (TVIEW_EQ: tview_tgt = tview_src)\n (PRM_EQ: prm_tgt = prm_src)\n (PRM_INDOM: forall loc to from val R,\n Memory.get loc to prm_tgt = Some (from, Message.concrete val R) ->\n exists to', inj loc to = Some to'):\n match_state_tlocal inj lo mem_src\n (State.mk R_tgt BB_tgt C_tgt cont_tgt Prog_tgt, tview_tgt, prm_tgt)\n (State.mk R_src BB_src C_src cont_src Prog_src, tview_src, prm_src).\n\n(** Match state for the thread state *)\nInductive match_state_cp:\n Mapping -> Ordering.LocOrdMap -> bool ->\n Thread.t rtl_lang -> Thread.t rtl_lang -> Prop :=\n| match_state_cp_intro\n inj inj' lo b\n state_tgt tview_tgt prm_tgt sc_tgt mem_tgt\n state_src tview_src prm_src sc_src mem_src\n (INV: I_cp lo inj' (Build_Rss sc_tgt mem_tgt sc_src mem_src))\n (MATCH_THRD_LOCAL: \n match_state_tlocal inj lo mem_src (state_tgt, tview_tgt, prm_tgt) (state_src, tview_src, prm_src))\n (ATM_BIT: (b = false /\\ (forall loc t t', inj loc t = Some t' -> inj' loc t = Some t')) \\/\n (b = true /\\ inj = inj'))\n (* wf local, closed sc, closed memory *)\n (LOCAL_WF_TGT: Local.wf (Local.mk tview_tgt prm_tgt) mem_tgt)\n (CLOSED_SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n (MEM_CLOSED_TGT: Memory.closed mem_tgt):\n match_state_cp inj lo b\n (Thread.mk rtl_lang state_tgt (Local.mk tview_tgt prm_tgt) sc_tgt mem_tgt)\n (Thread.mk rtl_lang state_src (Local.mk tview_src prm_src) sc_src mem_src).\n\nLemma sem_val_reg_ge\n aregs aregs' R\n (SEM_VAL_REG: sem_val_reg R aregs)\n (GE: VALSET.ge aregs' aregs):\n sem_val_reg R aregs'.\nProof.\n unfold sem_val_reg in *. ii.\n specialize (SEM_VAL_REG r).\n destruct (VALSET.get r aregs) eqn:Heqe1; ss.\n unfold VALSET.ge in *.\n specialize (GE r).\n unfold LVal.ge in *.\n destruct (VALSET.get r aregs') eqn:Heqe2; ss.\n rewrite Heqe1 in GE. ss.\n rewrite Heqe1 in GE. ss.\n destruct (VALSET.get r aregs') eqn:Heqe2; ss.\n unfold VALSET.ge in *.\n specialize (GE r).\n unfold LVal.ge in *.\n rewrite Heqe2, Heqe1 in GE; ss.\n des_ifH GE; ss. subst; eauto.\n unfold VALSET.ge in *.\n specialize (GE r).\n unfold LVal.ge in *.\n rewrite Heqe2, Heqe1 in GE; ss.\nQed.\n\nLemma sem_val_loc_ge\n tview mem amem amem' lo\n (SEM_VAL_LOC: sem_val_loc tview mem amem lo)\n (GE: VALSET.ge amem' amem):\n sem_val_loc tview mem amem' lo.\nProof.\n unfold sem_val_loc in *. ii.\n specialize (SEM_VAL_LOC loc).\n destruct (VALSET.get loc amem) eqn:Heqe1; ss.\n unfold VALSET.ge in GE. specialize (GE loc).\n unfold LVal.ge in GE.\n rewrite Heqe1 in GE.\n destruct (VALSET.get loc amem') eqn:Heqe2; ss.\n unfold VALSET.ge in GE. specialize (GE loc).\n unfold LVal.ge in GE.\n rewrite Heqe1 in GE.\n destruct (VALSET.get loc amem') eqn:Heqe2; ss.\n des_ifH GE; ss. subst. eauto.\nQed.\n\nLemma ge_val_interp_prsv\n ae ae' R tview mem lo\n (GE: ValDS.AI.ge ae' ae)\n (VAL_INTERP: val_interp R tview mem ae lo):\n val_interp R tview mem ae' lo.\nProof.\n destruct ae, ae'; ss. inv GE; ss.\n unfold val_interp in *; ss. des.\n split. eapply sem_val_reg_ge; eauto.\n eapply sem_val_loc_ge; eauto.\nQed.\n\nLemma vreg_ge_top\n aregs R\n (GE: VALSET.ge aregs VALSET.top):\n sem_val_reg R aregs.\nProof.\n unfold VALSET.ge in *.\n unfold sem_val_reg; ii.\n specialize (GE r).\n destruct (VALSET.get r aregs) eqn:AREGS; ss.\n rewrite PTree.gempty in GE. ss.\n rewrite PTree.gempty in GE. ss.\nQed.\n\nLemma vloc_ge_top\n tview mem amem lo\n (GE: VALSET.ge amem VALSET.top):\n sem_val_loc tview mem amem lo.\nProof.\n unfold VALSET.ge in *; ss.\n unfold sem_val_loc; ii.\n specialize (GE loc).\n rewrite PTree.gempty in GE.\n unfold LVal.ge in *; ss.\n destruct (VALSET.get loc amem) eqn:Heqe; ss.\nQed.\n\nLemma val_ge_top\n ae R tview mem lo\n (GE_TOP: ValDS.L.ge ae ValLat.top):\n val_interp R tview mem ae lo.\nProof.\n destruct ae; ss.\n unfold ValDS.L.ge in *; ss. des.\n unfold val_interp. ss.\n split.\n eapply vreg_ge_top; eauto.\n eapply vloc_ge_top; eauto.\nQed.\n \n\n \n \n\n \n\n\n \n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/ConstPropProofMState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2751297357103299, "lm_q1q2_score": 0.1418623711398559}} {"text": "Require Import Arith.\nRequire Import NPeano.\nRequire Import List.\nRequire Import Coq.Numbers.Natural.Abstract.NDiv.\nImport ListNotations.\nRequire Import Sorting.Permutation.\nRequire Import Omega.\n\nRequire Import Util.\nRequire Import Net.\nRequire Import Raft.\nRequire Import VerdiTactics.\nRequire Import CommonTheorems.\nRequire Import OneLeaderPerTerm.\n\nHint Extern 4 (@BaseParams) => apply base_params : typeclass_instances.\nHint Extern 4 (@MultiParams _) => apply multi_params : typeclass_instances.\nHint Extern 4 (@FailureParams _ _) => apply failure_params : typeclass_instances.\n\n\nSection LeaderSublog.\n Context {orig_base_params : BaseParams}.\n Context {one_node_params : OneNodeParams orig_base_params}.\n Context {raft_params : RaftParams orig_base_params}.\n\n Ltac prove_in :=\n match goal with\n | [ _ : nwPackets ?net = _,\n _ : In (?p : packet) _ |- _] =>\n assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n | [ _ : nwPackets ?net = _,\n _ : pBody ?p = _ |- _] =>\n assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n end.\n\n\n Definition leader_sublog_host_invariant (net : network) :=\n forall leader e h,\n type (nwState net leader) = Leader ->\n In e (log (nwState net h)) ->\n eTerm e = currentTerm (nwState net leader) ->\n In e (log (nwState net leader)).\n\n Definition leader_sublog_nw_invariant (net : network) :=\n forall leader p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n type (nwState net leader) = Leader ->\n In p (nwPackets net) ->\n pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n entries leaderCommit ->\n In e entries ->\n eTerm e = currentTerm (nwState net leader) ->\n In e (log (nwState net leader)).\n\n Definition leader_sublog_invariant (net : network) :=\n leader_sublog_host_invariant net /\\\n leader_sublog_nw_invariant net.\n\n Notation is_append_entries m :=\n (exists t n prevT prevI entries c,\n m = AppendEntries t n prevT prevI entries c).\n\n Lemma leader_sublog_invariant_same_state :\n forall net net',\n leader_sublog_host_invariant net ->\n (forall h, log (nwState net h) = log (nwState net' h)) ->\n (forall h, type (nwState net' h) = Leader ->\n type (nwState net h) = Leader /\\\n currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n leader_sublog_host_invariant net'.\n Proof.\n unfold leader_sublog_host_invariant in *. intros.\n specialize (H leader e h).\n forward H; [apply H1; auto|].\n intuition.\n rewrite H0 in *. specialize (H1 leader). intuition.\n rewrite H7 in *; auto.\n rewrite H0 in *. auto.\n Qed.\n\n Lemma leader_sublog_invariant_subset :\n forall net net',\n leader_sublog_invariant net ->\n (forall p, is_append_entries (pBody p) -> In p (nwPackets net') -> In p (nwPackets net)) ->\n (forall h, log (nwState net h) = log (nwState net' h)) ->\n (forall h, type (nwState net' h) = Leader ->\n type (nwState net h) = Leader /\\\n currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n leader_sublog_invariant net'.\n Proof.\n unfold leader_sublog_invariant in *. intros; intuition.\n - eauto using leader_sublog_invariant_same_state.\n - unfold leader_sublog_nw_invariant in *. intros.\n pose proof H1 leader.\n pose proof H2 leader; concludes.\n pose proof H3 leader. intuition.\n symmetry in H13. \n repeat find_rewrite.\n eapply H11; simpl in *; repeat find_rewrite; eauto.\n assert (is_append_entries (pBody p)) by (repeat eexists; eauto).\n eauto.\n Qed.\n\n Theorem leader_sublog_do_leader :\n raft_net_invariant_do_leader leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_do_leader.\n intros.\n unfold doLeader in *.\n break_match; try solve [\n find_inversion; simpl in *;\n eapply leader_sublog_invariant_subset;\n eauto; intuition; simpl in *;\n repeat find_apply_hyp_hyp; intuition;\n repeat find_higher_order_rewrite; repeat break_if; subst; intuition].\n break_if.\n - unfold replicaMessage in *. find_inversion. simpl in *.\n unfold leader_sublog_invariant in *; intuition.\n + unfold leader_sublog_host_invariant in *. intros.\n simpl in *. repeat find_higher_order_rewrite.\n repeat break_if; simpl in *; intuition eauto.\n + unfold leader_sublog_nw_invariant in *. intros.\n simpl in *. repeat find_higher_order_rewrite.\n find_apply_hyp_hyp.\n break_if; intuition idtac; simpl in *; subst; intuition eauto;\n simpl in *;\n repeat do_in_map; subst; simpl in *;\n find_inversion; eauto using findGtIndex_in.\n - find_inversion.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, advanceCommitIndex in *.\n\n intuition; find_higher_order_rewrite; repeat break_if; simpl in *; subst;\n repeat break_if; simpl in *; eauto;\n find_apply_hyp_hyp; intuition; eauto.\n Qed.\n\n Lemma leader_sublog_client_request :\n raft_net_invariant_client_request leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_client_request.\n intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleClientRequest in *. intuition idtac.\n - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n repeat break_if; subst; simpl in *;\n intuition eauto;\n simpl in *; in_crush_finish; intuition eauto. in_crush; eauto.\n exfalso.\n match goal with\n | H : raft_intermediate_reachable _ |- _ =>\n apply one_leader_per_term_invariant in H\n end.\n assert (leader = h) by (eapply_prop one_leader_per_term; eauto).\n intuition.\n - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n repeat break_if; find_apply_hyp_hyp; intuition eauto; subst.\n simpl in *.\n in_crush; eauto.\n Qed.\n\n Lemma leader_sublog_timeout :\n raft_net_invariant_timeout\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_timeout. intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleTimeout, tryToBecomeLeader in *.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto; solve_by_inversion.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto;\n find_apply_hyp_hyp; intuition eauto; try solve_by_inversion;\n in_crush; repeat find_inversion; discriminate.\n Qed.\n\n Lemma leader_sublog_append_entries :\n raft_net_invariant_append_entries\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_append_entries. intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleAppendEntries, advanceCurrentTerm in *.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto; try solve_by_inversion;\n do_in_app; intuition; eauto using removeAfterIndex_in.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto;\n find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n Qed.\n\n Lemma leader_sublog_append_entries_reply :\n raft_net_invariant_append_entries_reply\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_append_entries_reply. intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleAppendEntriesReply, advanceCurrentTerm in *.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto; try solve_by_inversion.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto;\n find_apply_hyp_hyp; intuition eauto; try discriminate.\n Qed.\n\n Lemma leader_sublog_request_vote :\n raft_net_invariant_request_vote\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_request_vote. intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleRequestVote, advanceCurrentTerm in *.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto; try solve_by_inversion.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto;\n find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n Qed.\n\n Require Import CandidateEntries.\n Require Import RaftRefinement.\n Require Import VotesCorrect.\n Require Import CroniesCorrect.\n\n Definition CandidateEntriesLowered net e h :=\n currentTerm (nwState net h) = eTerm e ->\n wonElection (dedup name_eq_dec (votesReceived (nwState net h))) = true ->\n type (nwState net h) <> Candidate.\n\n Lemma candidate_entries_lowered' :\n forall net,\n CandidateEntries net ->\n votes_correct net ->\n cronies_correct net ->\n forall h h' e,\n In e (log (snd (nwState net h'))) ->\n CandidateEntriesLowered (deghost net) e h.\n Proof.\n unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n intros. break_and.\n rewrite deghost_spec.\n\n apply_prop_hyp candidateEntries_host_invariant In.\n unfold candidateEntries in *. break_exists. break_and.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n intro.\n assert (x = h).\n {\n match goal with\n | H : wonElection _ = _ |- _ =>\n eapply wonElection_one_in_common in H; [|clear H; eauto]\n end.\n break_exists. break_and.\n\n eapply_prop one_vote_per_term;\n try solve [eapply_prop cronies_votes; eauto].\n eapply_prop cronies_votes.\n repeat find_reverse_rewrite.\n eapply_prop votes_received_cronies; auto.\n }\n subst.\n concludes.\n contradiction.\n Qed.\n\n Lemma candidate_entries_lowered :\n forall net,\n raft_intermediate_reachable net ->\n forall h h' e,\n In e (log (nwState net h')) ->\n CandidateEntriesLowered net e h.\n Proof.\n intros net H.\n pattern net.\n apply lower_prop; auto.\n clear H net.\n intros.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n eapply candidate_entries_lowered';\n eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n Qed.\n\n Definition CandidateEntriesLowered_rvr net e p :=\n In p (nwPackets net) ->\n pBody p = RequestVoteReply (eTerm e) true ->\n currentTerm (nwState net (pDst p)) = eTerm e ->\n wonElection (dedup name_eq_dec (pSrc p :: votesReceived (nwState net (pDst p)))) = true ->\n type (nwState net (pDst p)) <> Candidate.\n\n Lemma deghost_packet_exists :\n forall net p,\n In p (nwPackets (deghost net)) ->\n exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n In q (nwPackets net) /\\ p = deghost_packet q.\n Proof.\n unfold deghost.\n simpl.\n intros.\n do_in_map.\n eauto.\n Qed.\n\n Lemma candidate_entries_lowered_rvr' :\n forall net,\n CandidateEntries net ->\n votes_correct net ->\n cronies_correct net ->\n forall p h e,\n In e (log (snd (nwState net h))) ->\n CandidateEntriesLowered_rvr (deghost net) e p.\n Proof.\n unfold CandidateEntriesLowered_rvr, CandidateEntries, votes_correct, cronies_correct.\n intros. break_and.\n rewrite deghost_spec.\n\n find_apply_lem_hyp deghost_packet_exists.\n break_exists. break_and. subst.\n eapply_prop_hyp votes_nw pBody.\n\n apply_prop_hyp candidateEntries_host_invariant In.\n unfold candidateEntries in *. break_exists. break_and.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n match goal with\n | H : wonElection _ = _ |- _ =>\n eapply wonElection_one_in_common in H; [|clear H; eauto]\n end.\n break_exists.\n break_and.\n simpl in *.\n intuition.\n - subst.\n apply_prop_hyp cronies_votes In.\n assert (x0 = pDst x) by (eapply_prop one_vote_per_term; eauto).\n subst. concludes. contradiction.\n - apply_prop_hyp votes_received_cronies In. concludes.\n apply_prop_hyp cronies_votes In.\n apply_prop_hyp cronies_votes In.\n unfold raft_data in *. unfold raft_refined_base_params, raft_refined_multi_params in *.\n simpl in *.\n repeat find_reverse_rewrite.\n assert (x0 = pDst x) by (eapply_prop one_vote_per_term; eauto).\n subst.\n repeat concludes. contradiction.\n Qed.\n\n Lemma candidate_entries_lowered_rvr :\n forall net,\n raft_intermediate_reachable net ->\n forall p h e,\n In e (log (nwState net h)) ->\n CandidateEntriesLowered_rvr net e p.\n Proof.\n intros net H.\n pattern net.\n apply lower_prop; auto.\n clear H net.\n intros.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n eapply candidate_entries_lowered_rvr';\n eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n Qed.\n\n Lemma candidate_entries_lowered_nw' :\n forall net,\n CandidateEntries net ->\n votes_correct net ->\n cronies_correct net ->\n forall h p e t li pli plt es lc,\n pBody p = AppendEntries t li pli plt es lc ->\n In p (nwPackets (deghost net)) ->\n In e es ->\n CandidateEntriesLowered (deghost net) e h.\n Proof.\n unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n intros. break_and.\n rewrite deghost_spec.\n\n find_apply_lem_hyp deghost_packet_exists.\n break_exists. break_and. subst.\n\n eapply_prop_hyp candidateEntries_nw_invariant In; eauto.\n unfold candidateEntries in *. break_exists. break_and.\n match goal with\n | H : wonElection _ = _ |- _ =>\n eapply wonElection_one_in_common in H; [|clear H; eauto]\n end.\n break_exists. break_and.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n\n intro.\n assert (h = x0).\n {\n eapply_prop one_vote_per_term;\n eapply_prop cronies_votes.\n - eapply_prop votes_received_cronies; eauto.\n - find_reverse_rewrite. auto.\n }\n subst.\n concludes. contradiction.\n Qed.\n\n Lemma candidate_entries_lowered_nw :\n forall net,\n raft_intermediate_reachable net ->\n forall h p e t li pli plt es lc,\n pBody p = AppendEntries t li pli plt es lc ->\n In p (nwPackets net) ->\n In e es ->\n CandidateEntriesLowered net e h.\n Proof.\n intros net H.\n pattern net.\n apply lower_prop; auto.\n clear H net.\n intros.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n eapply candidate_entries_lowered_nw';\n eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n Qed.\n\n Lemma candidate_entries_lowered_nw_rvr' :\n forall net,\n CandidateEntries net ->\n votes_correct net ->\n cronies_correct net ->\n forall p' p e t li pli plt es lc,\n pBody p = AppendEntries t li pli plt es lc ->\n In p (nwPackets (deghost net)) ->\n In e es ->\n CandidateEntriesLowered_rvr (deghost net) e p'.\n Proof.\n unfold CandidateEntriesLowered_rvr, CandidateEntries, votes_correct, cronies_correct.\n intros. break_and.\n rewrite deghost_spec.\n\n find_apply_lem_hyp deghost_packet_exists.\n find_apply_lem_hyp deghost_packet_exists.\n break_exists. break_and. subst.\n eapply_prop_hyp votes_nw pBody. concludes.\n eapply_prop_hyp candidateEntries_nw_invariant pBody; auto.\n\n find_insterU. conclude_using eauto.\n unfold candidateEntries in *.\n break_exists. break_and.\n\n match goal with\n | H : wonElection _ = _ |- _ =>\n eapply wonElection_one_in_common in H; [|clear H; eauto]\n end.\n break_exists. break_and.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n simpl in *.\n break_or_hyp.\n - apply_prop_hyp cronies_votes In.\n assert (pDst x = x1) by (eapply_prop one_vote_per_term; eauto).\n subst. auto.\n - intro.\n assert (pDst x = x1).\n { eapply_prop one_vote_per_term;\n eapply_prop cronies_votes.\n - eapply_prop votes_received_cronies; eauto.\n - repeat find_reverse_rewrite. auto.\n }\n subst.\n concludes. contradiction.\n Qed.\n\n\n Lemma candidate_entries_lowered_nw_rvr :\n forall net,\n raft_intermediate_reachable net ->\n forall p' p e t li pli plt es lc,\n pBody p = AppendEntries t li pli plt es lc ->\n In p (nwPackets net) ->\n In e es ->\n CandidateEntriesLowered_rvr net e p'.\n Proof.\n intros net H.\n pattern net.\n apply lower_prop; auto.\n clear H net.\n intros.\n repeat match goal with\n | [ H : _ |- _ ] => rewrite deghost_spec in H\n end.\n eapply candidate_entries_lowered_nw_rvr';\n eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n Qed.\n\n Lemma leader_sublog_request_vote_reply :\n raft_net_invariant_request_vote_reply\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_request_vote_reply.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, handleRequestVoteReply, advanceCurrentTerm.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *; intuition eauto; try discriminate.\n + exfalso. eapply candidate_entries_lowered; eauto.\n + rewrite dedup_not_in_cons in * by auto.\n exfalso. eapply candidate_entries_lowered_rvr; eauto.\n do_bool.\n find_rewrite.\n f_equal.\n omega.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *; intuition eauto;\n find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n + exfalso. eapply candidate_entries_lowered_nw; eauto.\n + rewrite dedup_not_in_cons in * by auto.\n exfalso. eapply candidate_entries_lowered_nw_rvr; eauto.\n do_bool.\n find_rewrite.\n f_equal.\n omega.\n Qed.\n\n Lemma leader_sublog_do_generic_server :\n raft_net_invariant_do_generic_server\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_do_generic_server.\n intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, doGenericServer, applyEntries in *.\n intuition idtac; simpl in *.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto; try solve_by_inversion.\n - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n subst; simpl in *;\n intuition eauto;\n find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n Qed.\n \n Lemma leader_sublog_state_same_packet_subset :\n raft_net_invariant_state_same_packet_subset\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_state_same_packet_subset.\n intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant in *. intuition idtac;\n repeat find_reverse_higher_order_rewrite; intuition eauto.\n Qed.\n\n Lemma leader_sublog_reboot :\n raft_net_invariant_reboot\n leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_reboot. intros.\n unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n leader_sublog_host_invariant, reboot in *. intuition idtac.\n - repeat find_higher_order_rewrite.\n simpl in *. repeat break_match; subst; simpl in *; intuition eauto; discriminate.\n - repeat find_higher_order_rewrite.\n simpl in *. repeat find_rewrite.\n repeat break_match; subst; simpl in *;\n intuition eauto; try discriminate.\n Qed.\n\n Theorem leader_sublog_init :\n raft_net_invariant_init leader_sublog_invariant.\n Proof.\n unfold raft_net_invariant_init, leader_sublog_invariant,\n leader_sublog_host_invariant, leader_sublog_nw_invariant;\n intuition.\n Qed.\n \n Theorem leader_sublog_invariant_invariant :\n forall net,\n raft_intermediate_reachable net ->\n leader_sublog_invariant net.\n Proof.\n intros.\n eapply raft_net_invariant; eauto.\n - apply leader_sublog_init.\n - apply leader_sublog_client_request.\n - apply leader_sublog_timeout.\n - apply leader_sublog_append_entries.\n - apply leader_sublog_append_entries_reply.\n - apply leader_sublog_request_vote.\n - apply leader_sublog_request_vote_reply.\n - apply leader_sublog_do_leader.\n - apply leader_sublog_do_generic_server.\n - apply leader_sublog_state_same_packet_subset.\n - apply leader_sublog_reboot.\n Qed.\n \nEnd LeaderSublog.\n", "meta": {"author": "andres-erbsen", "repo": "notary", "sha": "a2bd24db19a19642480fe17d3ee83e75ae8df61f", "save_path": "github-repos/coq/andres-erbsen-notary", "path": "github-repos/coq/andres-erbsen-notary/notary-a2bd24db19a19642480fe17d3ee83e75ae8df61f/raft/LeaderSublog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2751297119360208, "lm_q1q2_score": 0.14186235888134863}} {"text": "(**************************************************************************)\n(* This file is part of CertrBPF, *)\n(* a formally verified rBPF verifier + interpreter + JIT in Coq. *)\n(* *)\n(* Copyright (C) 2022 Inria *)\n(* *)\n(* This program is free software; you can redistribute it and/or modify *)\n(* it under the terms of the GNU General Public License as published by *)\n(* the Free Software Foundation; either version 2 of the License, or *)\n(* (at your option) any later version. *)\n(* *)\n(* This program is distributed in the hope that it will be useful, *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)\n(* GNU General Public License for more details. *)\n(* *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import Regs State Monad LemmaNat.\nFrom bpf.monadicmodel Require Import Opcode rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n(**\nCheck get_opcode_mem_st_reg\nget_opcode_mem_st_reg\n : nat -> M opcode_mem_st_reg\n\n*)\n\nOpen Scope nat_scope.\n\nSection Get_opcode_mem_st_reg.\n Context {S: special_blocks}.\n (** The program contains our function of interest [fn] *)\n Definition p : Clight.program := prog.\n\n (* [Args,Res] provides the mapping between the Coq and the C types *)\n (* Definition Args : list CompilableType := [stateCompilableType].*)\n Definition args : list Type := [(nat:Type)].\n Definition res : Type := (opcode_mem_st_reg:Type).\n\n (* [f] is a Coq Monadic function with the right type *)\n Definition f : arrow_type args (M State.state res) := get_opcode_mem_st_reg.\n\n (* [fn] is the Cligth function which has the same behaviour as [f] *)\n Definition fn: Clight.function := f_get_opcode_mem_st_reg.\n\n (* [match_arg] relates the Coq arguments and the C arguments *)\n Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n (dcons (fun x => StateLess _ (opcode_correct x))\n (DList.DNil _)).\n\n (* [match_res] relates the Coq result and the C result *)\n Definition match_res : res -> Inv State.state := fun x => StateLess _ (opcode_mem_st_reg_correct x).\n\n Instance correct_function_get_opcode_mem_st_reg : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n Proof.\n correct_function_from_body args.\n correct_body.\n (** how to use correct_* *)\n unfold INV.\n unfold f.\n repeat intro.\n get_invariant _op.\n\n unfold stateless, opcode_correct in c0.\n destruct c0 as (Hc_eq & Hc_range).\n subst.\n\n eexists. exists m, Events.E0.\n unfold byte_to_opcode_mem_st_reg.\n split_and; unfold step2;auto.\n -\n forward_star.\n simpl.\n rewrite Int.zero_ext_idem; [| lia].\n rewrite Int.zero_ext_and; [| lia].\n change (two_p 8 - 1)%Z with 255%Z.\n rewrite Int.and_assoc.\n rewrite Int.and_idem.\n forward_star.\n -\n unfold match_res, opcode_mem_st_reg_correct.\n rewrite Nat_land_0xff; auto.\n destruct (c =? 99) eqn: Hstxw;\n [rewrite Nat.eqb_eq in Hstxw; subst; reflexivity | rewrite Nat.eqb_neq in Hstxw].\n destruct (c =? 107) eqn: Hstxh;\n [rewrite Nat.eqb_eq in Hstxh; subst; reflexivity | rewrite Nat.eqb_neq in Hstxh].\n destruct (c =? 115) eqn: Hstxb;\n [rewrite Nat.eqb_eq in Hstxb; subst; reflexivity | rewrite Nat.eqb_neq in Hstxb].\n destruct (c =? 123) eqn: Hstxdw;\n [rewrite Nat.eqb_eq in Hstxdw; subst; reflexivity | rewrite Nat.eqb_neq in Hstxdw].\n\n assert (Hswitch:\n match c with\n | 99 => op_BPF_STXW\n | 107 => op_BPF_STXH\n | 115 => op_BPF_STXB\n | 123 => op_BPF_STXDW\n | _ => op_BPF_STX_ILLEGAL_INS\n end = op_BPF_STX_ILLEGAL_INS). {\n do 99 (destruct c; [reflexivity |]).\n destruct c; [exfalso; apply Hstxw; reflexivity | ].\n do 7 (destruct c; [reflexivity |]).\n destruct c; [exfalso; apply Hstxh; reflexivity | ].\n do 7 (destruct c; [reflexivity |]).\n destruct c; [exfalso; apply Hstxb; reflexivity | ].\n do 7 (destruct c; [reflexivity |]).\n destruct c; [exfalso; apply Hstxdw; reflexivity | reflexivity].\n }\n rewrite Hswitch; clear Hswitch.\n exists c.\n split; [ | intuition ].\n unfold Int.and.\n change (Int.unsigned (Int.repr 255)) with (Z.of_nat (Z.to_nat 255%Z)).\n rewrite Int.unsigned_repr; [| change Int.max_unsigned with 4294967295%Z; lia].\n rewrite LemmaNat.land_land.\n change (Z.to_nat 255) with 255.\n rewrite Nat_land_0xff; auto.\n - constructor.\n simpl.\n rewrite Int.zero_ext_and.\n change (two_p 8 - 1)%Z with 255%Z.\n rewrite Int.and_assoc.\n rewrite Int.and_idem.\n reflexivity.\n lia.\n - apply unmodifies_effect_refl.\n Qed.\n\nEnd Get_opcode_mem_st_reg.\n\nClose Scope nat_scope.\n\nExisting Instance correct_function_get_opcode_mem_st_reg.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_opcode_mem_st_reg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.14180201896822847}} {"text": "Require Import RelationClasses.\nRequire Import List.\nRequire Import Omega.\nRequire Import sflib.\nFrom Paco Require Import paco.\nRequire Import Basics.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import Iteration.\n\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\nRequire Import Kildall.\nRequire Import Coqlib.\n\nRequire Import Integers.\nRequire Import LibTactics.\nRequire Import CorrectOpt.\nRequire Import CSE.\nRequire Import DetLoop.\nRequire Import LICM.\nRequire Import Lib_Ordering.\n\nRequire Import Language.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import MsgMapping.\nRequire Import LocalSim.\n\nRequire Import ConsistentStableEnv.\n\nSet Implicit Arguments.\n\n(** * Match state for loop invariant code motion proof *)\n\n(** ** Invariant for shared state *) \nDefinition I_linv (lo: Ordering.LocOrdMap) (inj: Mapping) (rss: Rss) : Prop :=\n match rss with\n | Build_Rss sc_tgt mem_tgt sc_src mem_src =>\n <> /\\\n <> /\\\n <> \n end.\n\n(** ** Well-defined pre-header *)\n(** A pre-header block is well-defined, if:\n - all registers in the pre-header have not used in the source code;\n - all locations in the pre-header are non-atomic location. *) \nFixpoint wdph (BB: BBlock.t) (l_entry: positive) (cdhp_s: CodeHeap) (lo: Ordering.LocOrdMap) :=\n match BB with\n | (Inst.assign r e) ## BB' =>\n (~ (RegSet.In r (regs_of_cdhp cdhp_s))) /\\ wdph BB' l_entry cdhp_s lo\n | (Inst.load r loc Ordering.plain) ## BB' =>\n (~ (RegSet.In r (regs_of_cdhp cdhp_s))) /\\ lo loc = Ordering.nonatomic /\\ wdph BB' l_entry cdhp_s lo\n | BBlock.jmp l =>\n if Pos.eq_dec l l_entry then True else False\n | _ => False\n end.\n\nInductive ptB_ph_rel: BBlock.t -> BBlock.t -> (PTree.t positive) -> Prop :=\n| ptB_ph_rel_inst\n c BB_t BB_s preheader\n (PT_CONT: ptB_ph_rel BB_t BB_s preheader):\n ptB_ph_rel (c ## BB_t) (c ## BB_s) preheader\n| ptB_ph_rel_jmp\n l_s l_t preheader\n (PT: PTree.get l_s preheader = Some l_t):\n ptB_ph_rel (BBlock.jmp l_t) (BBlock.jmp l_s) preheader\n| ptB_ph_rel_be1\n l_s l_t l preheader e\n (PT: PTree.get l_s preheader = Some l_t):\n ptB_ph_rel (BBlock.be e l_t l) (BBlock.be e l_s l) preheader\n| ptB_ph_rel_be2\n l l_s l_t preheader e\n (PT: PTree.get l_s preheader = Some l_t):\n ptB_ph_rel (BBlock.be e l l_t) (BBlock.be e l l_s) preheader\n| ptB_ph_rel_be3\n l_s l_t l_s' l_t' preheader e\n (PT1: PTree.get l_s preheader = Some l_t)\n (PT2: PTree.get l_s' preheader = Some l_t'):\n ptB_ph_rel (BBlock.be e l_t l_t') (BBlock.be e l_s l_s') preheader.\n\n(** ** Match state for the thread-local state *)\nInductive match_local\n (loop_P: PTree.t (list (positive * positive * list LOOP_INV))) (lo: Ordering.LocOrdMap):\n (RegFile.t * BBlock.t * CodeHeap * Code) ->\n (RegFile.t * BBlock.t * CodeHeap * Code) -> Prop :=\n| EXEC_NOT_PH\n (cdhp_s cdhp_t: CodeHeap)\n loopinvs preheader R_s R_t BB_s BB_t prog_s prog_t max_p max_p' f ep\n (TRANSC: TransC' cdhp_s (PTree.empty positive) loopinvs loopinvs max_p = (cdhp_t, max_p', preheader))\n (MAX_P_WF: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive)\n (LOOP_INVS: loop_P ! f = Some loopinvs)\n (CDHP_S: prog_s ! f = Some (cdhp_s, ep))\n (ORIGN_REGS: forall r, RegSet.In r (regs_of_cdhp cdhp_s) -> RegFun.find r R_t = RegFun.find r R_s)\n (SUBSET_REG: forall r, RegSet.In r (BBlock.regs_of_blk BB_s) -> RegSet.In r (regs_of_cdhp cdhp_s))\n (BLK_REL: BB_t = BB_s \\/ ptB_ph_rel BB_t BB_s preheader):\n match_local loop_P lo\n (R_t, BB_t, cdhp_t, prog_t) (R_s, BB_s, cdhp_s, prog_s)\n| EXEC_PH\n (cdhp_s cdhp_t: CodeHeap)\n loopinvs preheader R_s R_t BB_s BB_t prog_s prog_t max_p max_p' f l_entry ep\n (TRANSC: TransC' cdhp_s (PTree.empty positive) loopinvs loopinvs max_p = (cdhp_t, max_p', preheader))\n (MAX_P_WF: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive)\n (LOOP_INVS: loop_P ! f = Some loopinvs)\n (CDHP_S: prog_s ! f = Some (cdhp_s, ep))\n (ORIGN_REGS: forall r, RegSet.In r (regs_of_cdhp cdhp_s) -> RegFun.find r R_t = RegFun.find r R_s)\n (WDPH: wdph BB_t l_entry cdhp_s lo)\n (BLK_REL: cdhp_s ! l_entry = Some BB_s):\n match_local loop_P lo\n (R_t, BB_t, cdhp_t, prog_t) (R_s, BB_s, cdhp_s, prog_s). \n\nInductive match_cont\n (loop_P: PTree.t (list (positive * positive * list LOOP_INV))) (lo: Ordering.LocOrdMap):\n (Continuation.t * Code) -> (Continuation.t * Code) -> Prop :=\n| cont_done\n prog_t prog_s:\n match_cont loop_P lo (Continuation.done, prog_t) (Continuation.done, prog_s)\n| cont_stack\n R_t BB_t cdhp_t cont_t prog_t R_s BB_s cdhp_s cont_s prog_s\n (MATCH_CUR: match_local loop_P lo (R_t, BB_t, cdhp_t, prog_t) (R_s, BB_s, cdhp_s, prog_s))\n (MATCH_CONT: match_cont loop_P lo (cont_t, prog_t) (cont_s, prog_s)):\n match_cont loop_P lo\n (Continuation.stack R_t BB_t cdhp_t cont_t, prog_t)\n (Continuation.stack R_s BB_s cdhp_s cont_s, prog_s). \n\nInductive match_tlocal (lo: Ordering.LocOrdMap): State.t -> State.t -> Prop :=\n| match_tlocal_intro\n R_t BB_t cdhp_t cont_t prog_t R_s BB_s cdhp_s cont_s prog_s loop_P\n (OPT: LInv lo prog_s = Some prog_t)\n (DET_LOOP_INV: det_loop_invs prog_s lo = loop_P)\n (MATCH_CUR: match_local loop_P lo\n (R_t, BB_t, cdhp_t, prog_t) (R_s, BB_s, cdhp_s, prog_s))\n (MATCH_CONT: match_cont loop_P lo (cont_t, prog_t) (cont_s, prog_s)):\n match_tlocal lo\n (State.mk R_t BB_t cdhp_t cont_t prog_t)\n (State.mk R_s BB_s cdhp_s cont_s prog_s). \n\n(** Match state for the thread state *)\nInductive match_state_linv:\n Mapping -> Ordering.LocOrdMap -> bool ->\n Thread.t rtl_lang -> Thread.t rtl_lang -> Prop :=\n| match_state_linv_intro\n inj inj' lo b\n state_tgt tview_tgt prm_tgt sc_tgt mem_tgt\n state_src tview_src prm_src sc_src mem_src\n (INV: I_linv lo inj' (Build_Rss sc_tgt mem_tgt sc_src mem_src))\n (MATCH_THRD_LOCAL: match_tlocal lo state_tgt state_src)\n (TVIEW_LE: TView.le tview_src tview_tgt)\n (PRM_EQ: prm_src = prm_tgt)\n (PRM_INDOM: forall loc to from val R,\n Memory.get loc to prm_tgt = Some (from, Message.concrete val R) ->\n exists to', inj loc to = Some to')\n (ATM_BIT: (b = false /\\ (forall loc t t', inj loc t = Some t' -> inj' loc t = Some t')) \\/\n (b = true /\\ inj = inj'))\n (* wf local, closed sc, closed memory *)\n (LOCAL_WF_TGT: Local.wf (Local.mk tview_tgt prm_tgt) mem_tgt)\n (CLOSED_SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n (MEM_CLOSED_TGT: Memory.closed mem_tgt)\n (LOCAL_WF_SRC: Local.wf (Local.mk tview_src prm_src) mem_src)\n (CLOSED_SC_SRC: Memory.closed_timemap sc_src mem_src)\n (MEM_CLOSED_SRC: Memory.closed mem_src):\n match_state_linv inj lo b\n (Thread.mk rtl_lang state_tgt (Local.mk tview_tgt prm_tgt) sc_tgt mem_tgt)\n (Thread.mk rtl_lang state_src (Local.mk tview_src prm_src) sc_src mem_src).\n\nFixpoint wdph_aux (BB_t: BBlock.t) (f_entry: positive)\n (loop_invs: list (positive * positive * list LOOP_INV)) : Prop :=\n match BB_t with\n | Inst.assign r e ## BB_t' =>\n (exists l1 l2 loopinvs, In (l1, l2, loopinvs) loop_invs /\\ In (LINV_EXPR r e) loopinvs) /\\\n wdph_aux BB_t' f_entry loop_invs\n | Inst.load r loc Ordering.plain ## BB_t' =>\n (exists l1 l2 loopinvs, In (l1, l2, loopinvs) loop_invs /\\ In (LINV_LOC r loc) loopinvs) /\\\n wdph_aux BB_t' f_entry loop_invs\n | BBlock.jmp f => if Pos.eq_dec f f_entry then True else False\n | _ => False\n end.\n\nLemma wdph_aux_cons'\n linv loopinvs l_entry l1 l2 loop_invs BB loopinvs0\n (WDPH: wdph_aux BB l_entry loop_invs)\n (IN: In (l1, l2, loopinvs0 ++ linv :: loopinvs) loop_invs):\n wdph_aux (alloc_inst linv ## BB) l_entry loop_invs.\nProof.\n destruct linv; ss; splits; eauto.\n exists l1 l2 (loopinvs0 ++ LINV_EXPR r e :: loopinvs).\n split; eauto. eapply in_app. right. ss. eauto.\n exists l1 l2 (loopinvs0 ++ LINV_LOC r loc :: loopinvs).\n split; eauto. eapply in_app. right. ss. eauto.\nQed.\n\nLemma wdph_aux_cons:\n forall loopinvs l_entry loop_invs BB loopinvs0 l1 l2\n (WDPH: wdph_aux BB l_entry loop_invs)\n (IN: In (l1, l2, loopinvs0 ++ loopinvs) loop_invs),\n wdph_aux (consInv loopinvs BB) l_entry loop_invs.\nProof.\n induction loopinvs; ii; ss; eauto.\n eapply IHloopinvs; eauto.\n 2: { instantiate (1 := loopinvs0 ++ (a :: nil)). rewrite <- app_assoc. ss. eauto. }\n eapply wdph_aux_cons' in IN; eauto.\nQed.\n\nLemma wdph_aux_diff:\n forall BB l loop_invs l1 l2\n (WDPH_AUX: wdph_aux BB l loop_invs)\n (DISJ: l2 <> l),\n wdph_aux (ptB_ph l1 l2 BB) l loop_invs.\nProof.\n induction BB; ii; ss; eauto.\n - des_ifH WDPH_AUX; tryfalse; ss; eauto. subst.\n unfold pt_modify. des_if; eauto.\n des_ifH n; ss; eauto.\n - destruct c; ss; eauto.\n + des. split; eauto.\n + destruct or; ss.\n des. split; eauto.\nQed.\n\nLemma wdph_aux_alloc:\n forall loopinvs l1 l2 loop_invs loopinvs0\n (IN: In (l1, l2, loopinvs0 ++ loopinvs) loop_invs),\n wdph_aux (alloc_ph loopinvs l1) l1 loop_invs.\nProof.\n induction loopinvs; ii; ss; eauto.\n - des_if; eauto.\n - destruct a; ss; eauto.\n + split.\n exists l1 l2 (loopinvs0 ++ LINV_EXPR r e :: loopinvs). split; eauto.\n eapply in_or_app. right; ss. eauto.\n eapply IHloopinvs; eauto.\n instantiate (2 := l2).\n instantiate (1 := (loopinvs0 ++ (LINV_EXPR r e) :: nil)).\n rewrite <- app_assoc. eauto.\n + split.\n exists l1 l2 (loopinvs0 ++ LINV_LOC r loc :: loopinvs). split; eauto.\n eapply in_or_app. right; ss. eauto.\n eapply IHloopinvs; eauto.\n instantiate (2 := l2).\n instantiate (1 := (loopinvs0 ++ (LINV_LOC r loc) :: nil)).\n rewrite <- app_assoc. eauto.\nQed.\n\nLemma ptB_ph_rel_cons:\n forall BB preheader l_ph l_entry\n (PREHEADER: preheader ! l_entry = Some l_ph),\n (ptB_ph_rel (ptB_ph l_ph l_entry BB) BB preheader) \\/\n BB = (ptB_ph l_ph l_entry BB).\nProof.\n induction BB; ii; ss; eauto; try solve [econs; eauto].\n - unfold pt_modify. des_if; subst; eauto.\n left. econs; eauto.\n - unfold pt_modify.\n des_if; subst; eauto.\n des_if; subst; eauto.\n left. econs; eauto.\n left. econs; eauto.\n des_if; subst; eauto.\n left. econs; eauto.\n - exploit IHBB; eauto. i.\n des1.\n left. econs; eauto.\n right. rewrite <- H. eauto.\nQed.\n\nLemma ptB_ph_rel_cons2:\n forall BB_t l_ph l_entry BB_s preheader\n (ENTRY_NOT_PH: (l_entry < l_ph)%positive)\n (PTB_PH_REL: ptB_ph_rel BB_t (ptB_ph l_ph l_entry BB_s) preheader)\n (PREHEADER: preheader ! l_entry = Some l_ph)\n (PREHEADER2: preheader ! l_ph = None),\n BB_t = BB_s \\/ ptB_ph_rel BB_t BB_s preheader.\nProof.\n induction BB_t; ii; eauto.\n - destruct BB_s; ss; eauto;\n try solve [inv PTB_PH_REL; ss].\n unfold pt_modify in *. des_ifH PTB_PH_REL; ss; subst; eauto.\n inv PTB_PH_REL.\n unfold Language.fid, IdentMap.key in *. tryfalse.\n - destruct BB_s; ss; eauto; try solve [inv PTB_PH_REL; ss].\n - destruct BB_s; ss; eauto; try solve [inv PTB_PH_REL; ss].\n unfold pt_modify in *.\n des_ifH PTB_PH_REL; subst; ss; eauto.\n {\n des_ifH PTB_PH_REL; subst; ss; eauto.\n inv PTB_PH_REL;\n try solve [unfold Language.fid, IdentMap.key in *; ss; tryfalse].\n inv PTB_PH_REL;\n try solve [unfold Language.fid, IdentMap.key in *; ss; tryfalse].\n right. econs; eauto.\n }\n {\n des_ifH PTB_PH_REL; subst; ss; eauto.\n inv PTB_PH_REL;\n try solve [unfold Language.fid, IdentMap.key in *; ss; tryfalse].\n right. econs; eauto.\n }\n - inv PTB_PH_REL.\n - destruct BB_s; ss; eauto;\n try solve [inv PTB_PH_REL; ss].\n inv PTB_PH_REL.\n eapply IHBB_t in PT_CONT; eauto.\n des; subst; eauto.\n right. econs; eauto.\nQed.\n\nLemma well_defined_preheader_I':\n forall loop_invs0 cdhp_s cdhp_t BB_s preheader l_s l0\n max_p max_p' preheader0 loop_invs\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (BLK: cdhp_s ! l_s = Some BB_s)\n (PRE_HEADER0: preheader0 ! l0 = Some l_s)\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive)\n (WF_PH: forall l l', preheader0 ! l = Some l' -> exists BB, cdhp_s ! l' = Some BB)\n (IN: forall linv, In linv loop_invs0 -> In linv loop_invs)\n (WDPH: wdph_aux BB_s l0 loop_invs),\n exists BB_t, preheader ! l0 = Some l_s /\\ cdhp_t ! l_s = Some BB_t /\\\n wdph_aux BB_t l0 loop_invs.\nProof.\n induction loop_invs0; ii; ss; eauto.\n - inv TRANS. exists BB_s. splits; eauto.\n - destruct a. destruct p.\n destruct (preheader0 ! p) eqn:Heqe; ss.\n {\n (* the preheader of p has already been allocated *)\n exploit WF_PH; [eapply Heqe | eauto..]. i. des1.\n rewrite H in TRANS. \n destruct (Pos.eq_dec p l0); subst; eauto.\n {\n rewrite Heqe in PRE_HEADER0. inv PRE_HEADER0.\n rewrite BLK in H. inv H.\n eapply IHloop_invs0 with (BB_s := consInv l BB) in TRANS; eauto.\n {\n rewrite PTree.gss; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec l_s l1); subst; eauto.\n rewrite PTree.gso in H; eauto.\n }\n {\n ii. eapply WF_PH in H. des1.\n destruct (Pos.eq_dec l_s l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n exploit IN; eauto. ii. \n eapply wdph_aux_cons; eauto.\n instantiate (2 := p0). instantiate (1 := nil). ss. eauto.\n }\n }\n {\n destruct (Pos.eq_dec p1 l_s); subst; eauto.\n {\n rewrite BLK in H. inv H.\n eapply IHloop_invs0 with (BB_s := consInv l BB) in TRANS; eauto.\n {\n rewrite PTree.gss; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec l_s l1); subst; eauto.\n rewrite PTree.gso in H; eauto.\n }\n {\n ii. eapply WF_PH in H. des1.\n destruct (Pos.eq_dec l_s l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n { \n exploit IN; eauto. ii. \n eapply wdph_aux_cons; eauto.\n instantiate (2 := p0). instantiate (1 := nil). ss. eauto.\n }\n }\n {\n eapply IHloop_invs0 in TRANS; eauto.\n {\n rewrite PTree.gso; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec p1 l1); subst.\n rewrite PTree.gss in H0. inv H0. eauto.\n rewrite PTree.gso in H0; eauto.\n }\n {\n ii.\n eapply WF_PH in H0. des1.\n destruct (Pos.eq_dec p1 l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n }\n }\n }\n {\n (* the preheader of p has not been allocated *)\n eapply IHloop_invs0 with\n (BB_s := if is_exit l_s loop_invs then BB_s else ptB_ph max_p p BB_s) in TRANS; eauto.\n {\n destruct (Pos.eq_dec max_p l_s); subst; eauto.\n eapply WF_MAX_P in BLK; eauto.\n eapply Pos.lt_irrefl in BLK. ss.\n rewrite PTree.gso; eauto.\n unfold ptC_ph. rewrite PTree.gmap. unfold option_map. rewrite BLK. eauto.\n }\n {\n destruct (Pos.eq_dec p l0); subst; eauto; tryfalse.\n rewrite PTree.gso; eauto.\n }\n {\n ii. destruct (Pos.eq_dec max_p l1); subst.\n eapply Pos.lt_succ_diag_r; eauto.\n rewrite PTree.gso in H; eauto.\n eapply ptC_ph_dom_eq in H. do 2 des1.\n eapply WF_MAX_P in H.\n assert ((max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\n {\n ii. \n destruct (Pos.eq_dec p l1); subst.\n {\n rewrite PTree.gss in H. inv H.\n rewrite PTree.gss; eauto.\n }\n {\n rewrite PTree.gso in H; eauto.\n destruct (Pos.eq_dec max_p l'); subst; eauto.\n eapply WF_PH in H. des1. eapply WF_MAX_P in H.\n eapply POrderedType.Positive_as_OT.lt_irrefl in H. ss.\n rewrite PTree.gso; eauto.\n eapply WF_PH in H. des1.\n eapply ptC_ph_dom_eq2 in H; eauto. do 2 des1.\n rewrite H. eauto.\n }\n }\n {\n destruct (Pos.eq_dec p l0); subst. tryfalse.\n des_if; eauto.\n eapply wdph_aux_diff; eauto.\n }\n }\nQed.\n\nLemma well_defined_preheader_I'':\n forall loop_invs0 cdhp_s cdhp_t BB_t preheader l_s l_t\n max_p max_p' preheader0 loop_invs\n (PRE_HEADER: preheader ! l_s = Some l_t)\n (BLK: PTree.get l_t cdhp_t = Some BB_t)\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive)\n (WF_PH: forall l l', preheader0 ! l = Some l' -> exists BB, cdhp_s ! l' = Some BB)\n (IN: forall linv, In linv loop_invs0 -> In linv loop_invs)\n (WF_PH0: preheader0 ! l_s = None),\n (exists loopinvs l_s', In (l_s, l_s', loopinvs) loop_invs) /\\ wdph_aux BB_t l_s loop_invs /\\ (max_p <= l_t)%positive.\nProof.\n induction loop_invs0; ii; ss; eauto.\n - inv TRANS. tryfalse.\n - destruct a. destruct p.\n destruct (preheader0 ! p) eqn:Heqe1; ss.\n {\n (* the preheader of p has already been allocated *)\n exploit WF_PH; eauto. i. des1. rewrite H in TRANS; ss. clear H.\n eapply IHloop_invs0 in TRANS; eauto.\n\n ii. exploit WF_PH; eauto. i. des1. exploit WF_MAX_P; eauto. i.\n destruct (Pos.eq_dec p1 l0); subst; eauto.\n rewrite PTree.gso in H; eauto.\n\n ii.\n destruct (Pos.eq_dec p1 l'); subst; eauto.\n rewrite PTree.gss. eauto.\n rewrite PTree.gso; eauto.\n }\n {\n (* the preheader of p has not been allocated *)\n destruct (Pos.eq_dec p l_s); subst.\n {\n exploit well_defined_preheader_I'; eauto.\n {\n instantiate (2 := max_p). rewrite PTree.gss. eauto.\n }\n {\n instantiate (1 := l_s). rewrite PTree.gss; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec max_p l0); subst; eauto.\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n {\n rewrite PTree.gso in H; eauto.\n eapply ptC_ph_dom_eq in H. do 2 des1.\n eapply WF_MAX_P in H.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\n }\n {\n ii.\n destruct (Pos.eq_dec l_s l0); subst.\n {\n rewrite PTree.gss in H. inv H.\n rewrite PTree.gss; eauto.\n }\n {\n rewrite PTree.gso in H; eauto.\n destruct (Pos.eq_dec max_p l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply WF_PH in H. des1.\n eapply ptC_ph_dom_eq2 in H; eauto. do 2 des1.\n rewrite H; eauto.\n }\n }\n {\n exploit IN; eauto. ii.\n eapply wdph_aux_alloc; eauto.\n instantiate (2 := p0). instantiate (1 := nil). ss.\n }\n {\n ii. des. rewrite PRE_HEADER in H. inv H.\n rewrite BLK in H0. inv H0. splits; eauto.\n eapply Pos.le_refl; eauto.\n }\n }\n {\n eapply IHloop_invs0 in TRANS; eauto.\n {\n des. splits; eauto.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_le_incl; eauto.\n eapply Pos.lt_le_trans; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec max_p l0); subst; eauto.\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n {\n rewrite PTree.gso in H; eauto. \n eapply ptC_ph_dom_eq in H; eauto. do 2 des1.\n exploit WF_MAX_P; eauto. ii.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\n }\n {\n ii.\n destruct (Pos.eq_dec p l0); subst; eauto.\n {\n rewrite PTree.gss in H. inv H. rewrite PTree.gss. eauto.\n }\n {\n rewrite PTree.gso in H; eauto.\n exploit WF_PH; eauto. i. des1.\n exploit WF_MAX_P; eauto. i.\n destruct (Pos.eq_dec max_p l'); subst; tryfalse. eapply Pos.lt_irrefl in H1; ss.\n rewrite PTree.gso; eauto.\n eapply ptC_ph_dom_eq2 in H0; eauto. do 2 des1.\n rewrite H0. eauto.\n }\n }\n {\n rewrite PTree.gso; eauto.\n }\n }\n }\nQed.\n \nLemma well_defined_preheader_I\n loop_invs cdhp_s cdhp_t BB_t preheader l_s l_t\n max_p max_p'\n (PRE_HEADER: preheader ! l_s = Some l_t)\n (BLK: PTree.get l_t cdhp_t = Some BB_t)\n (TRANS: TransC' cdhp_s (PTree.empty positive) loop_invs loop_invs max_p = (cdhp_t, max_p', preheader))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive):\n (exists loopinvs l_s', In (l_s, l_s', loopinvs) loop_invs) /\\ wdph_aux BB_t l_s loop_invs /\\ (max_p <= l_t)%positive.\nProof.\n eapply well_defined_preheader_I''; eauto.\n ii. rewrite PTree.gempty in H. ss.\n rewrite PTree.gempty; eauto.\nQed.\n\nLemma wdph_aux_to_wdph:\n forall BB l cdhp lo ep\n (WDPH_AUX: wdph_aux BB l (loop_invC lo (cdhp, ep))),\n wdph BB l cdhp lo.\nProof.\n induction BB; ii; eauto.\n ss. destruct c; ss. des.\n eapply wf_loop_invC2 in WDPH_AUX; eauto.\n destruct or; ss.\n des.\n lets WDPH_AUX': WDPH_AUX.\n eapply wf_loop_invC2 in WDPH_AUX; eauto.\n eapply wf_loop_invC3 in WDPH_AUX'; eauto.\nQed.\n\nLemma well_defined_preheader\n loop_invs cdhp_s cdhp_t BB_t preheader l_s l_t max_p max_p' ep lo\n (PRE_HEADER: preheader ! l_s = Some l_t)\n (BLK: cdhp_t ! l_t = Some BB_t)\n (LOOP_INVS: loop_invs = loop_invC lo (cdhp_s, ep))\n (TRANS: TransC' cdhp_s (PTree.empty positive) loop_invs loop_invs max_p = (cdhp_t, max_p', preheader))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive):\n exists BB_s, cdhp_s ! l_s = Some BB_s /\\ cdhp_s ! l_t = None /\\ wdph BB_t l_s cdhp_s lo.\nProof.\n exploit well_defined_preheader_I; eauto. i. des. subst.\n exploit wf_loop_invC1; eauto. i. des.\n exists BB0. splits; eauto.\n destruct (cdhp_s ! l_t) eqn:Heqe; eauto.\n eapply WF_MAX_P in Heqe.\n exploit Pos.lt_le_trans; eauto. i. eapply Pos.lt_irrefl in H2. ss.\n eapply wdph_aux_to_wdph; eauto.\nQed.\n\nLemma well_defined_preheader2''':\n forall loop_invs0 loop_invs cdhp_s cdhp_t preheader0 preheader max_p max_p' l\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (WF_PH: forall l l', preheader0 ! l = Some l' -> exists BB, cdhp_s ! l' = Some BB)\n (IN: forall l_entry l_exit linvs, In (l_entry, l_exit, linvs) loop_invs0 ->\n (In (l_entry, l_exit, linvs) loop_invs /\\ (l_entry < max_p)%positive))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive)\n (PREHEADER: preheader0 ! l = None),\n (preheader ! l = None) \\/ (exists l_exit linvs, In (l, l_exit, linvs) loop_invs0).\nProof.\n induction loop_invs0; ii; ss; eauto.\n - inv TRANS. eauto.\n - destruct a. destruct p.\n destruct (preheader0 ! p) eqn:PREHEADER0; ss.\n {\n (* the preheader of p has already been allocated *)\n exploit WF_PH; eauto. i. des1. rewrite H in TRANS; ss; clear H.\n eapply IHloop_invs0 in TRANS; eauto.\n {\n des; eauto. \n }\n {\n ii. destruct (Pos.eq_dec p1 l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n ii. destruct (Pos.eq_dec p1 l1); subst; eauto.\n eapply WF_PH in PREHEADER0; eauto. des1.\n eapply WF_MAX_P in PREHEADER0; eauto.\n rewrite PTree.gso in H; ss; eauto.\n }\n }\n {\n (* the preheader of p has not been allocated *)\n destruct (Pos.eq_dec p l); subst; eauto.\n \n eapply IHloop_invs0 with (l := l) in TRANS; eauto.\n {\n des1; eauto.\n des. eauto.\n }\n {\n ii. destruct (Pos.eq_dec p l1); subst.\n rewrite PTree.gss in H. inv H. rewrite PTree.gss; eauto.\n rewrite PTree.gso in H; eauto.\n destruct (Pos.eq_dec max_p l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply WF_PH in H. des1.\n eapply ptC_ph_dom_eq2 in H; eauto. do 2 des1.\n rewrite H; eauto.\n }\n {\n ii; eauto. exploit IN; eauto. i. des1.\n split; eauto.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\n {\n ii. destruct (Pos.eq_dec max_p l1); subst; eauto.\n eapply Pos.lt_succ_diag_r; eauto.\n rewrite PTree.gso in H; eauto.\n eapply ptC_ph_dom_eq in H; eauto. do 2 des1.\n eapply WF_MAX_P in H.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\n {\n rewrite PTree.gso; eauto.\n }\n }\nQed.\n\nLemma well_defined_preheader2'':\n forall loop_invs0 loop_invs cdhp_s cdhp_t preheader0 preheader max_p max_p' l l'\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (PRE_HEADER: preheader0 ! l = Some l'),\n preheader ! l = Some l'.\nProof.\n induction loop_invs0; ss; eauto; ii.\n inv TRANS; eauto.\n destruct a. destruct p.\n destruct (preheader0 ! p) eqn:Heqe; eauto.\n {\n destruct (cdhp_s ! p1) eqn:Heqe1; ss; eauto.\n }\n {\n eapply IHloop_invs0 in TRANS; eauto.\n destruct (Pos.eq_dec p l); subst; tryfalse.\n rewrite PTree.gso; eauto.\n }\nQed.\n\nLemma well_defined_preheader2':\n forall loop_invs0 loop_invs cdhp_s cdhp_t BB_t l preheader0 preheader max_p max_p'\n (BLK: cdhp_t ! l = Some BB_t)\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (WF_PH: forall l l', preheader0 ! l = Some l' -> (exists BB, cdhp_s ! l' = Some BB))\n (WF_PH1: forall l l', preheader0 ! l = Some l' -> (exists BB, cdhp_s ! l = Some BB))\n (IN: forall l_entry l_exit linvs, In (l_entry, l_exit, linvs) loop_invs0 ->\n (In (l_entry, l_exit, linvs) loop_invs /\\ (exists BB, cdhp_s ! l_entry = Some BB)))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive),\n (exists l0, preheader ! l0 = Some l) \\/ \n (exists BB_s, cdhp_s ! l = Some BB_s /\\ (BB_t = BB_s \\/ ptB_ph_rel BB_t BB_s preheader)).\nProof.\n induction loop_invs0; ii; ss.\n - inv TRANS. right. exists BB_t. split; eauto.\n - destruct a. destruct p. \n destruct (preheader0 ! p) eqn:PRE_HEADER_p.\n {\n (* the preheader of p has already been allocated *)\n exploit WF_PH; eauto. i. des. rewrite H in TRANS.\n exploit IHloop_invs0; [ | eapply TRANS | eauto..]; eauto.\n {\n ii.\n destruct (Pos.eq_dec p1 l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n ii.\n destruct (Pos.eq_dec p1 l1); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n ii. exploit IN; eauto. i. des.\n split; eauto.\n destruct (Pos.eq_dec p1 l_entry); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n ii. destruct (Pos.eq_dec p1 l1); subst; eauto.\n rewrite PTree.gso in H0; eauto.\n }\n\n i. do 2 des1. eauto.\n des1.\n destruct (Pos.eq_dec p1 l); subst; eauto.\n {\n eapply well_defined_preheader2'' with (l := p) in TRANS; eauto.\n }\n {\n rewrite PTree.gso in H0; eauto.\n }\n }\n {\n (* the preheader of p has not been allocated *)\n lets PRE_HEADER': TRANS.\n lets TEMP: TRANS.\n eapply well_defined_preheader2'' with (l := p) (l' := max_p) in PRE_HEADER'; eauto.\n 2: { rewrite PTree.gss; eauto. }\n assert (P_LT_MAX_P: (p < max_p)%positive).\n {\n exploit IN; eauto. i. des.\n exploit WF_MAX_P; eauto.\n }\n \n destruct (Pos.eq_dec max_p l); subst; eauto.\n eapply IHloop_invs0 in TRANS; eauto.\n {\n des1. des1. eauto.\n do 2 des1.\n rewrite PTree.gso in TRANS; eauto. unfold ptC_ph in TRANS.\n rewrite PTree.gmap in TRANS.\n unfold option_map in TRANS.\n destruct (cdhp_s ! l) eqn:Heqe; eauto.\n des_ifH TRANS.\n inv TRANS; eauto.\n inv TRANS. des1; subst; eauto.\n {\n right. exists t. split; eauto.\n eapply ptB_ph_rel_cons with (BB := t) in PRE_HEADER'.\n des; subst; eauto.\n }\n {\n destruct (preheader0 ! max_p) eqn:PRE_HEADER0; ss.\n eapply WF_PH1 in PRE_HEADER0. des1.\n eapply WF_MAX_P in PRE_HEADER0. eapply Pos.lt_irrefl in PRE_HEADER0. ss.\n exploit ptB_ph_rel_cons2; eauto.\n eapply well_defined_preheader2''' with (l := max_p) in TEMP; eauto.\n {\n des1; eauto.\n do 2 des1. exploit IN; eauto. i. do 2 des1.\n eapply WF_MAX_P in H0.\n eapply Pos.lt_irrefl in H0. tryfalse.\n }\n {\n ii. destruct (Pos.eq_dec p l1); subst.\n rewrite PTree.gss in H. inv H.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso in H; eauto.\n destruct (Pos.eq_dec max_p l'); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply WF_PH in H. des1. eapply ptC_ph_dom_eq2 in H; eauto.\n do 2 des1. rewrite H; eauto.\n }\n {\n ii. exploit IN; eauto. i. do 2 des1.\n split; eauto.\n eapply WF_MAX_P in H1.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n eapply Pos.lt_succ_diag_r; eauto.\n eapply Pos.lt_trans; eauto.\n }\n {\n ii. destruct (Pos.eq_dec max_p l1); subst.\n eapply Pos.lt_succ_diag_r; eauto.\n rewrite PTree.gso in H; eauto.\n eapply ptC_ph_dom_eq in H; eauto. do 2 des1.\n eapply WF_MAX_P in H.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n eapply Pos.lt_succ_diag_r; eauto.\n eapply Pos.lt_trans; eauto.\n }\n {\n destruct (Pos.eq_dec p max_p); subst.\n eapply POrderedType.Positive_as_OT.lt_irrefl in P_LT_MAX_P; eauto. tryfalse.\n rewrite PTree.gso; eauto.\n }\n }\n }\n {\n ii.\n destruct (Pos.eq_dec max_p l'); subst; eauto.\n rewrite PTree.gss; eauto.\n destruct (Pos.eq_dec p l1); subst; eauto.\n rewrite PTree.gss in H. inv H. rewrite PTree.gss; eauto.\n rewrite PTree.gso in H; eauto.\n rewrite PTree.gso; eauto.\n eapply WF_PH in H; eauto. des1.\n eapply ptC_ph_dom_eq2 in H; eauto. do 2 des1.\n rewrite H; eauto.\n }\n {\n ii. destruct (Pos.eq_dec p l1); subst.\n {\n exploit IN; eauto. i. do 2 des1.\n destruct (Pos.eq_dec max_p l1); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply ptC_ph_dom_eq2 in H1; eauto. do 2 des1.\n rewrite H1. eauto.\n }\n {\n rewrite PTree.gso in H; eauto.\n destruct (Pos.eq_dec max_p l1); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply WF_PH1 in H. des1.\n eapply ptC_ph_dom_eq2 in H; eauto. do 2 des1.\n rewrite H. eauto.\n }\n }\n\n ii. exploit IN; eauto. i. do 2 des1.\n split; eauto.\n destruct (Pos.eq_dec max_p l_entry); subst; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso; eauto.\n eapply ptC_ph_dom_eq2 in H1; eauto. do 2 des1.\n rewrite H1. eauto.\n i. destruct (Pos.eq_dec max_p l1); subst.\n eapply Pos.lt_succ_diag_r; eauto.\n rewrite PTree.gso in H; eauto.\n eapply ptC_ph_dom_eq in H; eauto. do 2 des1.\n eapply WF_MAX_P in H.\n assert (SUCC_LT: (max_p < Pos.succ max_p)%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.lt_trans; eauto.\n }\nQed.\n\nLemma well_defined_preheader3:\n forall loop_invs0 loop_invs cdhp_s cdhp_t l preheader0 preheader max_p max_p' BB_s\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (GET_SRC: cdhp_s ! l = Some BB_s),\n exists BB_t, cdhp_t ! l = Some BB_t.\nProof.\n induction loop_invs0; ii; ss; eauto.\n inv TRANS. eauto.\n destruct a. destruct p; ss.\n destruct (preheader0 ! p) eqn:PREHEADER_P; ss; eauto.\n {\n destruct (cdhp_s ! p1) eqn:CDHP_S; ss; eauto.\n destruct (Pos.eq_dec p1 l); subst; eauto.\n eapply IHloop_invs0 in TRANS; eauto.\n rewrite PTree.gss; eauto.\n eapply IHloop_invs0 in TRANS; eauto.\n rewrite PTree.gso; eauto.\n }\n {\n destruct (Pos.eq_dec max_p l); subst.\n eapply IHloop_invs0 in TRANS; eauto. rewrite PTree.gss; eauto.\n eapply ptC_ph_dom_eq2 in GET_SRC. do 2 des1.\n eapply IHloop_invs0 in TRANS; eauto. rewrite PTree.gso; eauto.\n }\nQed.\n \nLemma well_defined_preheader4:\n forall loop_invs0 loop_invs cdhp_s cdhp_t l_s l_t preheader0 preheader max_p max_p'\n (TRANS: TransC' cdhp_s preheader0 loop_invs0 loop_invs max_p = (cdhp_t, max_p', preheader))\n (PRE_HEADER: preheader ! l_s = Some l_t),\n preheader0 ! l_s = Some l_t \\/ (exists BB_t, cdhp_t ! l_t = Some BB_t).\nProof.\n induction loop_invs0; ii; ss; eauto.\n inv TRANS. eauto.\n destruct a. destruct p.\n destruct (preheader0 ! p) eqn:PREHEADER_P; ss; eauto.\n {\n destruct (cdhp_s ! p1) eqn:CDHP_S; ss; eauto.\n }\n {\n lets TRANS': TRANS.\n eapply IHloop_invs0 in TRANS; eauto. des; eauto.\n destruct (Pos.eq_dec p l_s); subst; eauto.\n rewrite PTree.gss in TRANS. inv TRANS.\n eapply well_defined_preheader3 in TRANS'; eauto.\n rewrite PTree.gss; eauto.\n rewrite PTree.gso in TRANS; eauto.\n }\nQed.\n \nLemma transC'_prop\n cdhp_s cdhp_t l BB_s BB_t loop_invs max_p max_p' preheader ep lo\n (TRANSC': TransC' cdhp_s (PTree.empty positive) loop_invs loop_invs max_p = (cdhp_t, max_p', preheader))\n (BLK_TGT: cdhp_t ! l = Some BB_t)\n (BLK_SRC: cdhp_s ! l = Some BB_s)\n (LOOP_INVS: (cdhp_s ! ep = None /\\ loop_invs = nil) \\/\n (exists BB', cdhp_s ! ep = Some BB' /\\ loop_invC lo (cdhp_s, ep) = loop_invs))\n (WF_MAX_P: forall l BB, cdhp_s ! l = Some BB -> (l < max_p)%positive):\n BB_t = BB_s \\/ ptB_ph_rel BB_t BB_s preheader.\nProof.\n des1.\n\n des1. subst; ss. inv TRANSC'; eauto. rewrite BLK_TGT in BLK_SRC. inv BLK_SRC; eauto.\n\n do 2 des1. subst. clear LOOP_INVS.\n lets TRANSC2': TRANSC'.\n eapply well_defined_preheader2' in TRANSC'; eauto.\n {\n des1.\n {\n des1. exploit WF_MAX_P; eauto. i.\n eapply TransC'_new_allocated_prop in TRANSC2'; eauto.\n des1. rewrite PTree.gempty in TRANSC2'. ss.\n eapply Pos.lt_nle in H. eapply H in TRANSC2'. tryfalse.\n }\n {\n do 2 des1. rewrite BLK_SRC in TRANSC'. inv TRANSC'. eauto.\n }\n }\n {\n ii. rewrite PTree.gempty in H. ss.\n }\n {\n ii. rewrite PTree.gempty in H; ss.\n }\n {\n ii; eauto. subst.\n exploit wf_loop_invC1; eauto.\n ii; des; eauto.\n }\nQed.\n \nLemma transC_prop\n cdhp_s l_s cdhp_t l_t lo BB_t loop_invs\n (TRANSC: TransC (cdhp_s, l_s) loop_invs = (cdhp_t, l_t))\n (LOOP_INVS: (cdhp_s ! l_s = None /\\ loop_invs = nil) \\/\n (exists BB', cdhp_s ! l_s = Some BB' /\\ loop_invC lo (cdhp_s, l_s) = loop_invs))\n (GET_BB_T: cdhp_t ! l_t = Some BB_t):\n exists BB_s preheader max_p max_p',\n <> /\\ \n <> /\\\n < (l < max_p)%positive>> /\\ \n <>.\nProof.\n des.\n subst. simpl in TRANSC.\n assert ((PTree.empty positive) ! l_s = None).\n {\n rewrite PTree.gempty. eauto.\n }\n rewrite H in TRANSC. inv TRANSC. tryfalse.\n \n subst. unfold TransC in *.\n destruct (TransC' cdhp_s (PTree.empty positive) (loop_invC lo (cdhp_s, l_s)) (loop_invC lo (cdhp_s, l_s))\n (Pos.succ (max_labelled_node (PTree.elements cdhp_s) 1))) eqn:TRANSC'.\n destruct p as (cdhp_t', max_p). renames t to preheader.\n assert (ALLOC_NEW: forall l BB,\n cdhp_s ! l = Some BB ->\n (l < Pos.succ (max_labelled_node (PTree.elements cdhp_s) 1))%positive).\n { \n ii. exploit PTree.elements_remove; eauto. i. des. clear H1.\n assert (IN: In (l, BB) (PTree.elements cdhp_s)).\n {\n rewrite H0. eapply in_or_app. ss; eauto.\n }\n eapply max_lablled_node_prop in IN.\n instantiate (1 := 1%positive) in IN.\n assert (SUCC_LT: ((max_labelled_node (PTree.elements cdhp_s) 1) <\n Pos.succ (max_labelled_node (PTree.elements cdhp_s) 1))%positive).\n {\n eapply Pos.lt_succ_diag_r; eauto.\n }\n eapply Pos.le_lt_trans; eauto.\n }\n destruct (preheader ! l_s) eqn:PREHEADER.\n - inv TRANSC.\n exploit well_defined_preheader; eauto.\n i. do 3 des1.\n do 4 eexists.\n splits; eauto.\n - inv TRANSC.\n lets TRANSC2': TRANSC'.\n eapply well_defined_preheader2' in TRANSC'; eauto.\n {\n des1.\n {\n des1. exploit ALLOC_NEW; eauto. i.\n eapply TransC'_new_allocated_prop in TRANSC2'; eauto.\n des1. rewrite PTree.gempty in TRANSC2'. ss.\n eapply Pos.lt_nle in H. eapply H in TRANSC2'. tryfalse.\n }\n {\n do 2 des1.\n do 4 eexists. splits; eauto.\n }\n }\n {\n ii. rewrite PTree.gempty in H. ss.\n }\n {\n ii. rewrite PTree.gempty in H. ss.\n }\n {\n ii; eauto.\n exploit wf_loop_invC1; eauto.\n ii; des; eauto.\n }\nQed.\n\nLemma BBlock_cons\n BB_t BB_s c preheader\n (BLK_CONS: BB_t = c ## BB_s \\/ ptB_ph_rel BB_t (c ## BB_s) preheader):\n exists BB_t', BB_t = c ## BB_t' /\\\n (BB_t' = BB_s \\/ ptB_ph_rel BB_t' BB_s preheader).\nProof.\n des1. subst. exists BB_s. eauto.\n inv BLK_CONS. exists BB_t0. eauto.\nQed.\n\nLemma BBlock_cons'\n BB_t BB_s c preheader\n (BLK_CONS: c ## BB_t = BB_s \\/ ptB_ph_rel (c ## BB_t) BB_s preheader):\n exists BB_s', BB_s = c ## BB_s' /\\\n (BB_s' = BB_t \\/ ptB_ph_rel BB_t BB_s' preheader).\nProof.\n des1. subst. exists BB_t. split; eauto.\n inv BLK_CONS. eauto.\nQed. \n\nLemma wdph_implies_progress\n BB l_entry cdhp_s cdhp_t lo BB' R_t cont_t prog_t\n (WDPH: wdph BB l_entry cdhp_s lo)\n (GET: cdhp_t ! l_entry = Some BB'):\n exists e st2,\n State.step e {| State.regs := R_t; State.blk := BB;\n State.cdhp := cdhp_t; State.cont := cont_t; State.code := prog_t |} st2.\nProof.\n destruct BB; ss.\n - des_ifH WDPH; subst; ss.\n do 2 eexists. eapply State.step_jmp; eauto.\n - destruct c; ss. des.\n do 2 eexists. eapply State.step_assign; eauto.\n destruct or; ss.\n do 2 eexists. eapply State.step_load; eauto.\n Unshelve. exact Int.zero.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/LICMProofMState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.24220563966531902, "lm_q1q2_score": 0.14171479932271006}} {"text": "Require Import VST.msl.log_normalize.\nRequire Import VST.msl.alg_seplog.\nRequire Import VST.veric.base.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.res_predicates.\n\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import VST.veric.address_conflict.\nRequire Import VST.veric.val_lemmas.\nRequire Import VST.veric.Cop2.\nRequire Import VST.veric.shares.\nRequire Import VST.veric.slice.\n\nRequire Import VST.veric.mpred.\nRequire Import VST.veric.mapsto_memory_block.\n\n\nLemma relation_power_level: forall n x y,\n relation_power n age x y -> ((level x) = n + (level y))%nat.\nProof.\nintros n. induction n;intros.\n{ simpl. hnf in H. f_equal. auto. }\nsimpl in H. destruct H as [x' [? ?]].\napply IHn in H0. simpl. rewrite <- H0.\napply age_level. auto.\nQed.\n\n\nLemma share_sub_lub: forall sh1 sh2 sh3,\njoin_sub sh1 sh2 ->\njoin_sub sh1 sh3 ->\njoin_sub sh1 (Share.lub sh2 sh3).\nProof.\nintros. destruct H. destruct H0.\ndestruct H. destruct H0.\nexists (Share.lub x x0).\nsplit.\n- rewrite Share.distrib1. rewrite H. rewrite H0. rewrite Share.lub_bot. reflexivity.\n- rewrite <- (Share.lub_idem sh1).\n rewrite Share.lub_assoc. rewrite <- (Share.lub_assoc sh1 x).\n rewrite H1. rewrite (Share.lub_commute sh2 x0).\n rewrite <- Share.lub_assoc. rewrite H2.\n rewrite Share.lub_commute. reflexivity.\nQed.\n\n\nDefinition join_sub_share sh1 res :=\nmatch res with\n| YES sh _ _ _ | NO sh _ => join_sub sh1 sh\n| _ => True\nend.\n\nDefinition resourece_share res:= \nmatch res with\n| YES sh _ _ _ | NO sh _ => sh\n| _ => Share.top\nend.\n\n\nLemma join_rem_nsh rall sh1 sh2 \n(nsh: ~ readable_share (resourece_share rall))\n(JS1:join_sub sh1 (resourece_share rall)) (JS2:join_sub sh2 (resourece_share rall)) :\n~ readable_share (Share.glb (resourece_share rall) (Share.comp (Share.lub sh1 sh2))).\nProof.\nintros.\nintros C. apply nsh. destruct rall. \n{ simpl in *. destruct JS1 as [sh1' H], JS2 as [sh2' H0].\n pose proof share_cross_split _ _ _ _ _ H H0.\n destruct X as [shs E].\n destruct shs as [[[sh11 sh12] sh21] sh22].\n destruct E as (E1 & E2 & E3 & E4).\n apply join_comm in E2. apply join_comm in H.\n epose proof join_assoc E2 H. destruct X as [sh_u [E5 E6]].\n assert (Share.lub sh1 sh2 = sh_u).\n { destruct E5. rewrite <- H2. rewrite Share.lub_commute.\n destruct E3. rewrite <- H4.\n destruct E1. rewrite <- !H6.\n rewrite (Share.lub_commute sh11 sh21).\n rewrite Share.lub_assoc. rewrite <- (Share.lub_assoc sh11).\n rewrite Share.lub_idem. reflexivity. }\n rewrite H1 in C.\n assert (Share.glb sh (Share.comp sh_u) = sh22).\n { destruct E6. rewrite <- H3.\n rewrite Share.glb_commute. rewrite Share.distrib1.\n rewrite (Share.glb_commute _ sh_u). rewrite Share.comp2.\n rewrite Share.lub_bot. apply share_lemma87.\n rewrite Share.glb_commute. assumption. }\n rewrite H2 in C.\n eapply readable_share_join.\n { apply E6. } auto. }\n{ simpl in *. destruct JS1 as [sh1' H], JS2 as [sh2' H0].\n pose proof share_cross_split _ _ _ _ _ H H0.\n destruct X as [shs E].\n destruct shs as [[[sh11 sh12] sh21] sh22].\n destruct E as (E1 & E2 & E3 & E4).\n apply join_comm in E2. apply join_comm in H.\n epose proof join_assoc E2 H. destruct X as [sh_u [E5 E6]].\n assert (Share.lub sh1 sh2 = sh_u).\n { destruct E5. rewrite <- H2. rewrite Share.lub_commute.\n destruct E3. rewrite <- H4.\n destruct E1. rewrite <- !H6.\n rewrite (Share.lub_commute sh11 sh21).\n rewrite Share.lub_assoc. rewrite <- (Share.lub_assoc sh11).\n rewrite Share.lub_idem. reflexivity. }\n rewrite H1 in C.\n assert (Share.glb sh (Share.comp sh_u) = sh22).\n { destruct E6. rewrite <- H3.\n rewrite Share.glb_commute. rewrite Share.distrib1.\n rewrite (Share.glb_commute _ sh_u). rewrite Share.comp2.\n rewrite Share.lub_bot. apply share_lemma87.\n rewrite Share.glb_commute. assumption. }\n rewrite H2 in C.\n eapply readable_share_join.\n { apply E6. } auto. }\n{ simpl in C. simpl. auto. }\nQed.\n\n\nDefinition join_rem_of sh1 sh2 rall\n(JS1:join_sub sh1 (resourece_share rall))\n(JS2:join_sub sh2 (resourece_share rall)) :=\nmatch rall with\n| YES sh rsh k p =>\n let sh' := Share.glb sh (Share.comp (Share.lub sh1 sh2)) in\n match (dec_readable sh') with\n | left rsh' => YES sh' rsh' k p\n | right nsh' => NO sh' nsh'\n end\n| NO sh nsh =>\n let sh' := Share.glb (resourece_share rall) \n (Share.comp (Share.lub sh1 sh2)) in\n match (dec_readable (resourece_share rall)) with\n | left rsh' => NO Share.bot bot_unreadable\n | right nsh' =>\n NO sh' (join_rem_nsh rall sh1 sh2 nsh' JS1 JS2)\n end\n| PURE k p => PURE k p\nend.\n\n\n\n(* Using the notations from VST.msl.predicates_hered\nbelow are semantic-level lemmas *)\n\nLocal Open Scope pred_derives.\n\n\nDefinition identity_resource_of res :=\n match res with\n | PURE k p => PURE k p\n | NO _ _ | YES _ _ _ _ => NO Share.bot bot_unreadable\n end.\n\nLemma identity_resource_of_sem res: join res (identity_resource_of res) res.\nProof.\n unfold identity_resource_of.\n destruct res; constructor;apply join_bot_eq .\nQed.\n\nLemma identity_resource_at_approx:\n forall phi l,\n resource_fmap (approx (level phi)) (approx (level phi)) (identity_resource_of (phi @ l)) = (identity_resource_of (phi @ l)).\nProof.\n intros. symmetry. rewrite rmap_level_eq. unfold resource_at.\n case_eq (unsquash phi); intros.\n simpl.\n set (phi' := (squash (n, (resource_fmap (approx n) (approx n) oo fst r, snd r)))).\n pose proof I.\n generalize (unsquash_inj phi phi'); intro.\n spec H1.\n replace (unsquash phi) with (unsquash (squash (unsquash phi))).\n 2: rewrite squash_unsquash; auto.\n rewrite H.\n unfold phi'.\n repeat rewrite unsquash_squash.\n simpl.\n f_equal.\n unfold rmap_fmap, compose; simpl.\n f_equal.\n extensionality y.\n rewrite resource_fmap_fmap.\n rewrite approx_oo_approx; auto.\n unfold phi' in *; clear phi'.\n subst.\n rewrite unsquash_squash in H.\n injection H; clear H; intro.\n pattern r at 1. rewrite <- H.\n unfold rmap_fmap, compose.\n simpl; rewrite resource_fmap_fmap.\n rewrite approx_oo_approx; auto.\n destruct (fst r l);simpl;reflexivity.\nQed.\n\n\nNotation \"'ALL' x .. y , P \" :=\n (allp (fun x => .. (allp (fun y => P%pred)) ..)) (at level 65, x binder, y binder, right associativity) : pred.\n\n\nLemma share_resource_join_aux: forall sh1 sh2 sh3 sh5 sh,\njoin sh1 sh3 sh -> join sh2 sh5 sh -> join (Share.lub sh1 sh2) (Share.glb sh (Share.comp (Share.lub sh1 sh2))) sh.\nProof.\nintros.\npose proof share_cross_split _ _ _ _ _ H H0.\ndestruct X as [shs E].\ndestruct shs as [[[sh11 sh12] sh21] sh22].\ndestruct E as (E1 & E2 & E3 & E4).\napply join_comm in E2. apply join_comm in H.\nepose proof join_assoc E2 H. destruct X as [sh_u [E5 E6]].\nassert (Share.lub sh1 sh2 = sh_u).\n{ destruct E5. rewrite <- H2. rewrite Share.lub_commute.\n destruct E3. rewrite <- H4.\n destruct E1. rewrite <- !H6.\n rewrite (Share.lub_commute sh11 sh21).\n rewrite Share.lub_assoc. rewrite <- (Share.lub_assoc sh11).\n rewrite Share.lub_idem. reflexivity. }\nrewrite H1.\nassert (Share.glb sh (Share.comp sh_u) = sh22).\n{ destruct E6. rewrite <- H3.\n rewrite Share.glb_commute. rewrite Share.distrib1.\n rewrite (Share.glb_commute _ sh_u). rewrite Share.comp2.\n rewrite Share.lub_bot. apply share_lemma87.\n rewrite Share.glb_commute. assumption. }\nrewrite H2.\nauto.\nQed.\n\nLemma address_mapsto_preserve_necR {sh lbase m v}:\n forall r_mapsto' r_mapsto,\n necR r_mapsto r_mapsto' ->\n address_mapsto m v sh lbase r_mapsto' <->\n address_mapsto m v sh lbase r_mapsto.\nProof.\n intros. apply necR_power_age in H.\n destruct H as [n H]. revert dependent r_mapsto'.\n revert dependent r_mapsto.\n induction n;intros.\n - inv H. subst. tauto.\n - destruct H as [r_mapsto'' [? ?]].\n apply IHn in H0. rewrite H0. clear H0.\n hnf in H. split;intro.\n { inv H0. exists x. destruct H1 as [[? ?] ?].\n split;[split|].\n + simpl. simpl in H0. auto.\n + intros l. specialize (H1 l).\n hnf in H1. hnf. if_tac.\n { destruct H1. exists x0. hnf in H1.\n hnf. simpl. epose proof age1_YES _ _ _ _ _ _ H.\n apply H4 in H1. auto. }\n { epose proof age1_resource_at_identity _ _ _ H.\n apply H4 in H1. auto. }\n + epose proof age1_ghost_of_identity _ _ H.\n apply H3 in H2. auto.\n }\n { inv H0. exists x. destruct H1 as [[? ?] ?].\n split;[split|].\n + simpl. simpl in H0. auto.\n + intros l. specialize (H1 l).\n hnf in H1. hnf. if_tac.\n { destruct H1. exists x0. hnf in H1.\n hnf. simpl. epose proof age1_YES _ _ _ _ _ _ H.\n apply H4 in H1. auto. }\n { epose proof age1_resource_at_identity _ _ _ H.\n apply H4 in H1. auto. }\n + epose proof age1_ghost_of_identity _ _ H.\n apply H3 in H2. auto.\n }\nQed.\n\n\nLemma two_share_join: forall sh1 sh2,\njoin sh1 (Share.glb (Share.comp sh1) sh2) (Share.lub sh1 sh2).\nProof.\n intros. split.\n - rewrite <- Share.glb_assoc. rewrite Share.comp2.\n rewrite Share.glb_commute. rewrite Share.glb_bot. reflexivity.\n - rewrite Share.distrib2. rewrite Share.comp1.\n rewrite Share.glb_commute. rewrite Share.glb_top. reflexivity.\nQed.\n\n\n\nLemma list_nth_eq': forall {A:Type} (l1 l2: list A) d,\nDatatypes.length (rev l1) = Datatypes.length (rev l2) ->\n(forall l, (l < Datatypes.length (rev l1))%nat ->\n nth l (rev l1) d = nth l (rev l2) d) ->\nl1 = l2.\nProof.\nintros. generalize dependent l2.\ninduction l1.\n+ intros. destruct l2;auto.\n simpl in H. rewrite app_length in H. simpl in H. omega.\n+ intros. destruct l2.\n * simpl in H. rewrite app_length in H.\n inv H. omega.\n * assert (Datatypes.length (rev l1) = Datatypes.length (rev l2)).\n { rewrite !rev_length. rewrite !rev_length in H.\n simpl in H. inv H. auto. }\n f_equal.\n { specialize (H0 (Datatypes.length l1)).\n simpl in H0. rewrite <-!(rev_length l1) in H0.\n rewrite app_nth2 in H0; try omega.\n rewrite Nat.sub_diag in H0.\n rewrite H1 in H0.\n rewrite app_nth2 in H0; try omega.\n rewrite Nat.sub_diag in H0. simpl in H0.\n apply H0. rewrite <- H1. rewrite app_length.\n simpl. omega. \n }\n { apply IHl1;auto.\n intros. simpl in H0. specialize (H0 l).\n rewrite app_nth1 in H0;try omega.\n rewrite app_nth1 in H0;try omega.\n apply H0. rewrite app_length. simpl. omega.\n }\nQed.\n\nLemma list_nth_eq: forall {A:Type} (l1 l2: list A) d,\nDatatypes.length l1 = Datatypes.length l2 ->\n(forall l, (l < Datatypes.length l1)%nat ->\n nth l l1 d = nth l l2 d) ->\nl1 = l2.\nProof.\nintros. rewrite <- (rev_involutive l1) in *.\nrewrite <- (rev_involutive l2) in *. f_equal.\napply list_nth_eq' with (d0:=d);auto.\nQed.\n\n\nLemma address_mapsto_join_value: \nforall sh1 sh2 r1_maps r1_rem r v1 r2_maps r2_rem v2 m lbase,\njoin r1_maps r1_rem r ->\njoin r2_maps r2_rem r -> \naddress_mapsto m v1 sh1 lbase r1_maps ->\naddress_mapsto m v2 sh2 lbase r2_maps ->\nv1 = v2.\nProof.\nintros.\ndestruct H1 as [bm1 [[[E1a [E1b E1c]] E2] E3]].\ndestruct H2 as [bm2 [[[E2a [E2b E2c]] E4] E5]].\nsubst v1 v2.\nassert (forall l, adr_range lbase (size_chunk m) l ->\n nth (Z.to_nat (snd l - snd lbase)) bm1 Undef = \n nth (Z.to_nat (snd l - snd lbase)) bm2 Undef\n).\n{ intros. specialize (E2 l). specialize (E4 l).\n hnf in E2. hnf in E4. if_tac in E2;try tauto.\n destruct E2. destruct E4.\n apply resource_at_join with (loc:=l) in H.\n apply resource_at_join with (loc:=l) in H0.\n rewrite H3 in H. rewrite H4 in H0.\n inv H0; inv H;\n rewrite <- H11 in H10; inv H10; reflexivity.\n}\nf_equal. eapply list_nth_eq with (d:=Undef).\n+ omega.\n+ intros. destruct lbase.\n replace l with (Z.to_nat (snd (b, z + Z.of_nat l) - snd (b, z))).\n 2:{ simpl. rewrite <- Nat2Z.id.\n f_equal. omega. }\n apply H1. hnf. split;auto. rewrite E1a in H2.\n unfold size_chunk_nat in H2. rewrite <- (Nat2Z.id l) in H2.\n apply Z2Nat.inj_lt in H2;try omega. destruct m;simpl;omega.\nQed.\n\nLemma address_mapsto_nonlock_join: forall sh1 sh2 r1_maps r1_rem r v1 r2_maps r2_rem m lbase,\nreadable_share sh1 -> ~ readable_share sh2 ->\njoin r1_maps r1_rem r -> \njoin r2_maps r2_rem r -> \naddress_mapsto m v1 sh1 lbase r1_maps ->\nnonlock_permission_bytes sh2 lbase (size_chunk m) r2_maps ->\nexists r_maps r_rem, join r_maps r_rem r /\\\naddress_mapsto m v1 (Share.lub sh1 sh2) lbase r_maps.\nProof.\n intros.\n rename H1 into HJ1. rename H2 into HJ2.\n destruct H3 as [bm1 [[[E1a [E1b E1c]] E2] E3]].\n destruct H4.\n assert (rsh:readable_share (Share.lub sh1 sh2)).\n { rewrite Share.lub_commute. apply readable_share_lub. auto. }\n assert (JS1: forall l, adr_range lbase (size_chunk m) l -> join_sub sh1 (resourece_share (r @ l))).\n { intros. pose proof resource_at_join _ _ _ l HJ1 as Hl1.\n pose proof E2 l as Hml1. hnf in Hml1.\n if_tac in Hml1;try tauto.\n - destruct Hml1. rewrite H5 in Hl1.\n inv Hl1;simpl in *;auto.\n { exists sh3. auto. }\n { exists sh3. auto. }\n }\n assert (JS2: forall l, adr_range lbase (size_chunk m) l -> join_sub sh2 (resourece_share (r @ l))).\n { intros. pose proof resource_at_join _ _ _ l HJ2 as Hl3.\n pose proof H1 l as Hml2. hnf in Hml2.\n if_tac in Hml2;try tauto. destruct Hml2. hnf in H5.\n inv Hl3;simpl in *;auto;\n rewrite <- H8 in H5; inv H5; exists sh3; auto.\n }\n exists ((squash (level r, (\n (fun l => if (adr_range_dec lbase (size_chunk m) l)\n then YES (Share.lub sh1 sh2) rsh (VAL (nth (Z.to_nat (snd l - snd lbase)) bm1 Undef)) NoneP\n else match (r @ l) with\n | PURE k p => (r @ l)\n | _ => (NO Share.bot bot_unreadable) end),\n ghost_of r1_maps)))).\n exists (squash (level r, (\n (fun l => match (adr_range_dec lbase (size_chunk m) l) with\n | left i => join_rem_of sh1 sh2 (r @ l) (JS1 l i) (JS2 l i)\n | right _ => (r @ l) end),\n ghost_of r1_rem))).\n split.\n + apply join_unsquash. rewrite unsquash_squash. split;[|split].\n - simpl. rewrite unsquash_squash. simpl. rewrite rmap_level_eq. auto.\n - simpl. rewrite unsquash_squash. simpl. unfold compose. unfold join.\n unfold Join_pi. intros l.\n pose proof resource_at_join _ _ _ l HJ1 as Hl1.\n pose proof resource_at_join _ _ _ l HJ2 as Hl2.\n pose proof E2 l as Hml1. pose proof H1 l as Hml2.\n hnf in Hml1, Hml2. hnf. if_tac;simpl.\n { simpl. \n assert (join_sub sh1 (resourece_share (r@l))).\n { apply JS1. auto. }\n pose proof proof_irr (JS1 l H3) H4. rewrite H5. clear H5.\n clear JS1.\n assert (join_sub sh2 (resourece_share (r@l))).\n { apply JS2. auto. }\n pose proof proof_irr (JS2 l H3) H5. rewrite H6. clear H6.\n clear JS2. unfold join_rem_of.\n destruct (r@l) eqn:E;simpl.\n + destruct (dec_readable);try contradiction. simpl.\n destruct Hml1. rewrite H6 in Hl1. inv Hl1.\n + destruct Hml1 as [rsha Hml1], Hml2 as [Hml2a Hml2b].\n hnf in Hml2a.\n rewrite Hml1 in Hl1. inv Hl1.\n { inv Hl2;\n rewrite <- H7 in Hml2a; simpl in Hml2a; inv Hml2a;\n destruct (dec_readable);simpl;\n unfold \"@\" in E; rewrite E; constructor;\n eapply share_resource_join_aux;eassumption. }\n { inv Hl2;\n rewrite <- H7 in Hml2a; simpl in Hml2a; inv Hml2a;\n destruct (dec_readable);simpl;\n unfold \"@\" in E; rewrite E; constructor;\n eapply share_resource_join_aux;eassumption. }\n + destruct Hml1. hnf in H6. rewrite H6 in Hl1. inv Hl1.\n }\n { replace (fst (snd (unsquash r)) l) with (r@l) by reflexivity.\n destruct (r @ l) eqn:E.\n - simpl. constructor. apply bot_join_eq.\n - rewrite <- E. rewrite resource_at_approx. simpl.\n rewrite E. constructor. apply bot_join_eq.\n - rewrite <- E. rewrite resource_at_approx. simpl.\n rewrite E. constructor.\n }\n - simpl. rewrite unsquash_squash. simpl.\n replace (level r) with (level r1_maps).\n 2:{ apply join_level in HJ1. tauto. }\n rewrite ghost_of_approx.\n replace (level r1_maps) with (level r1_rem).\n 2:{ apply join_level in HJ1. omega. }\n rewrite ghost_of_approx. apply ghost_of_join. auto.\n + hnf. exists bm1. split;[split|].\n - simpl. auto.\n - intros l. hnf. specialize (E2 l). specialize (H1 l).\n hnf in E2. hnf in H1. if_tac.\n { exists rsh. simpl. unfold resource_at.\n rewrite unsquash_squash. simpl. unfold compose.\n if_tac;try tauto. }\n { simpl. unfold resource_at.\n rewrite unsquash_squash. simpl. unfold compose.\n if_tac;try tauto.\n destruct (fst (snd (unsquash r)) l);simpl;\n try apply NO_identity. apply PURE_identity. }\n - simpl. unfold ghost_of. rewrite unsquash_squash. simpl.\n replace (level r) with (level r1_maps).\n 2:{ apply join_level in HJ1. omega. }\n rewrite ghost_of_approx. auto.\nQed.\n\n\nLemma unreadable_share_lub: forall sh1 sh2, \n ~ readable_share sh1 -> ~ readable_share sh2 ->\n ~ (readable_share (Share.lub sh1 sh2)).\nProof.\n intros.\n intros C. unfold readable_share in *.\n unfold nonempty_share in *. unfold nonidentity in *.\n apply not_not_share_identity in H.\n apply not_not_share_identity in H0.\n apply C. apply identity_share_bot in H. \n apply identity_share_bot in H0.\n rewrite Share.distrib1. rewrite H. rewrite H0.\n rewrite Share.lub_bot. apply bot_identity.\nQed.\n\n\n\nLemma address_mapsto_join: forall sh1 sh2 r_mapsto1 r1_rem r v1 r_mapsto2 r2_rem v2 m loc,\nreadable_share sh1 -> readable_share sh2 ->\njoin r_mapsto1 r1_rem r -> \njoin r_mapsto2 r2_rem r -> \naddress_mapsto m v1 sh1 loc r_mapsto1 ->\naddress_mapsto m v2 sh2 loc r_mapsto2 ->\nv1 = v2 /\\ exists r_rem r_maps, join r_rem r_maps r /\\\naddress_mapsto m v1 (Share.lub sh1 sh2) loc r_maps.\nProof.\nintros. rename H1 into HJ1. rename H2 into HJ2.\nrename loc into lbase.\npose proof address_mapsto_join_value\n _ _ _ _ _ _ _ _ _ _ _ HJ1 HJ2 H3 H4. split;auto.\nsubst v2.\ndestruct H3 as [b1 [[[Hl [? ?]] Hm1] Hg1]].\ndestruct H4 as [b2 [[[Hl0 [? ?]] Hm2] Hg2]]. subst.\nassert (rsh:readable_share (Share.lub sh1 sh2)).\n{ apply readable_share_lub. auto. }\nassert (JS1: forall l, adr_range lbase (Z.of_nat (Datatypes.length b1)) l -> join_sub sh1 (resourece_share (r @ l))).\n{ intros. pose proof resource_at_join _ _ _ l HJ1 as Hl1.\n pose proof Hm1 l as Hml1. hnf in Hml1.\n if_tac in Hml1.\n - destruct Hml1. rewrite H6 in Hl1.\n inv Hl1;simpl in *;auto.\n { exists sh3. auto. }\n { exists sh3. auto. }\n - rewrite Hl in H1. rewrite size_chunk_conv in H5. tauto.\n}\nassert (JS2: forall l, adr_range lbase (Z.of_nat (Datatypes.length b1)) l -> join_sub sh2 (resourece_share (r @ l))).\n{ intros. pose proof resource_at_join _ _ _ l HJ2 as Hl3.\n pose proof Hm2 l as Hml2. hnf in Hml2.\n if_tac in Hml2;try tauto.\n - destruct Hml2. rewrite H6 in Hl3.\n inv Hl3;simpl in *;auto.\n { exists sh3. auto. }\n { exists sh3. auto. }\n - rewrite Hl in H1. rewrite size_chunk_conv in H5. tauto.\n}\n\nexists (squash (level r, (\n (fun l => match (adr_range_dec lbase (Z.of_nat (Datatypes.length b1)) l) with\n | left i => join_rem_of sh1 sh2 (r @ l) (JS1 l i) (JS2 l i)\n | right _ => (r @ l) end),\n ghost_of r1_rem))).\n\nexists (squash (level r, (\n (fun l => if (adr_range_dec lbase (Z.of_nat (Datatypes.length b1)) l)\n then YES (Share.lub sh1 sh2) rsh (VAL (nth (Z.to_nat (snd l - snd lbase)) b1 Undef)) NoneP\n else match (r @ l) with\n | PURE k p => (r @ l)\n | _ => (NO Share.bot bot_unreadable) end),\n ghost_of r_mapsto1))).\nsplit.\n\n- apply join_unsquash. split;[|split].\n + rewrite !unsquash_squash. simpl.\n rewrite rmap_level_eq. constructor;auto.\n + rewrite !unsquash_squash. simpl.\n unfold join. unfold Join_pi. intros l.\n pose proof resource_at_join _ _ _ l HJ1 as Hl1.\n pose proof resource_at_join _ _ _ l HJ2 as Hl2.\n pose proof Hm1 l as Hml1. pose proof Hm2 l as Hml2.\n hnf in Hml1. hnf in Hml2.\n rewrite size_chunk_conv in Hml1. rewrite <- Hl in Hml1.\n rewrite size_chunk_conv in Hml2. rewrite <- Hl in Hml2.\n simpl. unfold compose. if_tac; simpl.\n * simpl. \n assert (join_sub sh1 (resourece_share (r@l))).\n { apply JS1. auto. }\n pose proof proof_irr (JS1 l H1) H5. rewrite H6. clear H6.\n clear JS1.\n assert (join_sub sh2 (resourece_share (r@l))).\n { apply JS2. auto. }\n pose proof proof_irr (JS2 l H1) H6. rewrite H7. clear H7.\n clear JS2. unfold join_rem_of.\n destruct (r@l) eqn:E;simpl.\n { destruct (dec_readable);try contradiction.\n destruct Hml1. rewrite H7 in Hl1. inv Hl1. }\n { destruct Hml1 as [rsha Hml1], Hml2 as [rshb Hml2].\n rewrite Hml1 in Hl1. rewrite Hml2 in Hl2.\n unfold resource_at in E. rewrite E.\n assert (join (Share.glb sh (Share.comp (Share.lub sh1 sh2))) (Share.lub sh1 sh2) sh).\n { apply join_comm. destruct H5. destruct H6. \n eapply share_resource_join_aux ;eassumption. }\n inv Hl1; inv Hl2;destruct (dec_readable);\n constructor;auto. }\n { destruct Hml1 as [rsha Hml1], Hml2 as [rshb Hml2].\n rewrite Hml1 in Hl1. rewrite Hml2 in Hl2. inv Hl1. }\n * simpl. \n replace (fst (snd (unsquash r)) l) with (r@l) by reflexivity.\n destruct (r @ l) eqn:E.\n { simpl. constructor. apply join_bot_eq. }\n { rewrite <- E. rewrite resource_at_approx. simpl.\n rewrite E. constructor. apply join_bot_eq. }\n { rewrite <- E. rewrite resource_at_approx. simpl.\n rewrite E. constructor. }\n + rewrite !unsquash_squash. simpl.\n replace (level r) with (level r_mapsto1).\n 2:{ apply join_level in HJ1. tauto. }\n rewrite ghost_of_approx.\n replace (level r_mapsto1) with (level r1_rem).\n 2:{ apply join_level in HJ1. omega. }\n rewrite ghost_of_approx. apply ghost_of_join.\n auto.\n- exists b1. split.\n 2:{ simpl. unfold ghost_of. rewrite unsquash_squash. simpl.\n replace (level r) with (level r_mapsto1).\n 2:{ apply join_level in HJ1. tauto. }\n rewrite ghost_of_approx. auto. }\n split.\n { simpl. split;auto. }\n intros l.\n pose proof resource_at_join _ _ _ l HJ1 as Hl1.\n pose proof resource_at_join _ _ _ l HJ2 as Hl2.\n pose proof Hm1 l as Hml1. pose proof Hm2 l as Hml2.\n hnf in Hml1, Hml2. hnf. if_tac.\n + hnf. exists rsh. hnf. rewrite rmap_level_eq.\n unfold resource_at. rewrite unsquash_squash. simpl.\n unfold compose. if_tac;try tauto.\n { exfalso. apply H5. rewrite Hl. \n rewrite <- size_chunk_conv. auto. }\n + simpl. unfold resource_at at 1. rewrite unsquash_squash.\n simpl. unfold compose. if_tac;try tauto.\n { exfalso. apply H1. \n rewrite size_chunk_conv.\n rewrite <- Hl. auto. }\n destruct (r@l);simpl;try apply NO_identity; try apply PURE_identity.\nQed.\n\n\nLemma mapsto_join_andp_det: forall sh1 sh2 t p v1 v2,\n(* tc_val t v2 -> can't be undefined *)\nv1 <> Vundef -> v2 <> Vundef ->\nreadable_share sh1 -> readable_share sh2 ->\n(mapsto sh1 t p v1 * TT) && (mapsto sh2 t p v2 * TT)\n|-- (mapsto (Share.lub sh1 sh2) t p v1 * TT) && !!(v1 = v2).\nProof.\n intros sh1 sh2 t p v1 v2 H H0 Hsh1 Hsh2. unfold mapsto.\n assert (E: forall P, FF * TT && (FF * TT) |-- P).\n { rewrite !FF_sepcon. rewrite FF_and.\n apply FF_derives. }\n destruct (access_mode t);auto.\n destruct (type_is_volatile t);auto.\n destruct p;auto.\n if_tac; if_tac; try tauto.\n hnf. intros r.\n intros E0.\n destruct E0 as [Ea Eb].\n destruct Ea as [r1_maps [r1_rem [Ea1 [Eb1 _]]]].\n destruct Eb as [r2_maps [r2_rem [Ea2 [Eb2 _]]]].\n destruct Eb1 as [Eb1 | Eb1].\n 2:{ simpl in Eb1. tauto. }\n destruct Eb1 as [Eb1 Ec1].\n destruct Eb2 as [Eb2 | Eb2].\n 2:{ simpl in Eb2. tauto. }\n destruct Eb2 as [Eb2 Ec2].\n { pose proof address_mapsto_join\n _ _ _ _ _ _ _ _ _ _ _ H1 H2 Ea1 Ea2 Ec1 Ec2.\n destruct H3. subst v2.\n destruct H4 as [r_rem [r_maps [E1 E2]]].\n if_tac.\n 2:{ exfalso. apply H3. apply readable_share_lub. auto. }\n split. 2:{ simpl. auto. }\n exists r_maps, r_rem. repeat split;auto. left.\n split;auto.\n }\nQed.\n\n\n\nLemma mapsto__join_andp_det: forall sh1 sh2 t p,\n(* tc_val t v2 -> can't be undefined *)\n(* v1 <> Vundef -> v2 <> Vundef -> *)\nreadable_share sh1 -> readable_share sh2 ->\n(mapsto_ sh1 t p * TT) && (mapsto_ sh2 t p * TT)\n|-- (mapsto_ (Share.lub sh1 sh2) t p * TT).\nProof.\n intros sh1 sh2 t p Hsh1 Hsh2. unfold mapsto_. unfold mapsto.\n assert (E: forall P, FF * TT && (FF * TT) |-- P).\n { rewrite !FF_sepcon. rewrite FF_and.\n apply FF_derives. }\n destruct (access_mode t);auto.\n destruct (type_is_volatile t);auto.\n destruct p;auto.\n if_tac; if_tac; try tauto.\n hnf. intros r.\n intros E0.\n destruct E0 as [Ea Eb].\n destruct Ea as [r1_maps [r1_rem [Ea1 [Eb1 _]]]].\n destruct Eb as [r2_maps [r2_rem [Ea2 [Eb2 _]]]].\n destruct Eb1 as [Eb1 | Eb1].\n { exfalso. destruct Eb1. apply tc_val_Vundef in H1. auto. }\n destruct Eb1 as [_ [v1 Ec1]].\n destruct Eb2 as [Eb2 | Eb2].\n { exfalso. destruct Eb2. apply tc_val_Vundef in H1. auto. }\n destruct Eb2 as [_ [v2 Ec2]].\n { pose proof address_mapsto_join\n _ _ _ _ _ _ _ _ _ _ _ H H0 Ea1 Ea2 Ec1 Ec2.\n destruct H1. subst v2.\n destruct H2 as [r_rem [r_maps [E1 E2]]].\n if_tac.\n 2:{ exfalso. apply H1. apply readable_share_lub. auto. }\n exists r_maps, r_rem. repeat split;auto. right.\n split. { reflexivity. } exists v1. auto.\n }\nQed.\n\nLemma address_mapsto_join_lemma: forall {m sh1 sh2 v' v loc\nr1_mapsto r1_rem rj_mapsto rj_rem r rj_mapsto' r'},\nwritable_share sh1 -> writable_share sh2 ->\naddress_mapsto m v' sh1 loc r1_mapsto ->\njoin r1_mapsto r1_rem r ->\naddress_mapsto m v' (Share.lub sh1 sh2) loc rj_mapsto ->\njoin rj_mapsto rj_rem r ->\naddress_mapsto m v (Share.lub sh1 sh2) loc rj_mapsto' ->\njoin rj_mapsto' rj_rem r' ->\nexists r_mapsto' r_rem',\n join r_rem' r_mapsto' rj_mapsto' /\\\n join r_rem' rj_rem r1_rem /\\\n address_mapsto m v sh1 loc r_mapsto'.\nProof.\n intros m sh1 sh2 v' v loc \n r1_mapsto r1_rem rj_mapsto rj_rem r rj_mapsto' r'.\n intros H H0 H1_mapsto H1_join Hj_mapsto Hj_join Hj_mapsto' Hj_join' .\n assert (nsh2: ~ readable_share (Share.glb (Share.comp sh1) sh2)).\n { intros C. eapply join_writable_readable.\n 2:{ apply H. } 2:{ apply C. }\n apply two_share_join. }\n\n pose proof writable_readable_share H as Hr1.\n pose proof writable_readable_share H0 as Hr2.\n destruct Hj_mapsto as [bl Hj_mapsto].\n destruct Hj_mapsto' as [bl' Hj_mapsto'].\n\n set (squash (level rj_rem,(fun l =>\n if (adr_range_dec loc (size_chunk m) l) \n then YES sh1 Hr1 (VAL (nth (Z.to_nat (snd l - snd loc)) bl' Undef)) NoneP\n else (rj_mapsto' @ l)\n ,ghost_of rj_mapsto'))) as r_maps1'.\n\n set (squash (level rj_rem,(fun l =>\n if (adr_range_dec loc (size_chunk m) l) \n then NO (Share.glb (Share.comp sh1) sh2) nsh2 \n else identity_resource_of (rj_mapsto @ l)\n ,nil))) as r_rem2.\n \n exists r_maps1', r_rem2.\n split;[|split].\n + apply join_unsquash. subst r_rem2 r_maps1'.\n rewrite !unsquash_squash. split;[|split].\n - simpl. apply join_level in Hj_join'.\n rewrite rmap_level_eq in *.\n constructor; omega.\n - simpl. unfold join. unfold Join_pi. \n intros l. unfold compose. simpl.\n destruct Hj_mapsto' as [[? ?] ?]. \n specialize (H2 l). simpl in H2.\n if_tac.\n { simpl. destruct H2. unfold resource_at in H2.\n rewrite H2. constructor.\n apply join_comm. apply two_share_join. }\n { \n assert (level rj_rem = level rj_mapsto).\n { apply join_level in Hj_join. omega. }\n rewrite H5. \n rewrite identity_resource_at_approx.\n assert (level rj_mapsto = level rj_mapsto').\n { apply join_level in Hj_join.\n apply join_level in Hj_join'. omega. }\n rewrite H6. rewrite resource_at_approx.\n unfold resource_at. clear H5 H6.\n pose proof resource_at_join _ _ _ l Hj_join as Et1.\n pose proof resource_at_join _ _ _ l Hj_join' as Et2.\n destruct Hj_mapsto as [[? ?] ?].\n specialize (H6 l). simpl in H6.\n if_tac in H6; try tauto.\n pose proof H6 _ _ Et1.\n pose proof H2 _ _ Et2. rewrite H9 in *. rewrite H10 in *.\n unfold resource_at in Et1, Et2. clear H9. clear H10.\n\n destruct ((fst (snd (unsquash rj_mapsto)) l));simpl;\n destruct ((fst (snd (unsquash rj_mapsto')) l));simpl;\n try solve [inv Et1; inv Et2; congruence];\n try constructor;try apply bot_join_eq.\n\n inv Et1. inv Et2. rewrite H12. rewrite <- H13. constructor.\n }\n - simpl. assert (level rj_rem = level rj_mapsto').\n { apply join_level in Hj_join'. omega. }\n rewrite H1. rewrite ghost_of_approx. unfold ghost_of.\n constructor.\n \n\n + apply join_comm. apply join_unsquash. subst r_rem2.\n rewrite !unsquash_squash. split;[|split].\n - simpl. apply join_level in Hj_join.\n apply join_level in H1_join.\n rewrite rmap_level_eq in *.\n constructor;omega.\n - simpl. unfold join. unfold Join_pi. \n intros l. unfold compose. simpl.\n destruct H1_mapsto as [bl1 [[? ?] ?]].\n destruct Hj_mapsto as [[? ?] ?].\n specialize (H2 l). simpl in H2.\n specialize (H5 l). simpl in H5.\n if_tac.\n { simpl.\n destruct H2. destruct H5.\n pose proof resource_at_join _ _ _ l H1_join as Et1.\n pose proof resource_at_join _ _ _ l Hj_join as Et2.\n rewrite H2 in Et1. rewrite H5 in Et2.\n inv Et1; inv Et2.\n { rewrite <- H13 in H15. inv H15.\n unfold resource_at in H12, H14.\n rewrite <- H12, <- H14.\n constructor.\n pose proof two_share_join sh1 sh2.\n destruct (join_assoc H8 RJ0) as [sh3' [? ?]].\n apply join_comm in H11. apply join_comm in RJ.\n pose proof join_canc RJ H11. subst. auto.\n (* KEY: join_canc of Share.t *)\n }\n { assert (writable_share (Share.lub sh1 sh2)).\n { eapply join_writable1;[|apply H].\n apply two_share_join. }\n apply join_writable_readable in RJ0;auto. tauto. }\n { apply join_writable_readable in RJ;auto. tauto. }\n { apply join_writable_readable in RJ;auto. tauto. }\n }\n { assert (level rj_rem = level rj_mapsto).\n { apply join_level in Hj_join. omega. }\n rewrite H8. rewrite identity_resource_at_approx. clear H8.\n unfold resource_at.\n pose proof resource_at_join _ _ _ l H1_join as Et1.\n pose proof resource_at_join _ _ _ l Hj_join as Et2.\n pose proof H2 _ _ Et1. \n pose proof H5 _ _ Et2. \n unfold resource_at in *.\n rewrite H9 in *. rewrite H8 in *.\n clear H9. clear H8.\n\n destruct ((fst (snd (unsquash rj_mapsto)) l));simpl;\n destruct ((fst (snd (unsquash r1_mapsto)) l));simpl; try solve [inv Et1; inv Et2; congruence].\n { inv Et1; inv Et2; try constructor; try apply join_bot_eq. }\n { inv Et1; inv Et2; try constructor; try apply join_bot_eq. }\n { inv Et1; inv Et2; try constructor; try apply join_bot_eq. }\n { inv Et1; inv Et2; try constructor; try apply join_bot_eq. }\n { inv Et1; inv Et2; try constructor. rewrite <- H11 in H12.\n rewrite H12. constructor. }\n }\n - simpl.\n destruct H1_mapsto as [? [[? ?] ?]].\n destruct Hj_mapsto as [[? ?] ?].\n apply ghost_of_join in H1_join.\n apply ghost_of_join in Hj_join.\n apply H3 in H1_join.\n apply H6 in Hj_join. unfold ghost_of in H1_join, Hj_join.\n rewrite H1_join. rewrite Hj_join. constructor.\n \n\n + subst r_maps1'. destruct Hj_mapsto' as [[? ?] ?].\n exists bl'. split;[split|].\n - simpl. apply H1.\n - intros l. simpl. if_tac.\n { exists Hr1. unfold resource_at. rewrite unsquash_squash.\n simpl. unfold compose. if_tac;try tauto. }\n { unfold resource_at. rewrite unsquash_squash. simpl.\n unfold compose. if_tac; try tauto.\n assert (level rj_rem = level rj_mapsto').\n { apply join_level in Hj_join'. omega. }\n rewrite H6. replace (fst (snd (unsquash rj_mapsto')) l) with\n (rj_mapsto' @ l) by reflexivity.\n rewrite resource_at_approx.\n specialize (H2 l). simpl in H2. if_tac in H2;try tauto. }\n - simpl. unfold ghost_of. rewrite unsquash_squash.\n simpl. \n assert (level rj_rem = level rj_mapsto').\n { apply join_level in Hj_join'.\n apply join_level in Hj_join. omega. }\n rewrite H4. rewrite ghost_of_approx. auto.\nQed.\n\nLemma address_mapsto_join_andp_write:\n forall sh1 sh2 v1 v2 v' P1 P2 loc m,\n writable_share sh1 ->\n writable_share sh2 ->\n (address_mapsto m v1 sh1 loc *\n (address_mapsto m v' sh1 loc -* P1)) &&\n (address_mapsto m v2 sh2 loc *\n (address_mapsto m v' sh2 loc -* P2))\n |-- (address_mapsto m v1 (Share.lub sh1 sh2) loc *\n (address_mapsto m v' (Share.lub sh1 sh2) loc -*\n (P1 && P2))).\nProof.\n intros. intro r.\n intros [[r1_mapsto [r1_rem [H1_join [H1_mapsto H1_frame]]]]\n [r2_mapsto [r2_rem [H2_join [H2_mapsto H2_frame]]]]].\n pose proof writable_readable_share H as Hr1.\n pose proof writable_readable_share H0 as Hr2.\n pose proof address_mapsto_join \n _ _ _ _ _ _ _ _ _ _ _ Hr1 Hr2\n H1_join H2_join H1_mapsto H2_mapsto.\n destruct H1. subst v2.\n destruct H2 as [rj_rem [rj_mapsto [Hj_join Hj_mapsto]]].\n exists rj_mapsto, rj_rem. split;[|split];auto.\n\n intros rj_rem'' rj_mapsto'' rj''.\n intros Hj_necR Hj_join'' Hj_mapsto'.\n pose proof sepalg_list.nec_join3 Hj_join'' Hj_necR.\n destruct H1 as [rj_mapsto' [r' [Hj_join' [Hj_necR1 Hj_necR2]]]].\n eapply pred_nec_hereditary; try eassumption.\n apply (@address_mapsto_preserve_necR \n (Share.lub sh1 sh2) loc m v' _ _ Hj_necR1) in Hj_mapsto'.\n clear dependent rj_rem''.\n clear dependent rj_mapsto''. clear dependent rj''.\n\n split.\n { apply join_comm in Hj_join'.\n apply join_comm in Hj_join.\n epose proof address_mapsto_join_lemma\n H H0\n H1_mapsto H1_join\n Hj_mapsto Hj_join\n Hj_mapsto' Hj_join'.\n destruct H1 as [r_mapsto' [r_rem' [E1 [E2 E3]]]].\n apply join_comm in E1.\n apply join_comm in E2.\n\n hnf in H1_frame. eapply H1_frame.\n 3:{ apply E3. }\n { apply necR_refl. }\n destruct (join_assoc E1 Hj_join') as [r1_rem' [E5 E6]].\n assert (r1_rem' = r1_rem).\n { eapply join_eq. apply E5. apply join_comm. auto. }\n subst r1_rem'. auto.\n }\n { apply join_comm in Hj_join'.\n apply join_comm in Hj_join.\n rewrite Share.lub_commute in *.\n epose proof address_mapsto_join_lemma\n H0 H\n H2_mapsto H2_join\n Hj_mapsto Hj_join\n Hj_mapsto' Hj_join'.\n destruct H1 as [r_mapsto' [r_rem' [E1 [E2 E3]]]].\n apply join_comm in E1.\n apply join_comm in E2.\n\n (* specialize (H2_frame v'). *)\n hnf in H2_frame. eapply H2_frame.\n 3:{ apply E3. }\n { apply necR_refl. }\n destruct (join_assoc E1 Hj_join') as [r2_rem' [E5 E6]].\n assert (r2_rem' = r2_rem).\n { eapply join_eq. apply E5. apply join_comm. auto. }\n subst r2_rem'. auto.\n }\nQed.\n\nLemma mapsto_join_andp_write_det: forall sh1 sh2 t p P1 P2 v',\ntc_val t v' -> \nwritable_share sh1 -> writable_share sh2 ->\n(mapsto_ sh1 t p * (mapsto sh1 t p v' -* P1)) && \n(mapsto_ sh2 t p * (mapsto sh2 t p v' -* P2))\n|-- \n(mapsto_ (Share.lub sh1 sh2) t p * (mapsto (Share.lub sh1 sh2) t p v' -* (P1 && P2))).\nProof.\n intros sh1 sh2 t p P1 P2 v' Htc Hsh1w Hsh2w.\n unfold mapsto_. unfold mapsto.\n pose proof writable_readable_share Hsh1w as Hsh1.\n pose proof writable_readable_share Hsh2w as Hsh2.\n destruct (access_mode t); try solve [rewrite FF_sepcon; rewrite FF_and; auto].\n destruct (type_is_volatile t); try solve [rewrite FF_sepcon; rewrite FF_and; auto].\n destruct p; try solve [rewrite FF_sepcon; rewrite FF_and; auto].\n if_tac; try tauto. if_tac; try tauto.\n hnf. intros r.\n intros [E1 E2].\n destruct E1 as [r1_maps [r1_rem [Ea1 [Eb1 Ec1]]]].\n destruct E2 as [r2_maps [r2_rem [Ea2 [Eb2 Ec2]]]].\n destruct Eb1 as [Eb1 | Eb1].\n { destruct Eb1 as [H1 ?]. exfalso. eapply tc_val_Vundef. apply H1. }\n destruct Eb1 as [_ Eb1]. destruct Eb1 as [v1 Eb1].\n destruct Eb2 as [Eb2 | Eb2].\n { destruct Eb2 as [H1 ?]. exfalso. eapply tc_val_Vundef. apply H1. }\n destruct Eb2 as [_ Eb2]. destruct Eb2 as [v2 Eb2].\n { \n pose proof address_mapsto_join_value\n _ _ _ _ _ _ _ _ _ _ _ Ea1 Ea2 Eb1 Eb2.\n subst v2.\n if_tac.\n 2:{ exfalso. apply H1. apply readable_share_lub. auto. }\n pose proof address_mapsto_join_andp_write\n sh1 sh2 v1 v1 v' P1 P2 (b, Ptrofs.unsigned i) m\n Hsh1w Hsh2w r.\n destruct H2 as [rj_mapsto [rj_rem [Hj_join [Hj_mapsto Hj_rem]]]].\n { split.\n + exists r1_maps, r1_rem. repeat split;auto.\n hnf. intros r1_rem' r1_mapsto' r''.\n intros. specialize (Ec1 r1_rem' r1_mapsto' r'' H2 H3).\n apply Ec1. left. split;auto.\n + exists r2_maps, r2_rem. repeat split;auto.\n hnf. intros r2_rem' r2_mapsto' r''.\n intros. specialize (Ec2 r2_rem' r2_mapsto' r'' H2 H3).\n apply Ec2. left. split;auto.\n }\n exists rj_mapsto, rj_rem. split;[|split];auto.\n { right. split;hnf;auto. exists v1. auto. }\n { hnf. intros rj_rem' rj_mapsto' r''. intros.\n eapply Hj_rem.\n { apply H2. } { apply H3. }\n destruct H4. { destruct H4. auto. }\n { destruct H4. hnf in H4. subst v'.\n apply tc_val_Vundef in Htc. tauto. }\n }\n }\nQed.\n\n\nLemma necR_split_1n: forall n r1 r2,\nrelation_power (S n) age r1 r2 -> exists y, age r1 y /\\ necR y r2.\nProof.\nintros n. induction n.\n- intros. destruct H as [?[? ?]]. exists x. split;auto.\n apply necR_power_age. exists 0%nat. auto.\n- intros. destruct H as [?[? ?]].\n apply IHn in H0. exists x. split;auto.\n destruct H0 as [? [? ?]].\n eapply rt_trans;[|apply H1]. apply rt_step. auto.\nQed.\n\n\n\nRequire Import VST.veric.semax_call.\n\n\n(* for some reason when p is too complicated, coq will not inversion it *)\nLemma pure_eq_inv: forall p1 p2 k1 k2,\n PURE k1 p1 = PURE k2 p2 -> k1 = k2 /\\ p1 = p2.\nintros.\ninv H. auto.\nQed.\n\n\n\nLemma func_at_unique2: forall r\nfsig cc A P1 Q1 NEP1 NEQ1\nP2 Q2 NEP2 NEQ2 l,\nseplog.func_at (mk_funspec fsig cc A P1 Q1 NEP1 NEQ1) l r ->\nseplog.func_at (mk_funspec fsig cc A P2 Q2 NEP2 NEQ2) l r ->\n((((box laterM (unfash (fash (ALL ts x vl, (P2 ts x vl <--> P1 ts x vl)))) r)) /\\\n( (box laterM (unfash (fash (ALL ts x vl, (Q2 ts x vl <--> Q1 ts x vl)))) r )))).\nProof.\n intros.\n unfold seplog.func_at in *. unfold pureat in *.\n simpl in H, H0. rewrite H in H0.\n apply pure_eq_inv in H0. destruct H0.\n apply function_pointer_aux in H1;auto.\n destruct H1.\n split. \n { rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros ts. specialize (H1 ts).\n rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros x. specialize (H1 x).\n rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros vl. specialize (H1 vl).\n rewrite later_unfash. auto. }\n { rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros ts. specialize (H2 ts).\n rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros x. specialize (H2 x).\n rewrite fash_allp. rewrite semax.unfash_allp. rewrite later_allp.\n intros vl. specialize (H2 vl).\n rewrite later_unfash. auto. }\nQed.\n\n\nLemma func_at_unique2_later: forall r\nfsig cc A P1 Q1 NEP1 NEQ1\nP2 Q2 NEP2 NEQ2 l,\nseplog.func_at (mk_funspec fsig cc A P1 Q1 NEP1 NEQ1) l r ->\nseplog.func_at (mk_funspec fsig cc A P2 Q2 NEP2 NEQ2) l r ->\n((((box laterM \n (andp (unfash (fash (ALL ts x vl, (P2 ts x vl <--> P1 ts x vl))))\n (unfash (fash (ALL ts x vl, (Q2 ts x vl <--> Q1 ts x vl))))))\n r))).\nProof.\n intros. rewrite later_andp.\n eapply func_at_unique2.\n { apply H. }\n { apply H0. }\nQed.\n\n\nLemma func_at_unique2': forall r\nfsig cc A P1 Q1 NEP1 NEQ1\nP2 Q2 NEP2 NEQ2 l,\nseplog.func_at (mk_funspec fsig cc A P1 Q1 NEP1 NEQ1) l r ->\nseplog.func_at (mk_funspec fsig cc A P2 Q2 NEP2 NEQ2) l r ->\n(((forall ts x vl, (box laterM (unfash (fash (P2 ts x vl <--> P1 ts x vl))) r )) /\\\n(forall ts x vl, (box laterM (unfash (fash (Q2 ts x vl <--> Q1 ts x vl))) r )))).\nProof.\n intros.\n unfold seplog.func_at in *. unfold pureat in *.\n simpl in H, H0. rewrite H in H0.\n apply pure_eq_inv in H0. destruct H0.\n apply function_pointer_aux in H1;auto.\n destruct H1.\n split. \n { intros ts x vl. specialize (H1 ts x vl).\n rewrite <- later_unfash in H1.\n auto.\n }\n { intros ts x vl. specialize (H2 ts x vl).\n rewrite <- later_unfash in H2.\n auto.\n }\nQed.\n\nLemma func_at_unique1: forall r\n { fsig1 cc1 A1 P1 Q1 NEP1 NEQ1\n fsig2 cc2 A2 P2 Q2 NEP2 NEQ2 } l,\n seplog.func_at (mk_funspec fsig1 cc1 A1 P1 Q1 NEP1 NEQ1) l r ->\n seplog.func_at (mk_funspec fsig2 cc2 A2 P2 Q2 NEP2 NEQ2) l r ->\n (fsig1 = fsig2 /\\ cc1 = cc2 /\\ A1 = A2).\nProof.\nintros.\nunfold seplog.func_at in *. unfold pureat in *.\nsimpl in H, H0. rewrite H in H0. inv H0. auto.\nQed.\n\nRequire VST.floyd.SeparationLogicFacts.\n\nDefinition precise_funspec := \nfun (Delta : seplog.tycontext) (f : funspec) =>\nmatch f with\n| mk_funspec fsig0 _ A P R _ _ =>\n\tforall (bl : environ -> list val) (Q1 Q2 : environ -> mpred)\n (ret : option ident) r,\n (snd fsig0 = Tvoid -> ret = None) ->\n tc_fn_return Delta ret (snd fsig0) ->\n ((EX (ts1 : list Type)\n (x1 : (fix dtfr (T : rmaps.TypeTree) : functor :=\n match T with\n | rmaps.ConstType A0 => fconst A0\n | rmaps.Mpred => fidentity\n | rmaps.DependentType n => fconst (nth n ts1 unit)\n | rmaps.ProdType T1 T2 => fpair (dtfr T1) (dtfr T2)\n | rmaps.ArrowType T1 T2 => ffunc (dtfr T1) (dtfr T2)\n | rmaps.SigType I0 f0 => fsig (fun i : I0 => dtfr (f0 i))\n | rmaps.PiType I0 f0 => fpi (fun i : I0 => dtfr (f0 i))\n | rmaps.ListType T0 => flist (dtfr T0)\n end) A mpred),\n @lift.liftx (lift.Tarrow environ (LiftEnviron mpred)) (P ts1 x1 : environ -> mpred) (SeparationLogic.make_args' fsig0 bl) r *\n SeparationLogicFacts.oboxopt Delta ret (fun rho => maybe_retval (R ts1 x1) (snd fsig0) ret rho -* Q1 rho) r) &&\n (EX (ts2 : list Type)\n (x2 : (fix dtfr (T : rmaps.TypeTree) : functor :=\n match T with\n | rmaps.ConstType A0 => fconst A0\n | rmaps.Mpred => fidentity\n | rmaps.DependentType n => fconst (nth n ts2 unit)\n | rmaps.ProdType T1 T2 => fpair (dtfr T1) (dtfr T2)\n | rmaps.ArrowType T1 T2 => ffunc (dtfr T1) (dtfr T2)\n | rmaps.SigType I0 f0 => fsig (fun i : I0 => dtfr (f0 i))\n | rmaps.PiType I0 f0 => fpi (fun i : I0 => dtfr (f0 i))\n | rmaps.ListType T0 => flist (dtfr T0)\n end) A mpred),\n @lift.liftx (lift.Tarrow environ (LiftEnviron mpred)) (P ts2 x2 : environ -> mpred) (SeparationLogic.make_args' fsig0 bl) r *\n SeparationLogicFacts.oboxopt Delta ret (fun rho => maybe_retval (R ts2 x2) (snd fsig0) ret rho -* Q2 rho) r))\n |-- (EX (ts : list Type)\n (x : (fix dtfr (T : rmaps.TypeTree) : functor :=\n match T with\n | rmaps.ConstType A0 => fconst A0\n | rmaps.Mpred => fidentity\n | rmaps.DependentType n => fconst (nth n ts unit)\n | rmaps.ProdType T1 T2 => fpair (dtfr T1) (dtfr T2)\n | rmaps.ArrowType T1 T2 => ffunc (dtfr T1) (dtfr T2)\n | rmaps.SigType I0 f0 => fsig (fun i : I0 => dtfr (f0 i))\n | rmaps.PiType I0 f0 => fpi (fun i : I0 => dtfr (f0 i))\n | rmaps.ListType T0 => flist (dtfr T0)\n end) A mpred),\n @lift.liftx (lift.Tarrow environ (LiftEnviron mpred)) (P ts x : environ -> mpred) (SeparationLogic.make_args' fsig0 bl) r *\n SeparationLogicFacts.oboxopt Delta ret\n (fun rho => maybe_retval (R ts x) (snd fsig0) ret rho -* Q1 rho && Q2 rho) r)\nend.\n\nDefinition precise_fun_at_ptr (Delta:seplog.tycontext) (v:val) : mpred:= \n (allp (fun (fs:funspec) =>\n allp (fun (b: block) =>\n imp ((!! (v = Vptr b Ptrofs.zero)) && seplog.func_at fs (b, 0)) \n (!! (precise_funspec Delta fs) ))))%pred.\n\nLemma func_ptr_der: forall Delta argsig1 argsig2 retsig cc A1 A2 P1 P2 R1 R2 NEP1 NER1 NEP2 NER2 v,\n(( (seplog.func_ptr_si (mk_funspec (argsig1, retsig) cc A1 P1 R1 NEP1 NER1))) v &&\n((seplog.func_ptr_si (mk_funspec (argsig2, retsig) cc A2 P2 R2 NEP2 NER2))) v && \nprecise_fun_at_ptr Delta v)\n|--\n!! (argsig1 = argsig2) &&\n(EX (blk_fun: block) (gA : rmaps.TypeTree)\n (gP1 gP2 gR1 gR2 : forall ts : list Type,\n functors.MixVariantFunctor._functor\n (rmaps.dependent_type_functor_rec ts (AssertTT gA)) mpred) NEgP1 NEgP2 NEgR1 NEgR2,\n !! (v = Vptr blk_fun Ptrofs.zero \n /\\ precise_funspec Delta (mk_funspec (argsig1, retsig) cc gA gP1 gR1 NEgP1 NEgR1)\n ) &&\n ((seplog.func_at (mk_funspec (argsig1, retsig) cc gA gP1 gR1 NEgP1 NEgR1) (blk_fun, 0)) ) &&\n ((seplog.func_at (mk_funspec (argsig1, retsig) cc gA gP2 gR2 NEgP2 NEgR2) (blk_fun, 0)) ) &&\n ((seplog.funspec_sub_si (mk_funspec (argsig1, retsig) cc gA gP1 gR1 NEgP1 NEgR1)\n (mk_funspec (argsig1, retsig) cc A1 P1 R1 NEP1 NER1))) &&\n ((seplog.funspec_sub_si (mk_funspec (argsig1, retsig) cc gA gP2 gR2 NEgP2 NEgR2)\n (mk_funspec (argsig1, retsig) cc A2 P2 R2 NEP2 NER2)))).\nProof.\n intros.\n unfold seplog.func_ptr_si.\n repeat rewrite exp_andp1; apply exp_left; intro blk1.\n repeat rewrite andp_assoc; apply prop_andp_left; intros.\n repeat rewrite exp_andp1; apply exp_left; intro gs1.\n rewrite andp_comm.\n repeat rewrite exp_andp1; apply exp_left; intro blk2.\n repeat rewrite andp_assoc; apply prop_andp_left; intros.\n repeat rewrite exp_andp1; apply exp_left; intro gs2.\n rewrite H in H0. inv H0.\n destruct gs1 as [gsig1 gcc1 gA1 gP1 gQ1 gNP1 gNQ1].\n destruct gs2 as [gsig2 gcc2 gA2 gP2 gQ2 gNP2 gNQ2].\n subst. intro r.\n intros [[E1 E2] [E5 [E3 E4]]].\n pose proof func_at_unique1 _ _ E2 E4.\n destruct H as [? [? ?]]. subst.\n pose proof E1 as E1'.\n hnf in E1'. destruct E1' as [Heq E1']. clear E1'.\n pose proof E3 as E3'.\n hnf in E3'. destruct E3' as [Heq' E3']. clear E3'.\n destruct Heq. destruct Heq'. destruct gsig1. inv H.\n inv H1. subst. split. { reflexivity. }\n exists blk2.\n exists gA1, gP1, gP2, gQ1, gQ2.\n exists gNP1, gNP2, gNQ1, gNQ2.\n split;[split|];[split| |];auto. split;auto.\n split;auto.\n specialize (E5 (mk_funspec (argsig1, retsig) cc gA1 gP1 gQ1 gNP1 gNQ1) blk2).\n \n eapply E5. { apply necR_refl. }\n split;auto. reflexivity.\nQed.\n\nLemma fun_beta: forall {A B:Type} (a: A -> B) y, (fun x => a x) y = a y.\nProof.\n reflexivity.\nQed.\n\n\n\nRequire VST.veric.SeparationLogic.\n(* Require Import VST.veric.lift. *)\nRequire VST.floyd.SeparationLogicFacts.\nRequire Import VST.veric.extend_tc.\nNotation \"P '-*' Q\" := (wand P Q) : pred.\n\n\n\nLemma corable_fash_spec: forall (P: pred nat) (w1:rmap) (w2:rmap), core w1 = core w2 ->\n (! P)%pred w1 -> (! P)%pred w2.\nProof.\n intros.\n pose proof semax.corable_unfash _ _ _ _ _ _ P.\n rewrite corable_spec in H1.\n apply H1 with (x:=w1);auto.\nQed.\n\nLemma necR_unfash_spec: forall (P: pred rmap) (w1:rmap) (w2:rmap), necR w1 w2 ->\n (! # P)%pred w1 -> (P)%pred w2.\nProof.\n intros. unfold unfash in *. simpl in *.\n pose proof necR_level _ _ H.\n apply H0;auto.\nQed.\n\nLemma oboxopt_K':\n forall (Delta : seplog.tycontext) (i : option ident)\n\t(P Q : environ -> pred rmap) r (w:rmap),\n ((P r w) -> (Q r w)) ->\n (forall i v, (P (env_set r i v) w) -> (Q (env_set r i v) w)) ->\n ((SeparationLogicFacts.oboxopt Delta i P : environ -> pred rmap) r w) ->\n ((SeparationLogicFacts.oboxopt Delta i Q : environ -> pred rmap) r w).\nProof.\n intros. \n unfold SeparationLogicFacts.oboxopt. destruct i;auto.\n simpl in H1. unfold SeparationLogicFacts.obox in *. simpl in *.\n replace seplog.allp with (@allp rmap ag_rmap val) by reflexivity.\n replace seplog.allp with (@allp rmap ag_rmap val) in H1 by reflexivity.\n intro v. specialize (H1 v). rewrite fun_beta in H1.\n destruct ((seplog.temp_types Delta) ! i );auto.\n replace seplog.imp with (@imp rmap ag_rmap) by reflexivity.\n replace seplog.imp with (@imp rmap ag_rmap) in H1 by reflexivity.\n\n intros w' E E1.\n pose proof H1 _ (necR_refl _) E1.\n unfold SeparationLogic.subst in *.\n apply (pred_nec_hereditary _ _ _ E).\n unfold lift.liftx in *. simpl in *.\n unfold lift.lift in *. auto.\nQed.\n\nLemma oboxopt_sepcon:\n forall (Delta : seplog.tycontext) (i : option ident) (P Q : environ -> mpred) r,\n SeparationLogicFacts.oboxopt Delta i P r * \n SeparationLogicFacts.oboxopt Delta i Q r \n |-- SeparationLogicFacts.oboxopt Delta i (fun rho => sepcon (P rho) (Q rho)) r.\nProof.\n intros.\n pose proof SeparationLogicFacts.oboxopt_sepcon Delta i P Q.\n apply H.\nQed.\n\n\n\nLemma funspec_rewrite: forall CS gA gP gR \n(gNP: super_non_expansive gP) (gNR: super_non_expansive gR)\nargsig retsig cc A P R \n(NEP: super_non_expansive P)\n(NER: super_non_expansive R)\nr bl ret ts1 x1 Q Delta, \n(* ret a bl P Q R r ts1 x1, *)\n seplog.tc_environ Delta r ->\n SeparationLogic.tc_exprlist Delta (snd (split argsig)) bl r &&\n(seplog.funspec_sub_si (mk_funspec (argsig, retsig) cc gA gP gR gNP gNR)\n(mk_funspec (argsig, retsig) cc A P R NEP NER))\n&& (P ts1 x1\n(SeparationLogic.make_args' (argsig, retsig)\n (@expr.eval_exprlist CS (snd (split argsig)) bl) r) *\n SeparationLogicFacts.oboxopt Delta ret\n (fun rho : environ =>\n wand (maybe_retval (R ts1 x1) retsig ret rho) (Q rho)) r) \n|-- ((EX ts' x',\n (gP ts' x' \n (SeparationLogic.make_args' (argsig, retsig)\n (@expr.eval_exprlist CS (snd (split argsig)) bl) r)) *\n SeparationLogicFacts.oboxopt Delta ret\n (fun rho : environ => \n wand (maybe_retval (gR ts' x') retsig ret rho) (Q rho)) r)).\nProof.\n intros.\n \n intro w.\n \n \n intros [[E1 E2] E4].\n pose proof assert_lemmas.corable_funspec_sub_si\n (mk_funspec (argsig, retsig) cc gA gP gR gNP gNR)\n (mk_funspec (argsig, retsig) cc A P R NEP NER) as Ecor.\n\n rewrite corable_spec in Ecor.\n\n pose proof semax_call.tc_environ_make_args' argsig retsig bl r Delta H _ E1 as Et.\n simpl in Et. destruct E4 as [w1 [w2 [Ejoin [E4 E5]]]].\n\n\n (* w\n / \\\n w1 w2\n / \\ \\\n w1b w1a \\\n | | \\\n gP F (R -* Q) \n [x]\n\n w' = w1a + w2\n w1 |= forall r, forall a a', F * gR --> R\n\nStep 1:\n w' |= forall r, forall a a', F * gR --> R\n*)\n\n assert (Ecor1: core w = core w1).\n { symmetry. apply join_core in Ejoin. auto. }\n pose proof Ecor _ _ Ecor1 E2.\n\n destruct H0 as [_ E3].\n rewrite semax.unfash_allp in E3. specialize (E3 ts1).\n rewrite fun_beta in E3.\n rewrite semax.unfash_allp in E3. specialize (E3 x1).\n rewrite fun_beta in E3.\n rewrite semax.unfash_allp in E3. \n specialize (E3 ((SeparationLogic.make_args' (argsig, retsig)\n (expr.eval_exprlist (snd (split argsig)) bl) r))).\n rewrite fun_beta in E3.\n apply semax.unfash_fash in E3.\n unfold imp in E3. \n specialize (E3 w1 (necR_refl _)).\n destruct E3 as [ts' [x' [F [E3a E3b]]]].\n { split;auto. }\n \n destruct E3a as [w1a [w1b [Ejoin2 [E3a1 E3a2]]]].\n exists ts', x'.\n apply join_comm in Ejoin2.\n destruct (join_assoc Ejoin2 Ejoin) as [w' [Ejoin3 Ejoin4]].\n exists w1b, w'. split;auto. split;auto.\n\nsimpl.\n apply oboxopt_K' with (P:= (fun rho : environ =>\n sepcon F (maybe_retval (R ts1 x1) retsig ret rho -* Q rho)%pred)).\n { intros. destruct H0 as [m1 [m2 [Emjoin1 [Em1 Em2]]]].\n hnf. intros w'' m3 m4 EmnecR Emjoin2 Em3.\n (* \n m4 |=? Q\n / \\\n w' ~~~~~ w'' m3\n / \\ / \\ | \n m1 m2 m1' m2' gR\n / \\ / \\ \n F (R -* Q) F (R -* Q)\n *)\n\n\n destruct (nec_join2 Emjoin1 EmnecR) as [m1' [m2' [Emjoin3 [EmnecR1 EmnecR2]]]].\n pose proof pred_nec_hereditary _ _ _ EmnecR1 Em1 as Em1'.\n pose proof pred_nec_hereditary _ _ _ EmnecR2 Em2 as Em2'.\n (* \n m4 |=? Q\n / \\\n w'' m3\n / \\ | \n m1' m2' gR\n / \\ \n F (R -* Q)\n\n m' = m1' + m3 |= F * gR --> R\n *)\n apply join_comm in Emjoin3.\n destruct (join_assoc Emjoin3 Emjoin2) as [m' [Emjoin4 Emjoin5]].\n apply Em2 with (x':=m2') (y:=m');auto.\n\n\n rewrite <- semax.unfash_allp in E3b.\n rewrite <- fash_allp in E3b.\n assert (exists m'', necR m'' m' /\\ core m'' = core w1).\n { apply join_comm in Emjoin3.\n destruct (nec_join4 _ _ _ _ Emjoin3 EmnecR) as [? [? [? [? ?]]]].\n destruct (sepalg_list.nec_join3 Emjoin4 H1) as [? [? [? [? ?]]]].\n exists x3;split;auto.\n apply join_core in H3. apply join_core in H0.\n apply join_comm in Ejoin4. apply join_core in Ejoin4.\n congruence.\n }\n destruct H0 as [m'' [HnecRm Hcorm]].\n\n apply corable_fash_spec with (w2 := m'')in E3b;auto.\n apply necR_unfash_spec with (w2 := m')in E3b ;auto.\n\n (* Ready to use subsumption about post to prove F * gR --> R *)\n (* Case analysis on maybe_retval *)\n unfold maybe_retval. unfold maybe_retval in Em3.\n destruct ret.\n\n + specialize (E3b (Clight_seplog.get_result1 i r)).\n rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0. }\n { exists m1', m3;auto. }\n + \n (* For non-void case *)\n assert (Htmp:\n (EX v : val, gR ts' x'\n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred m3\n -> (EX v : val, R ts1 x1 \n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred m').\n { intros E0. simpl in E0.\n destruct E0 as [v E0]. exists v.\n specialize (E3b ((seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))).\n rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n }\n { exists m1', m3. auto. }\n }\n \n destruct retsig;auto. clear Htmp.\n * specialize (E3b (seplog.globals_only r)). rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0. }\n { exists m1', m3;auto. }\n }\n { intros. destruct H0 as [m1 [m2 [Emjoin1 [Em1 Em2]]]].\n hnf. intros w'' m3 m4 EmnecR Emjoin2 Em3.\n (* \n m4 |=? Q\n / \\\n w' ~~~~~ w'' m3\n / \\ / \\ | \n m1 m2 m1' m2' gR\n / \\ / \\ \n F (R -* Q) F (R -* Q)\n *)\n\n\n destruct (nec_join2 Emjoin1 EmnecR) as [m1' [m2' [Emjoin3 [EmnecR1 EmnecR2]]]].\n pose proof pred_nec_hereditary _ _ _ EmnecR1 Em1 as Em1'.\n pose proof pred_nec_hereditary _ _ _ EmnecR2 Em2 as Em2'.\n (* \n m4 |=? Q\n / \\\n w'' m3\n / \\ | \n m1' m2' gR\n / \\ \n F (R -* Q)\n\n m' = m1' + m3 |= F * gR --> R\n *)\n apply join_comm in Emjoin3.\n destruct (join_assoc Emjoin3 Emjoin2) as [m' [Emjoin4 Emjoin5]].\n apply Em2 with (x':=m2') (y:=m');auto.\n\n\n rewrite <- semax.unfash_allp in E3b.\n rewrite <- fash_allp in E3b.\n assert (exists m'', necR m'' m' /\\ core m'' = core w1).\n { apply join_comm in Emjoin3.\n destruct (nec_join4 _ _ _ _ Emjoin3 EmnecR) as [? [? [? [? ?]]]].\n destruct (sepalg_list.nec_join3 Emjoin4 H1) as [? [? [? [? ?]]]].\n exists x3;split;auto.\n apply join_core in H3. apply join_core in H0.\n apply join_comm in Ejoin4. apply join_core in Ejoin4.\n congruence.\n }\n destruct H0 as [m'' [HnecRm Hcorm]].\n\n apply corable_fash_spec with (w2 := m'')in E3b;auto.\n apply necR_unfash_spec with (w2 := m')in E3b ;auto.\n\n (* Ready to use subsumption about post to prove F * gR --> R *)\n (* Case analysis on maybe_retval *)\n unfold maybe_retval. unfold maybe_retval in Em3.\n destruct ret.\n\n + specialize (E3b (Clight_seplog.get_result1 i0 (env_set r i v))).\n rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0. }\n { exists m1', m3;auto. }\n + \n (* For non-void case *)\n assert (Htmp:\n (EX v : val, gR ts' x'\n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) (env_set r i v)))%pred m3\n -> (EX v : val, R ts1 x1 \n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) (env_set r i v)))%pred m').\n { intros E0. simpl in E0.\n destruct E0 as [v' E0]. exists v'.\n specialize (E3b ((seplog.make_args (Clight_seplog.ret_temp :: nil) (v' :: nil) (env_set r i v)))).\n rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n }\n { exists m1', m3. auto. }\n }\n \n destruct retsig;auto. clear Htmp.\n * specialize (E3b (seplog.globals_only r)). rewrite fun_beta in E3b.\n specialize (E3b m' (necR_refl _)).\n apply E3b. split.\n { hnf. simpl. split3.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0.\n + hnf. intros. split;intros.\n - rewrite PTree.gempty in H0. inv H0.\n - destruct H0. inv H0.\n + hnf. intros. rewrite PTree.gempty in H0. inv H0. }\n { exists m1', m3;auto. }\n }\n { apply oboxopt_sepcon. exists w1a, w2. split;auto.\n split;auto.\n unfold SeparationLogicFacts.oboxopt. destruct ret;auto.\n unfold SeparationLogicFacts.obox. simpl.\n replace seplog.allp with (@allp rmap ag_rmap val) by reflexivity.\n intros x. destruct ((seplog.temp_types Delta) ! i ).\n { replace seplog.imp with (@imp rmap ag_rmap) by reflexivity.\n hnf. intros. unfold SeparationLogic.subst.\n apply pred_nec_hereditary with (a:= w1a);auto. }\n { replace seplog.prop with (@prop rmap ag_rmap)by reflexivity.\n simpl. auto. }\n }\nQed.\n(* TODO: about this proof,\n can be simplified since proofs for\n [\n ((P r w) -> (Q r w)) ->\n (forall i v, (P (env_set r i v) w) -> (Q (env_set r i v) w)) ->\n ]\n are similar\n*)\n\n\nLemma func_ptr_self: forall gs fs v blk,\n v = Vptr blk Ptrofs.zero ->\n seplog.funspec_sub_si gs fs &&\n seplog.func_at gs (blk, 0) |--\n SeparationLogic.func_ptr gs v.\nProof.\n intros. intro w.\n intros [E1 E2].\n hnf. exists blk.\n split;auto.\n exists gs.\n split;auto.\n apply seplog.funspec_sub_si_refl.\n auto.\nQed.\n\n\nLemma later_andp_aux: forall (P Q : mpred) r,\n (|> P)%pred r ->\n (|> Q)%pred r ->\n (|> andp P Q)%pred r.\nProof.\n intros. rewrite later_andp.\n split;auto.\nQed.\n\n\nLemma func_at_unique_rewrite : forall Delta argsig retsig cc A gP1\ngP2 gR1 gR2 NEgP1 NEgP2 NEgR1 NEgR2 address (vl: environ -> environ) ret Q (r: environ),\n(lift.liftx (seplog.func_at (mk_funspec (argsig, retsig) cc A gP2 gR2 NEgP2 NEgR2) address)) r &&\n(lift.liftx (seplog.func_at (mk_funspec (argsig, retsig) cc A gP1 gR1 NEgP1 NEgR1) address)) r &&\n(box laterM (EX ts x, (((@lift.liftx (lift.Tarrow environ (LiftEnviron mpred)) (gP1 ts x : environ -> mpred)) (vl)) r) * SeparationLogicFacts.oboxopt Delta ret (fun rho => wand (SeparationLogic.maybe_retval (gR1 ts x) retsig ret rho) (Q rho)) r))\n|-- (box laterM (EX ts x, (((@lift.liftx (lift.Tarrow environ (LiftEnviron mpred)) (gP2 ts x: environ -> mpred)) (vl)) r) * SeparationLogicFacts.oboxopt Delta ret (fun rho => wand ((SeparationLogic.maybe_retval (gR2 ts x) retsig ret) rho) (Q rho)) r)).\nProof.\n intros. intros w.\n intros [[E1 E2] E3].\n pose proof func_at_unique2_later _ _ _ _ _ _ NEgP1 NEgR1 _ _ NEgP2 NEgR2 _ E2 E1.\n pose proof later_andp_aux _ _ _ E3 H as Eder.\n clear H.\n eapply later_derives. 2:{ apply Eder. } \n clear Eder.\n intros w'.\n intros [Ew1 [Ew2 Ew3]].\n\n clear E1 E2 E3.\n\n destruct Ew1 as [ts [x [w1 [w2 [Ewjoin [Ew1 Ew4]]]]]].\n exists ts, x, w1, w2. split;auto. split.\n { unfold lift.liftx. unfold lift.lift. simpl.\n apply corable_fash_spec with (w2 := w1)in Ew2;auto.\n 2:{ apply join_core in Ewjoin;auto. }\n apply semax.unfash_fash in Ew2.\n specialize (Ew2 ts x (vl r)).\n destruct Ew2. apply H0;auto. }\n { apply corable_fash_spec with (w2 := w2)in Ew3;auto.\n 2:{ apply join_comm in Ewjoin. apply join_core in Ewjoin;auto. }\n eapply oboxopt_K'.\n 3:{ apply Ew4. }\n (* \n w' z\n / \\ / \\\n w1 w2 ------ x' y\n \n w' |= !# gR1 <-> gR2\n y |= gR2\n Goal: y |= gR1\n *)\n { simpl. intros.\n apply H with (x' := x') (y := y) (z:= z);auto.\n pose proof pred_nec_hereditary _ _ _ H0 Ew3 as Ew3'.\n apply corable_fash_spec with (w2 := y) in Ew3';auto.\n 2:{ apply join_core2 in H1. auto. }\n apply semax.unfash_fash in Ew3'.\n unfold maybe_retval. unfold maybe_retval in H2.\n destruct ret.\n { specialize (Ew3' ts x (Clight_seplog.get_result1 i r)).\n destruct Ew3'. apply H3;auto. }\n\n (* For non-void case *)\n assert (Htmp:\n (EX v : val, gR2 ts x\n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred y\n -> ((EX v : val, gR1 ts x \n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred y)).\n { intros E0. simpl in E0.\n destruct E0 as [v' E0]. exists v'.\n specialize (Ew3' ts x (env_set (seplog.globals_only r) Clight_seplog.ret_temp v')).\n apply Ew3';auto. }\n\n destruct retsig;auto.\n specialize (Ew3' ts x (seplog.globals_only r)).\n apply Ew3';auto.\n }\n\n { simpl. intros i0 v0. intros.\n apply H with (x' := x') (y := y) (z:= z);auto.\n pose proof pred_nec_hereditary _ _ _ H0 Ew3 as Ew3'.\n apply corable_fash_spec with (w2 := y) in Ew3';auto.\n 2:{ apply join_core2 in H1. auto. }\n apply semax.unfash_fash in Ew3'.\n unfold maybe_retval. unfold maybe_retval in H2.\n destruct ret.\n { specialize (Ew3' ts x (Clight_seplog.get_result1 i (env_set r i0 v0))).\n destruct Ew3'. apply H3;auto. }\n\n (* For non-void case *)\n assert (Htmp:\n (EX v : val, gR2 ts x\n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred y\n -> ((EX v : val, gR1 ts x \n (seplog.make_args (Clight_seplog.ret_temp :: nil) (v :: nil) r))%pred y)).\n { intros E0. simpl in E0.\n destruct E0 as [v' E0]. exists v'.\n specialize (Ew3' ts x (env_set (seplog.globals_only r) Clight_seplog.ret_temp v')).\n apply Ew3';auto. }\n\n destruct retsig;auto.\n specialize (Ew3' ts x (seplog.globals_only r)).\n apply Ew3';auto.\n }\n }\nQed.", "meta": {"author": "QinxiangCao", "repo": "VST-A-VSTpart", "sha": "fd8e5b0846a121c20b267fef7ca36e33dd24fae6", "save_path": "github-repos/coq/QinxiangCao-VST-A-VSTpart", "path": "github-repos/coq/QinxiangCao-VST-A-VSTpart/VST-A-VSTpart-fd8e5b0846a121c20b267fef7ca36e33dd24fae6/CSplit/model_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.1416673369255674}} {"text": "Require Import Program.Basics.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic.\nFrom imm Require Import Events Execution TraversalConfig Traversal\n Prog ProgToExecution ProgToExecutionProperties imm_s imm_s_hb\n CombRelations SimTraversal TraversalCounting.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import ImmProperties.\nRequire Import EventStructure.\nRequire Import Consistency.\nRequire Import Step.\nRequire Import Execution.\nRequire Import EventToAction.\nRequire Import SimRelCont.\nRequire Import SimRelEventToAction.\nRequire Import SimRel.\nRequire Import SimRelInit.\nRequire Import SimRelStep.\nRequire Import ProgES.\nRequire Import CertRf.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection Compilation.\n Variable prog : stable_prog_type.\n Variable G : execution.\n Variable sc : relation actid.\n\n Notation \"'GE'\" := G.(acts_set).\n Notation \"'GEinit'\" := (is_init ∩₁ GE).\n Notation \"'GEninit'\" := ((set_compl is_init) ∩₁ GE).\n\n Notation \"'Glab'\" := (Execution.lab G).\n Notation \"'Gloc'\" := (Events.loc (lab G)).\n Notation \"'Gtid'\" := (Events.tid).\n\n Notation \"'GTid' t\" := (fun x => Gtid x = t) (at level 1).\n Notation \"'GNTid' t\" := (fun x => Gtid x <> t) (at level 1).\n\n Notation \"'GR'\" := (fun a => is_true (is_r Glab a)).\n Notation \"'GW'\" := (fun a => is_true (is_w Glab a)).\n Notation \"'GF'\" := (fun a => is_true (is_f Glab a)).\n\n Notation \"'GRel'\" := (fun a => is_true (is_rel Glab a)).\n Notation \"'GAcq'\" := (fun a => is_true (is_acq Glab a)).\n\n Notation \"'Gsb'\" := (Execution.sb G).\n Notation \"'Grmw'\" := (Execution.rmw G).\n Notation \"'Grf'\" := (Execution.rf G).\n Notation \"'Gco'\" := (Execution.co G).\n\n Notation \"'Grs'\" := (imm_s_hb.rs G).\n Notation \"'Grelease'\" := (imm_s_hb.release G).\n Notation \"'Gsw'\" := (imm_s_hb.sw G).\n Notation \"'Ghb'\" := (imm_s_hb.hb G).\n\n Notation \"'Gfurr'\" := (furr G sc).\n\n Notation \"'Geco'\" := (Execution_eco.eco G).\n\n Section Extraction.\n\n Variable S : ES.t.\n Variable TC : trav_config.\n Variable X : eventid -> Prop.\n Variable T : thread_id -> Prop.\n\n Notation \"'SE'\" := S.(ES.acts_set).\n Notation \"'SEinit'\" := S.(ES.acts_init_set).\n Notation \"'SEninit'\" := S.(ES.acts_ninit_set).\n Notation \"'Stid'\" := (S.(ES.tid)).\n Notation \"'Slab'\" := (S.(ES.lab)).\n Notation \"'Sloc'\" := (loc S.(ES.lab)).\n Notation \"'K'\" := S.(ES.cont_set).\n\n Notation \"'STid' t\" := (fun x => Stid x = t) (at level 1).\n\n Notation \"'SR'\" := (fun a => is_true (is_r Slab a)).\n Notation \"'SW'\" := (fun a => is_true (is_w Slab a)).\n Notation \"'SF'\" := (fun a => is_true (is_f Slab a)).\n Notation \"'SRel'\" := (fun a => is_true (is_rel Slab a)).\n\n Notation \"'Ssb'\" := (S.(ES.sb)).\n Notation \"'Scf'\" := (S.(ES.cf)).\n Notation \"'Srmw'\" := (S.(ES.rmw)).\n Notation \"'Sjf'\" := (S.(ES.jf)).\n Notation \"'Sjfi'\" := (S.(ES.jfi)).\n Notation \"'Sjfe'\" := (S.(ES.jfe)).\n Notation \"'Srf'\" := (S.(ES.rf)).\n Notation \"'Srfi'\" := (S.(ES.rfi)).\n Notation \"'Srfe'\" := (S.(ES.rfe)).\n Notation \"'Sco'\" := (S.(ES.co)).\n Notation \"'Sew'\" := (S.(ES.ew)).\n\n Notation \"'Srs'\" := (S.(Consistency.rs)).\n Notation \"'Srelease'\" := (S.(Consistency.release)).\n Notation \"'Ssw'\" := (S.(Consistency.sw)).\n Notation \"'Shb'\" := (S.(Consistency.hb)).\n\n Notation \"'C'\" := (covered TC).\n Notation \"'I'\" := (issued TC).\n\n (* Relation stating that extracted subset `X` is `isomorphic` to execution graph `G`.\n * This definition is actually has nothing to do with `simrel`, \n * but for historical reasons it's defined here. *)\n Definition simrel_extracted :=\n ⟪ GACTS : GE ≡₁ e2a S □₁ X ⟫ /\\\n ⟪ GLAB : eq_dom X Slab (Glab ∘ e2a S) ⟫ /\\\n ⟪ GSB : Gsb ≡ e2a S □ (Ssb ∩ X × X) ⟫ /\\\n ⟪ GRMW : Grmw ≡ e2a S □ (Srmw ∩ X × X) ⟫ /\\\n ⟪ GRF : Grf ≡ e2a S □ (Srf ∩ X × X) ⟫ /\\\n ⟪ GCO : Gco ≡ e2a S □ (Sco ∩ X × X) ⟫.\n\n Lemma simrel_extract\n (SRC : simrel_consistent prog S G sc TC X T)\n (* condition that all the events are covered implies that \n * the traversal configuration `TC` is terminal *)\n (COVinG : GE ⊆₁ C) :\n simrel_extracted.\n Proof.\n assert (ES.Wf S) as SWF.\n { apply SRC. }\n assert (Wf G) as GWF.\n { apply SRC. }\n assert (tc_coherent G sc TC) as TCCOH.\n { apply SRC. }\n assert (Execution.t S X) as EXEC.\n { apply SRC. }\n assert (simrel prog S G sc TC X T) as SRC_.\n { apply SRC. }\n assert (simrel_e2a S G sc) as SRE2A.\n { apply SRC. }\n\n assert (GE ≡₁ C) as COVG.\n { split; auto. eapply coveredE; eauto. }\n assert (GE ≡₁ C ∪₁ I) as COVISSG.\n { split; auto.\n { rewrite COVG. basic_solver. }\n apply set_subset_union_l. split.\n { eapply coveredE; eauto. }\n eapply issuedE; eauto. }\n assert (GE ≡₁ C ∪₁ dom_rel (Gsb^? ⨾ ⦗ I ⦘)) as DCOV.\n { rewrite COVG.\n split; [basic_solver|].\n unionL; auto.\n rewrite issuedE; [|apply SRC].\n rewrite COVG.\n rewrite crE. relsf.\n split; auto.\n eapply dom_sb_covered; eauto. }\n assert (GE ∩₁ GW ≡₁ I) as ISSG.\n { split.\n { rewrite COVG. rewrite set_interC.\n eapply w_covered_issued; eauto. }\n apply set_subset_inter_r. split.\n { eapply issuedE; eauto. }\n eapply issuedW; eauto. }\n\n constructor; splits.\n 3-6: split.\n\n { rewrite DCOV. symmetry.\n eapply ex_cov_iss; eauto. }\n\n { eapply eq_dom_more;\n [| | | eapply ex_cov_iss_lab; eauto].\n all : auto.\n rewrite <- COVISSG, DCOV.\n fold (CsbI G TC).\n erewrite <- ex_cov_iss; eauto.\n erewrite set_inter_absorb_r; auto.\n apply set_in_map_collect. }\n\n { arewrite (Gsb ≡ ⦗C⦘ ⨾ Gsb ⨾ ⦗C⦘).\n { rewrite wf_sbE at 1; auto. by rewrite COVG. }\n rewrite <- restr_cross, restr_relE.\n eapply sb_restr_cov_in_ex; eauto. }\n\n { rewrite collect_rel_interi.\n erewrite e2a_sb; try apply SRC.\n basic_solver. }\n\n { arewrite (Grmw ≡ ⦗C⦘ ⨾ Grmw ⨾ ⦗C⦘).\n { rewrite wf_rmwE at 1; auto. by rewrite COVG. }\n rewrite <- restr_cross, restr_relE.\n eapply rmw_restr_cov_in_ex; eauto. }\n\n { rewrite collect_rel_interi.\n erewrite e2a_rmw; try apply SRC.\n basic_solver. }\n\n { arewrite (Grf ≡ ⦗GE ∩₁ GW⦘ ⨾ Grf ⨾ ⦗GE⦘).\n { rewrite wf_rfE, wf_rfD; auto. basic_solver. }\n rewrite ISSG, COVG.\n rewrite <- restr_cross, restr_relE.\n eapply iss_rf_cov_in_ex; eauto. }\n\n { intros x' y' [x [y [[RF [Xx Xy]] [EQx' EQy']]]].\n unfolder. ins. desf.\n eapply jf_cov_in_rf; eauto.\n unfold ES.rf in RF.\n destruct RF as [[z [EW JF]] nCF].\n exists z, y.\n splits; auto.\n { apply seq_eqv_r.\n unfolder; splits; auto.\n apply COVG.\n eapply e2a_GE.\n { apply SRC. }\n eexists; splits; eauto.\n eapply Execution.ex_inE; eauto. }\n symmetry.\n eapply e2a_ew; eauto.\n basic_solver 10. }\n\n { arewrite (Gco ≡ ⦗GE ∩₁ GW⦘ ⨾ Gco ⨾ ⦗GE ∩₁ GW⦘).\n { rewrite wf_coE, wf_coD at 1; auto. basic_solver. }\n rewrite ISSG.\n rewrite <- restr_cross, restr_relE.\n eapply co_restr_iss_in_ex; eauto. }\n\n unfolder. ins. desf.\n eapply e2a_co_ncf; eauto.\n unfolder; do 2 eexists; splits; eauto.\n intros CF.\n eapply Execution.ex_ncf.\n { apply SRC. }\n apply seq_eqv_lr; eauto.\n\n Qed.\n\n End Extraction.\n\n Lemma simrel_traversal\n (nInitProg : ~ IdentMap.In tid_init prog)\n (GProg : program_execution (stable_prog_to_prog prog) G)\n (GWF : Execution.Wf G)\n (IMMCONS : imm_consistent G sc)\n (nLocsEmpty : g_locs G <> [])\n (GCLOS : forall t m n (LT : m < n) (NE : GE (ThreadEvent t n)),\n GE (ThreadEvent t m)) :\n let T := (fun t => IdentMap.In t prog) in\n forall TC (TC_STEPS : (sim_trav_step G sc)* (init_trav G) TC),\n exists S X,\n ⟪ STEPS : (step Weakestmo)* (prog_g_es_init prog G) S ⟫ /\\\n ⟪ SRC : simrel_consistent prog S G sc TC X T ⟫.\n Proof.\n eapply clos_refl_trans_ind_left.\n { exists (prog_g_es_init prog G), (ES.acts_set (prog_g_es_init prog G)).\n splits; auto using rt_refl, simrel_init. }\n intros TC TC' TC_STEPS IH TC_STEP. desc.\n destruct TC_STEP as [thread TC_ISTEP].\n edestruct simrel_step as [X' [S' HH]]; eauto.\n { apply stable_prog_to_prog_in.\n eapply CertGraph.trstep_thread_prog; eauto.\n apply SRC. }\n destruct HH as [STEPS' SRC'].\n red in STEPS', SRC'.\n exists S', X'. splits; auto.\n eapply rt_trans; eauto.\n Qed.\n\n Theorem compilation_correctness\n (nInitProg : ~ IdentMap.In tid_init prog)\n (GProg : program_execution (stable_prog_to_prog prog) G)\n (GWF : Execution.Wf G)\n (IMMCONS : imm_consistent G sc)\n (nLocsEmpty : g_locs G <> [])\n (GCLOS : forall t m n (LT : m < n) (NE : GE (ThreadEvent t n)),\n GE (ThreadEvent t m)) :\n exists S X,\n ⟪ STEPS : (step Weakestmo)* (prog_g_es_init prog G) S ⟫ /\\\n ⟪ EXEC : simrel_extracted S X ⟫.\n Proof.\n edestruct sim_traversal\n as [TC [TC_STEPS GCOV]];\n eauto.\n edestruct simrel_traversal\n as [S [X [STEPS SRC]]];\n eauto.\n red in STEPS, SRC.\n exists S, X.\n splits; auto.\n eapply simrel_extract; eauto.\n Qed.\n\nEnd Compilation.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/Compilation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.14130209507966085}} {"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import AsmC.\nRequire SimMemInjInvC.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import AsmregsC.\nRequire Import MatchSimModSem.\nRequire Import StoreArguments StoreArgumentsProps.\nRequire Import AsmStepInj IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import AsmExtra IdSimExtra IdSimAsmExtra IdSimInvExtra.\n\nRequire Import MatchSimModSemExcl2.\nRequire Import Conventions1C.\n\nRequire Import mktac.\n\n\nSet Implicit Arguments.\n\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\n\n\nSection INJINV.\n\nLocal Existing Instance SimSymbDropInv.SimMemInvTop.\nLocal Existing Instance SimSymbDropInv.SimSymbDropInv.\nLocal Existing Instance SoundTop.Top.\n\n\nLemma asm_inj_inv_drop\n (asm: Asm.program)\n (WF: Sk.wf (module asm))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimSymbDropInv.mk bot1 _ _).\n econs; ss; i.\n { econs; ss; i; clarify.\n inv WF. auto. }\n eapply MatchSimModSemExcl2.match_states_sim with\n (match_states :=\n @match_states\n SimMemInjInv.top_inv SimMemInjInv.top_inv\n skenv_link_tgt\n (SkEnv.revive (SkEnv.project skenv_link_src (Sk.of_program fn_sig asm)) asm)\n (SkEnv.revive (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig asm)) asm))\n (match_states_at := top4)\n (sidx := unit); ss; eauto; ii.\n - apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation.\n\n - (** ******************* initial **********************************)\n destruct sm_arg as [sm_arg mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n inv SIMARGS.\n { ss. clarify.\n inv INITTGT; clarify. ss. inv TYP. cinv STORE.\n\n exploit store_arguments_parallel; eauto.\n { eapply typify_has_type_list; eauto. }\n { exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto. i. des.\n inv WFTGT. rpapply WFPARAM; eauto; ss. }\n { eapply inject_list_typify_list; try eassumption.\n erewrite inject_list_length; eauto. } i. des.\n hexploit (assign_junk_blocks_parallel n); eauto. i. des.\n eexists (AsmC.mkstate (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd))) # PC <- fptr_src)\n # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA)))\n # RSP <- (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero)\n (Asm.State _ _)).\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv SimMemInjInv.top_inv sm_arg sm0); eauto.\n { etrans; eauto. }\n\n eexists (SimMemInjInv.mk sm0 _ _). esplits; eauto.\n { econs; ss; eauto.\n - inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto. i.\n setoid_rewrite FINDF in H2. clarify.\n - assert (JUNK: JunkBlock.is_junk_value m0 (JunkBlock.assign_junk_blocks m0 n) (rs RA)).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; ss. }\n split.\n + unfold Pregmap.set, src_junk_val. des_ifs.\n + unfold Pregmap.set, src_junk_val. des_ifs; ss; des; eauto.\n - unfold Pregmap.set. des_ifs. unfold src_junk_val, JunkBlock.is_junk_value in *.\n des_ifs. ii. clarify. apply n1.\n assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm1) - Mem.nextblock (SimMemInj.tgt sm1)) (Mem.nextblock (SimMemInj.src sm1))).\n { eapply Plt_Ple_trans; eauto.\n inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.\n rewrite NBSRC.\n etrans; eauto. etrans; eauto. eapply Mem.unchanged_on_nextblock; eauto. }\n exfalso. eapply Plt_lemma; eauto.\n - econs; eauto. erewrite inject_list_length; eauto.\n - inv ARGTGT. econs; ss; eauto.\n econs; try eassumption; eauto.\n eapply extcall_arguments_same; eauto. i.\n unfold Pregmap.set, to_mregset, to_pregset, to_preg.\n erewrite to_preg_to_mreg. des_ifs; clarify; ss.\n + unfold preg_of in *; des_ifs.\n + unfold preg_of in *; des_ifs.\n + unfold preg_of in *; des_ifs.\n + unfold set_regset_junk. des_ifs; clarify; eauto.\n exfalso. eapply Loc.notin_not_in in n3. eauto.\n - i. unfold Pregmap.set in *. des_ifs; eauto.\n { exploit PTRFREE.\n - ii. eapply src_junk_val_junk in H2; eauto.\n - i. des; clarify. } left.\n unfold to_pregset, set_regset_junk, to_mregset in *. des_ifs; ss.\n + exploit PTRFREE.\n * ii. eapply src_junk_val_junk in H2; eauto.\n * i. erewrite to_mreg_some_to_preg in *; eauto. des; ss.\n clarify. esplits; eauto.\n + esplits; eauto. erewrite loc_notin_not_in in n3. tauto. }\n\n { econs; ss; eauto. etrans; eauto. }\n\n { assert (AGREE0:\n AsmStepInj.agree\n (SimMemInj.inj sm0)\n (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd)))\n # PC <- fptr_src) # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA))) # RSP <-\n (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero) rs).\n { ii. unfold Pregmap.set, to_mregset, to_pregset, to_preg.\n inv MLE0. des_ifs; ss; eauto.\n - eapply val_inject_incr; eauto. rewrite INJ.\n unfold update_meminj. rewrite H1. econs; des_ifs. ss.\n - rewrite MINJ. eapply src_junk_val_inj; eauto. inv MWF0. eauto.\n - inv MLE. eapply val_inject_incr; eauto.\n - unfold set_regset_junk. des_ifs.\n + erewrite to_mreg_preg_of; eauto. rewrite MINJ.\n eapply src_junk_val_inj; eauto. inv MWF0. eauto.\n + eapply val_inject_incr; eauto. rewrite INJ in *.\n specialize (AGREE m). unfold to_mregset in *.\n erewrite to_mreg_preg_of in *; eauto. }\n econs; eauto.\n - rewrite <- MTGT. auto.\n\n - instantiate (1:=fd). inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto. i.\n setoid_rewrite FINDF in H2. clarify.\n - econs.\n + econs; eauto.\n * unfold Pregmap.set. des_ifs.\n * unfold Pregmap.set. des_ifs. unfold src_junk_val. des_ifs.\n * unfold Pregmap.set. des_ifs. unfold src_junk_val.\n assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs RA)).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify. }\n clear - RADEF JUNK.\n unfold JunkBlock.is_junk_value, Mem.valid_block in *. des_ifs; des; eauto.\n + econs; ss. ii. congruence.\n + { unfold to_pregset, set_regset, Pregmap.set. ii.\n rewrite to_preg_to_mreg in *. des_ifs.\n + apply f_equal with (f:=to_mreg) in e.\n rewrite to_preg_to_mreg in e. ss.\n + apply f_equal with (f:=to_mreg) in e.\n rewrite to_preg_to_mreg in e. ss.\n + unfold set_regset_junk in *. des_ifs.\n * assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs (to_preg r))).\n { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify.\n erewrite to_preg_to_mreg in MR. clarify.\n eapply Loc.notin_not_in; eauto. }\n unfold src_junk_val in *. des_ifs_safe.\n unfold JunkBlock.is_junk_value in *.\n unfold to_mregset in *. rewrite Heq in *.\n unfold Mem.valid_block in *. exfalso. des. des_ifs.\n * erewrite loc_notin_not_in in n3. apply NNPP in n3.\n apply loc_args_callee_save_disjoint in n3. exfalso. eauto. }\n + ss.\n - unfold Genv.find_funct, Genv.find_funct_ptr, Genv.find_def. des_ifs.\n eapply Genv.genv_defs_range in Heq0. exfalso. eapply RANOTFPTR; eauto.\n - unfold Pregmap.set. des_ifs. ii. clarify. rewrite MINJ. rewrite INJ.\n unfold junk_inj, update_meminj. des_ifs; eauto. }\n }\n { ss. inv INITTGT; clarify. ss.\n hexploit (assign_junk_blocks_parallel n); eauto. i. des.\n\n eexists (AsmC.mkstate\n (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))\n (Asm.State\n (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))\n (SimMemInj.src sm1))).\n esplits; eauto.\n - econs 2; ss; eauto.\n + inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto.\n * eapply RS.\n * i. setoid_rewrite FINDF in H. clarify.\n + unfold Pregmap.set. des_ifs. unfold src_junk_val.\n des_ifs; split; ss; eauto; des; clarify.\n + unfold src_junk_val. des_ifs. i. clarify. ii. apply n0.\n assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm_arg) - Mem.nextblock (SimMemInj.tgt sm_arg)) (Mem.nextblock (SimMemInj.src sm_arg))).\n { eapply Plt_Ple_trans; eauto.\n inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.\n rewrite NBSRC. etrans; eauto. }\n exfalso. eapply Plt_lemma; eauto.\n + rewrite MSRC. eapply src_junk_val_junk; eauto.\n - instantiate (1:=SimMemInjInv.mk sm1 _ _). econs; ss.\n - cinv MWF. econs; eauto; simpl.\n + eapply AsmStepInj.agree_step; eauto.\n * eapply agree_incr; try apply RS; eauto.\n rewrite MINJ. eapply junk_inj_incr; eauto.\n * rewrite MINJ. eapply src_junk_val_inj; eauto.\n + eapply AsmStepInj.agree_step; eauto.\n * eapply agree_incr; try apply RS; eauto.\n rewrite MINJ. eapply junk_inj_incr; eauto.\n * rewrite MINJ. eapply src_junk_val_inj; eauto.\n + hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv SimMemInjInv.top_inv sm_arg sm1); eauto.\n + rewrite Pregmap.gso; clarify.\n inv SAFESRC; clarify. ss. des.\n exploit match_globals_find_funct; eauto.\n * eapply RS.\n * i. setoid_rewrite FINDF in H. clarify. eauto.\n + econs 2; eauto.\n * unfold src_junk_val. econs; eauto; rewrite Pregmap.gss.\n { des_ifs. }\n { des_ifs; clarify; ss; des; clarify. }\n * econs; eauto; rewrite Pregmap.gss.\n + rewrite Pregmap.gss. unfold Genv.find_funct, Genv.find_funct_ptr. des_ifs.\n eapply Genv.genv_defs_range in Heq. exfalso. eapply RANOTFPTR; eauto.\n + i. des. clarify. }\n\n - (** ******************* safe **********************************)\n exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH. des.\n inv SAFESRC.\n { inv TYP. inv SIMARGS; clarify. ss.\n eapply asm_initial_frame_succeed; eauto.\n + apply inject_list_length in VALS.\n transitivity (Datatypes.length vs_src); eauto.\n + exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto.\n i. des. inv WFSRC. eapply WFPARAM in H; eauto.\n + exploit match_globals_find_funct; eauto. }\n { inv SIMARGS; clarify. ss.\n eapply asm_initial_frame_succeed_asmstyle; eauto.\n exploit match_globals_find_funct; eauto. eapply RS. }\n\n - inv MATCH. ss.\n\n - (** ******************* at external **********************************)\n inv SIMSKENV. inv CALLSRC.\n { inv MATCH.\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n des; ss; clarify. des_ifs.\n set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.\n assert (delta = 0).\n { clear EXTERNAL. rewrite <- H0 in *. ss.\n unfold Genv.find_funct_ptr in *. des_ifs.\n inv SIMSKELINK. exploit SIMDEF; eauto. i. des. eauto. }\n clarify. psimpl. ss.\n exploit extcall_arguments_inject; eauto.\n { inv MWF. eauto. }\n i. des. cinv (AGREE Asm.RSP); rewrite RSP in *; clarify.\n\n exploit SimMemInjC.Mem_free_parallel'; eauto. i. des.\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv SimMemInjInv.top_inv sm0 sm1); eauto.\n\n eexists (Args.mk (Vptr b2 _) _ _). eexists (SimMemInjInv.mk sm1 _ _).\n esplits; eauto; ss; i.\n + econs; auto.\n * eauto.\n * rewrite <- H0 in *. ss. exploit SimSymbDropInv_find_None; try eassumption.\n { unfold Genv.find_funct. des_ifs. eauto. }\n { clarify. }\n { ii. des_ifs. }\n * rewrite <- H0 in *. esplits; eauto. inv SIMSKELINK.\n unfold Genv.find_funct, Genv.find_funct_ptr in *. ss.\n clear RAWF EXTERNAL. des_ifs_safe.\n exploit SIMDEF; try apply Heq1; eauto. i. des. clarify.\n rewrite DEFTGT. eauto.\n * clear - AGREE TPTR RADEF. splits.\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n * eauto.\n * eauto.\n * destruct (zlt 0 (size_arguments sg)).\n { inv MWF. exploit Mem.mi_representable; eauto.\n - right.\n instantiate (1:=Ptrofs.add ofs (Ptrofs.repr (4 * size_arguments sg))).\n eapply Mem.perm_cur.\n eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].\n rewrite unsigned_add.\n + clear - ARGSRANGE l. lia.\n + clear- ARGSRANGE. set (size_arguments_above sg).\n set (Ptrofs.unsigned_range_2 ofs). lia.\n - repeat rewrite unsigned_add. i. des.\n + lia.\n + exploit Mem.mi_representable; eauto. left. eapply Mem.perm_cur.\n eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].\n clear - ARGSRANGE l. lia.\n + clear - ARGSRANGE.\n set (size_arguments_above sg).\n set (Ptrofs.unsigned_range_2 ofs). lia. }\n { set (Ptrofs.unsigned_range_2 (Ptrofs.add ofs (Ptrofs.repr delta))). lia. }\n * inv MWF. i. erewrite Mem.address_inject; eauto; cycle 1.\n { eapply Mem.free_range_perm; eauto.\n set (size_chunk_pos chunk). lia. }\n eapply Z.divide_add_r; eauto.\n inv PUBLIC. inv mi_inj. exploit mi_align; eauto.\n eapply Mem.free_range_perm in FREE.\n intros ofs0 RANGE. exploit FREE; eauto.\n -- instantiate (1:=ofs0). instantiate (1:=Ptrofs.unsigned ofs) in RANGE. nia.\n -- i. eapply Mem.perm_cur_max. eapply Mem.perm_implies; eauto. econs.\n * eauto.\n + inv MLE. econs; s; eauto. rewrite H0. rewrite H1. eauto.\n }\n { ss. inv MATCH.\n des; ss; clarify. des_ifs.\n set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.\n assert (delta = 0).\n { clear EXTERNAL. rewrite <- H0 in *. ss.\n unfold Genv.find_funct_ptr in *. des_ifs.\n inv SIMSKELINK. exploit SIMDEF; eauto. i. des. eauto. } clarify. psimpl. ss.\n exists (Args.Asmstyle rs_tgt (SimMemInj.tgt sm0.(SimMemInjInv.minj))). esplits; eauto.\n - econs 2; eauto.\n + exploit SimSymbDropInv_find_None; try eassumption.\n { ii. rewrite H in *. ss. }\n { unfold Genv.find_funct. des_ifs. }\n + rewrite <- H0 in *. esplits; eauto. inv SIMSKELINK.\n unfold Genv.find_funct, Genv.find_funct_ptr in *. ss.\n clear RAWF EXTERNAL. des_ifs_safe.\n exploit SIMDEF; try apply Heq1; eauto. i. des. clarify.\n rewrite DEFTGT. eauto.\n + clear - AGREE TPTR RADEF. splits.\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n { rename TPTR into TPTR0. unfold Tptr in *.\n des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }\n - econs 2; eauto.\n - refl. }\n\n - (** ******************* after external **********************************)\n exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } instantiate (1:=asm). intros GEMATCH.\n inv MATCH. inv AFTERSRC.\n { inv SIMRET; clarify. inv HISTORY; clarify.\n inv CALLSRC; clarify; cycle 1.\n { ss. des. clarify. }\n inv CALLTGT; clarify; cycle 1.\n { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify.\n rewrite RSRSP in *. des. ss. des_ifs. clarify.\n cinv (AGREE Asm.RSP); rewrite RSRSP in *; ss; clarify; rewrite RSP0 in *; clarify.\n\n assert (SKD: skd1 = skd).\n { inv SIMSKENV. inv SIMSKELINK. ss.\n clear - AGREE FPTR SIG0 SIG1 SIG2 SIG3 SIMDEFINV.\n cinv (AGREE PC); rewrite <- H1 in *; clarify. rewrite <- H0 in *. ss.\n unfold Genv.find_funct_ptr in *. des_ifs.\n exploit SIMDEFINV; eauto. i. des. clarify. } clarify.\n\n hexploit (@Mem_unfree_parallel SimMemInjInv.top_inv sm0 sm_arg sm_ret); eauto.\n\n i. des. esplits; eauto. i.\n esplits; ss; eauto.\n\n + econs; ss; eauto.\n + dup MLE2. rename MLE4 into MINVLE2.\n destruct MLE2 as [MLE2 MINVEQSRC2 MINVEQTGT2].\n econs; try refl; eauto.\n * clarify. inv MLE2. ii.\n unfold set_pair, Pregmap.set, loc_external_result, map_rpair.\n des_ifs; ss; eauto.\n { rewrite MINJ. eauto. }\n { unfold regset_after_external. des_ifs; ss; eauto. }\n { rewrite MINJ. eapply Val.loword_inject. eauto. }\n { rewrite MINJ. eapply Val.hiword_inject. eauto. }\n { unfold regset_after_external. des_ifs; ss; eauto. }\n * inv MLE2. eapply agree_incr; eauto.\n * inv MLE2. i. exploit RSPDELTA; eauto. i. des. esplits; eauto.\n }\n { inv SIMRET; clarify. inv HISTORY; clarify.\n inv CALLSRC; clarify.\n { ss. des. clarify. }\n inv CALLTGT; clarify.\n { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify. ss.\n exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n eexists. eexists (AsmC.mkstate _ (Asm.State _ _)). esplits; eauto.\n - etrans; eauto.\n - clear - MLE0. inv MLE0. inv MLE. ss. econs; ss; eauto. eapply SimMemInj.frozen_refl.\n - i. esplits; eauto.\n + econs 2; eauto.\n + exploit SimMemInjInvC.unlift_wf; try apply MLE0; eauto. i. inv MLE2.\n cinv MLE3. ss.\n econs; try apply H; auto; eauto.\n * eapply AsmStepInj.agree_step; eauto.\n * eapply AsmStepInj.agree_incr; eauto.\n * i. exploit RSPDELTA; eauto. i. des. eauto. }\n\n - (** ******************* final **********************************)\n\n exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n inv MATCH. inv FINALSRC.\n {\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.\n exploit SimMemInjC.Mem_free_parallel'; eauto.\n { instantiate (3:=Ptrofs.zero). zsimpl. psimpl. eauto. }\n i. des.\n hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv SimMemInjInv.top_inv sm0 sm1); eauto.\n\n assert (delta = 0).\n { rewrite FINDF in *. clarify. exploit RSPDELTA; eauto. i. des. clarify. }\n clarify. ss. zsimpl.\n\n esplits; ss; eauto.\n + cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.\n econs; ss; ii; eauto.\n * des. esplits; eauto.\n eapply match_globals_find_funct; eauto.\n * unfold external_state in *.\n des_ifs_safe. exfalso.\n cinv (AGREE PC); try rewrite Heq in *; clarify; eauto.\n { des_ifs. clear RANOTFPTR.\n unfold Genv.find_funct, Genv.find_funct_ptr in INITSIG, Heq2, Heq0.\n des_ifs_safe.\n unfold SkEnv.revive in *. ss.\n apply Genv_map_defs_def in Heq3. des.\n unfold o_bind, o_bind2, o_join, o_map, curry2, fst in MAP.\n des_ifs_safe.\n apply Genv.invert_find_symbol in Heq5.\n inv SIMSKENV. inv SIMSKE. ss.\n exploit SIMDEFINV; try apply FIND; eauto. i. des. clarify.\n exploit Genv_map_defs_def_inv; try apply DEFSRC.\n i. revert Heq2. rewrite H0.\n unfold o_bind, o_bind2, o_join, o_map, curry2, fst.\n erewrite Genv.find_invert_symbol.\n - rewrite Heq6; eauto. clarify.\n - exploit SIMSYMB3; eauto. i. des.\n rewrite BLKSRC. f_equal.\n exploit DISJ; eauto. }\n { rewrite <- H3 in *. inv WFINITRS; clarify. inv WFINITSRC. eauto. }\n * inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.\n unfold Val.has_type in TPTR. des_ifs.\n -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n -- ss. clear RANOTFPTR. des_ifs.\n cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n * specialize (CALLEESAVE _ H0).\n specialize (AGREEINIT (to_preg mr0)).\n specialize (AGREE (to_preg mr0)). inv WFINITRS; clarify.\n clear - CALLEESAVE AGREEINIT AGREE WFINITSRC WFINITTGT H0 UNDEF.\n inv WFINITSRC.\n eapply lessdef_commute; eauto.\n * cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify.\n cinv (AGREE RSP); rewrite RSRSP in *; clarify.\n + econs; ss. eapply val_inject_incr; cycle 1; eauto.\n inv MLE. eauto.\n + econs; ss; eauto.\n }\n { exists sm0. exists (Retv.Asmstyle rs_tgt sm0.(SimMemInjInv.minj).(SimMemInj.tgt)).\n esplits; ss; eauto.\n + econs 2; ss; ii; eauto.\n * des. esplits; eauto.\n eapply match_globals_find_funct; eauto.\n * unfold external_state in *.\n des_ifs_safe. exfalso.\n cinv (AGREE PC); try rewrite Heq in *; clarify; eauto.\n { des_ifs. clear RANOTFPTR.\n unfold Genv.find_funct, Genv.find_funct_ptr in INITSIG, Heq2, Heq0.\n des_ifs_safe.\n unfold SkEnv.revive in *. ss.\n apply Genv_map_defs_def in Heq3. des.\n unfold o_bind, o_bind2, o_join, o_map, curry2, fst in MAP.\n des_ifs_safe.\n apply Genv.invert_find_symbol in Heq4.\n inv SIMSKENV. inv SIMSKE. ss.\n exploit SIMDEFINV; try apply FIND; eauto. i. des. clarify.\n exploit Genv_map_defs_def_inv; try apply DEFSRC.\n i. revert Heq2. rewrite H.\n unfold o_bind, o_bind2, o_join, o_map, curry2, fst.\n erewrite Genv.find_invert_symbol.\n - rewrite Heq5; eauto. clarify.\n - exploit SIMSYMB3; eauto. i. des.\n rewrite BLKSRC. f_equal.\n exploit DISJ; eauto. }\n { rewrite <- H1 in *. ss. des. inv WFINITRS; clarify. inv WFINITSRC. eauto. }\n * des. des_ifs. clarify.\n inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.\n unfold Val.has_type in TPTR. des_ifs.\n -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n -- ss. clear RANOTFPTR. des_ifs.\n cinv (AGREEINIT RA); rewrite Heq in *; clarify.\n cinv (AGREE PC); rewrite RSRA in *; clarify.\n + econs 2; ss.\n + refl. }\n\n\n - (** ******************* step **********************************)\n left; i.\n esplits; ss; i.\n + apply AsmC.modsem_receptive.\n + exists O.\n { inv STEPSRC. destruct st_src0, st_src1. inv MATCH. ss.\n inv SIMSKENV. destruct st0. ss. clarify.\n destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n dup MWF. rename MWF0 into MINVWF.\n destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.\n\n exploit asm_step_preserve_injection; eauto.\n { exploit SimSymbDropInv_match_globals; eauto.\n intros MATCH. inv MATCH. econs; ss; i; eauto.\n exploit DEFLE; eauto. i. des. clarify. esplits; eauto. }\n { eapply symbols_inject_weak_imply.\n exploit SimSymbDropInv.sim_skenv_symbols_inject; eauto. }\n { cinv MWF. eauto. }\n\n i. des.\n eexists (AsmC.mkstate init_rs_tgt (Asm.State _ _)).\n\n exploit SimMemInjC.parallel_gen; eauto.\n { ii. eapply asm_step_max_perm; eauto. }\n { ii. eapply asm_step_max_perm; eauto. }\n i. des.\n hexploit SimMemInjInv.le_inj_wf_wf; eauto. intros MWFINV0.\n eexists (SimMemInjInv.mk _ _ _).\n\n esplits; eauto.\n - left. econs; cycle 1.\n + apply star_refl.\n + symmetry. apply E0_right.\n + econs.\n * apply AsmC.modsem_determinate.\n * econs; ss; eauto.\n - econs; ss; eauto.\n - econs; ss; eauto.\n + eapply agree_incr; eauto.\n + i. exploit RSPDELTA; eauto. i. des. esplits; eauto.\n }\nQed.\n\nEnd INJINV.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/demo/unreadglob/IdSimAsmDropInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.23651624720889433, "lm_q1q2_score": 0.14106612946550276}} {"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import ReorderStep.\nRequire Import ProgressStep.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive reorder_update r1 l1 rmw1 or1 ow1: forall (i2:Instr.t), Prop :=\n| reorder_update_load\n r2 l2 o2\n (ORDW1: Ordering.le ow1 Ordering.relaxed)\n (ORD2: Ordering.le o2 Ordering.relaxed)\n (LOC: l1 <> l2)\n (REGS: RegSet.disjoint (Instr.regs_of (Instr.update r1 l1 rmw1 or1 ow1))\n (Instr.regs_of (Instr.load r2 l2 o2))):\n reorder_update r1 l1 rmw1 or1 ow1 (Instr.load r2 l2 o2)\n| reorder_update_store\n l2 v2 o2\n (ORDW1: Ordering.le ow1 Ordering.relaxed)\n (ORD2: Ordering.le or1 Ordering.acqrel \\/ Ordering.le o2 Ordering.acqrel)\n (LOC: l1 <> l2)\n (REGS: RegSet.disjoint (Instr.regs_of (Instr.update r1 l1 rmw1 or1 ow1))\n (Instr.regs_of (Instr.store l2 v2 o2))):\n reorder_update r1 l1 rmw1 or1 ow1 (Instr.store l2 v2 o2)\n| reorder_update_update\n r2 l2 rmw2 or2 ow2\n (ORDW1: Ordering.le ow1 Ordering.relaxed)\n (ORDR2: Ordering.le or2 Ordering.relaxed)\n (ORDW2: Ordering.le or1 Ordering.acqrel \\/ Ordering.le ow2 Ordering.acqrel)\n (LOC: l1 <> l2)\n (REGS: RegSet.disjoint (Instr.regs_of (Instr.update r1 l1 rmw1 or1 ow1))\n (Instr.regs_of (Instr.update r2 l2 rmw2 or2 ow2))):\n reorder_update r1 l1 rmw1 or1 ow1 (Instr.update r2 l2 rmw2 or2 ow2)\n.\n\nInductive sim_update: forall (st_src:lang.(Language.state)) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n (st_tgt:lang.(Language.state)) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_update_intro\n r1 l1 from1 to1 vr1 vret1 vw1 releasedr1 releasedw1 rmw1 or1 ow1 i2 rs\n lc1_src sc1_src mem1_src\n lc1_tgt sc1_tgt mem1_tgt\n lc2_src\n lc3_src sc3_src\n (RMW: RegFile.eval_rmw rs rmw1 vr1 = (vret1, vw1))\n (REORDER: reorder_update r1 l1 rmw1 or1 ow1 i2)\n (READ: Local.read_step lc1_src mem1_src l1 from1 vr1 releasedr1 or1 lc2_src)\n (FULFILL: match vw1 with \n | Some val => fulfill_step lc2_src sc1_src l1 from1 to1 val releasedr1 releasedw1 ow1 lc3_src sc3_src \n | None => lc3_src = lc2_src /\\ sc3_src = sc1_src\n end)\n (LOCAL: sim_local lc3_src lc1_tgt)\n (SC: TimeMap.le sc3_src sc1_tgt)\n (MEMORY: sim_memory mem1_src mem1_tgt)\n (WF_SRC: Local.wf lc1_src mem1_src)\n (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n (MEM_SRC: Memory.closed mem1_src)\n (MEM_TGT: Memory.closed mem1_tgt):\n sim_update\n (State.mk rs [Stmt.instr i2; Stmt.instr (Instr.update r1 l1 rmw1 or1 ow1)]) lc1_src sc1_src mem1_src\n (State.mk (RegFun.add r1 vret1 rs) [Stmt.instr i2]) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_update_mon\n st_src lc_src sc1_src mem1_src\n st_tgt lc_tgt sc1_tgt mem1_tgt\n sc2_src mem2_src\n sc2_tgt mem2_tgt\n (SIM1: sim_update st_src lc_src sc1_src mem1_src\n st_tgt lc_tgt sc1_tgt mem1_tgt)\n (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n (MEM_FUTURE_TGT: Memory.future mem1_tgt mem2_tgt)\n (SC1: TimeMap.le sc2_src sc2_tgt)\n (MEM1: sim_memory mem2_src mem2_tgt)\n (WF_SRC: Local.wf lc_src mem2_src)\n (WF_TGT: Local.wf lc_tgt mem2_tgt)\n (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n (SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt)\n (MEM_SRC: Memory.closed mem2_src)\n (MEM_TGT: Memory.closed mem2_tgt):\n sim_update st_src lc_src sc2_src mem2_src\n st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n inv SIM1.\n exploit Local.read_step_future; eauto. i. des.\n exploit future_read_step; try exact READ; eauto. i. des.\n exploit Local.read_step_future; eauto. i. des.\n destruct vw1 as [vw1|]; cycle 1.\n { ss; des; subst. econs; [eauto|..]; s; eauto; etrans; eauto. }\n exploit future_fulfill_step; try exact FULFILL; eauto.\n { by inv REORDER. }\n i. des.\n exploit sim_local_fulfill; try apply x0; try exact LOCAL0; try refl;\n try exact WF0; try by viewtac.\n { econs.\n - apply WF2.\n - eapply TView.future_closed; eauto. apply WF2.\n - inv READ. apply WF_SRC.\n - apply WF2.\n }\n i. des.\n econs; [eauto|..]; s; eauto; etrans; eauto.\nGrab Existential Variables.\n{ econs 2. }\n{ econs. econs 3. }\nQed.\n\nLemma sim_update_future\n st_src lc_src sc1_src mem1_src\n st_tgt lc_tgt sc1_tgt mem1_tgt\n sc2_src mem2_src\n (SC1: TimeMap.le sc1_src sc1_tgt)\n (MEM1: sim_memory mem1_src mem1_tgt)\n (SIM1: sim_update st_src lc_src sc1_src mem1_src\n st_tgt lc_tgt sc1_tgt mem1_tgt)\n (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n (WF_SRC: Local.wf lc_src mem2_src)\n (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n (MEM_SRC: Memory.closed mem2_src):\n exists lc'_src sc2_tgt mem2_tgt,\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <> /\\\n <>.\nProof.\n inv SIM1.\n destruct vw1 as [vw1|]; cycle 1.\n { ss. des. subst.\n exploit future_read_step; try exact READ; eauto. i. des.\n exploit SimPromises.future; try apply MEM1; eauto.\n { inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite <- PROMISES.\n inv READ. ss. apply SimPromises.sem_bot.\n }\n i. des. \n\n esplits.\n - etrans.\n + apply Memory.max_timemap_spec; eauto. viewtac.\n + apply sim_memory_max_timemap; eauto.\n - eauto.\n - etrans.\n + apply Memory.max_timemap_spec; eauto. viewtac.\n + apply Memory.future_max_timemap; eauto.\n - auto.\n - auto.\n - apply Memory.max_timemap_closed. viewtac.\n - auto.\n - econs; [eauto|..]; s; eauto.\n + etrans; eauto.\n + etrans.\n * apply Memory.max_timemap_spec; eauto. viewtac.\n * apply sim_memory_max_timemap; eauto.\n + apply Memory.max_timemap_closed. viewtac.\n }\n\n exploit Local.read_step_future; eauto. i. des.\n exploit fulfill_step_future; eauto; try by viewtac. i. des.\n exploit future_read_step; try exact READ; eauto. i. des.\n exploit Local.read_step_future; eauto. i. des.\n exploit future_fulfill_step; try exact FULFILL; eauto; try refl; try by viewtac.\n { by inv REORDER. }\n i. des.\n exploit fulfill_step_future; try apply x0; try exact WF1; eauto; try by viewtac.\n { econs.\n - apply WF2.\n - eapply TView.future_closed; eauto. apply WF2.\n - inv READ. apply WF_SRC.\n - apply WF2.\n }\n i. des.\n exploit sim_local_fulfill; try exact x0; try exact LOCAL0; try refl; eauto.\n { econs.\n - apply WF2.\n - eapply TView.future_closed; eauto. apply WF2.\n - inv READ. apply WF_SRC.\n - apply WF2.\n }\n i. des.\n exploit fulfill_step_future; eauto. i. des.\n exploit SimPromises.future; try apply MEM1; eauto.\n { inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite <- PROMISES.\n apply SimPromises.sem_bot.\n }\n i. des. esplits.\n - etrans.\n + apply Memory.max_timemap_spec; eauto. viewtac.\n + apply sim_memory_max_timemap; eauto.\n - eauto.\n - etrans.\n + apply Memory.max_timemap_spec; eauto. viewtac.\n + apply Memory.future_max_timemap; eauto.\n - auto.\n - auto.\n - apply Memory.max_timemap_closed. viewtac.\n - auto.\n - econs; [eauto|..]; s; eauto.\n + etrans; eauto.\n + etrans.\n * apply Memory.max_timemap_spec; eauto. viewtac.\n * apply sim_memory_max_timemap; eauto.\n + apply Memory.max_timemap_closed. viewtac.\nGrab Existential Variables.\n{ econs 2. }\n{ econs. econs 3. }\nQed.\n\nLemma sim_update_step\n st1_src lc1_src sc1_src mem1_src\n st1_tgt lc1_tgt sc1_tgt mem1_tgt\n (SIM: sim_update st1_src lc1_src sc1_src mem1_src\n st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n _sim_thread_step lang lang ((sim_thread (sim_terminal eq)) \\8/ sim_update)\n st1_src lc1_src sc1_src mem1_src\n st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n inv SIM. ii.\n exploit Local.read_step_future; eauto. i. des.\n destruct vw1 as [vw1|]; cycle 1.\n { ss. des. subst.\n inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n try (inv STATE; inv INSTR; inv REORDER); ss.\n - (* promise *)\n exploit Local.promise_step_future; eauto. i. des.\n exploit sim_local_promise; eauto. i. des.\n exploit reorder_read_promise; try exact READ; try exact STEP_SRC; eauto. i. des.\n exploit Local.promise_step_future; eauto. i. des.\n esplits; try apply SC; eauto.\n + econs 2. econs. econs; eauto.\n + eauto.\n + right. econs; [eauto|..]; s; eauto. etrans; eauto.\n - (* load *)\n exploit sim_local_read; (try by etrans; eauto); eauto; try refl. i. des.\n exploit reorder_read_read; try exact READ; try exact STEP_SRC; try by eauto. i. des.\n esplits.\n + econs 2; [|econs 1]. econs.\n * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n * eauto.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n * apply RegFile.eq_except_singleton.\n * ii. eapply REGS; eauto.\n apply RegSet.add_spec. auto.\n + eauto.\n + eauto.\n + eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n apply RegFun.add_add. ii. subst. eapply REGS; cycle 1.\n * apply RegSet.singleton_spec. eauto.\n * apply RegSet.add_spec. auto.\n - (* update-load *)\n guardH ORDW2.\n exploit sim_local_read; (try by etrans; eauto); eauto; try refl. i. des.\n exploit reorder_read_read; try exact READ; try exact STEP_SRC; try by eauto. i. des.\n esplits.\n + econs 2; [|econs 1]. econs.\n * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n erewrite <- RegFile.eq_except_rmw; eauto; try apply RegFile.eq_except_singleton.\n ii. eapply REGS; eauto.\n { eapply RegSet.add_spec. left. apply RegSet.singleton_spec. eauto. }\n { eapply RegSet.add_spec. eauto. }\n * eauto.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n * apply RegFile.eq_except_singleton.\n * ii. eapply REGS; eauto.\n { eapply RegSet.add_spec. right. eauto. }\n { eapply RegSet.add_spec. left. apply RegSet.singleton_spec. eauto. }\n + eauto.\n + eauto.\n + eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n apply RegFun.add_add. ii. subst. eapply REGS.\n * apply RegSet.add_spec. left. eauto.\n * apply RegSet.add_spec. left. eauto.\n - (* store *)\n guardH ORD2.\n hexploit sim_local_write; try exact LOCAL1; try exact SC;\n try exact WF2; try refl; eauto; try by viewtac. i. des.\n exploit reorder_read_write; try exact READ; try exact STEP_SRC; eauto; try by viewtac. i. des.\n esplits.\n + econs 2; [|econs 1]. econs.\n * econs. econs 2. econs; [|econs 3]; eauto. econs.\n s. erewrite RegFile.eq_except_value; eauto. econs.\n ii. apply RegFun.add_spec_neq. ii. subst. apply REG.\n eapply RegSet.add_spec. auto.\n * eauto.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs. econs. eauto.\n + eauto.\n + eauto.\n + etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss. etrans; eauto.\n - (* update *)\n guardH ORDW2.\n exploit Local.read_step_future; try exact LOCAL1; eauto. i. des.\n exploit sim_local_read; try exact LOCAL1; eauto; try refl. i. des.\n exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n hexploit sim_local_write; try exact LOCAL2; try exact SC; eauto; try refl. i. des.\n exploit reorder_read_read; try exact READ; try exact STEP_SRC; eauto; try congr. i. des.\n exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n exploit reorder_read_write; try exact STEP2; try exact STEP_SRC0; eauto; try congr. i. des.\n esplits.\n + econs 2; [|econs 1]. econs.\n * econs. econs 2. econs; [|econs 4]; eauto. econs. econs.\n erewrite <- RegFile.eq_except_rmw; eauto; try apply RegFile.eq_except_singleton.\n ii. eapply REGS; eauto.\n { eapply RegSet.add_spec. left. apply RegSet.singleton_spec. eauto. }\n { eapply RegSet.add_spec. eauto. }\n * eauto.\n + econs 2. econs 2. econs; [|econs 2]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; cycle 2.\n * apply RegFile.eq_except_singleton.\n * eauto.\n * ii. apply RegSet.singleton_spec in LHS. subst.\n eapply REGS; eauto.\n { eapply RegSet.add_spec. right. eauto. }\n { eapply RegSet.add_spec. eauto. }\n + eauto.\n + eauto.\n + etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n * apply RegFun.add_add. ii. subst. eapply REGS.\n { apply RegSet.add_spec. left. eauto. }\n { apply RegSet.add_spec. left. eauto. }\n * etrans; eauto.\n } \n\n exploit fulfill_step_future; eauto. i. des.\n inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n try (inv STATE; inv INSTR; inv REORDER); ss.\n - (* promise *)\n exploit Local.promise_step_future; eauto. i. des.\n exploit sim_local_promise; try apply LOCAL0; (try by etrans; eauto); eauto. i. des.\n exploit reorder_update_promise; try exact READ; try exact FULFILL; try exact STEP_SRC; eauto. i. des.\n exploit Local.promise_step_future; eauto. i. des.\n esplits.\n + eauto.\n + econs 2. econs 1. econs; eauto.\n + auto.\n + etrans; eauto.\n + auto.\n + right. econs; [eauto|..]; s; eauto.\n * etrans; eauto.\n * etrans; eauto.\n * eapply Memory.future_closed_timemap; eauto.\n - (* load *)\n apply RegSet.disjoint_add in REGS. des.\n exploit sim_local_read; try apply LOCAL0; (try by etrans; eauto); eauto; try refl. i. des.\n exploit reorder_update_read; try exact FULFILL; try exact READ; try exact STEP_SRC; eauto. i. des.\n exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n exploit fulfill_write; eauto. i. des.\n esplits.\n + econs 2; eauto. econs.\n * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n * auto.\n + econs 2. econs 2. econs; [|econs 4]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n * apply RegFile.eq_except_singleton.\n * symmetry. eauto.\n + auto.\n + auto.\n + etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n apply RegFun.add_add. ii. subst. eapply REGS.\n apply RegSet.Facts.singleton_iff. auto.\n - (* update-load *)\n guardH ORDW2.\n apply RegSet.disjoint_add in REGS. des.\n exploit sim_local_read; try apply LOCAL0; (try by etrans; eauto); eauto; try refl. i. des.\n exploit reorder_update_read; try exact FULFILL; try exact READ; try exact STEP_SRC; eauto. i. des.\n exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n exploit fulfill_write; eauto. i. des.\n esplits.\n + econs 2; eauto. econs.\n * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n { symmetry. apply RegFile.eq_except_singleton. }\n { ii. apply RegSet.singleton_spec in LHS. subst. contradict REGS. apply RegSet.add_spec. auto. }\n * auto.\n + econs 2. econs 2. econs; [|econs 4]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n * apply RegFile.eq_except_singleton.\n * ii. apply RegSet.singleton_spec in LHS. subst. \n eapply REGS0; eauto. apply RegSet.add_spec. auto.\n + auto.\n + auto.\n + etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n apply RegFun.add_add. ii. subst. \n eapply REGS. apply RegSet.add_spec. auto. \n - (* store *)\n guardH ORD2.\n apply RegSet.disjoint_add in REGS. des.\n hexploit sim_local_write; try exact LOCAL1; try exact LOCAL; try exact SC; try exact WF0; try refl; eauto; try by viewtac. i. des.\n hexploit reorder_update_write; try exact READ; try exact FULFILL; try exact STEP_SRC; eauto; try by viewtac.\n { ii. subst. inv FULFILL. eapply Time.lt_strorder. eauto. }\n i. des.\n exploit Local.write_step_future; try exact STEP1; eauto; try by viewtac. i. des.\n exploit Local.read_step_future; try exact STEP2; eauto; try by viewtac. i. des.\n exploit fulfill_write; eauto. i. des.\n esplits.\n + econs 2; eauto. econs.\n * econs. econs 2. econs; [|econs 3]; eauto. econs.\n erewrite RegFile.eq_except_value; cycle 2.\n { apply RegFile.eq_except_singleton. }\n { econs. }\n { ii. apply RegSet.singleton_spec in LHS. subst. congr. }\n * auto.\n + econs 2. econs 2. econs; [|econs 4]; eauto. econs. econs. eauto.\n + auto.\n + etrans; eauto.\n + etrans; eauto. etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n etrans; eauto.\n - (* update *)\n guardH ORDW2.\n apply RegSet.disjoint_add in REGS. des.\n symmetry in REGS0. apply RegSet.disjoint_add in REGS0. des.\n exploit fulfill_step_future; try exact FULFILL; eauto; try by viewtac. i. des.\n exploit Local.read_step_future; try exact LOCAL1; eauto; try by viewtac. i. des.\n exploit sim_local_read; try exact LOCAL1; (try by etrans; eauto); eauto; try refl. i. des.\n exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n hexploit sim_local_write; try exact LOCAL2; eauto; try refl; try by viewtac. i. des.\n hexploit ReorderStep.reorder_update_update; try exact FULFILL; try exact READ; try exact STEP_SRC0; eauto.\n { ii. subst. inv FULFILL. eapply Time.lt_strorder. eauto. }\n i. des.\n exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n exploit Local.write_step_future; try exact STEP2; eauto. i. des.\n exploit Local.read_step_future; try exact STEP3; eauto. i. des.\n exploit fulfill_write; eauto. i. des.\n esplits.\n + econs 2; eauto. econs.\n * econs. econs 2. econs; [|econs 4]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; eauto; cycle 1.\n { symmetry. apply RegFile.eq_except_singleton. }\n { ii. apply RegSet.singleton_spec in LHS. subst. contradict REGS. apply RegSet.add_spec. auto. }\n * auto.\n + econs 2. econs 2. econs; [|econs 4]; eauto. econs. econs.\n erewrite RegFile.eq_except_rmw; cycle 2.\n * apply RegFile.eq_except_singleton.\n * eauto.\n * ii. apply RegSet.singleton_spec in LHS. subst. congr.\n + auto.\n + etrans; eauto.\n + etrans; eauto. etrans; eauto.\n + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n * apply RegFun.add_add. ii. subst. apply REGS. apply RegSet.add_spec. auto.\n * etrans; eauto.\nGrab Existential Variables.\n{ econs 2. }\n{ econs. econs 3. }\nQed.\n\nLemma sim_update_sim_thread:\n sim_update <8= (sim_thread (sim_terminal eq)).\nProof.\n pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n - inv TERMINAL_TGT. inv PR; ss.\n - exploit sim_update_mon; eauto. i.\n exploit sim_update_future; try apply x0; eauto. i. des.\n esplits; eauto.\n - exploit sim_update_mon; eauto. i.\n inversion x0. subst. i.\n exploit (progress_program_step (RegFun.add r1 (fst (RegFile.eval_rmw rs rmw1 vr1)) rs) i2 nil); eauto. i. des.\n destruct th2. exploit sim_update_step; eauto.\n { rewrite RMW in *. ss. econs 2. eauto. }\n i. des.\n + exploit program_step_promise; eauto. i.\n exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n exploit Thread.opt_step_future; eauto. s. i. des.\n exploit Thread.program_step_future; eauto. s. i. des.\n punfold SIM. exploit SIM; try apply SC3; eauto; try refl. s. i. des.\n exploit PROMISES; eauto. i. des.\n esplits; [|eauto].\n\t etrans; eauto. etrans; [|eauto].\n inv STEP_SRC; eauto. econs 2; eauto. econs.\n * econs. eauto.\n * etrans; eauto.\n destruct e; by inv STEP; inv STATE; inv INSTR; inv REORDER.\n + inv SIM. inv STEP; inv STATE.\n - exploit sim_update_mon; eauto. i. des.\n exploit sim_update_step; eauto. i. des.\n + esplits; eauto.\n left. eapply paco9_mon; eauto. ss.\n + esplits; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/ReorderUpdate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.23934934732271168, "lm_q1q2_score": 0.14095023254858052}} {"text": "Require Import Sail.Base.\nRequire Import String.\nRequire Import List.\nRequire Import Lia.\nImport List.ListNotations.\nOpen Scope Z.\n\nDefinition MEMr {regval a e} (addr : mword a) size `{ArithFact (size >=? 0)} : monad regval (mword (8 * size)) e := read_mem Read_plain a addr size.\nDefinition MEMr_reserve {regval a e} (addr : mword a) size `{ArithFact (size >=? 0)} : monad regval (mword (8 * size)) e := read_mem Read_reserve a addr size.\nDefinition MEM_sync {rv e} (_:unit) : monad rv unit e := barrier (Barrier_MIPS_SYNC tt).\n\nDefinition MEMr_tagged {rv a e} (addr : mword a) size (allowTag : bool) `{ArithFact (size >? 0)} : monad rv (bool * mword (size * 8)) e :=\n (if allowTag then\n read_memt Read_plain addr size\n else\n (read_mem Read_plain a addr size >>= fun v => returnm (v, B0))) >>= fun '(v, t) =>\n maybe_fail \"bool_of_bitU\" (bool_of_bitU t) >>= fun t =>\n returnm (t, v).\n\nDefinition MEMr_tagged_reserve {rv a e} (addr : mword a) size (allowTag : bool) `{ArithFact (size >? 0)} : monad rv (bool * mword (size * 8)) e :=\n (if allowTag then\n read_memt Read_plain addr size\n else\n (read_mem Read_plain a addr size >>= fun v => returnm (v, B0))) >>= fun '(v, t) =>\n maybe_fail \"bool_of_bitU\" (bool_of_bitU t) >>= fun t =>\n returnm (t, v).\n\nDefinition MEMea {regval a e} (addr : mword a) size : monad regval unit e := write_mem_ea Write_plain a addr size.\nDefinition MEMea_conditional {regval a e} (addr : mword a) size : monad regval unit e := write_mem_ea Write_conditional a addr size.\n\nDefinition MEMval {regval a e} (addr : mword a) (size : Z) (v : mword (8 * size)) : monad regval unit e := write_mem Write_plain a addr size v >>= fun _ => returnm tt.\nDefinition MEMval_conditional {regval a e} (addr : mword a) (size : Z) (v : mword (8 * size)) : monad regval bool e := write_mem Write_conditional a addr size v.\n\nDefinition MEMval_tagged {rv a e} (addr : mword a) size t (v : mword (size * 8)) : monad rv unit e := write_memt Write_plain addr size v (bitU_of_bool t) >>= fun _ => returnm tt.\nDefinition MEMval_tagged_conditional {rv a e} (addr : mword a) size t (v : mword (size * 8)) :monad rv bool e := write_memt Write_conditional addr size v (bitU_of_bool t).\n\nDefinition MEMw_tagged {rv a e} (addr : mword a) size t (v : mword (size * 8)) : monad rv unit e := MEMea addr size >> MEMval_tagged addr size t v.\nDefinition MEMw_tagged_conditional {rv a e} (addr : mword a) size t (v : mword (size * 8)) : monad rv bool e := MEMea_conditional addr size >> MEMval_tagged_conditional addr size t v.\n\n(* Some wrappers copied from aarch64_extras *)\n(* TODO: Harmonise into a common library *)\n(*\nDefinition get_slice_int_bl len n lo :=\n (* TODO: Is this the intended behaviour? *)\n let hi := lo + len - 1 in\n let bs := bools_of_int (hi + 1) n in\n subrange_list false bs hi lo\n\nval get_slice_int : forall 'a. Bitvector 'a => integer -> integer -> integer -> 'a\nDefinition get_slice_int len n lo := of_bools (get_slice_int_bl len n lo)\n*)\nDefinition write_ram {rv e} m size (_ : mword m) (addr : mword m) (data : mword (8 * size)) : monad rv unit e :=\n MEMea addr size >>\n MEMval addr size data.\n\nDefinition read_ram {rv e} m size `{ArithFact (size >=? 0)} (_ : mword m) (addr : mword m) : monad rv (mword (8 * size)) e := MEMr addr size.\n(*\nDefinition string_of_bits bs := string_of_bv (bits_of bs).\nDefinition string_of_int := show\n\nDefinition _sign_extend bits len := maybe_failwith (of_bits (exts_bv len bits))\nDefinition _zero_extend bits len := maybe_failwith (of_bits (extz_bv len bits))\n*)\nDefinition shift_bits_left {rv e a b} (v : mword a) (n : mword b) : monad rv (mword a) e :=\n maybe_fail \"shift_bits_left\" (unsigned n) >>= fun n =>\n returnm (shiftl v n).\n\nDefinition shift_bits_right {rv e a b} (v : mword a) (n : mword b) : monad rv (mword a) e :=\n maybe_fail \"shift_bits_right\" (unsigned n) >>= fun n =>\n returnm (shiftr v n).\n\nDefinition shift_bits_right_arith {rv e a b} (v : mword a) (n : mword b) : monad rv (mword a) e :=\n maybe_fail \"shift_bits_right\" (unsigned n) >>= fun n =>\n returnm (arith_shiftr v n).\n\n(* Use constants for undefined values for now *)\nDefinition internal_pick {rv a e} (vs : list a) : monad rv a e :=\nmatch vs with\n| (h::_) => returnm h\n| _ => Fail \"empty list in internal_pick\"\nend.\nDefinition undefined_string {rv e} (_:unit) : monad rv string e := returnm \"\"%string.\nDefinition undefined_unit {rv e} (_:unit) : monad rv unit e := returnm tt.\nDefinition undefined_int {rv e} (_:unit) : monad rv Z e := returnm (0:ii).\n(*val undefined_vector : forall 'rv 'a 'e. integer -> 'a -> monad 'rv (list 'a) 'e*)\nDefinition undefined_vector {rv a e} len (u : a) `{ArithFact (len >=? 0)} : monad rv (vec a len) e := returnm (vec_init u len).\n(*val undefined_bitvector : forall 'rv 'a 'e. Bitvector 'a => integer -> monad 'rv 'a 'e*)\nDefinition undefined_bitvector {rv e} len `{ArithFact (len >=? 0)} : monad rv (mword len) e := returnm (mword_of_int 0).\n(*val undefined_bits : forall 'rv 'a 'e. Bitvector 'a => integer -> monad 'rv 'a 'e*)\nDefinition undefined_bits {rv e} := @undefined_bitvector rv e.\nDefinition undefined_bit {rv e} (_:unit) : monad rv bitU e := returnm BU.\n(*Definition undefined_real {rv e} (_:unit) : monad rv real e := returnm (realFromFrac 0 1).*)\nDefinition undefined_range {rv e} i j `{ArithFact (i <=? j)} : monad rv {z : Z & ArithFact (i <=? z <=? j)} e := returnm (build_ex i).\nDefinition undefined_atom {rv e} i : monad rv Z e := returnm i.\nDefinition undefined_nat {rv e} (_:unit) : monad rv Z e := returnm (0:ii).\n\nDefinition skip {rv e} (_:unit) : monad rv unit e := returnm tt.\n\n(*val elf_entry : unit -> integer*)\nDefinition elf_entry (_:unit) : Z := 0.\n(*declare ocaml target_rep function elf_entry := `Elf_loader.elf_entry`*)\n\n(*Definition print_bits msg bs := prerr_endline (msg ^ (string_of_bits bs))\n\nval get_time_ns : unit -> integer*)\nDefinition get_time_ns (_:unit) : Z := 0.\n(*declare ocaml target_rep function get_time_ns := `(fun () -> Big_int.of_int (int_of_float (1e9 *. Unix.gettimeofday ())))`*)\n\nDefinition eq_bit (x : bitU) (y : bitU) : bool :=\n match x, y with\n | B0, B0 => true\n | B1, B1 => true\n | BU, BU => true\n | _,_ => false\n end.\n\nRequire Import Zeuclid.\nDefinition euclid_modulo (m n : Z) `{ArithFact (n >? 0)} : {z : Z & ArithFact (0 <=? z <=? n-1)}.\nrefine (existT _ (ZEuclid.modulo m n) _).\nconstructor.\ndestruct H.\nunbool_comparisons; unbool_comparisons_goal.\nassert (Z.abs n = n). { rewrite Z.abs_eq; auto with zarith. }\nrewrite <- H at 3.\nlapply (ZEuclid.mod_always_pos m n); lia.\nQed.\n\n(* Override the more general version *)\n\nDefinition mults_vec {n} (l : mword n) (r : mword n) : mword (2 * n) := mults_vec l r.\nDefinition mult_vec {n} (l : mword n) (r : mword n) : mword (2 * n) := mult_vec l r.\n\n\nDefinition print_endline (_:string) : unit := tt.\nDefinition prerr_endline (_:string) : unit := tt.\nDefinition prerr_string (_:string) : unit := tt.\nDefinition putchar {T} (_:T) : unit := tt.\nRequire DecimalString.\nDefinition string_of_int z := DecimalString.NilZero.string_of_int (Z.to_int z).\n\nLemma __MIPS_read_lemma : forall width, 8 * width = 8 * (8 * width ÷ 8).\nintros.\nrewrite Z.mul_comm.\nrewrite Z.quot_mul; auto with zarith.\nQed.\nHint Resolve __MIPS_read_lemma : sail.\n\nLemma MEMr_wrapper_lemma : forall size : Z, 8 * size = 8 * (8 * (8 * size ÷ 8) ÷ 8).\nintros.\nrewrite Z.mul_comm.\nrewrite Z.quot_mul; auto with zarith.\nrewrite Z.mul_comm with (m := size).\nrewrite Z.quot_mul; auto with zarith.\nQed.\nHint Resolve MEMr_wrapper_lemma : sail.\n\nLemma getCapOffset_lemma {x0 x1 x2 x : Z} :\n 0 <= x0 <= 18446744073709551616 - 1 ->\n 0 <= x1 <= 18446744073709551616 - 1 ->\n 18446744073709551616 <= x2 <= 18446744073709551616 ->\n x = ZEuclid.modulo (x0 - x1) x2 ->\n 0 <= x <= 18446744073709551616 - 1.\nintros.\nmatch goal with H:context [ZEuclid.modulo ?X ?Y] |- _ => pose proof (ZEuclid.mod_always_pos X Y) end.\nlia.\nQed.\nHint Resolve getCapOffset_lemma : sail.\n\n", "meta": {"author": "CTSRD-CHERI", "repo": "sail-cheri-mips", "sha": "13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724", "save_path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips", "path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips/sail-cheri-mips-13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724/prover_snapshots/coq/cheri-mips-snapshot/mips_extras.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.14078845116941713}} {"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import strings gmap.\nFrom melocoton.mlanguage Require Import mlanguage.\nFrom iris.algebra Require Import stepindex.\n\nModule Link.\nSection Linking.\n Context {val : Type}.\n Context (public_state : Type).\n Context (Λ1 Λ2 : mlanguage val).\n Context {lk1: linkable Λ1 public_state}.\n Context {lk2: linkable Λ2 public_state}.\n\n Definition func : Type :=\n (Λ1.(func) + Λ2.(func)).\n\n Inductive simple_expr : Type :=\n (* The linked module produces a value\n (following one of the underlying modules producing a value) *)\n | ExprV (v : val)\n (* The linked module performs a call (corresponding to an external call\n performed by one of the underlying modules). This is not necessarily an\n external call of the linked module, it can correspond to a function\n implemented in the other linked module. *)\n | ExprCall (fn_name : string) (args : list val)\n (* Incoming call of one of the functions implemented by the linked module. It\n will be dispatched against the corresponding underlying module. *)\n | RunFunction (fn : func) (args : list val)\n (* Execution of code belonging to the first underlying module. *)\n | Expr1 (e : Λ1.(mlanguage.expr))\n (* Execution of code belonging to the second underlying module. *)\n | Expr2 (e : Λ2.(mlanguage.expr)).\n\n Definition cont : Type :=\n list (Λ1.(cont) + Λ2.(cont)).\n\n (* expr need to be wrapped in a fresh inductive for the language canonical\n structure to work when using WP *)\n Inductive expr : Type :=\n LkE (se: simple_expr) (k: cont).\n\n Definition private_state : Type :=\n (lk1.(private_state) * lk2.(private_state)).\n\n Inductive state : Type :=\n | St (pubσ : public_state)\n (privσ1 : lk1.(mlanguage.private_state))\n (privσ2 : lk2.(mlanguage.private_state))\n | St1 (σ1 : Λ1.(mlanguage.state)) (privσ2 : lk2.(mlanguage.private_state))\n | St2 (privσ1 : lk1.(mlanguage.private_state)) (σ2 : Λ2.(mlanguage.state)).\n\n Inductive split_state : state → public_state → private_state → Prop :=\n | LinkSplitSt pubσ privσ1 privσ2 :\n split_state (St pubσ privσ1 privσ2) pubσ (privσ1, privσ2).\n\n Definition of_val (v:val) : expr := LkE (ExprV v) [].\n Definition to_val (e:expr) : option val := match e with\n LkE (ExprV v) [] => Some v\n | _ => None end.\n\n Definition comp_cont (K1 K2 : cont) : cont :=\n K2 ++ K1.\n\n Definition resume_with (K : cont) (e : expr) : expr :=\n let 'LkE se k := e in\n LkE se (k ++ K).\n\n Definition apply_func (fn : func) (args : list val) : option expr :=\n Some (LkE (RunFunction fn args) []).\n\n Definition is_call e (fn_name:string) args C := e = LkE (ExprCall fn_name args) C.\n\n Local Notation prog := (gmap string func).\n\n Definition proj1_prog (p : prog) : mlanguage.prog Λ1 :=\n omap (λ fn, match fn with inl fn1 => Some fn1 | inr _ => None end) p.\n Definition proj2_prog (p : prog) : mlanguage.prog Λ2 :=\n omap (λ fn, match fn with inl _ => None | inr fn2 => Some fn2 end) p.\n\n Implicit Types X : expr * state → Prop.\n\n Inductive prim_step_mrel (p : prog) : expr * state → (expr * state → Prop) → Prop :=\n (* Internal step of an underlying module. *)\n | Step1S e1 C σ1 privσ2 (X1 X : _ → Prop) :\n mlanguage.to_val e1 = None →\n mlanguage.prim_step (proj1_prog p) (e1, σ1) X1 →\n (∀ e1' σ1',\n X1 (e1', σ1') →\n X (LkE (Expr1 e1') C, St1 σ1' privσ2)) →\n prim_step_mrel p (LkE (Expr1 e1) C, St1 σ1 privσ2) X\n | Step2S e2 C σ2 privσ1 (X2 X : _ → Prop) :\n mlanguage.to_val e2 = None →\n mlanguage.prim_step (proj2_prog p) (e2, σ2) X2 →\n (∀ e2' σ2',\n X2 (e2', σ2') →\n X (LkE (Expr2 e2') C, St2 privσ1 σ2')) →\n prim_step_mrel p (LkE (Expr2 e2) C, St2 privσ1 σ2) X\n (* Stuck module calls bubble up as calls at the level of the linking module.\n (They may get unstuck then, if they match a function implemented by the\n other module.) *)\n | MakeCall1S e1 C σ1 pubσ privσ1 privσ2 fn_name arg k1 X :\n mlanguage.is_call e1 fn_name arg k1 →\n proj1_prog p !! fn_name = None →\n mlanguage.split_state σ1 pubσ privσ1 →\n X (LkE (ExprCall fn_name arg) (inl k1 :: C), St pubσ privσ1 privσ2) →\n prim_step_mrel p (LkE (Expr1 e1) C, St1 σ1 privσ2) X\n | MakeCall2S e2 C σ2 pubσ privσ1 privσ2 fn_name arg k2 X :\n mlanguage.is_call e2 fn_name arg k2 →\n proj2_prog p !! fn_name = None →\n mlanguage.split_state σ2 pubσ privσ2 →\n X (LkE (ExprCall fn_name arg) (inr k2 :: C), St pubσ privσ1 privσ2) →\n prim_step_mrel p (LkE (Expr2 e2) C, St2 privσ1 σ2) X\n (* Producing a value when execution is finished *)\n | Val1S e1 C σ1 v pubσ privσ1 privσ2 X :\n mlanguage.to_val e1 = Some v →\n (* Splitting the state is angelic, the underlying language can choose a concrete splitting. *)\n (* If no such splitting exists, we have UB *)\n mlanguage.split_state σ1 pubσ privσ1 →\n X (LkE (ExprV v) C, St pubσ privσ1 privσ2) →\n prim_step_mrel p (LkE (Expr1 e1) C, St1 σ1 privσ2) X\n | Val2S e2 C σ2 v pubσ privσ1 privσ2 X :\n mlanguage.to_val e2 = Some v →\n (* Splitting the state is angelic, the underlying language can choose a concrete splitting. *)\n (* If no such splitting exists, we have UB *)\n mlanguage.split_state σ2 pubσ privσ2 →\n X (LkE (ExprV v) C, St pubσ privσ1 privσ2) →\n prim_step_mrel p (LkE (Expr2 e2) C, St2 privσ1 σ2) X\n (* Entering a function. Change the view of the heap in the process.\n Merging the state is angelic. *)\n | RunFunction1S fn1 args C e1 σ1 pubσ privσ1 privσ2 X :\n mlanguage.apply_func fn1 args = Some e1 →\n mlanguage.split_state σ1 pubσ privσ1 →\n X (LkE (Expr1 e1) C, St1 σ1 privσ2) →\n prim_step_mrel p (LkE (RunFunction (inl fn1) args) C, St pubσ privσ1 privσ2) X\n | RunFunction2S fn2 args C e2 σ2 pubσ privσ1 privσ2 X :\n mlanguage.apply_func fn2 args = Some e2 →\n mlanguage.split_state σ2 pubσ privσ2 →\n X (LkE (Expr2 e2) C, St2 privσ1 σ2) →\n prim_step_mrel p (LkE (RunFunction (inr fn2) args) C, St pubσ privσ1 privσ2) X\n (* Continuing execution by returning a value to its caller. *)\n | Ret1S v k1 C σ1 pubσ privσ1 privσ2 X :\n mlanguage.split_state σ1 pubσ privσ1 →\n X (LkE (Expr1 (mlanguage.resume_with k1 (mlanguage.of_val Λ1 v))) C, St1 σ1 privσ2) →\n prim_step_mrel p (LkE (ExprV v) (inl k1 :: C), St pubσ privσ1 privσ2) X\n | Ret2S v k2 C σ2 pubσ privσ1 privσ2 X :\n mlanguage.split_state σ2 pubσ privσ2 →\n X (LkE (Expr2 (mlanguage.resume_with k2 (mlanguage.of_val Λ2 v))) C, St2 privσ1 σ2) →\n prim_step_mrel p (LkE (ExprV v) (inr k2 :: C), St pubσ privσ1 privσ2) X\n (* Resolve an internal call to a module function *)\n | CallS fn_name fn arg σ C X :\n p !! fn_name = Some fn →\n X (LkE (RunFunction fn arg) C, σ) →\n prim_step_mrel p (LkE (ExprCall fn_name arg) C, σ) X\n (* Terminate execution with NB on values *)\n | ValStopS v σ X :\n prim_step_mrel p (LkE (ExprV v) [], σ) X.\n\n Program Definition prim_step (p : prog) : umrel (expr * state) :=\n {| mrel := prim_step_mrel p |}.\n Next Obligation.\n intros p. intros [[se k] σ] X Y Hstep HXY. inversion Hstep; subst;\n [ eapply Step1S | eapply Step2S | eapply MakeCall1S | eapply MakeCall2S\n | eapply Val1S | eapply Val2S | eapply RunFunction1S | eapply RunFunction2S\n | eapply Ret1S | eapply Ret2S | eapply CallS | eapply ValStopS ];\n eauto; naive_solver.\n Qed.\n\n Lemma mlanguage_mixin :\n MlanguageMixin (val:=val) of_val to_val is_call resume_with comp_cont\n apply_func prim_step.\n Proof using.\n constructor.\n - intros v. done.\n - intros e c. destruct e as [e [|]]; destruct e; cbn; intros; by simplify_eq.\n - intros *. eapply ValStopS.\n - intros p e fn_name arg C σ X ->. split.\n + inversion 1; simplify_eq. do 2 eexists. repeat split; eauto.\n + intros (?&[]&?&?&?). unfold apply_func in *. simplify_eq.\n econstructor; eauto.\n - intros e [v Hv] f vs C ->. done.\n - intros ? C1 C2 s vv ->. cbn. done.\n - intros [] C [v Hv]; cbn in Hv. repeat case_match; simplify_eq.\n apply app_eq_nil in H0 as [-> ->]. done.\n - intros [] C1 C2. rewrite /= app_assoc //.\n - intros p C [es eC] σ X Hnv. inversion 1; simplify_eq.\n 1,2: econstructor; eauto; intros; eexists (LkE _ _); by eauto. (* StepS *)\n { eapply MakeCall1S; eauto; eexists (LkE _ _); split; eauto;\n unfold resume_with; by eauto. }\n { eapply MakeCall2S; eauto; eexists (LkE _ _); split; eauto;\n unfold resume_with; by eauto. }\n { eapply Val1S; eauto. eexists (LkE _ _). split; eauto. }\n { eapply Val2S; eauto. eexists (LkE _ _). split; eauto. }\n 1,2: econstructor; eauto; eexists (LkE _ _); split; eauto. (* RunFunctionS *)\n 1,2: econstructor; eauto; eexists (LkE _ _); split; eauto. (* RetS *)\n eapply CallS; eauto; eexists (LkE _ _); split; eauto.\n - intros p [[] eC] σ Hnv; simplify_eq;\n try by (intros _; inversion 1; simplify_eq; eauto).\n + destruct eC as [|[] eC']; first done; intros _;\n inversion 1; simplify_eq; eauto.\n + intros _. inversion 1; simplify_eq; eauto.\n eapply prim_step_no_NB in H5 as (e1 & σ1' & ?); eauto.\n + intros _. inversion 1; simplify_eq; eauto.\n eapply prim_step_no_NB in H5 as (e2 & σ2' & ?); eauto.\n Qed.\nEnd Linking.\nEnd Link.\n\nArguments Link.ExprV {_ _ _} _.\nArguments Link.ExprCall {_ _ _} _ _.\nArguments Link.RunFunction {_ _ _} _ _.\nArguments Link.Expr1 {_ _ _} _.\nArguments Link.Expr2 {_ _ _} _.\nArguments Link.St {_ _ _ _ _ _} _ _ _.\nArguments Link.St1 {_ _ _ _ _ _} _ _.\nArguments Link.St2 {_ _ _ _ _ _} _ _.\n\nArguments Link.LkE {_ _ _} _ _.\nNotation LkSE se := (Link.LkE se []).\n\nCanonical Structure link_lang {val public_state} Λ1 Λ2 {lk1 lk2} : mlanguage val :=\n Mlanguage (@Link.mlanguage_mixin val public_state Λ1 Λ2 lk1 lk2).\n\nGlobal Program Instance link_linkable\n {val public_state} (Λ1 Λ2 : mlanguage val)\n (lk1 : linkable Λ1 public_state)\n (lk2 : linkable Λ2 public_state) :\nlinkable (link_lang Λ1 Λ2) public_state := {\n mlanguage.private_state := Link.private_state _ Λ1 Λ2;\n mlanguage.split_state := Link.split_state _ Λ1 Λ2;\n}.\n\nDefinition link_prog {val public_state} (Λ1 Λ2 : mlanguage val)\n {lk1 : linkable Λ1 public_state} {lk2 : linkable Λ2 public_state}\n (p1 : mlang_prog Λ1) (p2 : mlang_prog Λ2) :\nmlang_prog (link_lang Λ1 Λ2) :=\n fmap inl p1 ∪ fmap inr p2.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/linking/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.27825680567280014, "lm_q1q2_score": 0.14021532137023524}} {"text": "From cap_machine Require Export logrel.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Import ftlr_base monotone.\nFrom cap_machine Require Import rules_base interp_weakening.\nFrom cap_machine.rules Require Import rules_Lea.\n\nSection fundamental.\n Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n {stsg : STSG Addr region_type Σ} {heapg : heapG Σ}\n {nainv: logrel_na_invs Σ}\n `{MachineParameters}.\n\n Notation STS := (leibnizO (STS_states * STS_rels)).\n Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n Notation WORLD := (prodO STS_STD STS).\n Implicit Types W : WORLD.\n\n Notation D := (WORLD -n> (leibnizO Word) -n> iPropO Σ).\n Notation R := (WORLD -n> (leibnizO Reg) -n> iPropO Σ).\n Implicit Types w : (leibnizO Word).\n Implicit Types interp : (D).\n\n Lemma lea_case (W : WORLD) (r : leibnizO Reg) (p : Perm)\n (g : Locality) (b e a : Addr) (w : Word) (ρ : region_type) (dst : RegName) (r0 : Z + RegName) (P:D):\n ftlr_instr W r p g b e a w (Lea dst r0) ρ P.\n Proof.\n intros Hp Hsome i Hbae Hpers Hpwl Hregion Hnotrevoked Hnotmonostatic Hnotuninitialized Hi.\n iIntros \"#IH #Hinv #Hreg #Hinva #Hrcond #Hwcond Hmono Hw Hsts Hown\".\n iIntros \"Hr Hstate Ha HPC Hmap\".\n rewrite delete_insert_delete.\n iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n iApply (wp_lea with \"[$Ha $Hmap]\"); eauto.\n { by rewrite lookup_insert. }\n { rewrite /subseteq /map_subseteq /set_subseteq. intros rr _.\n apply elem_of_gmap_dom. apply lookup_insert_is_Some'; eauto. }\n\n iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n destruct HSpec as [ * Hdst ? Hz Hoffset HUa HincrPC |].\n { apply incrementPC_Some_inv in HincrPC as (p''&g''&b''&e''&a''& ? & HPC & Z & Hregs' & XX).\n\n assert (p'' = p ∧ g'' = g ∧ b'' = b ∧ e'' = e) as (-> & -> & -> & ->).\n { destruct (decide (PC = dst)); simplify_map_eq; auto. }\n\n iApply wp_pure_step_later; auto. iNext.\n iDestruct (region_close with \"[$Hstate $Hr $Ha $Hmono Hw]\") as \"Hr\"; eauto.\n { destruct ρ;auto;[|specialize (Hnotmonostatic g1)|specialize (Hnotuninitialized w0)];contradiction. }\n iApply (\"IH\" $! _ regs' with \"[%] [] [Hmap] [$Hr] [$Hsts] [$Hown]\").\n { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n { iIntros (ri Hri). subst regs'.\n erewrite locate_ne_reg; [ | | reflexivity]; auto.\n destruct (decide (ri = dst)).\n { subst ri. unshelve iSpecialize (\"Hreg\" $! dst _); eauto.\n erewrite locate_eq_reg; [ | reflexivity]; auto. simplify_map_eq.\n rewrite /RegLocate Hdst. iApply interp_weakening; eauto; try solve_addr.\n - destruct p0; simpl; auto.\n - eapply PermFlowsToReflexive.\n - destruct g0; auto. }\n { repeat (erewrite locate_ne_reg; [ | | reflexivity]; auto).\n iApply \"Hreg\"; auto. } }\n { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n { iPureIntro. tauto. }\n eauto. }\n { iApply wp_pure_step_later; auto. iNext.\n iApply wp_value; auto. iIntros; discriminate. }\n Qed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/ftlr/Lea.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.14021531835425646}} {"text": "From iris.algebra Require Import gmap auth agree gset coPset excl csum.\nFrom Perennial.base_logic.lib Require Export fancy_updates.\nFrom stdpp Require Export namespaces.\nFrom Perennial.base_logic.lib Require Import wsat invariants ae_invariants saved_prop.\nFrom Perennial.Helpers Require Import Qextra.\nFrom iris.algebra Require Import gmap.\nFrom iris.proofmode Require Import tactics.\nFrom Perennial.program_logic Require Export step_fupd_extra crash_weakestpre ae_invariants_mutable later_res private_invariants staged_invariant_alt.\nFrom iris.prelude Require Import options.\n\nSet Default Proof Using \"Type\".\n\n#[global]\nExisting Instances pri_inv_tok_timeless later_tok_timeless.\n\nSection def.\nContext `{IRISG: !irisGS Λ Σ, !generationGS Λ Σ}.\nContext `{!pri_invG IRISG}.\nContext `{!later_tokG IRISG}.\nContext `{!stagedG Σ}.\n\nDefinition staged_value_inuse e E1' E1 mj mj_wp mj_ukeep Φ Φc P :=\n (∃ E2 mj_wp_init mj_ishare mj_ushare γsaved γfinished γstatus γprop γprop',\n ⌜ E1 ⊆ E1' ⌝ ∗\n ⌜ to_val e = None ⌝ ∗\n ⌜ (1 < mj + mj_ukeep)%Qp ⌝ ∗\n ⌜ (mj_ukeep + mj_ushare = /2)%Qp ⌝ ∗\n ⌜ (mj_wp ≤ mj) ⌝%Qp ∗\n ⌜ (mj_wp ≤ / 2 + mj_ishare) ⌝%Qp ∗\n own γsaved (◯ Excl' (γprop, γprop')) ∗\n own γstatus (◯ Excl' (inuse mj_wp mj_ushare)) ∗\n saved_prop_own γprop DfracDiscarded (wpc0 NotStuck mj_wp E1 e\n (λ v : val Λ, (wpc_crash_modality E1 mj_wp P) ∗ (wpc_crash_modality E1 mj_wp Φc ∧ Φ v))\n (Φc ∗ P)) ∗\n saved_prop_own γprop' DfracDiscarded Φc ∗\n later_tok ∗\n pri_inv_tok mj_ukeep E2 ∗\n ⌜ /2 < mj ⌝%Qp ∗\n pri_inv E2 (staged_inv_inner E1' E2 mj_wp_init mj_ishare γsaved γfinished γstatus P))%I.\n\nEnd def.\n\nSection inv.\nContext `{IRISG: !irisGS Λ Σ, !generationGS Λ Σ}.\nContext `{!pri_invG IRISG}.\nContext `{!later_tokG IRISG}.\nContext `{!stagedG Σ}.\nImplicit Types i : positive.\nImplicit Types N : namespace.\nImplicit Types P Q R : iProp Σ.\n\nLemma wpc_staged_inv_aux e E1' mj mj_wp mj_ukeep Φ Φc P :\n staged_value_inuse e E1' ⊤ mj mj_wp mj_ukeep Φ Φc P -∗\n wpc0 NotStuck mj ⊤ e Φ Φc.\nProof.\n iIntros \"Hsv\".\n iLöb as \"IH\" forall (e).\n iDestruct \"Hsv\" as (????????? Hsub)\n \"(%Hnval&%Hinvalid&%Heq_mj&%Hle2&%Hinvalid2&Hown&Hownstat&#Hsaved1&#Hsaved2&Hltok&Hitok&%Hlt2&#Hinv)\".\n iEval (rewrite wpc0_unfold).\n rewrite /wpc_pre. iSplit; last first.\n {\n iIntros (g1 ns D' κs) \"Hg #HC Hlc\".\n iDestruct (pri_inv_tok_disj with \"[$]\") as %[Hdisj|Hval]; last first.\n { exfalso. apply Qp.lt_nge in Hinvalid. revert Hval. rewrite frac_valid. eauto. }\n iMod (pri_inv_acc with \"[$]\") as \"(Hinner&Hclo)\".\n { set_solver. }\n iEval (rewrite staged_inv_inner_unfold) in \"Hinner\".\n iDestruct \"Hinner\" as (?????) \"(>Hown'&#Hsaved1'&#Hsaved2'&>Hstatus'&>Hitok_ishare&Hinner)\".\n iDestruct (own_valid_2 with \"Hown' Hown\") as \"#H\".\n iDestruct \"H\" as %[Heq%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n iDestruct (own_valid_2 with \"Hstatus' Hownstat\") as \"#Heq_status\".\n iDestruct \"Heq_status\" as %[Heq_status%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n inversion Heq; subst.\n iMod (later_tok_decr with \"[$]\") as (ns' Hlt') \"Hg\".\n iMod (fupd2_mask_subseteq ∅ ∅) as \"Hclo'\"; [set_solver+..|].\n iModIntro. iApply (step_fupd2N_le (S (S (num_laters_per_step ns')))).\n { etransitivity; last eapply (num_laters_per_step_exp ns'); lia. }\n iDestruct (saved_prop_agree with \"Hsaved1 Hsaved1'\") as \"Hequiv1\".\n iDestruct (saved_prop_agree with \"Hsaved2 Hsaved2'\") as \"Hequiv2\".\n iEval (simpl).\n iModIntro. iModIntro. iModIntro.\n iDestruct \"Hinner\" as \"[(%Hlt''&HPs&Hs)|Hfin]\"; last first.\n {\n iDestruct \"Hfin\" as \"(HPR&Hrest)\".\n iMod (saved_prop_alloc True%I) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored, γprop_remainder') ⋅\n ◯ Excl' (γprop_stored, γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iApply step_fupd2N_later. iModIntro. iNext. iModIntro. iNext.\n iMod \"Hclo'\".\n iMod (\"Hclo\" with \"[-Hg HPR]\").\n { iNext. iEval (rewrite staged_inv_inner_unfold). iExists _, _, _, _, _. iFrame \"∗ #\". }\n iRewrite \"Hequiv2\". iFrame.\n iMod (global_state_interp_le with \"[$]\") as \"$\"; auto.\n lia.\n }\n iModIntro. iNext.\n iDestruct \"Hs\" as \"(Hitok'&#Hwand)\".\n iMod \"Hclo'\".\n iDestruct (pri_inv_tok_join with \"Hitok Hitok'\") as \"Hitok\".\n rewrite Heq_mj.\n iDestruct (pri_inv_tok_join with \"Hitok Hitok_ishare\") as \"Hitok\".\n iDestruct (pri_inv_tok_global_le_acc _ _ _ mj_wp with \"[] Hg\") as \"(Hg_inv&Hg_inv_clo)\".\n { iPureIntro; split; naive_solver. }\n iDestruct (pri_inv_tok_le_acc mj_wp with \"Hitok\") as \"(Hitok_wp&Hitok_inv_clo)\".\n { naive_solver. }\n iMod (pri_inv_tok_disable_reenable with \"[$]\") as \"(Hg&Hreenable)\".\n iRewrite -\"Hequiv1\" in \"HPs\".\n iEval (rewrite wpc0_unfold /wpc_pre) in \"HPs\".\n iDestruct \"HPs\" as \"(_&HPs)\".\n\n rewrite /wpc_crash_modality.\n replace (⊤ ∖ D' ∖ E2) with (⊤ ∖ (E2 ∪ D')) by set_solver.\n iDestruct (lc_weaken with \"Hlc\") as \"Hlc\".\n { apply (num_laters_per_step_exp ns'). lia. }\n iDestruct \"Hlc\" as \"[[Hlc1 Hlc2] Hlc3]\".\n iSpecialize (\"HPs\" with \"[$] [$] [$]\").\n iMod \"HPs\".\n iModIntro. iApply (step_fupd2N_wand with \"HPs\"). iIntros \"HPs\".\n iMod \"HPs\" as \"(Hg&HPr&HP)\".\n iMod (\"Hreenable\" with \"[$Hg]\") as \"(Hitok&Hg)\".\n iDestruct (\"Hitok_inv_clo\" with \"[$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_split with \"Hitok\") as \"(Hitok&Hitok_ishare)\".\n rewrite -Heq_mj.\n iDestruct (pri_inv_tok_split with \"Hitok\") as \"(Hitok_ukeep&Hitok_ushare)\".\n iMod (saved_prop_alloc True%I) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored, γprop_remainder') ⋅\n ◯ Excl' (γprop_stored, γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iDestruct (\"Hg_inv_clo\" with \"[$]\") as \"Hg\".\n\n iMod (\"Hclo\" with \"[-HPr Hg]\").\n { iNext. iEval (rewrite staged_inv_inner_unfold). iExists _, _, _, _, _. iFrame \"∗ #\". iRight. iFrame. }\n iFrame.\n iMod (global_state_interp_le _ ns with \"[$]\"); first lia. iModIntro; iFrame.\n }\n {\n rewrite Hnval.\n iIntros (q σ1 g1 ns D κ κs nt) \"Hσ Hg HNC Hlc\".\n iDestruct (pri_inv_tok_disj with \"[$]\") as %[Hdisj|Hval]; last first.\n { exfalso. apply Qp.lt_nge in Hinvalid. revert Hval. rewrite frac_valid. eauto. }\n iMod (pri_inv_acc with \"[$]\") as \"(Hinner&Hclo)\".\n { set_solver. }\n iEval (rewrite staged_inv_inner_unfold) in \"Hinner\".\n iDestruct \"Hinner\" as (?????) \"(>Hown'&#Hsaved1'&#Hsaved2'&>Hstatus'&>Hitok_ishare&Hinner)\".\n iDestruct (own_valid_2 with \"Hown' Hown\") as \"#H\".\n iDestruct \"H\" as %[Heq%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n iDestruct (own_valid_2 with \"Hstatus' Hownstat\") as \"#Heq_status\".\n iDestruct \"Heq_status\" as %[Heq_status%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n inversion Heq; subst.\n iMod (later_tok_decr with \"[$]\") as (ns' Hlt') \"Hg\".\n iMod (fupd2_mask_subseteq ∅ ∅) as \"Hclo'\"; [set_solver+..|].\n iModIntro. iApply (step_fupd2N_le (S (S (S (num_laters_per_step ns'))))).\n { assert (ns' < ns) as Hlt by lia. apply num_laters_per_step_exp in Hlt. lia. }\n iDestruct (saved_prop_agree with \"Hsaved1 Hsaved1'\") as \"Hequiv1\".\n iDestruct (saved_prop_agree with \"Hsaved2 Hsaved2'\") as \"Hequiv2\".\n iEval (simpl).\n iModIntro. iModIntro. iModIntro.\n iDestruct \"Hinner\" as \"[(%Hlt''&HPs&Hs)|Hfin]\"; last first.\n {\n iDestruct \"Hfin\" as \"(HPR&HC&Hrest)\".\n iDestruct (NC_C with \"[$] [$]\") as %[].\n }\n iModIntro. iNext.\n iDestruct \"Hs\" as \"(Hitok'&#Hwand)\".\n iMod \"Hclo'\".\n iDestruct (pri_inv_tok_join with \"Hitok Hitok'\") as \"Hitok\".\n rewrite Heq_mj.\n iDestruct (pri_inv_tok_join with \"Hitok Hitok_ishare\") as \"Hitok\".\n iDestruct (pri_inv_tok_global_le_acc _ _ _ mj_wp with \"[] Hg\") as \"(Hg_inv&Hg_inv_clo)\".\n { iPureIntro; split; naive_solver. }\n iDestruct (pri_inv_tok_le_acc mj_wp with \"Hitok\") as \"(Hitok_wp&Hitok_inv_clo)\".\n { naive_solver. }\n iMod (pri_inv_tok_disable_reenable with \"[$]\") as \"(Hg&Hreenable)\".\n iRewrite -\"Hequiv1\" in \"HPs\".\n iEval (rewrite wpc0_unfold /wpc_pre) in \"HPs\".\n iDestruct \"HPs\" as \"(Hwp&_)\".\n rewrite Hnval.\n replace (⊤ ∖ D ∖ E2) with (⊤ ∖ (E2 ∪ D)) by set_solver.\n iMod (\"Hwp\" with \"[$] [$] [$] [Hlc]\") as \"Hwp\".\n { iApply (lc_weaken with \"Hlc\").\n apply num_laters_per_step_lt in Hlt'. lia. }\n iModIntro. iApply (step_fupd2N_wand with \"Hwp\").\n iIntros \"($&Hwp)\".\n iIntros. iMod (\"Hwp\" with \"[//]\") as \"($&Hg&H&Hefs&HNC)\".\n destruct (to_val e2) eqn:Heq_val.\n {\n iEval (rewrite wpc0_unfold /wpc_pre) in \"H\".\n iDestruct \"H\" as \"(H&_)\".\n rewrite Heq_val.\n iMod (\"H\" with \"[$] [$]\") as \"H\".\n iDestruct \"H\" as \"((Hcm&Hv)&Hg&HNC)\".\n iMod (saved_prop_alloc (wpc_crash_modality ⊤ mj_wp P)) as (γprop_stored') \"#Hsaved1''\".\n { apply dfrac_valid_discarded. }\n iMod (saved_prop_alloc True%I) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored', γprop_remainder') ⋅\n ◯ Excl' (γprop_stored', γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (\"Hreenable\" with \"[$Hg]\") as \"(Hitok&Hg)\".\n iDestruct (\"Hitok_inv_clo\" with \"[$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok&Hitok_ishare)\".\n iEval (rewrite -Heq_mj) in \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok_ukeep&Hitok_ushare)\".\n iMod (\"Hclo\" with \"[Hown' Hstatus' Hcm Hitok_ishare Hitok_ushare]\").\n { iNext.\n iEval (rewrite staged_inv_inner_unfold).\n iExists _, _, _, _, _. iFrame \"∗ #\".\n iLeft.\n iSplit.\n { iPureIntro. split_and!; auto; try naive_solver. }\n iFrame.\n iModIntro. iIntros \"Hwpc\".\n assert (E1' = ⊤) as -> by set_solver.\n rewrite /wpc_crash_modality.\n iIntros (????) \"Hg HC Hlc\".\n iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n iIntros \"($&$)\"; eauto.\n }\n iMod (later_tok_incr with \"[$]\") as \"(Hg&Hltok)\".\n iDestruct (\"Hg_inv_clo\" with \"Hg\") as \"Hg\".\n iMod (global_state_interp_le with \"Hg\") as \"$\".\n { apply Nat.le_succ_l, step_count_next_mono; lia. }\n iModIntro. iFrame.\n iSplitR \"Hefs\".\n - iEval (rewrite wpc0_unfold /wpc_pre).\n rewrite Heq_val.\n iSplit.\n * iIntros. iModIntro. iFrame. iDestruct \"Hv\" as \"(_&$)\".\n * iDestruct \"Hv\" as \"(H&_)\". iIntros.\n iDestruct (pri_inv_tok_global_le_acc _ _ _ mj_wp with \"[] [$]\") as \"(Hg&Hg_clo)\".\n { iPureIntro; naive_solver. }\n iSpecialize (\"H\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"H\"); auto.\n iIntros \"(Hg&$)\".\n iApply \"Hg_clo\". iFrame.\n - iApply (big_sepL_mono with \"Hefs\").\n iIntros. iApply (wpc0_mj_le); last by iFrame.\n split; auto. naive_solver.\n }\n iFrame \"HNC\".\n iMod (saved_prop_alloc\n (wpc0 NotStuck mj_wp ⊤ e2\n (λ v : val Λ, wpc_crash_modality ⊤ mj_wp P ∗ (wpc_crash_modality ⊤ mj_wp Φc ∧ Φ v))\n (Φc ∗ P))%I) as (γprop_stored') \"#Hsaved1''\".\n { apply dfrac_valid_discarded. }\n iMod (saved_prop_alloc Φc) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored', γprop_remainder') ⋅\n ◯ Excl' (γprop_stored', γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (own_update_2 _ _ _ (● Excl' (inuse mj_wp mj_ushare) ⋅ ◯ Excl' (inuse mj_wp mj_ushare))\n with \"Hstatus' Hownstat\") as \"[Hstatus' Hownstat]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (\"Hreenable\" with \"[$Hg]\") as \"(Hitok&Hg)\".\n iDestruct (\"Hitok_inv_clo\" with \"[$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok&Hitok_ishare)\".\n iEval (rewrite -Heq_mj) in \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok_ukeep&Hitok_ushare)\".\n iMod (\"Hclo\" with \"[Hown' Hstatus' H Hitok_ishare Hitok_ushare]\").\n { iNext.\n iEval (rewrite staged_inv_inner_unfold).\n iExists _, _, _, _, _. iFrame \"∗ #\".\n iLeft.\n iSplit.\n { iPureIntro. split_and!; auto; try naive_solver. }\n iFrame.\n iModIntro. iIntros \"Hwpc\".\n iEval (rewrite wpc0_unfold) in \"Hwpc\". iDestruct \"Hwpc\" as \"(_&Hwpc)\".\n rewrite /wpc_crash_modality.\n iIntros (????) \"Hg HC Hlc\".\n iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n }\n iDestruct (\"Hg_inv_clo\" with \"Hg\") as \"Hg\".\n iMod (later_tok_incr with \"[$]\") as \"(Hg&Hltok)\".\n iMod (global_state_interp_le with \"Hg\") as \"$\".\n { apply Nat.le_succ_l, step_count_next_mono; lia. }\n iModIntro. iSplitR \"Hefs\"; last first.\n { iApply (big_sepL_mono with \"Hefs\").\n iIntros. iApply (wpc0_mj_le); last by iFrame.\n split; auto. naive_solver.\n }\n iApply \"IH\".\n iExists _, _, mj_ishare, _, _, _, _, _. iExists _. iFrame \"∗\".\n iSplit; first eauto.\n iFrame \"Hsaved1'' Hsaved2''\".\n iSplit; first eauto.\n iSplit; first eauto.\n iSplit.\n { iPureIntro. rewrite /mj_wp. naive_solver. }\n iSplit; first eauto.\n iSplit; first eauto.\n iSplit; first eauto.\n iExact \"Hinv\".\n }\nQed.\n\nLemma wpc_staged_inv_inuse E1 e Φ Φc Qs P :\n to_val e = None →\n staged_value ⊤ Qs P ∗\n ((∀ mj_wp, wpc_crash_modality E1 mj_wp Φc) ∧\n (Qs -∗ ∀ mj_wp, ⌜ (/2 < mj_wp)%Qp ⌝ → WPC e @ E1\n {{λ v, wpc_crash_modality ⊤ mj_wp P ∗ (wpc_crash_modality E1 mj_wp Φc ∧ Φ v)}}\n {{ Φc ∗ P }}))\n ⊢ WPC e @ E1 {{ Φ }} {{ Φc }}.\nProof.\n iIntros (Hnval) \"(Hstaged&Hwp)\".\n iDestruct \"Hstaged\" as (??????) \"(Hown&Hownstat&#Hsaved1&#Hsaved2&Hltok&Hitok&Hinv)\".\n iDestruct \"Hinv\" as (mj_wp_init mj_ishare Hlt) \"#Hinv\".\n rewrite /staged_inv.\n rewrite wpc_eq /wpc_def. iIntros (mj).\n\n iLöb as \"IH\" forall (γprop γprop' Qs) \"Hsaved1 Hsaved2\".\n\n (* Base case *)\n iEval (rewrite wpc0_unfold).\n rewrite /wpc_pre. iSplit; last first.\n {\n iDestruct \"Hwp\" as \"(Hwp&_)\".\n iIntros (g1 ns D' κs) \"Hg #HC Hlc\".\n iSpecialize (\"Hwp\" $! mj with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"Hwp\"); auto.\n }\n rewrite Hnval.\n iIntros (q σ1 g1 ns D κ κs nt) \"Hσ Hg HNC Hlc\".\n iDestruct (pri_inv_tok_disj_inv_half with \"[$]\") as %Hdisj.\n iMod (pri_inv_acc with \"[$]\") as \"(Hinner&Hclo)\".\n { set_solver. }\n iEval (rewrite staged_inv_inner_unfold) in \"Hinner\".\n iDestruct \"Hinner\" as (?????) \"(>Hown'&#Hsaved1'&#Hsaved2'&>Hstatus'&>Hitok_ishare&Hinner)\".\n iDestruct (own_valid_2 with \"Hown' Hown\") as \"#H\".\n iDestruct \"H\" as %[Heq%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n iDestruct (own_valid_2 with \"Hstatus' Hownstat\") as \"#Heq_status\".\n iDestruct \"Heq_status\" as %[Heq_status%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n inversion Heq; subst.\n iMod (later_tok_decr with \"[$]\") as (ns' Hlt') \"Hg\".\n iMod (fupd2_mask_subseteq ∅ ∅) as \"Hclo'\"; [set_solver+..|].\n iModIntro. simpl. iModIntro. iNext. iModIntro. iApply (step_fupd2N_le (S (S (num_laters_per_step ns')))).\n { etransitivity; last eapply (num_laters_per_step_exp ns'); lia. }\n simpl.\n iDestruct (saved_prop_agree with \"Hsaved1 Hsaved1'\") as \"Hequiv1\".\n iDestruct (saved_prop_agree with \"Hsaved2 Hsaved2'\") as \"Hequiv2\".\n iModIntro. iModIntro. iModIntro.\n iDestruct \"Hinner\" as \"[(HPs&_)|Hfin]\"; last first.\n { (* Impossible, since we have NC token. *)\n iDestruct \"Hfin\" as \"(_&HC&_)\". iDestruct (NC_C with \"[$] [$]\") as %[]. }\n iRewrite -\"Hequiv1\" in \"HPs\".\n iDestruct \"Hwp\" as \"(_&Hwp)\".\n iSpecialize (\"Hwp\" with \"[$]\").\n\n iDestruct (pri_inv_tok_global_valid with \"Hg\") as %(Hmin&Hvalid).\n destruct (Qp_plus_inv_2_gt_1_split mj) as (mj_ukeep&mj_ushare&Heq_mj&Hinvalid); first auto.\n set (mj_wp := (mj_wp_init `min` mj `min` (/2 + mj_ishare) `min` (/2 + mj_ushare))%Qp).\n assert (/ 2 < mj_wp)%Qp.\n {\n - rewrite /mj_wp. apply Qp_min_glb1_lt; auto.\n * apply Qp_min_glb1_lt; auto.\n ** apply Qp_min_glb1_lt; auto.\n ** apply Qp.lt_add_l.\n * apply Qp.lt_add_l.\n }\n iDestruct (pri_inv_tok_global_le_acc _ _ _ mj_wp with \"[] Hg\") as \"(Hg_inv&Hg_inv_clo)\".\n { iPureIntro; split; auto.\n rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n apply Qp.le_min_r.\n }\n\n iDestruct (pri_inv_tok_join with \"[$Hitok] [$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_le_acc mj_wp with \"Hitok\") as \"(Hitok_wp&Hitok_inv_clo)\".\n { rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n apply Qp.le_min_r. }\n\n\n iMod (pri_inv_tok_disable_reenable with \"[$]\") as \"(Hg&Hreenable)\".\n unshelve (iSpecialize (\"Hwp\" $! mj_wp _ mj_wp)).\n { rewrite //=. }\n iEval (rewrite wpc0_unfold) in \"Hwp\".\n iDestruct \"Hwp\" as \"(Hwp&_)\".\n iMod (\"Hclo'\").\n rewrite Hnval.\n replace (⊤ ∖ D ∖ E2) with (⊤ ∖ (E2 ∪ D)) by set_solver.\n iMod (\"Hwp\" with \"[$] [$] [$] [Hlc]\") as \"Hwp\".\n { iApply (lc_weaken with \"Hlc\").\n apply num_laters_per_step_lt in Hlt'. lia. }\n simpl. iMod \"Hwp\". iModIntro. iNext. iMod \"Hwp\". iModIntro.\n iApply (step_fupd2N_wand with \"Hwp\"). iIntros \"(%Hred&Hwp)\".\n iSplit. { eauto. }\n iIntros (e2 σ2 g2 efs Hstep). iMod (\"Hwp\" with \"[//]\") as \"($&Hg&H&Hefs&HNC)\".\n iMod (later_tok_incr with \"[$]\") as \"(Hg&Hltok)\".\n\n destruct (to_val e2) eqn:Heq_val.\n {\n iEval (rewrite wpc0_unfold /wpc_pre) in \"H\".\n iDestruct \"H\" as \"(H&_)\".\n rewrite Heq_val.\n iMod (\"H\" with \"[$] [$]\") as \"H\".\n\n iDestruct \"H\" as \"((Hcm&Hv)&Hg&HNC)\".\n iMod (saved_prop_alloc (wpc_crash_modality ⊤ mj_wp P)) as (γprop_stored') \"#Hsaved1''\".\n { apply dfrac_valid_discarded. }\n iMod (saved_prop_alloc True%I) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored', γprop_remainder') ⋅\n ◯ Excl' (γprop_stored', γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (own_update_2 _ _ _ (● Excl' (inuse mj_wp mj_ushare) ⋅ ◯ Excl' (inuse mj_wp mj_ushare))\n with \"Hstatus' Hownstat\") as \"[Hstatus' Hownstat]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (\"Hreenable\" with \"[$Hg]\") as \"(Hitok&Hg)\".\n iDestruct (\"Hitok_inv_clo\" with \"[$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok&Hitok_ishare)\".\n iEval (rewrite -Heq_mj) in \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok_ukeep&Hitok_ushare)\".\n iMod (\"Hclo\" with \"[Hown' Hstatus' Hcm Hitok_ishare Hitok_ushare]\").\n { iNext.\n iEval (rewrite staged_inv_inner_unfold).\n iExists _, _, _, _, _. iFrame \"∗ #\".\n iLeft.\n iSplit.\n { iPureIntro. split_and!; auto; try naive_solver.\n - etransitivity; first eapply Qp.le_min_r. reflexivity.\n - etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_l. }\n iFrame.\n iModIntro. iIntros \"Hwpc\".\n rewrite /wpc_crash_modality.\n iIntros (????) \"Hg HC Hlc\".\n iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n iIntros \"($&$)\"; eauto.\n }\n iDestruct (\"Hg_inv_clo\" with \"Hg\") as \"Hg\".\n iMod (global_state_interp_le with \"Hg\") as \"$\".\n { apply Nat.le_succ_l, step_count_next_mono; lia. }\n iModIntro. iFrame.\n iSplitR \"Hefs\".\n - iEval (rewrite wpc0_unfold /wpc_pre).\n rewrite Heq_val.\n iSplit.\n * iIntros. iModIntro. iFrame. iDestruct \"Hv\" as \"(_&$)\".\n * iDestruct \"Hv\" as \"(H&_)\". iIntros.\n iDestruct (pri_inv_tok_global_le_acc _ _ _ mj_wp with \"[] [$]\") as \"(Hg&Hg_clo)\".\n { iPureIntro; split; auto.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_r. }\n iSpecialize (\"H\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"H\"); auto.\n iIntros \"(Hg&$)\".\n iApply \"Hg_clo\". iFrame.\n - iApply (big_sepL_mono with \"Hefs\").\n iIntros. iApply (wpc0_mj_le); last by iFrame.\n split; auto.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_r. }\n\n iFrame \"HNC\".\n iMod (saved_prop_alloc\n (wpc0 NotStuck mj_wp ⊤ e2\n (λ v : val Λ, wpc_crash_modality ⊤ mj_wp P ∗ (wpc_crash_modality ⊤ mj_wp Φc ∧ Φ v))\n (Φc ∗ P))%I) as (γprop_stored') \"#Hsaved1''\".\n { apply dfrac_valid_discarded. }\n iMod (saved_prop_alloc Φc) as (γprop_remainder') \"#Hsaved2''\".\n { apply dfrac_valid_discarded. }\n iMod (own_update_2 _ _ _ (● Excl' (γprop_stored', γprop_remainder') ⋅\n ◯ Excl' (γprop_stored', γprop_remainder'))\n with \"Hown' Hown\") as \"[Hown' Hown]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (own_update_2 _ _ _ (● Excl' (inuse mj_wp mj_ushare) ⋅ ◯ Excl' (inuse mj_wp mj_ushare))\n with \"Hstatus' Hownstat\") as \"[Hstatus' Hownstat]\".\n { by apply auth_update, option_local_update, exclusive_local_update. }\n iMod (\"Hreenable\" with \"[$Hg //]\") as \"(Hitok&Hg)\".\n iDestruct (\"Hitok_inv_clo\" with \"[$]\") as \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok&Hitok_ishare)\".\n iEval (rewrite -Heq_mj) in \"Hitok\".\n iDestruct (pri_inv_tok_split with \"[$Hitok]\") as \"(Hitok_ukeep&Hitok_ushare)\".\n iMod (\"Hclo\" with \"[Hown' Hstatus' H Hitok_ishare Hitok_ushare]\").\n { iNext.\n iEval (rewrite staged_inv_inner_unfold).\n iExists _, _, _, _, _. iFrame \"∗ #\".\n iLeft.\n iSplit.\n { iPureIntro. split_and!; auto.\n - rewrite /mj_wp. apply Qp.le_min_r.\n - rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_l.\n }\n iSplitL \"H\".\n { iApply (wpc0_strong_mono with \"H\"); auto.\n iSplit; last by (iIntros; iModIntro; iFrame).\n iIntros (?) \"($&H)\". iModIntro.\n iSplit.\n - iDestruct \"H\" as \"(H&_)\". iApply (wpc_crash_modality_strong_wand with \"[$]\"); auto.\n - iDestruct \"H\" as \"(_&$)\".\n }\n iFrame.\n iModIntro. iIntros \"Hwpc\".\n iEval (rewrite wpc0_unfold) in \"Hwpc\". iDestruct \"Hwpc\" as \"(_&Hwpc)\".\n rewrite /wpc_crash_modality.\n iIntros (????) \"Hg HC Hlc\".\n iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n }\n iDestruct (\"Hg_inv_clo\" with \"Hg\") as \"Hg\".\n iMod (global_state_interp_le with \"Hg\") as \"$\".\n { apply Nat.le_succ_l, step_count_next_mono; lia. }\n iModIntro. iSplitR \"Hefs\"; last first.\n { iApply (big_sepL_mono with \"Hefs\").\n iIntros. iApply (wpc0_mj_le); last by iFrame.\n split; auto.\n - rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_r.\n }\n iAssert (staged_value_inuse e2 ⊤ ⊤ mj mj_wp mj_ukeep Φ Φc P) with \"[-]\" as \"Hsv\".\n {\n iExists _, _, mj_ishare, _, _, _, _, _. iExists _. iFrame \"∗\".\n iSplit; first eauto.\n iFrame \"Hsaved1'' Hsaved2''\".\n iSplit; first eauto.\n iSplit; first eauto.\n iSplit; first eauto.\n iSplit.\n { iPureIntro. rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_r. }\n iSplit.\n { iPureIntro. rewrite /mj_wp.\n etransitivity; first eapply Qp.le_min_l.\n eapply Qp.le_min_r. }\n iSplit; first eauto.\n iExact \"Hinv\".\n }\n iApply (wpc_staged_inv_aux with \"[$]\").\nQed.\n\nEnd inv.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_logic/staged_invariant_use_inuse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.14020316977694033}} {"text": "From cap_machine Require Export logrel.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Import ftlr_base_binary.\nFrom cap_machine Require Export rules_UnSeal.\nFrom cap_machine.ftlr_binary Require Import interp_weakening.\nFrom cap_machine.rules_binary Require Import rules_binary_base.\n\nSection fundamental.\n Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n {nainv: logrel_na_invs Σ} {cfgsg: cfgSG Σ}\n `{MachineParameters}.\n\n Notation D := ((prodO (leibnizO Word) (leibnizO Word)) -n> iPropO Σ).\n Notation R := ((prodO (leibnizO Reg) (leibnizO Reg)) -n> iPropO Σ).\n Implicit Types ww : (prodO (leibnizO Word) (leibnizO Word)).\n Implicit Types w : (leibnizO Word).\n Implicit Types interp : (D).\n\n Lemma unseal_case (r : prodO (leibnizO Reg) (leibnizO Reg)) (p : Perm)\n (b e a : Addr) (w w' : Word) (dst : RegName) (src1 src2 : RegName) (P : D):\n ftlr_instr r p b e a w w' (UnSeal dst src1 src2) P.\n Proof.\n intros Hp Hsome HisCorrect Hbae Hi.\n iIntros \"#IH #Hspec #Hinv #Hreg #Hinva #Hread Hsmap Hown Hs Ha Ha' HP Hcls HPC Hmap\".\n rewrite delete_insert_delete.\n iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n iApply (wp_UnSeal with \"[$Ha $Hmap]\"); eauto.\n { eapply lookup_insert. }\n { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n apply elem_of_dom. apply lookup_insert_is_Some'; eauto. destruct Hsome with rr; eauto. }\n iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n\n (* we assert that w = w' *)\n iAssert (⌜w = w'⌝)%I as %Heqw.\n { iDestruct \"Hread\" as \"[Hread _]\". iSpecialize (\"Hread\" with \"HP\"). by iApply interp_eq. }\n destruct r as [r1 r2]. simpl in *.\n iDestruct (interp_reg_eq r1 r2 (WCap p b e a) with \"[]\") as %Heq;[iSplit;auto|]. rewrite -!Heq.\n\n destruct HSpec; cycle 1.\n - (* In case of failure, we do not necessarily get a contradiction, but the proof is trivial *)\n iApply wp_pure_step_later; auto.\n iMod (\"Hcls\" with \"[Ha Ha' HP]\"); [iExists w,w'; iFrame|iModIntro].\n iNext; iIntros \"_\".\n iApply wp_value; auto. iIntros; discriminate.\n - destruct (decide (src1 = PC)) as [->|Hnesp]; simplify_map_eq.\n specialize (Hsome src1) as (_ & (vr2 & Hsr1')).\n iAssert (interp(_,vr2)) as \"HFalse\".\n { iApply (\"Hreg\" $! src1); eauto. }\n rewrite !fixpoint_interp1_eq /=. done.\nQed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/ftlr_binary/UnSeal_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2658804614657029, "lm_q1q2_score": 0.1402031605746494}} {"text": "Require Import Kami.Notations.\nRequire Import Kami.Syntax.\nRequire Import List.\nRequire Import Kami.Rewrites.Notations_rewrites.\nRequire Import Program.Equality.\nRequire Import Kami.Rewrites.ReflectionPre.\nRequire Import Kami.Rewrites.ReflectionSoundTopTheorems.\nRequire Import Kami.Rewrites.ReflectionSoundTheorems1.\nRequire Import Kami.Rewrites.ReflectionSoundTheorems2.\nRequire Import Kami.WfMod_Helper.\n\nDefinition KRSimplifyTop_ImplProp (e: KRExpr_Prop) : KRExpr_Prop :=\n match e with\n | KRDisjKey_RegInitT a b => match a with\n | KRApp_list_RegInitT x y => KRAnd_Prop (KRDisjKey_RegInitT x b) (KRDisjKey_RegInitT y b)\n | KRCons_list_RegInitT x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_RegInitT_string x) (KRmap_RegInitT_string KRfst_RegInitT_string_Func b))) (KRDisjKey_RegInitT y b)\n | KRNil_list_RegInitT => KRTrue_Prop\n | _ => match b with\n | KRApp_list_RegInitT x y => KRAnd_Prop (KRDisjKey_RegInitT a x) (KRDisjKey_RegInitT a y)\n | KRCons_list_RegInitT x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_RegInitT_string x) (KRmap_RegInitT_string KRfst_RegInitT_string_Func a))) (KRDisjKey_RegInitT a y)\n | KRNil_list_RegInitT => KRTrue_Prop\n | _ => KRDisjKey_RegInitT a b\n end\n end\n | KRDisjKey_DefMethT a b => match a with\n | KRApp_list_DefMethT x y => KRAnd_Prop (KRDisjKey_DefMethT x b) (KRDisjKey_DefMethT y b)\n | KRCons_list_DefMethT x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_DefMethT_string x) (KRmap_DefMethT_string KRfst_DefMethT_string_Func b))) (KRDisjKey_DefMethT y b)\n | KRNil_list_DefMethT => KRTrue_Prop\n | _ => match b with\n | KRApp_list_DefMethT x y => KRAnd_Prop (KRDisjKey_DefMethT a x) (KRDisjKey_DefMethT a y)\n | KRCons_list_DefMethT x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_DefMethT_string x) (KRmap_DefMethT_string KRfst_DefMethT_string_Func a))) (KRDisjKey_DefMethT a y)\n | KRNil_list_DefMethT => KRTrue_Prop\n | _ => KRDisjKey_DefMethT a b\n end\n end\n | KRDisjKey_Rule a b => match a with\n | KRApp_list_Rule x y => KRAnd_Prop (KRDisjKey_Rule x b) (KRDisjKey_Rule y b)\n | KRCons_list_Rule x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_Rule_string x) (KRmap_Rule_string KRfst_Rule_string_Func b))) (KRDisjKey_Rule y b)\n | KRNil_list_Rule => KRTrue_Prop\n | _ => match b with\n | KRApp_list_Rule x y => KRAnd_Prop (KRDisjKey_Rule a x) (KRDisjKey_Rule a y)\n | KRCons_list_Rule x y => KRAnd_Prop (KRNot_Prop (KRIn_string_Prop (KRfst_Rule_string x) (KRmap_Rule_string KRfst_Rule_string_Func a))) (KRDisjKey_Rule a y)\n | KRNil_list_Rule => KRTrue_Prop\n | _ => KRDisjKey_Rule a b\n end\n end\n | KRAnd_Prop a KRTrue_Prop => a\n | KRAnd_Prop a KRFalse_Prop => KRFalse_Prop\n | KRAnd_Prop KRTrue_Prop a => a\n | KRAnd_Prop KRFalse_Prop a => KRFalse_Prop\n | KROr_Prop a KRTrue_Prop => KRTrue_Prop\n | KROr_Prop a KRFalse_Prop => a\n | KROr_Prop KRTrue_Prop a => KRTrue_Prop\n | KROr_Prop KRFalse_Prop a => a\n | KRNot_Prop (KRTrue_Prop) => KRFalse_Prop\n | KRNot_Prop (KRFalse_Prop) => KRTrue_Prop\n (*| KRNot_Prop (KRNot_Prop a) => a*)\n (*| KRNot_Prop (KRAnd_Prop a b) => (KROr_Prop (KRNot_Prop a) (KRNot_Prop b))\n | KRNot_Prop (KROr_Prop a b) => (KRAnd_Prop (KRNot_Prop a) (KRNot_Prop b))*)\n | KRIn_string_Prop x (KRApp_list_string a b) => (KROr_Prop (KRIn_string_Prop x a) (KRIn_string_Prop x b))\n | KRIn_string_Prop x (KRCons_list_string a b) => (KROr_Prop (KREq_string_Prop x a) (KRIn_string_Prop x b))\n | KRIn_string_Prop x (KRNil_list_string) => KRFalse_Prop\n | KRIn_RegInitT_Prop x (KRApp_list_RegInitT a b) => (KROr_Prop (KRIn_RegInitT_Prop x a) (KRIn_RegInitT_Prop x b))\n | KRIn_RegInitT_Prop x (KRCons_list_RegInitT a b) => (KROr_Prop (KREq_RegInitT_Prop x a) (KRIn_RegInitT_Prop x b))\n | KRIn_RegInitT_Prop x (KRNil_list_RegInitT) => KRFalse_Prop\n | KRIn_Rule_Prop x (KRApp_list_Rule a b) => (KROr_Prop (KRIn_Rule_Prop x a) (KRIn_Rule_Prop x b))\n | KRIn_Rule_Prop x (KRCons_list_Rule a b) => (KROr_Prop (KREq_Rule_Prop x a) (KRIn_Rule_Prop x b))\n | KRIn_Rule_Prop x (KRNil_list_Rule) => KRFalse_Prop\n | KRIn_DefMethT_Prop x (KRApp_list_DefMethT a b) => (KROr_Prop (KRIn_DefMethT_Prop x a) (KRIn_DefMethT_Prop x b))\n | KRIn_DefMethT_Prop x (KRCons_list_DefMethT a b) => (KROr_Prop (KREq_DefMethT_Prop x a) (KRIn_DefMethT_Prop x b))\n | KRIn_DefMethT_Prop x (KRNil_list_DefMethT) => KRFalse_Prop\n | KREq_string_Prop (KRstring_append p (KRConst_string a)) (KRstring_append q (KRConst_string b)) => if sdisjPrefix (srev a) (srev b) then KRFalse_Prop else e\n (*| KREq_string_Prop (KRstring_append (KRVar_string p) a) (KRstring_append (KRVar_string q) b) => if String.eqb p q then (KREq_string_Prop a b) else KREq_string_Prop (KRstring_append (KRVar_string p) a) (KRstring_append (KRVar_string q) b)\n | KREq_string_Prop (KRVar_string a) (KRVar_string b) => if String.eqb a b then KRTrue_Prop else\n (KREq_string_Prop (KRVar_string a) (KRVar_string b))*)\n | e => e\n end.\n\nFixpoint KRSimplify_ImplProp(p:KRExpr_Prop) :=\n KRSimplifyTop_ImplProp (match p with\n | KRAnd_Prop a b => KRAnd_Prop (KRSimplify_ImplProp a) (KRSimplify_ImplProp b)\n | KROr_Prop a b => KROr_Prop (KRSimplify_ImplProp a) (KRSimplify_ImplProp b)\n | KRNot_Prop a => KRNot_Prop (KRSimplify_ImplProp a)\n | KRIn_string_Prop a b => KRIn_string_Prop (KRSimplify_string a) (KRSimplify_list_string b)\n | KRIn_RegInitT_Prop a b => KRIn_RegInitT_Prop (KRSimplify_RegInitT a) (KRSimplify_list_RegInitT b)\n | KRIn_DefMethT_Prop a b => KRIn_DefMethT_Prop (KRSimplify_DefMethT a) (KRSimplify_list_DefMethT b)\n | KRIn_Rule_Prop a b => KRIn_Rule_Prop (KRSimplify_Rule a) (KRSimplify_list_Rule b)\n | KRDisjKey_RegInitT a b => KRDisjKey_RegInitT (KRSimplify_list_RegInitT a) (KRSimplify_list_RegInitT b)\n | KRDisjKey_DefMethT a b => KRDisjKey_DefMethT (KRSimplify_list_DefMethT a) (KRSimplify_list_DefMethT b)\n | KRDisjKey_Rule a b => KRDisjKey_Rule (KRSimplify_list_Rule a) (KRSimplify_list_Rule b)\n | KREq_string_Prop a b => KREq_string_Prop (KRSimplify_string a) (KRSimplify_string b)\n | KREq_RegInitT_Prop a b => KREq_RegInitT_Prop (KRSimplify_RegInitT a) (KRSimplify_RegInitT b)\n | KREq_Rule_Prop a b => KREq_Rule_Prop (KRSimplify_Rule a) (KRSimplify_Rule b)\n | KREq_DefMethT_Prop a b => KREq_DefMethT_Prop (KRSimplify_DefMethT a) (KRSimplify_DefMethT b)\n | p => p\n end).\n\nTheorem KRSimplify_ImplProp_KRAnd_Prop: forall a b,\n KRSimplify_ImplProp (KRAnd_Prop a b)= KRSimplifyTop_ImplProp (KRAnd_Prop (KRSimplify_ImplProp a) (KRSimplify_ImplProp b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRAnd_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KROr_Prop: forall a b,\n KRSimplify_ImplProp (KROr_Prop a b)= KRSimplifyTop_ImplProp (KROr_Prop (KRSimplify_ImplProp a) (KRSimplify_ImplProp b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KROr_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRNot_Prop: forall a,\n KRSimplify_ImplProp (KRNot_Prop a)= KRSimplifyTop_ImplProp (KRNot_Prop (KRSimplify_ImplProp a)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRNot_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRIn_string_Prop: forall a b,\n KRSimplify_ImplProp (KRIn_string_Prop a b)= KRSimplifyTop_ImplProp (KRIn_string_Prop (KRSimplify_string a) (KRSimplify_list_string b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRIn_string_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRIn_RegInitT_Prop: forall a b,\n KRSimplify_ImplProp (KRIn_RegInitT_Prop a b)= KRSimplifyTop_ImplProp (KRIn_RegInitT_Prop (KRSimplify_RegInitT a) (KRSimplify_list_RegInitT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRIn_RegInitT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRIn_DefMethT_Prop: forall a b,\n KRSimplify_ImplProp (KRIn_DefMethT_Prop a b)= KRSimplifyTop_ImplProp (KRIn_DefMethT_Prop (KRSimplify_DefMethT a) (KRSimplify_list_DefMethT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRIn_DefMethT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRIn_Rule_Prop: forall a b,\n KRSimplify_ImplProp (KRIn_Rule_Prop a b)= KRSimplifyTop_ImplProp (KRIn_Rule_Prop (KRSimplify_Rule a) (KRSimplify_list_Rule b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRIn_Rule_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRDisjKey_RegInitT_Prop: forall a b,\n KRSimplify_ImplProp (KRDisjKey_RegInitT a b)= KRSimplifyTop_ImplProp (KRDisjKey_RegInitT (KRSimplify_list_RegInitT a) (KRSimplify_list_RegInitT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRDisjKey_RegInitT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRDisjKey_DefMethT_Prop: forall a b,\n KRSimplify_ImplProp (KRDisjKey_DefMethT a b)= KRSimplifyTop_ImplProp (KRDisjKey_DefMethT (KRSimplify_list_DefMethT a) (KRSimplify_list_DefMethT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRDisjKey_DefMethT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KRDisjKey_Rule_Prop: forall a b,\n KRSimplify_ImplProp (KRDisjKey_Rule a b)= KRSimplifyTop_ImplProp (KRDisjKey_Rule (KRSimplify_list_Rule a) (KRSimplify_list_Rule b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KRDisjKey_Rule_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KREq_string_Prop: forall a b,\n KRSimplify_ImplProp (KREq_string_Prop a b)= KRSimplifyTop_ImplProp (KREq_string_Prop (KRSimplify_string a) (KRSimplify_string b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KREq_string_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KREq_RegInitT_Prop: forall a b,\n KRSimplify_ImplProp (KREq_RegInitT_Prop a b)= KRSimplifyTop_ImplProp (KREq_RegInitT_Prop (KRSimplify_RegInitT a) (KRSimplify_RegInitT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KREq_RegInitT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KREq_DefMethT_Prop: forall a b,\n KRSimplify_ImplProp (KREq_DefMethT_Prop a b)= KRSimplifyTop_ImplProp (KREq_DefMethT_Prop (KRSimplify_DefMethT a) (KRSimplify_DefMethT b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KREq_DefMethT_Prop : KRSimplify.\n\nTheorem KRSimplify_ImplProp_KREq_Rule_Prop: forall a b,\n KRSimplify_ImplProp (KREq_Rule_Prop a b)= KRSimplifyTop_ImplProp (KREq_Rule_Prop (KRSimplify_Rule a) (KRSimplify_Rule b)).\nProof.\n reflexivity.\nQed.\n\nHint Rewrite KRSimplify_ImplProp_KREq_Rule_Prop : KRSimplify.\n\nTheorem sdisjPrefix_false': forall p1 p2 s1 s2,\n sdisjPrefix (srev s1) (srev s2)=true -> (p1++s1=p2++s2)%string -> False.\nProof.\n intros p1 p2 s1 s2.\n repeat (rewrite <- sappend_append).\n assert ((p2++s2)%string=sappend p2 s2).\n - rewrite <- sappend_append.\n reflexivity.\n - rewrite H.\n intros.\n eapply sdisjPrefix_sappend_false.\n + apply H0.\n + apply H1.\nQed.\n\nLtac unitSolve :=\n simpl in *; simpl;\n match goal with\n | H: ?X |- ?X => apply H\n | |- True => apply I\n | H: False |- _ => inversion H\n | H: _ /\\ _ |- _ => inversion H; subst; clear H; unitSolve\n | H: _ \\/ _ |- _ => inversion H; subst; clear H; unitSolve\n | |- _ \\/ _ => left; solve [unitSolve]\n | |- _ \\/ _ => right; solve [unitSolve]\n | |- _ /\\ _ => split; unitSolve\n | |- DisjKey _ [] => apply DisjKey_nil2\n | |- DisjKey [] _ => apply DisjKey_nil1\n | |- DisjKey (_::_) _ => apply DisjKey_Cons1; unitSolve\n | |- DisjKey _ (_::_) => apply DisjKey_Cons2; unitSolve\n | |- DisjKey (_++_) _ => apply DisjKey_Append1; unitSolve\n | |- DisjKey _ (_++_) => apply DisjKey_Append2; unitSolve\n (*| H: DisjKey _ [] |- _ => inversion H; subst; clear H; unitSolve\n | H: DisjKey [] _ |- _ => inversion H; subst; clear H; unitSolve\n | H: DisjKey (_::_) _ |- _ => rewrite DisjKey_Cons1 in H; unitSolve\n | H: DisjKey _ (_::_) |- _ => rewrite DisjKey_Cons2 in H; unitSolve\n | H: DisjKey (_++_) _ |- _ => inversion H; subst; clear H; unitSolve\n | H: DisjKey _ (_++_) |- _ => inversion H; subst; clear H; unitSolve*)\n | |- { _=_ }+{ _<>_ } => repeat (decide equality)\n | |- forall _,_ => intros; unitSolve\n end.\n\nTheorem KRSimplifyTopSound_ImplProp: forall e,\n KRExprDenote_Prop (KRSimplifyTop_ImplProp e) -> KRExprDenote_Prop e.\nProof.\n intros.\n destruct e; try unitSolve.\n - destruct e1; destruct e2; split; try (unitSolve).\n - destruct e1; destruct e2; try (unitSolve).\n - destruct e; try (unitSolve).\n + simpl.\n intro X.\n apply X.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app.\n try unitSolve.\n - destruct k; destruct k0; try unitSolve; try (destruct k2; unitSolve).\n destruct k2; try unitSolve.\n destruct k0_2; try unitSolve.\n simpl in H.\n simpl.\n remember (sdisjPrefix (srev s) (srev s0)).\n destruct b.\n * simpl in H.\n inversion H.\n * simpl in H.\n apply H.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app.\n try unitSolve.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app.\n try unitSolve.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app.\n try unitSolve.\n - destruct k; destruct k0; try unitSolve.\n - destruct k; destruct k0; try unitSolve.\n - destruct k; destruct k0; try unitSolve.\nQed.\n\nTheorem KRSimplifyTopSound_RevImplProp: forall e,\n KRExprDenote_Prop e -> KRExprDenote_Prop (KRSimplifyTop_ImplProp e).\nProof.\n intros.\n destruct e; try unitSolve.\n - destruct e1; destruct e2; try (unitSolve).\n - destruct e1; destruct e2; try (unitSolve).\n - destruct e; try (unitSolve).\n + simpl in H.\n simpl.\n apply H.\n apply I.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app in H.\n try unitSolve.\n - destruct k; destruct k0; try unitSolve; try (destruct k2; unitSolve).\n destruct k2; try unitSolve.\n destruct k0_2; try unitSolve.\n simpl in H.\n simpl.\n remember (sdisjPrefix (srev s) (srev s0)).\n destruct b.\n * apply sdisjPrefix_false' in H. simpl in H.\n ++ inversion H.\n ++ rewrite Heqb.\n reflexivity.\n * simpl.\n apply H.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app in H.\n try unitSolve.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app in H.\n try unitSolve.\n - destruct k0; try unitSolve.\n + simpl in H.\n simpl.\n inversion H; subst; clear H.\n * left.\n rewrite H0.\n reflexivity.\n * right.\n apply H0.\n + simpl in H.\n simpl.\n rewrite in_app in H.\n try unitSolve.\n - destruct k; destruct k0; try unitSolve.\n + simpl in H; rewrite DisjKey_Cons2 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H; rewrite DisjKey_Append2 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H; rewrite DisjKey_Cons1 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H. simpl. split.\n * intro X.\n inversion X.\n * apply DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n apply H1.\n repeat (decide equality).\n + simpl.\n rewrite DisjKey_Cons2.\n simpl in H.\n rewrite DisjKey_Cons2 in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n simpl in H0.\n inversion H1; subst; clear H1.\n split.\n * intro X.\n inversion X; subst; clear X.\n ++ rewrite H1 in H0.\n simpl in H0.\n apply H0.\n left.\n reflexivity.\n ++ apply H.\n apply H1.\n * split.\n ++ intro X.\n apply H0.\n right.\n apply X.\n ++ apply H2.\n * repeat (decide equality).\n * intros.\n repeat (decide equality).\n * intros.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n split.\n * apply H0.\n * apply H1.\n * intros.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n - destruct k; destruct k0; try unitSolve.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n split.\n * intro X.\n inversion X.\n * apply DisjKey_nil2.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n simpl in H.\n inversion H; subst; clear H.\n rewrite DisjKey_Cons1 in H1;try (repeat (decide equality)).\n inversion H1; subst; clear H1.\n split.\n * intro X.\n inversion X; subst; clear X.\n ++ rewrite H1 in H0.\n simpl in H0.\n apply H0.\n left.\n reflexivity.\n ++ apply H.\n apply H1.\n * rewrite DisjKey_Cons2; try (repeat (decide equality)).\n split.\n ++ intro X.\n apply H0.\n right.\n apply X.\n ++ apply H2.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n - destruct k; destruct k0; try unitSolve.\n + simpl in H; rewrite DisjKey_Cons2 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H; rewrite DisjKey_Append2 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H; rewrite DisjKey_Cons1 in H; [simpl; apply H | repeat (decide equality)].\n + simpl in H. simpl. split.\n * intro X.\n inversion X.\n * apply DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n apply H1.\n repeat (decide equality).\n + simpl.\n rewrite DisjKey_Cons2.\n simpl in H.\n rewrite DisjKey_Cons2 in H.\n rewrite DisjKey_Cons1 in H.\n inversion H; subst; clear H.\n simpl in H0.\n inversion H1; subst; clear H1.\n split.\n * intro X.\n inversion X; subst; clear X.\n ++ rewrite H1 in H0.\n simpl in H0.\n apply H0.\n left.\n reflexivity.\n ++ apply H.\n apply H1.\n * split.\n ++ intro X.\n apply H0.\n right.\n apply X.\n ++ apply H2.\n * repeat (decide equality).\n * intros.\n repeat (decide equality).\n * intros.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Append1 in H.\n unitSolve.\n repeat (decide equality).\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Cons2 in H;try (repeat (decide equality)).\n apply H.\n + simpl.\n simpl in H.\n rewrite DisjKey_Append2 in H;try (repeat (decide equality)).\n apply H.\nQed.\n\nTheorem KRSimplifySound_ImplProp: forall e,\n KRExprDenote_Prop (KRSimplify_ImplProp e) <-> KRExprDenote_Prop e.\nProof.\n induction e; try (simpl; split; unitSolve).\n - split.\n * intros.\n simpl.\n autorewrite with KRSimplify in H.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n inversion H; subst; clear H.\n apply IHe1 in H0.\n apply IHe2 in H1.\n split.\n ++ apply H0.\n ++ apply H1.\n * intros.\n simpl in H.\n autorewrite with KRSimplify.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n inversion H; subst; clear H.\n split.\n ++ apply IHe1.\n apply H0.\n ++ apply IHe2.\n apply H1.\n - split.\n * intros.\n simpl.\n autorewrite with KRSimplify in H.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n inversion H; subst; clear H.\n + left.\n apply IHe1.\n apply H0.\n + right.\n apply IHe2.\n apply H0.\n * intros.\n simpl in H.\n autorewrite with KRSimplify.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n inversion H; subst; clear H.\n + left.\n apply IHe1.\n apply H0.\n + right.\n apply IHe2.\n apply H0.\n - split.\n * intros.\n simpl.\n autorewrite with KRSimplify in H.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n intro X.\n apply IHe in X.\n apply H in X.\n inversion X.\n * intros.\n simpl in H.\n autorewrite with KRSimplify.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n intro X.\n apply IHe in X.\n apply H in X.\n inversion X.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\n - autorewrite with KRSimplify.\n split.\n * intros.\n simpl.\n apply KRSimplifyTopSound_ImplProp in H.\n simpl in H.\n autorewrite with KRSimplify in H.\n apply H.\n * intros.\n simpl in H.\n apply KRSimplifyTopSound_RevImplProp.\n simpl.\n autorewrite with KRSimplify.\n apply H.\nQed.\n\nHint Rewrite KRSimplifySound_ImplProp : KRSimplify.\n\n(*Goal forall (a:ModuleElt) (b:list ModuleElt) c, app (cons a b) c=cons a (app b c).\n intros.\n match goal with\n | |- ?A = ?B => let x := (ltac:(KRExprReify A (KRTypeList (KRTypeElem KRElemModuleElt)))) in\n change A with (KRExprDenote_list_ModuleElt x);\n rewrite KRSimplifySound_list_ModuleElt;\n cbv [KRSimplify_list_ModuleElt KRSimplifyTop_list_ModuleElt KRExprDenote_list_ModuleElt KRExprDenote_ModuleElt KRSimplifyTop_ModuleElt KRSimplify_ModuleElt]\n end.\nAbort.*)\n\nLtac KRSimplifyTac e tp :=\n let x := (ltac:(KRExprReify e tp)) in\n let denote := match tp with\n | (KRTypeElem KRElemRegInitT) => KRExprDenote_RegInitT\n | (KRTypeElem KRElemRule) => KRExprDenote_Rule\n | (KRTypeElem KRElemDefMethT) => KRExprDenote_DefMethT\n | (KRTypeElem KRElemModuleElt) => KRExprDenote_ModuleElt\n | (KRTypeList (KRTypeElem KRElemRegInitT)) => KRExprDenote_list_RegInitT\n | (KRTypeList (KRTypeElem KRElemRule)) => KRExprDenote_list_Rule\n | (KRTypeList (KRTypeElem KRElemDefMethT)) => KRExprDenote_list_DefMethT\n | (KRTypeList (KRTypeElem KRElemModuleElt)) => KRExprDenote_list_ModuleElt\n | (KRTypeList (KRTypeList (KRTypeElem KRElemRegInitT))) => KRExprDenote_list_list_RegInitT\n | (KRTypeList (KRTypeList (KRTypeElem KRElemRule))) => KRExprDenote_list_list_Rule\n | (KRTypeList (KRTypeList (KRTypeElem KRElemDefMethT))) => KRExprDenote_list_list_DefMethT\n | (KRTypeList (KRTypeList (KRTypeElem KRElemModuleElt))) => KRExprDenote_list_list_ModuleElt\n | (KRTypeElem KRElemBaseModule) => KRExprDenote_BaseModule\n | (KRTypeElem KRElemMod) => KRExprDenote_Mod\n | (KRTypeList (KRTypeElem KRElemMod)) => KRExprDenote_list_Mod\n | (KRTypeElem KRElemString) => KRExprDenote_string\n | (KRTypeList (KRTypeElem KRElemString)) => KRExprDenote_list_string\n | (KRTypeList (KRTypeList (KRTypeElem KRElemString))) => KRExprDenote_list_list_string\n | (KRTypeElem KRElemRegFileBase) => KRExprDenote_RegFileBase\n | (KRTypeList (KRTypeElem KRElemRegFileBase)) => KRExprDenote_list_RegFileBase\n | (KRTypeElem KRElemCallWithSign) => KRExprDenote_CallWithSign\n | (KRTypeList (KRTypeElem KRElemCallWithSign)) => KRExprDenote_list_CallWithSign\n | (KRTypeList (KRTypeList (KRTypeElem KRElemCallWithSign))) => KRExprDenote_list_list_CallWithSign\n | (KRTypeElem KRElemProp) => KRExprDenote_Prop\n end in\n let simplifySound := match tp with\n | (KRTypeElem KRElemRegInitT) => KRSimplifySound_RegInitT\n | (KRTypeElem KRElemRule) => KRSimplifySound_Rule\n | (KRTypeElem KRElemDefMethT) => KRSimplifySound_DefMethT\n | (KRTypeElem KRElemModuleElt) => KRSimplifySound_ModuleElt\n | (KRTypeList (KRTypeElem KRElemRegInitT)) => KRSimplifySound_list_RegInitT\n | (KRTypeList (KRTypeElem KRElemRule)) => KRSimplifySound_list_Rule\n | (KRTypeList (KRTypeElem KRElemDefMethT)) => KRSimplifySound_list_DefMethT\n | (KRTypeList (KRTypeElem KRElemModuleElt)) => KRSimplifySound_list_ModuleElt\n | (KRTypeList (KRTypeList (KRTypeElem KRElemRegInitT))) => KRSimplifySound_list_RegInitT\n | (KRTypeList (KRTypeList (KRTypeElem KRElemRule))) => KRSimplifySound_list_Rule\n | (KRTypeList (KRTypeList (KRTypeElem KRElemDefMethT))) => KRSimplifySound_list_DefMethT\n | (KRTypeList (KRTypeList (KRTypeElem KRElemModuleElt))) => KRSimplifySound_list_list_ModuleElt\n | (KRTypeElem KRElemString) => KRSimplifySound_string\n | (KRTypeList (KRTypeElem KRElemString)) => KRSimplifySound_list_string\n | (KRTypeList (KRTypeList (KRTypeElem KRElemString))) => KRSimplifySound_list_list_string\n | (KRTypeElem KRElemRegFileBase) => KRSimplifySound_RegFileBase\n | (KRTypeList (KRTypeElem KRElemRegFileBase)) => KRSimplify_list_RegFileBase\n | (KRTypeElem KRElemCallWithSign) => KRSimplifySound_CallWithSign\n | (KRTypeList (KRTypeElem KRElemCallWithSign)) => KRSimplify_list_CallWithSign\n | (KRTypeElem KRElemBaseModule) => KRSimplifySound_BaseModule\n | (KRTypeElem KRElemMod) => KRSimplifySound_Mod\n | (KRTypeList (KRTypeElem KRElemMod)) => KRSimplifySound_list_Mod\n | (KRTypeElem KRElemProp) => KRSimplifySound_ImplProp\n end in\n change e with (denote x);repeat (rewrite <- simplifySound;try (repeat (decide equality));cbv [\n sappend srev sdisjPrefix String.eqb Ascii.eqb Bool.eqb\n KRSimplify_RegInitT KRSimplifyTop_RegInitT\n KRSimplify_RegInitValT KRSimplifyTop_RegInitValT\n KRSimplify_Rule KRSimplifyTop_Rule\n KRSimplify_DefMethT KRSimplifyTop_DefMethT\n KRSimplify_ModuleElt KRSimplifyTop_ModuleElt\n KRSimplify_list_RegInitT KRSimplifyTop_list_RegInitT\n KRSimplify_list_Rule KRSimplifyTop_list_Rule\n KRSimplify_list_DefMethT KRSimplifyTop_list_DefMethT\n KRSimplify_list_ModuleElt KRSimplifyTop_list_ModuleElt\n KRSimplify_list_list_RegInitT KRSimplifyTop_list_list_RegInitT\n KRSimplify_list_list_Rule KRSimplifyTop_list_list_Rule\n KRSimplify_list_list_DefMethT KRSimplifyTop_list_list_DefMethT\n KRSimplify_list_list_ModuleElt KRSimplifyTop_list_list_ModuleElt\n KRSimplify_BaseModule KRSimplifyTop_BaseModule\n KRSimplify_RegFileBase KRSimplifyTop_RegFileBase\n KRSimplify_list_RegFileBase KRSimplifyTop_list_RegFileBase\n KRSimplify_string KRSimplifyTop_string\n KRSimplify_list_string KRSimplifyTop_list_string\n KRSimplify_list_list_string KRSimplifyTop_list_list_string\n KRSimplify_Mod KRSimplifyTop_Mod\n KRSimplify_Mod KRSimplifyTop_list_Mod\n KRSimplify_ImplProp KRSimplifyTop_ImplProp\n ]);\n cbv [\n sappend srev sdisjPrefix String.eqb Ascii.eqb Bool.eqb\n KRExprDenote_RegInitT\n KRExprDenote_RegInitValT\n KRExprDenote_Rule\n KRExprDenote_DefMethT\n KRExprDenote_ModuleElt\n KRExprDenote_list_RegInitT\n KRExprDenote_list_Rule\n KRExprDenote_list_DefMethT\n KRExprDenote_ActionVoid\n KRExprDenote_MethodT\n KRExprDenote_list_ModuleElt\n KRExprDenote_list_list_RegInitT\n KRExprDenote_list_list_Rule\n KRExprDenote_list_list_DefMethT\n KRExprDenote_list_list_ModuleElt\n KRExprDenote_BaseModule\n KRExprDenote_Mod\n KRExprDenote_list_Mod\n KRExprDenote_RegFileBase\n KRExprDenote_list_RegFileBase\n KRExprDenote_string\n KRExprDenote_list_string\n KRExprDenote_list_list_string\n KRExprDenote_Prop].\n\n\n(*Ltac KRPrintReify e :=\n let x := (ltac:(KRExprReify e t)) in\n let t := eval compute in (KRTypeDenote x) in\n let xx := (ltac:(KRExprReify e t)) in\n idtac t;idtac x.\n *)\n\nGoal forall a b c d e, Registers ([a;b]++[c;d])=e.\n intros.\n match goal with\n | |- ?A = ?B => KRSimplifyTac A (KRTypeList (KRTypeElem KRElemModuleElt))\n end.\nAbort.\nGoal forall a b c d e, makeModule_regs [MERegister a;MERule b;MEMeth c;MERegister d]=e.\n intros.\n match goal with\n | |- ?A = ?B => \n (*let x := (ltac:(KRExprReify A (KRTypeList (KRTypeElem KRElemRegInitT)))) in\n idtac x*)\n KRSimplifyTac A (KRTypeList (KRTypeElem KRElemRegInitT))\n end.\nAbort.\nGoal forall a b c d e, makeModule_rules [MERegister a;MERule b;MEMeth c;MERegister d]=e.\n intros.\n match goal with\n | |- ?A = ?B =>\n KRSimplifyTac A (KRTypeList (KRTypeElem KRElemRule))\n end.\nAbort.\nGoal forall a b c d e, makeModule_meths [MEMeth a;MERule b;MERegister c;MERegister d]=e.\n intros.\n match goal with\n | |- ?A = ?B => \n KRSimplifyTac A (KRTypeList (KRTypeElem KRElemDefMethT))\n end.\nAbort.\nGoal forall e, makeModule_regs []=e.\n intros.\n match goal with\n | |- ?A = ?B => \n KRSimplifyTac A (KRTypeList (KRTypeElem KRElemRegInitT))\n end.\nAbort.\nGoal forall x, x \\/ True.\n intros.\n match goal with\n | |- ?X => KRSimplifyTac X (KRTypeElem KRElemProp)\n end.\nAbort.\nGoal forall proc_name, ~(( proc_name ++ \"_\" ++ \"a\")%string = (proc_name ++ \"_\" ++ \"b\")%string).\n intros.\n match goal with\n | |- ~ ?A => \n let x := (ltac:(KRExprReify (~A) (KRTypeElem KRElemProp))) in change (~A) with (KRExprDenote_Prop x)\n end.\n rewrite <- KRSimplifySound_ImplProp.\n cbv [\n KRSimplify_RegInitT KRSimplifyTop_RegInitT\n KRSimplify_RegInitValT KRSimplifyTop_RegInitValT\n KRSimplify_Rule KRSimplifyTop_Rule\n KRSimplify_DefMethT KRSimplifyTop_DefMethT\n KRSimplify_ModuleElt KRSimplifyTop_ModuleElt\n KRSimplify_list_RegInitT KRSimplifyTop_list_RegInitT\n KRSimplify_list_Rule KRSimplifyTop_list_Rule\n KRSimplify_list_DefMethT KRSimplifyTop_list_DefMethT\n KRSimplify_list_ModuleElt KRSimplifyTop_list_ModuleElt\n KRSimplify_list_list_RegInitT KRSimplifyTop_list_list_RegInitT\n KRSimplify_list_list_Rule KRSimplifyTop_list_list_Rule\n KRSimplify_list_list_DefMethT KRSimplifyTop_list_list_DefMethT\n KRSimplify_list_list_ModuleElt KRSimplifyTop_list_list_ModuleElt\n KRSimplify_BaseModule KRSimplifyTop_BaseModule\n KRSimplify_RegFileBase KRSimplifyTop_RegFileBase\n KRSimplify_list_RegFileBase KRSimplifyTop_list_RegFileBase\n KRSimplify_string KRSimplifyTop_string\n KRSimplify_list_string KRSimplifyTop_list_string\n KRSimplify_list_list_string KRSimplifyTop_list_list_string\n KRSimplify_Mod KRSimplifyTop_Mod\n KRSimplify_Mod KRSimplifyTop_list_Mod\n KRSimplify_ImplProp KRSimplifyTop_ImplProp\n ].\n cbv [ sappend srev sdisjPrefix\n KRExprDenote_RegInitT\n KRExprDenote_Rule\n KRExprDenote_DefMethT\n KRExprDenote_ModuleElt\n KRExprDenote_list_RegInitT\n KRExprDenote_list_Rule\n KRExprDenote_list_DefMethT\n KRExprDenote_list_ModuleElt\n KRExprDenote_list_list_RegInitT\n KRExprDenote_list_list_Rule\n KRExprDenote_list_list_DefMethT\n KRExprDenote_list_list_ModuleElt\n KRExprDenote_BaseModule\n KRExprDenote_Mod\n KRExprDenote_list_Mod\n KRExprDenote_RegFileBase\n KRExprDenote_list_RegFileBase\n KRExprDenote_string\n KRExprDenote_list_string\n KRExprDenote_list_list_string\n KRExprDenote_Prop].\nAbort.\n\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Rewrites/ReflectionImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.268941415510503, "lm_q1q2_score": 0.13972080371511422}} {"text": "Require Import Bool List String Peano_dec Lia.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Msi Ex.Msi.Msi.\n\nSet Implicit Arguments.\n\nImport PropMonadNotations.\nImport CaseNotations.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\n#[global] Existing Instance Msi.ImplOStateIfc.\n\nSection ObjInv.\n Variable topo: DTree.\n\n Definition MsiUpLockObjInv (oidx: IdxT): ObjInv :=\n fun ost orq =>\n (rqiu <+- orq@[upRq];\n rmsg <+- rqiu.(rqi_msg);\n match case rmsg.(msg_id) on idx_dec default True with\n | msiRqS:\n ost#[owned] = false /\\ ost#[status] <= msiI /\\\n ost#[dir].(dir_st) <= msiS\n | msiRqM:\n ost#[owned] = false /\\ ost#[status] <= msiS /\\\n ost#[dir].(dir_st) <= msiS\n end).\n\n Definition DownLockFromChild (oidx: IdxT) (rqid: RqInfo Msg) :=\n exists cidx,\n rqid.(rqi_midx_rsb) = Some (downTo cidx) /\\\n parentIdxOf topo cidx = Some oidx.\n\n Definition DownLockFromParent (oidx: IdxT) (rqid: RqInfo Msg) :=\n rqid.(rqi_midx_rsb) = Some (rsUpFrom oidx).\n\n Definition MsiDownLockObjInv (oidx: IdxT): ObjInv :=\n fun ost orq =>\n (rqid <+- orq@[downRq];\n rmsg <+- rqid.(rqi_msg);\n match case rmsg.(msg_id) on idx_dec default True with\n | msiRqS: DownLockFromChild oidx rqid /\\\n ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM /\\\n In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n | msiRqM: DownLockFromChild oidx rqid /\\\n ost#[status] <= msiS /\\\n ((ost#[owned] = true /\\ ost#[dir].(dir_st) = msiS /\\\n SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n (rsb <+- rqid.(rqi_midx_rsb);\n map fst rqid.(rqi_rss) =\n map rsUpFrom (remove idx_dec (objIdxOf rsb) ost#[dir].(dir_sharers)))) \\/\n (ost#[dir].(dir_st) = msiM /\\\n In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n | msiDownRqS: DownLockFromParent oidx rqid /\\\n ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM /\\\n In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n | msiDownRqIS: DownLockFromParent oidx rqid /\\\n ost#[dir].(dir_st) = msiS /\\\n SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)\n | msiDownRqIM: DownLockFromParent oidx rqid /\\\n ((ost#[dir].(dir_st) = msiS /\\\n SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)) \\/\n (ost#[dir].(dir_st) = msiM /\\\n In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n end).\n\n Definition MsiObjInvs (oidx: IdxT): ObjInv :=\n fun ost orq =>\n MsiUpLockObjInv oidx ost orq /\\\n MsiDownLockObjInv oidx ost orq.\n\nEnd ObjInv.\n\nLtac disc_msi_obj_invs :=\n repeat\n match goal with\n | [H: MsiObjInvs _ _ _ _ |- _] => destruct H\n | [H: MsiUpLockObjInv _ _ _ |- _] =>\n red in H; mred; simpl in H; disc_rule_conds_const\n | [H: MsiDownLockObjInv _ _ _ _ |- _] =>\n red in H; mred; simpl in H; disc_rule_conds_const\n | [Hmsg: msg_id ?rmsg = _, H: context [msg_id ?rmsg] |- _] =>\n rewrite Hmsg in H; simpl in H\n end.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Ex/Msi/MsiObjInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2689414096510108, "lm_q1q2_score": 0.13972079666955253}} {"text": "Require Import Bool Vector List String Peano_dec.\nRequire Import Common FMap HVector ListSupport IndexSupport.\nRequire Import Syntax Topology Semantics Invariant.\nRequire Import RqRsLang.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template Ex.Mesi.\nRequire Import Ex.Mesi.Mesi Ex.Mesi.MesiObjInv.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\nSection System.\n Variable tr: tree.\n Hypothesis (Htr: tr <> Node nil).\n\n Local Notation topo := (fst (tree2Topo tr 0)).\n Local Notation cifc := (snd (tree2Topo tr 0)).\n Local Notation impl := (impl Htr).\n\n Hint Extern 0 (TreeTopo _) => apply tree2Topo_TreeTopo.\n Hint Extern 0 (WfDTree _) => apply tree2Topo_WfDTree.\n\n Lemma mesi_indices:\n map obj_idx (sys_objs impl) = c_li_indices cifc ++ c_l1_indices cifc.\n Proof.\n simpl; rewrite c_li_indices_head_rootOf at 2 by assumption.\n simpl; f_equal.\n rewrite map_app, map_map, map_id; simpl.\n rewrite map_map, map_id; reflexivity.\n Qed.\n\n Lemma mesi_GoodORqsInit: GoodORqsInit (initsOf impl).\n Proof.\n apply initORqs_GoodORqsInit.\n Qed.\n\n Lemma mesi_WfDTree: WfDTree topo.\n Proof.\n apply tree2Topo_WfDTree.\n Qed.\n\n Lemma mesi_RqRsChnsOnDTree: RqRsChnsOnDTree topo.\n Proof.\n apply tree2Topo_RqRsChnsOnDTree.\n Qed.\n\n Lemma mesi_RqRsChnsOnSystem: RqRsChnsOnSystem topo impl.\n Proof.\n eapply tree2Topo_RqRsChnsOnSystem with (tr0:= tr) (bidx:= [0]); try reflexivity.\n - destruct (tree2Topo _ _); reflexivity.\n - simpl.\n rewrite map_app.\n do 2 rewrite map_trans.\n do 2 rewrite map_id.\n rewrite app_comm_cons.\n rewrite <-c_li_indices_head_rootOf by assumption.\n reflexivity.\n Qed.\n\n Lemma mesi_ExtsOnDTree: ExtsOnDTree topo impl.\n Proof.\n eapply tree2Topo_ExtsOnDTree with (tr0:= tr) (bidx:= [0]); try reflexivity.\n destruct (tree2Topo _ _); reflexivity.\n Qed.\n\n Lemma mesi_RqRsDTree: RqRsDTree topo impl.\n Proof.\n red; repeat ssplit.\n - auto using mesi_WfDTree.\n - auto using mesi_RqRsChnsOnDTree.\n - auto using mesi_RqRsChnsOnSystem.\n - auto using mesi_ExtsOnDTree.\n Qed.\n\n Ltac solve_GoodRqRsRule_unfold ::= autounfold with MesiRules.\n\n Lemma mesi_GoodRqRsSys: GoodRqRsSys topo impl.\n Proof.\n repeat\n match goal with\n | |- GoodRqRsSys _ _ => red\n | |- GoodRqRsObj _ _ _ => red\n | |- Forall _ _ => simpl; constructor; simpl\n | |- Forall _ (_ ++ _) => apply Forall_app\n end.\n\n - (** Main memory *)\n\n assert (In (rootOf topo) (c_li_indices cifc)) as Hrin.\n { rewrite c_li_indices_head_rootOf by assumption.\n left; reflexivity.\n }\n\n simpl.\n repeat\n match goal with\n | |- Forall _ (_ ++ _) => apply Forall_app\n | |- Forall _ (_ :: _) => constructor\n | |- Forall _ nil => constructor\n end.\n\n apply Forall_forall; intros.\n unfold liRulesFromChildren in H.\n apply concat_In in H; dest.\n apply in_map_iff in H; dest; subst.\n dest_in.\n all: try (solve_GoodRqRsRule; fail).\n\n - (** Li caches *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; simpl.\n\n (* pre-register a fact: an Li cache always has a parent *)\n pose proof (c_li_l1_indices_has_parent\n Htr _ _ (in_or_app _ _ _ (or_introl H0))).\n destruct H as [pidx ?].\n\n repeat\n match goal with\n | |- Forall _ (_ ++ _) => apply Forall_app\n | |- Forall _ (_ :: _) => constructor\n | |- Forall _ nil => constructor\n end.\n all: try (solve_GoodRqRsRule; fail).\n\n 1: {\n apply Forall_forall; intros.\n unfold liRulesFromChildren in H1.\n apply concat_In in H1; dest.\n apply in_map_iff in H1; dest; subst.\n dest_in.\n all: try (solve_GoodRqRsRule; fail).\n\n { (* [liGetSRqUpDownME] *)\n apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n rewrite <-mesi_indices in H1.\n\n rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n (** [RqUpDownSound] *)\n red; simpl; intros; dest.\n apply subtreeChildrenIndsOf_parentIdxOf in H4; [|apply tree2Topo_WfDTree].\n repeat ssplit; [discriminate| |intuition auto].\n repeat constructor; try assumption.\n }\n\n { (* [liGetMRqUpDownME] *)\n apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n rewrite <-mesi_indices in H1.\n\n rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n (** [RqUpDownSound] *)\n red; simpl; intros; dest.\n apply subtreeChildrenIndsOf_parentIdxOf in H4; [|apply tree2Topo_WfDTree].\n repeat ssplit; [discriminate| |intuition auto].\n repeat constructor; try assumption.\n }\n\n { (* [liGetMRqUpDownS] *)\n apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n rewrite <-mesi_indices in H1.\n\n rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n (** [RqUpDownSound] *)\n red; simpl; intros; dest.\n repeat ssplit.\n { assumption. }\n { apply Forall_forall; intros.\n apply in_remove in H9.\n apply H4 in H9.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n { apply remove_In. }\n }\n }\n\n { (* [liDownSRqDownDownME] *)\n rule_rqdd.\n eapply rqDownDownRule_RqFwdRule; eauto.\n\n (** [RqDownDownSound] *)\n red; simpl; intros; dest.\n repeat ssplit; [discriminate|].\n repeat constructor.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n\n { (* [liGetMRsDownRqDownDirS] *)\n rule_rsrq; eapply rsDownRqDownRule_RsDownRqDownRule; eauto.\n\n (** [RsDownRqDownSound] *)\n red; simpl; intros; dest.\n red in H1.\n unfold getUpLockIdxBackI, getUpLockIdxBack in *.\n destruct (orq@[upRq]) as [rqiu|]; simpl in *; auto.\n destruct H1 as [rcidx [rqUp ?]]; dest.\n pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H1).\n rewrite <-mesi_indices in H9.\n intros; rewrite H11 in *.\n repeat ssplit.\n { assumption. }\n { apply Forall_forall; intros.\n apply in_remove in H12.\n apply H3 in H12.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n { exists rcidx, rqUp.\n repeat split; try assumption.\n }\n }\n\n { (* [liDownIRqDownDownDirS] *)\n rule_rqdd.\n eapply rqDownDownRule_RqFwdRule; eauto.\n\n (** [RqDownDownSound] *)\n red; simpl; intros; dest.\n repeat ssplit; [assumption|].\n apply Forall_forall; intros.\n apply H2 in H4.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n\n { (* [liDownIRqDownDownDirME] *)\n rule_rqdd.\n eapply rqDownDownRule_RqFwdRule; eauto.\n\n (** [RqDownDownSound] *)\n red; simpl; intros; dest.\n repeat ssplit; [discriminate|].\n repeat constructor.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n\n { (* [liDownIRqDownDownDirMES] *)\n rule_rqdd.\n eapply rqDownDownRule_RqFwdRule; eauto.\n\n (** [RqDownDownSound] *)\n red; simpl; intros; dest.\n repeat ssplit; [assumption|].\n apply Forall_forall; intros.\n apply H2 in H4.\n eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n }\n\n - (** L1 caches *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; simpl.\n\n (* pre-register a fact: an L1 cache always has a parent *)\n pose proof (c_li_l1_indices_has_parent\n Htr _ _ (in_or_app _ _ _ (or_intror H0))).\n destruct H as [pidx ?].\n\n repeat\n match goal with\n | |- Forall _ (_ ++ _) => apply Forall_app\n | |- Forall _ (_ :: _) => constructor\n | |- Forall _ nil => constructor\n end.\n all: try (solve_GoodRqRsRule; fail).\n Qed.\n\n Ltac exfalso_RqToUpRule_unfold ::= repeat autounfold with MesiRules in *.\n Ltac exfalso_RsToUpRule_unfold ::= repeat autounfold with MesiRules in *.\n Ltac disc_rule_custom ::= disc_mesi_obj_invs.\n\n Lemma mesi_RqUpRsUpOkSys: RqUpRsUpOkSys topo impl (MesiObjInvs topo).\n Proof. (* SKIP_PROOF_ON\n repeat\n match goal with\n | |- RqUpRsUpOkSys _ _ _ => red\n | |- Forall _ _ => simpl; constructor; simpl\n | |- Forall _ (_ ++ _) => apply Forall_app\n end.\n\n - (** The main memory: no RqUp rules *)\n red; intros.\n simpl in H; unfold liRulesFromChildren in H.\n apply concat_In in H; dest.\n apply in_map_iff in H; dest; subst.\n dest_in.\n all: try (exfalso_RqToUpRule; fail).\n\n - (** Li cache *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; intros.\n\n simpl in H; apply in_app_or in H; destruct H;\n [unfold liRulesFromChildren in H;\n apply concat_In in H; dest;\n apply in_map_iff in H; dest; subst;\n dest_in|dest_in].\n all: try (exfalso_RqToUpRule; fail).\n\n + simpl in H2; apply in_app_or in H2; destruct H2;\n [unfold liRulesFromChildren in H;\n apply concat_In in H; dest;\n apply in_map_iff in H; dest; subst;\n dest_in|dest_in].\n all: try (exfalso_RsToUpRule; fail).\n\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; auto.\n { destruct H17; dest; try solve [congruence|solve_mesi]. }\n { destruct H17; dest; try solve [congruence|solve_mesi]. }\n }\n { clear; solve_rule_conds_ex; auto.\n { destruct H17; dest; try solve [congruence|solve_mesi]. }\n { destruct H17; dest; try solve [congruence|solve_mesi]. }\n }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi.\n f_equal; apply M.add_remove_comm; discriminate.\n }\n { clear; solve_rule_conds_ex; try solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi.\n f_equal; apply M.add_remove_comm; discriminate.\n }\n\n + simpl in H2; apply in_app_or in H2; destruct H2;\n [unfold liRulesFromChildren in H;\n apply concat_In in H; dest;\n apply in_map_iff in H; dest; subst;\n dest_in|dest_in].\n all: try (exfalso_RsToUpRule; fail).\n\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi.\n all: try (destruct H17; dest; try solve [congruence|solve_mesi]).\n }\n { clear; solve_rule_conds_ex; try solve_mesi.\n all: try (destruct H17; dest; try solve [congruence|solve_mesi]).\n }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi.\n f_equal; apply M.add_remove_comm; discriminate.\n }\n { clear; solve_rule_conds_ex; try solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi.\n f_equal; apply M.add_remove_comm; discriminate.\n }\n\n + simpl in H2; apply in_app_or in H2; destruct H2;\n [unfold liRulesFromChildren in H;\n apply concat_In in H; dest;\n apply in_map_iff in H; dest; subst;\n dest_in|dest_in].\n all: try (exfalso_RsToUpRule; fail).\n\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_const; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_const.\n all: rewrite invalidate_I; solve_mesi.\n }\n { clear; solve_rule_conds_const; try solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi. }\n { clear; solve_rule_conds_ex; try solve_mesi. }\n\n + simpl in H2; apply in_app_or in H2; destruct H2;\n [unfold liRulesFromChildren in H;\n apply concat_In in H; dest;\n apply in_map_iff in H; dest; subst;\n dest_in|dest_in].\n all: try (exfalso_RsToUpRule; fail).\n\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_const; try intuition solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_const.\n rewrite invalidate_I; [|solve_mesi].\n intuition solve_mesi.\n }\n { clear; solve_rule_conds_const; try intuition solve_mesi. }\n { clear; solve_rule_conds_ex; solve_mesi. }\n { clear; solve_rule_conds_ex; try intuition solve_mesi. }\n { clear; solve_rule_conds_ex; try intuition solve_mesi. }\n\n - (** L1 cache *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; intros.\n\n phide H2; dest_in.\n all: try (exfalso_RqToUpRule; fail).\n\n + preveal H4; dest_in.\n all: try (exfalso_RsToUpRule; fail).\n { clear; solve_rule_conds_const; solve_mesi. }\n { clear; solve_rule_conds_const; auto. }\n { clear; solve_rule_conds_const; auto. }\n\n + preveal H4; dest_in.\n all: try (exfalso_RsToUpRule; fail).\n { clear; solve_rule_conds_const. }\n { clear; solve_rule_conds_const; solve_mesi. }\n { clear; solve_rule_conds_const; solve_mesi. }\n\n + preveal H4; dest_in.\n all: try (exfalso_RsToUpRule; fail).\n { clear; solve_rule_conds_const; try solve_mesi. }\n { clear; solve_rule_conds_const.\n all: rewrite invalidate_I; solve_mesi.\n }\n { clear; solve_rule_conds_const.\n all: rewrite invalidate_I; solve_mesi.\n }\n\n + preveal H4; dest_in.\n all: try (exfalso_RsToUpRule; fail).\n { clear; solve_rule_conds_const; try solve_mesi. }\n { clear; solve_rule_conds_const.\n rewrite invalidate_I; solve_mesi.\n }\n { clear; solve_rule_conds_const.\n rewrite invalidate_I; solve_mesi.\n }\n\n END_SKIP_PROOF_ON *) admit.\n Qed.\n\n Lemma mesi_GoodExtRssSys: GoodExtRssSys impl.\n Proof. (* SKIP_PROOF_ON\n red; simpl.\n constructor; [|apply Forall_app].\n - (** the main memory *)\n red; simpl.\n apply Forall_forall; intros.\n unfold memRulesFromChildren in H.\n apply concat_In in H; dest.\n apply in_map_iff in H; dest; subst.\n dest_in.\n all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n\n - (** Li cache *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; simpl.\n apply Forall_app.\n\n + apply Forall_forall; intros.\n unfold liRulesFromChildren in H.\n apply concat_In in H; dest.\n apply in_map_iff in H; dest; subst.\n dest_in.\n all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n { (* [liGetMRqUpDownS] *)\n red; simpl; disc_rule_conds_ex.\n apply in_map_iff in H3; dest; subst.\n apply in_remove in H12.\n apply H5 in H12.\n simpl in *; solve_GoodExtRssSys.\n }\n\n + repeat constructor.\n all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n { (* [liGetMRsDownRqDownDirS] *)\n red; simpl; disc_rule_conds_ex.\n apply in_map_iff in H2; dest; subst.\n apply in_remove in H5.\n apply H11 in H5.\n simpl in *; solve_GoodExtRssSys.\n }\n { (* [liDownIRqDownDownDirS] *)\n red; simpl; disc_rule_conds_ex.\n apply in_map_iff in H2; dest; subst.\n apply H4 in H7.\n simpl in *; solve_GoodExtRssSys.\n }\n { (* [liDownIRqDownDownDirMES] *)\n red; simpl; disc_rule_conds_ex.\n apply in_map_iff in H2; dest; subst.\n apply H4 in H7.\n simpl in *; solve_GoodExtRssSys.\n }\n\n - (** L1 cache *)\n apply Forall_forall; intros.\n apply in_map_iff in H.\n destruct H as [oidx [? ?]]; subst.\n red; simpl.\n repeat constructor.\n all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n\n END_SKIP_PROOF_ON *) admit.\n Qed.\n\n Lemma mesi_GoodRqRsInterfSys: GoodRqRsInterfSys topo impl (MesiObjInvs topo).\n Proof.\n split.\n - apply mesi_RqUpRsUpOkSys.\n - apply mesi_GoodExtRssSys.\n Qed.\n\n Lemma mesi_RqRsSys: RqRsSys topo impl (MesiObjInvs topo).\n Proof.\n red; repeat ssplit.\n - apply mesi_RqRsDTree.\n - apply mesi_GoodRqRsSys.\n - apply mesi_GoodRqRsInterfSys.\n Qed.\n\nEnd System.\n\n#[global] Hint Resolve mesi_GoodORqsInit mesi_WfDTree mesi_RqRsDTree mesi_RqRsSys.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Ex/Mesi/MesiTopo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2689414096510108, "lm_q1q2_score": 0.13972079666955253}} {"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import Classes.SetoidTactics.\nRequire Import FunctionalExtensionality.\nRequire Import Omega.\nRequire Import Eqdep_dec.\nRequire Import ListUtils.\nRequire Import AsyncDisk.\nRequire Import Pred.\nRequire Import SepAuto.\nRequire Import GenSepN.\nRequire Import MapUtils.\nRequire Import FMapFacts.\nRequire Import RelationClasses.\nRequire Import Morphisms.\nRequire Import Array.\nRequire Import DiskLogHash.\nRequire Import Word.\nRequire Import PredCrash.\nRequire Import Prog.\n\nImport AddrMap.\nImport ListNotations.\n\nDefinition valumap := Map.t valu.\nDefinition vmap0 := map0 valu.\nDefinition diskstate := list valuset.\n\nLemma map_empty_vmap0 : Map.Empty vmap0.\nProof.\n apply Map.empty_1.\nQed.\n\n\nModule LogReplay.\n\n Definition replay_mem (log : DLog.contents) init : valumap :=\n fold_left (fun m e => Map.add (fst e) (snd e) m) log init.\n\n Definition replay_disk (log : DLog.contents) (m : diskstate) : diskstate:=\n fold_left (fun m' e => updN m' (fst e) (snd e, nil)) log m.\n\n Definition map_merge (m1 m2 : valumap) :=\n replay_mem (Map.elements m2) m1.\n\n Definition map_replay ms old cur : Prop :=\n cur = replay_disk (Map.elements ms) old.\n\n Hint Resolve MapProperties.eqke_equiv.\n Hint Resolve KNoDup_map_elements.\n\n Lemma replay_disk_length : forall l m,\n length (replay_disk l m) = length m.\n Proof.\n induction l; intros; simpl; auto.\n rewrite IHl.\n rewrite length_updN; auto.\n Qed.\n\n Lemma replay_disk_updN_comm : forall l d a v,\n ~ In a (map fst l)\n -> replay_disk l (updN d a v) = updN (replay_disk l d) a v.\n Proof.\n induction l; simpl; intuition; simpl in *.\n rewrite updN_comm by auto.\n apply IHl; auto.\n Qed.\n\n Lemma replay_disk_selN_other : forall l d a def,\n ~ In a (map fst l)\n -> selN (replay_disk l d) a def = selN d a def.\n Proof.\n induction l; simpl; intuition; simpl in *.\n rewrite IHl; auto.\n rewrite selN_updN_ne; auto.\n Qed.\n\n Lemma replay_disk_selN_In : forall l m a v def,\n In (a, v) l -> NoDup (map fst l) -> a < length m ->\n selN (replay_disk l m) a def = (v, nil).\n Proof.\n induction l; simpl; intros; auto.\n inversion H.\n inversion H0; subst.\n destruct a; intuition; simpl.\n inversion H2; subst.\n rewrite replay_disk_updN_comm by auto.\n rewrite selN_updN_eq; auto.\n erewrite replay_disk_length; auto.\n simpl in *.\n apply IHl; auto.\n rewrite length_updN; auto.\n Qed.\n\n Lemma replay_disk_selN_In_KNoDup : forall a v l m def,\n In (a, v) l -> KNoDup l -> a < length m ->\n selN (replay_disk l m) a def = (v, nil).\n Proof.\n intros.\n eapply replay_disk_selN_In; eauto.\n apply KNoDup_NoDup; auto.\n Qed.\n\n Lemma replay_disk_selN_MapsTo : forall a v ms m def,\n Map.MapsTo a v ms -> a < length m ->\n selN (replay_disk (Map.elements ms) m) a def = (v, nil).\n Proof.\n intros.\n apply replay_disk_selN_In_KNoDup; auto.\n apply InA_eqke_In.\n apply MapFacts.elements_mapsto_iff; auto.\n Qed.\n\n Lemma replay_disk_selN_not_In : forall a ms m def,\n ~ Map.In a ms\n -> selN (replay_disk (Map.elements ms) m) a def = selN m a def.\n Proof.\n intros.\n apply replay_disk_selN_other; auto.\n contradict H.\n erewrite MapFacts.elements_in_iff.\n apply in_map_fst_exists_snd in H; destruct H.\n eexists. apply In_InA; eauto.\n Qed.\n\n Hint Rewrite replay_disk_length : lists.\n\n Lemma replay_disk_add : forall a v ds m,\n replay_disk (Map.elements (Map.add a v ds)) m = updN (replay_disk (Map.elements ds) m) a (v, nil).\n Proof.\n intros.\n eapply list_selN_ext.\n autorewrite with lists; auto.\n intros.\n destruct (eq_nat_dec pos a); subst; autorewrite with lists in *.\n rewrite selN_updN_eq by (autorewrite with lists in *; auto).\n apply replay_disk_selN_MapsTo; auto.\n apply Map.add_1; auto. reflexivity.\n\n rewrite selN_updN_ne by auto.\n case_eq (Map.find pos ds); intros; autorewrite with lists in *.\n (* [pos] is in the transaction *)\n apply Map.find_2 in H0.\n setoid_rewrite replay_disk_selN_MapsTo at 2; eauto.\n erewrite replay_disk_selN_MapsTo; eauto.\n apply Map.add_2; eauto.\n (* [pos] is not in the transaction *)\n repeat rewrite replay_disk_selN_not_In; auto.\n apply MapFacts.not_find_in_iff; auto.\n apply MapFacts.not_find_in_iff.\n rewrite MapFacts.add_neq_o by auto; auto.\n Unshelve.\n exact ($0, nil).\n Qed.\n\n\n Lemma replay_disk_eq : forall a v v' ms d vs,\n Map.find a ms = Some v ->\n (exists F, F * a |-> (v', vs))%pred (list2nmem (replay_disk (Map.elements ms) d)) ->\n v = v'.\n Proof.\n intros.\n destruct H0.\n eapply list2nmem_sel with (def := ($0, nil)) in H0 as Hx.\n erewrite replay_disk_selN_MapsTo in Hx.\n inversion Hx; auto.\n apply Map.find_2; auto.\n apply list2nmem_ptsto_bound in H0.\n repeat rewrite replay_disk_length in *; auto.\n Qed.\n\n Lemma replay_disk_none_selN : forall a v ms d def,\n Map.find a ms = None ->\n (exists F, F * a |-> v)%pred\n (list2nmem (replay_disk (Map.elements ms) d)) ->\n selN d a def = v.\n Proof.\n intros.\n destruct H0.\n eapply list2nmem_sel in H0 as Hx.\n rewrite Hx.\n rewrite replay_disk_selN_not_In; eauto;\n apply MapFacts.not_find_in_iff; auto.\n Qed.\n\n Lemma synced_data_replay_inb : forall a v c1 d,\n (exists F, F * a |-> v)%pred (list2nmem (replay_disk c1 d))\n -> a < length d.\n Proof.\n intros.\n destruct H.\n apply list2nmem_ptsto_bound in H.\n autorewrite with lists in *; auto.\n Qed.\n\n\n Lemma replay_disk_is_empty : forall d ms,\n Map.is_empty ms = true -> replay_disk (Map.elements ms) d = d.\n Proof.\n intros.\n apply Map.is_empty_2 in H.\n apply MapProperties.elements_Empty in H.\n rewrite H.\n simpl; auto.\n Qed.\n\n\n Lemma replay_mem_map0 : forall m,\n Map.Equal (replay_mem (Map.elements m) vmap0) m.\n Proof.\n intros; hnf; intro.\n unfold replay_mem.\n rewrite <- Map.fold_1.\n rewrite MapProperties.fold_identity; auto.\n Qed.\n\n Local Hint Resolve MapFacts.Equal_refl.\n\n Lemma replay_mem_app' : forall l m,\n Map.Equal (replay_mem ((Map.elements m) ++ l) vmap0) (replay_mem l m).\n Proof.\n induction l using rev_ind; intros.\n rewrite app_nil_r; simpl.\n rewrite replay_mem_map0; auto.\n rewrite app_assoc.\n setoid_rewrite fold_left_app; simpl.\n rewrite <- IHl; auto.\n Qed.\n\n Lemma replay_mem_app : forall l2 l m,\n Map.Equal m (replay_mem l vmap0) ->\n Map.Equal (replay_mem (l ++ l2) vmap0) (replay_mem l2 m).\n Proof.\n induction l2 using rev_ind; intros.\n rewrite app_nil_r; simpl.\n rewrite H; auto.\n rewrite app_assoc.\n setoid_rewrite fold_left_app; simpl.\n rewrite <- IHl2; auto.\n Qed.\n\n Lemma replay_mem_equal : forall l m1 m2,\n Map.Equal m1 m2 ->\n Map.Equal (replay_mem l m1) (replay_mem l m2).\n Proof.\n induction l; simpl; intros; auto.\n hnf; intro.\n apply IHl.\n apply MapFacts.add_m; auto.\n Qed.\n\n\n Instance replay_mem_proper :\n Proper (eq ==> Map.Equal ==> Map.Equal) replay_mem.\n Proof.\n unfold Proper, respectful; intros; subst.\n apply replay_mem_equal; auto.\n Qed.\n\n Lemma replay_mem_add : forall l k v m,\n ~ KIn (k, v) l -> KNoDup l ->\n Map.Equal (replay_mem l (Map.add k v m)) (Map.add k v (replay_mem l m)).\n Proof.\n induction l; simpl; intros; auto.\n destruct a; simpl.\n rewrite <- IHl.\n apply replay_mem_equal.\n apply map_add_comm.\n contradict H; inversion H0; subst.\n constructor; hnf; simpl; auto.\n contradict H.\n apply InA_cons.\n right; auto.\n inversion H0; auto.\n Qed.\n\n\n Lemma In_replay_mem_mem0 : forall l k,\n KNoDup l ->\n In k (map fst (Map.elements (replay_mem l vmap0))) ->\n In k (map fst l).\n Proof.\n induction l; intros; simpl; auto.\n destruct a; simpl in *.\n destruct (addr_eq_dec k0 k).\n left; auto.\n right.\n inversion H; subst.\n apply In_map_fst_MapIn in H0.\n rewrite replay_mem_add in H0 by auto.\n apply MapFacts.add_neq_in_iff in H0; auto.\n apply IHl; auto.\n apply In_map_fst_MapIn; auto.\n Qed.\n\n Lemma replay_disk_replay_mem0 : forall l d,\n KNoDup l ->\n replay_disk l d = replay_disk (Map.elements (elt:=valu) (replay_mem l vmap0)) d.\n Proof.\n induction l; intros; simpl; auto.\n destruct a; inversion H; subst; simpl.\n rewrite IHl by auto.\n rewrite replay_disk_updN_comm.\n rewrite <- replay_disk_add.\n f_equal; apply eq_sym.\n apply mapeq_elements.\n apply replay_mem_add; auto.\n contradict H2.\n apply In_fst_KIn; simpl.\n apply In_replay_mem_mem0; auto.\n Qed.\n\n Lemma replay_disk_merge' : forall l1 l2 d,\n KNoDup l1 -> KNoDup l2 ->\n replay_disk l2 (replay_disk l1 d) =\n replay_disk (Map.elements (replay_mem l2 (replay_mem l1 vmap0))) d.\n Proof.\n induction l1; intros; simpl.\n induction l2; simpl; auto.\n inversion H0; subst.\n erewrite mapeq_elements.\n 2: apply replay_mem_add; destruct a; auto.\n rewrite replay_disk_add.\n rewrite <- IHl2 by auto.\n apply replay_disk_updN_comm.\n contradict H3.\n apply In_fst_KIn; auto.\n\n induction l2; destruct a; simpl; auto.\n inversion H; simpl; subst.\n erewrite mapeq_elements.\n 2: apply replay_mem_add; auto.\n rewrite replay_disk_add.\n rewrite replay_disk_updN_comm.\n f_equal.\n\n apply replay_disk_replay_mem0; auto.\n contradict H3.\n apply In_fst_KIn; auto.\n\n destruct a0; simpl in *.\n inversion H; inversion H0; simpl; subst.\n rewrite replay_disk_updN_comm.\n rewrite IHl2 by auto.\n rewrite <- replay_disk_add.\n f_equal.\n apply eq_sym.\n apply mapeq_elements.\n apply replay_mem_add; auto.\n contradict H7.\n apply In_fst_KIn; simpl; auto.\n Qed.\n\n\n Lemma replay_disk_merge : forall m1 m2 d,\n replay_disk (Map.elements m2) (replay_disk (Map.elements m1) d) =\n replay_disk (Map.elements (map_merge m1 m2)) d.\n Proof.\n intros.\n unfold map_merge.\n setoid_rewrite mapeq_elements at 3.\n 2: eapply replay_mem_equal with (m2 := m1); auto.\n rewrite replay_disk_merge' by auto.\n f_equal.\n apply mapeq_elements.\n apply replay_mem_equal.\n apply replay_mem_map0.\n Qed.\n\n Lemma replay_mem_not_in' : forall l a v ms,\n KNoDup l ->\n ~ In a (map fst l) ->\n Map.MapsTo a v (replay_mem l ms) ->\n Map.MapsTo a v ms.\n Proof.\n induction l; intros; auto.\n destruct a; simpl in *; intuition.\n apply IHl; auto.\n inversion H; subst; auto.\n rewrite replay_mem_add in H1.\n apply Map.add_3 in H1; auto.\n inversion H; auto.\n inversion H; auto.\n Qed.\n\n Lemma replay_mem_not_in : forall a v ms m,\n Map.MapsTo a v (replay_mem (Map.elements m) ms) ->\n ~ Map.In a m ->\n Map.MapsTo a v ms.\n Proof.\n intros.\n eapply replay_mem_not_in'; eauto.\n contradict H0.\n apply In_map_fst_MapIn; auto.\n Qed.\n\n Lemma map_merge_repeat' : forall l m,\n KNoDup l ->\n Map.Equal (replay_mem l (replay_mem l m)) (replay_mem l m).\n Proof.\n induction l; intros; auto.\n destruct a; inversion H; simpl; subst.\n rewrite replay_mem_add by auto.\n rewrite IHl by auto.\n setoid_rewrite replay_mem_add; auto.\n apply map_add_repeat.\n Qed.\n\n Lemma map_merge_repeat : forall a b,\n Map.Equal (map_merge (map_merge a b) b) (map_merge a b).\n Proof.\n unfold map_merge; intros.\n apply map_merge_repeat'; auto.\n Qed.\n\n\n Lemma map_merge_id: forall m,\n Map.Equal (map_merge m m) m.\n Proof.\n unfold map_merge, replay_mem; intros.\n rewrite <- Map.fold_1.\n apply MapProperties.fold_rec_nodep; auto.\n intros.\n rewrite H0.\n apply MapFacts.Equal_mapsto_iff; intros.\n\n destruct (eq_nat_dec k0 k); subst; split; intros.\n apply MapFacts.add_mapsto_iff in H1; intuition; subst; auto.\n apply MapFacts.add_mapsto_iff; left; intuition.\n eapply MapFacts.MapsTo_fun; eauto.\n eapply Map.add_3; hnf; eauto.\n eapply Map.add_2; hnf; eauto.\n Qed.\n\n\n\n Lemma replay_disk_updN_absorb : forall l a v d,\n In a (map fst l) -> KNoDup l ->\n replay_disk l (updN d a v) = replay_disk l d.\n Proof.\n induction l; intros; simpl; auto.\n inversion H.\n destruct a; simpl in *; intuition; subst.\n rewrite updN_twice; auto.\n inversion H0; subst.\n setoid_rewrite <- IHl at 2; eauto.\n rewrite updN_comm; auto.\n contradict H3; subst.\n apply In_fst_KIn; auto.\n Qed.\n\n Lemma replay_disk_twice : forall l d,\n KNoDup l ->\n replay_disk l (replay_disk l d) = replay_disk l d.\n Proof.\n induction l; simpl; intros; auto.\n destruct a; inversion H; subst; simpl.\n rewrite <- replay_disk_updN_comm.\n rewrite IHl; auto.\n rewrite updN_twice; auto.\n contradict H2.\n apply In_fst_KIn; auto.\n Qed.\n\n\n Lemma replay_disk_eq_length_eq : forall l l' a b,\n replay_disk l a = replay_disk l' b ->\n length a = length b.\n Proof.\n induction l; destruct l'; simpl; intros; subst;\n repeat rewrite replay_disk_length; autorewrite with lists; auto.\n setoid_rewrite <- length_updN.\n eapply IHl; eauto.\n Qed.\n\n Lemma ptsto_replay_disk_not_in' : forall l F a v d,\n ~ In a (map fst l) ->\n KNoDup l ->\n (F * a |-> v)%pred (list2nmem (replay_disk l d)) ->\n ((arrayN_ex (@ptsto _ addr_eq_dec valuset) d a) * a |-> v)%pred (list2nmem d).\n Proof.\n induction l; simpl; intros; auto.\n erewrite list2nmem_sel with (x := v); eauto.\n apply list2nmem_ptsto_cancel.\n eapply list2nmem_ptsto_bound; eauto.\n\n inversion H0; destruct a; subst.\n erewrite list2nmem_sel with (x := v); eauto.\n eapply IHl; simpl; auto.\n rewrite replay_disk_updN_comm, selN_updN_ne.\n apply list2nmem_ptsto_cancel.\n apply list2nmem_ptsto_bound in H1.\n rewrite replay_disk_length, length_updN in *; auto.\n intuition.\n contradict H4.\n apply In_KIn; auto.\n Unshelve. all: eauto.\n Qed.\n\n Lemma ptsto_replay_disk_not_in : forall F a v d m,\n ~ Map.In a m ->\n (F * a |-> v)%pred (list2nmem (replay_disk (Map.elements m) d)) ->\n ((arrayN_ex (@ptsto _ addr_eq_dec valuset) d a) * a |-> v)%pred (list2nmem d).\n Proof.\n intros.\n eapply ptsto_replay_disk_not_in'; eauto.\n contradict H.\n apply In_map_fst_MapIn; auto.\n Qed.\n\n Lemma replay_disk_updN_eq_not_in : forall Fd a v vs d ms,\n ~ Map.In a ms ->\n (Fd * a |-> vs)%pred (list2nmem (replay_disk (Map.elements ms) d)) ->\n updN (replay_disk (Map.elements ms) d) a (v, (vsmerge vs)) =\n replay_disk (Map.elements ms) (vsupd d a v).\n Proof.\n unfold vsupd; intros.\n rewrite replay_disk_updN_comm.\n repeat f_equal.\n erewrite <- replay_disk_selN_not_In; eauto.\n eapply list2nmem_sel; eauto.\n contradict H.\n apply In_map_fst_MapIn; eauto.\n Qed.\n\n Lemma replay_disk_updN_eq_empty : forall Fd a v vs d ms,\n Map.Empty ms ->\n (Fd * a |-> vs)%pred (list2nmem (replay_disk (Map.elements ms) d)) ->\n updN (replay_disk (Map.elements ms) d) a (v, (vsmerge vs)) =\n replay_disk (Map.elements ms) (vsupd d a v).\n Proof.\n intros.\n eapply replay_disk_updN_eq_not_in; eauto.\n apply MapFacts.not_find_in_iff.\n rewrite MapFacts.elements_o.\n apply MapProperties.elements_Empty in H.\n rewrite H; auto.\n Qed.\n\n\n\n Lemma replay_disk_selN_snd_nil : forall l a d,\n In a (map fst l) ->\n snd (selN (replay_disk l d) a ($0, nil)) = nil.\n Proof.\n induction l; simpl; intros; intuition.\n destruct a; subst; simpl.\n destruct (In_dec (eq_nat_dec) n (map fst l)).\n apply IHl; auto.\n rewrite replay_disk_updN_comm by auto.\n destruct (lt_dec n (length d)).\n rewrite selN_updN_eq; auto.\n rewrite replay_disk_length; auto.\n rewrite selN_oob; auto.\n rewrite length_updN, replay_disk_length; omega.\n Qed.\n\n Lemma replay_disk_vssync_comm_list : forall l d a,\n vssync (replay_disk l d) a =\n replay_disk l (vssync d a).\n Proof.\n induction l; simpl; auto; intros.\n rewrite IHl; unfold vssync; destruct a; simpl in *.\n destruct (addr_eq_dec a0 n); subst.\n - repeat rewrite updN_twice.\n destruct (lt_dec n (length d)).\n repeat rewrite selN_updN_eq; auto.\n rewrite selN_oob; repeat rewrite updN_oob; auto; try omega.\n - repeat rewrite selN_updN_ne by auto.\n rewrite updN_comm; auto.\n Qed.\n\n Lemma replay_disk_vssync_vecs_comm_list : forall l ents d,\n vssync_vecs (replay_disk ents d) l =\n replay_disk ents (vssync_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n rewrite <- IHl by auto.\n rewrite replay_disk_vssync_comm_list; auto.\n Qed.\n\n Lemma replay_disk_vssync_comm : forall m d a,\n vssync (replay_disk (Map.elements m) d) a =\n replay_disk (Map.elements m) (vssync d a).\n Proof.\n intros; apply replay_disk_vssync_comm_list.\n Qed.\n\n Lemma replay_disk_vssync_vecs_comm : forall l m d,\n vssync_vecs (replay_disk (Map.elements m) d) l =\n replay_disk (Map.elements m) (vssync_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n rewrite <- IHl by auto.\n rewrite replay_disk_vssync_comm; auto.\n Qed.\n\n\n Lemma replay_disk_empty : forall m d,\n Map.Empty m ->\n replay_disk (Map.elements m) d = d.\n Proof.\n intros.\n apply MapProperties.elements_Empty in H.\n rewrite H; simpl; auto.\n Qed.\n\n\n Lemma replay_disk_remove_updN_eq : forall F m d a v,\n (F * a |-> v)%pred (list2nmem (replay_disk (Map.elements m) d)) ->\n replay_disk (Map.elements m) d =\n replay_disk (Map.elements (Map.remove a m)) (updN d a v).\n Proof.\n intros.\n eapply list_selN_ext with (default := ($0, nil)); intros.\n repeat rewrite replay_disk_length; rewrite length_updN; auto.\n rewrite replay_disk_updN_comm.\n\n destruct (Nat.eq_dec pos a); subst.\n rewrite selN_updN_eq; [ apply eq_sym | ].\n eapply list2nmem_sel; eauto.\n rewrite replay_disk_length in *; eauto.\n\n rewrite selN_updN_ne by auto.\n case_eq (Map.find pos m); intros.\n apply Map.find_2 in H1.\n rewrite replay_disk_length in *.\n repeat erewrite replay_disk_selN_MapsTo; eauto.\n apply Map.remove_2; eauto.\n\n apply MapFacts.not_find_in_iff in H1.\n setoid_rewrite replay_disk_selN_not_In; auto.\n apply not_in_remove_not_in; auto.\n\n rewrite In_map_fst_MapIn.\n apply Map.remove_1; now auto.\n Qed.\n\n\n Lemma list2nmem_replay_disk_remove_updN_ptsto : forall F a vs vs' d ms,\n (F * a |-> vs)%pred (list2nmem (replay_disk (Map.elements ms) d)) ->\n (F * a |-> vs')%pred\n (list2nmem (replay_disk (Map.elements (Map.remove a ms)) (updN d a vs'))).\n Proof.\n intros.\n rewrite replay_disk_updN_comm.\n erewrite <- updN_twice.\n eapply list2nmem_updN.\n rewrite <- replay_disk_updN_comm.\n erewrite <- replay_disk_remove_updN_eq; eauto.\n\n rewrite In_map_fst_MapIn; apply Map.remove_1; now auto.\n rewrite In_map_fst_MapIn; apply Map.remove_1; now auto.\n Qed.\n\n\n Set Regular Subst Tactic.\n\n\n Lemma updN_replay_disk_remove_eq : forall m d a v,\n d = replay_disk (Map.elements m) d ->\n updN d a v = replay_disk (Map.elements (Map.remove a m)) (updN d a v).\n Proof.\n intros.\n eapply list_selN_ext with (default := ($0, nil)); intros.\n repeat rewrite replay_disk_length; rewrite length_updN; auto.\n rewrite replay_disk_updN_comm.\n rewrite length_updN in H0.\n\n destruct (Nat.eq_dec pos a); subst.\n repeat rewrite selN_updN_eq; auto.\n rewrite replay_disk_length in *; eauto.\n\n repeat rewrite selN_updN_ne by auto.\n rewrite H at 1.\n case_eq (Map.find pos m); intros.\n apply Map.find_2 in H1.\n repeat erewrite replay_disk_selN_MapsTo; eauto.\n apply Map.remove_2; eauto.\n\n apply MapFacts.not_find_in_iff in H1.\n setoid_rewrite replay_disk_selN_not_In; auto.\n apply not_in_remove_not_in; auto.\n\n rewrite In_map_fst_MapIn.\n apply Map.remove_1; now auto.\n Qed.\n\n\n Lemma replay_mem_add_find_none : forall l a v m,\n ~ Map.find a (replay_mem l (Map.add a v m)) = None.\n Proof.\n induction l; simpl; intros.\n rewrite MapFacts.add_eq_o; congruence.\n destruct a; simpl.\n destruct (addr_eq_dec n a0); subst.\n rewrite map_add_repeat.\n apply IHl.\n rewrite map_add_comm by auto.\n apply IHl.\n Qed.\n\n\n Lemma map_find_replay_mem_not_in : forall a l m,\n Map.find a (replay_mem l m) = None ->\n ~ In a (map fst l).\n Proof.\n induction l; intuition; simpl in *.\n eapply IHl; intuition eauto; subst.\n destruct a0; simpl in *.\n contradict H.\n apply replay_mem_add_find_none.\n Qed.\n\n Lemma replay_mem_find_none_mono : forall l a m,\n Map.find a (replay_mem l m) = None ->\n Map.find a m = None.\n Proof.\n induction l; simpl; intros; auto.\n destruct a; simpl in *.\n destruct (addr_eq_dec n a0); subst.\n contradict H.\n apply replay_mem_add_find_none.\n erewrite <- MapFacts.add_neq_o; eauto.\n Qed.\n\n Definition ents_remove a (ents : DLog.contents) := \n filter (fun e => if (addr_eq_dec (fst e) a) then false else true) ents.\n\n\n Lemma ents_remove_not_in : forall ents a,\n ~ In a (map fst (ents_remove a ents)).\n Proof.\n induction ents; auto; intros; simpl.\n destruct a; simpl.\n destruct (addr_eq_dec n a0); subst; auto.\n simpl; intuition.\n eapply IHents; eauto.\n Qed.\n\n Local Hint Resolve ents_remove_not_in.\n Lemma replay_disk_ents_remove_updN : forall ents d a v,\n updN (replay_disk (ents_remove a ents) d) a v = updN (replay_disk ents d) a v.\n Proof.\n induction ents; intros; simpl; auto.\n destruct a; simpl.\n destruct (addr_eq_dec n a0); subst; simpl; auto.\n rewrite <- replay_disk_updN_comm by auto.\n rewrite <- IHents.\n rewrite <- replay_disk_updN_comm by auto.\n rewrite updN_twice; auto.\n Qed.\n\n Definition ents_remove_list (al : list addr) (ents: DLog.contents) := \n filter (fun e => if (In_dec addr_eq_dec (fst e) al) then false else true) ents.\n\n\n (**********************\n * validity of map and log entries \n *\n *)\n\n\n Definition map_valid (ms : valumap) (m : diskstate) :=\n forall a v, Map.MapsTo a v ms -> a <> 0 /\\ a < length m.\n\n Definition log_valid (ents : DLog.contents) (m : diskstate) :=\n KNoDup ents /\\ forall a v, KIn (a, v) ents -> a <> 0 /\\ a < length m.\n\n\n Lemma map_valid_map0 : forall m,\n map_valid vmap0 m.\n Proof.\n unfold map_valid, map0; intuition; exfalso;\n apply MapFacts.empty_mapsto_iff in H; auto.\n Qed.\n\n Lemma map_valid_empty : forall l m,\n Map.Empty m -> map_valid m l.\n Proof.\n unfold map_valid; intros.\n exfalso; eapply map_empty_find_exfalso; eauto.\n apply Map.find_1; eauto.\n Qed.\n\n Lemma map_valid_add : forall d a v ms,\n map_valid ms d ->\n a < length d -> a <> 0 ->\n map_valid (Map.add a v ms) d.\n Proof.\n unfold map_valid; intros.\n destruct (addr_eq_dec a0 a); subst.\n eauto.\n eapply H.\n eapply Map.add_3; hnf; eauto.\n Qed.\n\n Lemma map_valid_updN : forall m d a v,\n map_valid m d -> map_valid m (updN d a v).\n Proof.\n unfold map_valid; simpl; intuition.\n eapply H; eauto.\n rewrite length_updN.\n eapply H; eauto.\n Qed.\n\n\n Lemma map_valid_remove : forall a ms d1 d2,\n map_valid ms d1 ->\n length d1 = length d2 ->\n map_valid (Map.remove a ms) d2.\n Proof.\n unfold map_valid; intros.\n erewrite <- H0.\n eapply H.\n eapply Map.remove_3; eauto.\n Qed.\n\n\n Lemma map_valid_equal : forall d m1 m2,\n Map.Equal m1 m2 -> map_valid m1 d -> map_valid m2 d.\n Proof.\n induction d; unfold map_valid; simpl; intros; split;\n eapply H0; rewrite H; eauto.\n Qed.\n\n\n Lemma length_eq_map_valid : forall m a b,\n map_valid m a -> length b = length a -> map_valid m b.\n Proof.\n unfold map_valid. intros * Hv Hlen * Hm. split; firstorder.\n specialize (Hv _ _ Hm) as [? ?]. omega.\n Qed.\n\n Lemma map_valid_vsupd_vecs : forall l d m,\n map_valid m d ->\n map_valid m (vsupd_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n apply IHl.\n apply map_valid_updN; auto.\n Qed.\n\n Lemma map_valid_vssync_vecs : forall l d m,\n map_valid m d ->\n map_valid m (vssync_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n apply IHl.\n apply map_valid_updN; auto.\n Qed.\n\n\n Lemma map_valid_Forall_fst_synced : forall d ms,\n map_valid ms d ->\n Forall (fun e => fst e < length d) (Map.elements ms).\n Proof.\n unfold map_valid; intros.\n apply Forall_forall; intros.\n autorewrite with lists.\n destruct x; simpl.\n apply (H n w).\n apply Map.elements_2.\n apply In_InA; auto.\n Qed.\n\n Hint Resolve map_valid_Forall_fst_synced.\n\n Lemma map_valid_Forall_synced_map_fst : forall d ms,\n map_valid ms d ->\n Forall (fun e => e < length d) (map fst (Map.elements ms)).\n Proof.\n unfold map_valid; intros.\n apply Forall_forall; intros.\n autorewrite with lists.\n apply In_map_fst_MapIn in H0.\n apply MapFacts.elements_in_iff in H0.\n destruct H0.\n eapply (H x).\n apply Map.elements_2; eauto.\n Qed.\n\n\n Lemma map_valid_replay : forall d ms1 ms2,\n map_valid ms1 d ->\n map_valid ms2 d ->\n map_valid ms1 (replay_disk (Map.elements ms2) d).\n Proof.\n unfold map_valid; induction d; intros.\n rewrite replay_disk_length; eauto.\n split.\n apply (H a0 v); auto.\n rewrite replay_disk_length.\n apply (H a0 v); auto.\n Qed.\n\n Lemma map_valid_replay_mem : forall d ms1 ms2,\n map_valid ms1 d ->\n map_valid ms2 d ->\n map_valid (replay_mem (Map.elements ms1) ms2) d.\n Proof.\n unfold map_valid; intros.\n destruct (MapFacts.In_dec ms1 a).\n apply MapFacts.in_find_iff in i.\n destruct (Map.find a ms1) eqn:X.\n eapply H.\n apply MapFacts.find_mapsto_iff; eauto.\n tauto.\n eapply H0.\n eapply replay_mem_not_in; eauto.\n Qed.\n\n Lemma map_valid_replay_disk : forall l m d,\n map_valid m d ->\n map_valid m (replay_disk l d).\n Proof.\n unfold map_valid; induction d; intros.\n rewrite replay_disk_length; eauto.\n split.\n apply (H a0 v); auto.\n rewrite replay_disk_length.\n apply (H a0 v); auto.\n Qed.\n\n\n\n\n\n\n Lemma log_valid_nodup : forall l d,\n log_valid l d -> KNoDup l.\n Proof.\n unfold log_valid; intuition.\n Qed.\n\n Lemma map_valid_log_valid : forall ms d,\n map_valid ms d ->\n log_valid (Map.elements ms) d.\n Proof.\n unfold map_valid, log_valid; intuition;\n apply KIn_exists_elt_InA in H0;\n destruct H0; simpl in H0;\n eapply H; eauto;\n apply Map.elements_2; eauto.\n Qed.\n\n\n Lemma log_valid_entries_valid : forall ents d l raw,\n goodSize addrlen (length raw) ->\n d = replay_disk l raw ->\n log_valid ents d -> DLog.entries_valid ents.\n Proof.\n unfold log_valid, DLog.entries_valid; intuition.\n rewrite Forall_forall.\n intros; destruct x.\n unfold PaddedLog.entry_valid, PaddedLog.addr_valid; intuition.\n eapply H3; eauto; simpl.\n apply In_fst_KIn.\n eapply in_map; eauto.\n\n simpl; subst.\n rewrite replay_disk_length in *.\n eapply goodSize_trans; [ | apply H].\n apply Nat.lt_le_incl.\n eapply H3.\n apply In_fst_KIn.\n eapply in_map; eauto.\n Qed.\n\n Lemma log_vaild_filter : forall ents d f,\n log_valid ents d ->\n log_valid (filter f ents) d.\n Proof.\n unfold log_valid; intuition.\n apply KNoDup_filter; eauto.\n edestruct H1; eauto.\n eapply InA_filter; eauto.\n edestruct H1; eauto.\n eapply InA_filter; eauto.\n Qed.\n\n Local Hint Resolve Map.is_empty_1 Map.is_empty_2.\n\n Lemma map_valid_replay_mem' : forall ents d ms,\n log_valid ents d ->\n map_valid ms d ->\n map_valid (replay_mem ents ms) d.\n Proof.\n unfold map_valid, log_valid; intros.\n destruct (InA_dec (@eq_key_dec valu) (a, v) ents).\n eapply H; eauto.\n eapply H0.\n eapply replay_mem_not_in'.\n 3: eauto. apply H.\n contradict n.\n apply In_fst_KIn; simpl; auto.\n Qed.\n\n Lemma log_valid_replay : forall ents d ms,\n map_valid ms d ->\n log_valid ents (replay_disk (Map.elements ms) d) ->\n log_valid ents d.\n Proof.\n unfold log_valid, map_valid; intros.\n split; intros.\n apply H0.\n rewrite replay_disk_length in H0.\n eapply H0; eauto.\n Qed.\n\n Lemma log_valid_length_eq : forall ents d d',\n log_valid ents d ->\n length d = length d' ->\n log_valid ents d'.\n Proof.\n unfold log_valid; intuition.\n eapply H2; eauto.\n substl (length d').\n eapply H2; eauto.\n Qed.\n\n Lemma replay_disk_replay_mem : forall l m d,\n log_valid l (replay_disk (Map.elements m) d) ->\n replay_disk l (replay_disk (Map.elements m) d) =\n replay_disk (Map.elements (replay_mem l m)) d.\n Proof.\n unfold log_valid; induction l; intros; intuition; auto.\n destruct a; inversion H0; subst; simpl.\n rewrite replay_disk_updN_comm.\n rewrite IHl.\n setoid_rewrite mapeq_elements at 2.\n 2: apply replay_mem_add; auto.\n rewrite replay_disk_add; auto.\n split; auto; intros.\n eapply H1.\n apply InA_cons_tl; eauto.\n contradict H3.\n apply In_fst_KIn; auto.\n Qed.\n\n Instance map_valid_iff_proper :\n Proper (Map.Equal ==> eq ==> iff) map_valid.\n Proof.\n unfold Proper, respectful; intros; subst; split;\n apply map_valid_equal; auto.\n apply MapFacts.Equal_sym; auto.\n Qed.\n\n Instance map_valid_impl_proper :\n Proper (Map.Equal ==> eq ==> Basics.impl) map_valid.\n Proof.\n unfold Proper, respectful, impl; intros; subst.\n eapply map_valid_equal; eauto.\n Qed.\n\n Instance map_valid_impl_proper2 :\n Proper (Map.Equal ==> eq ==> flip Basics.impl) map_valid.\n Proof.\n unfold Proper, respectful, impl, flip; intros; subst.\n apply MapFacts.Equal_sym in H.\n eapply map_valid_equal; eauto.\n Qed.\n\n Lemma possible_crash_log_valid : forall l l' ents,\n possible_crash (list2nmem l) (list2nmem l')\n -> log_valid ents l'\n -> log_valid ents l.\n Proof.\n intros.\n eapply log_valid_length_eq; eauto.\n erewrite <- possible_crash_list2nmem_length; eauto.\n Qed.\n\n Lemma possible_crash_replay_disk : forall ents d d',\n log_valid ents d'\n -> possible_crash (list2nmem d)\n (list2nmem d')\n -> possible_crash (list2nmem (replay_disk ents d))\n (list2nmem (replay_disk ents d')).\n Proof.\n induction ents; intros; simpl.\n unfold replay_disk; simpl; auto.\n eapply possible_crash_log_valid in H as H'; eauto.\n\n apply IHents.\n unfold log_valid in *.\n split.\n unfold KNoDup.\n eapply KNoDup_cons_inv; intuition eauto.\n intros.\n rewrite length_updN.\n eapply H.\n unfold KIn in *.\n eapply InA_cons_tl; eauto.\n\n repeat erewrite listupd_memupd; eauto.\n eapply possible_crash_upd; auto.\n destruct a; simpl; auto.\n\n unfold log_valid in *; intuition.\n eapply H2 with (v:=snd a).\n unfold KIn.\n eapply InA_cons_hd.\n unfold Map.eq_key; now eauto.\n\n unfold log_valid in *; intuition.\n eapply H3 with (v:=snd a).\n unfold KIn.\n eapply InA_cons_hd.\n unfold Map.eq_key; now eauto.\n Qed.\n\n Lemma crash_xform_replay_disk : forall ents d d',\n log_valid ents d'\n -> crash_xform (diskIs (list2nmem d))\n (list2nmem d')\n -> crash_xform (diskIs (list2nmem (replay_disk ents d)))\n (list2nmem (replay_disk ents d')).\n Proof.\n intros.\n eapply crash_xform_diskIs in H0.\n destruct_lift H0.\n unfold diskIs in *; subst.\n eapply crash_xform_diskIs_r; unfold diskIs; eauto.\n eapply possible_crash_replay_disk; auto.\n Qed.\n\n Lemma replay_disk_vsupd_vecs : forall l d,\n KNoDup l\n -> replay_disk l d = replay_disk l (vsupd_vecs d l).\n Proof.\n induction l; intros; simpl; auto.\n\n destruct (in_dec eq_nat_dec (fst a) (map fst l));\n denote KNoDup as HKNoDup;\n apply KNoDup_cons_inv in HKNoDup.\n rewrite replay_disk_updN_absorb; auto.\n rewrite replay_disk_updN_absorb; auto.\n rewrite <- IHl; auto.\n unfold vsupd.\n rewrite replay_disk_updN_absorb; auto.\n\n rewrite vsupd_vecs_vsupd_notin; auto.\n unfold vsupd.\n rewrite updN_twice.\n repeat rewrite replay_disk_updN_comm; auto.\n rewrite IHl; auto.\n Qed.\n\n Set Implicit Arguments.\n\n Fixpoint overlap V (l : list addr) (m : Map.t V) : bool :=\n match l with\n | nil => false\n | a :: rest => if (Map.mem a m) then true else overlap rest m\n end.\n\n Lemma overlap_firstn_overlap : forall V n l (m : Map.t V),\n overlap (firstn n l) m = true ->\n overlap l m = true.\n Proof.\n induction n; destruct l; simpl; try congruence; firstorder.\n destruct (MapFacts.In_dec m n0); auto.\n rewrite Map.mem_1; auto.\n apply MapFacts.not_mem_in_iff in n1; rewrite n1 in *; auto.\n Qed.\n\n Lemma In_MapIn_overlap : forall V l a (ms : Map.t V),\n In a l ->\n Map.In a ms ->\n overlap l ms = true.\n Proof.\n induction l; intros; simpl.\n inversion H.\n destruct (MapFacts.In_dec ms a); auto.\n rewrite Map.mem_1; auto.\n apply MapFacts.not_mem_in_iff in n as Hx; rewrite Hx in *; auto.\n inversion H; destruct (addr_eq_dec a a0); subst; firstorder.\n Qed.\n\n Lemma overlap_empty : forall V al (m : Map.t V),\n Map.Empty m ->\n overlap al m = false.\n Proof.\n induction al; simpl; auto; intros.\n replace (Map.mem a m) with false; eauto.\n symmetry.\n eapply MapFacts.not_mem_in_iff.\n apply map_empty_not_In; auto.\n Qed.\n\n\n Lemma replay_disk_vsupd_vecs_nonoverlap : forall l m d,\n overlap (map fst l) m = false ->\n vsupd_vecs (replay_disk (Map.elements m) d) l =\n replay_disk (Map.elements m) (vsupd_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n destruct (MapFacts.In_dec m (fst a)); simpl in *.\n rewrite Map.mem_1 in H; congruence.\n apply MapFacts.not_mem_in_iff in n as Hx; rewrite Hx in *; auto.\n rewrite <- IHl by auto.\n unfold vsupd, vsmerge.\n rewrite replay_disk_updN_comm.\n erewrite replay_disk_selN_not_In; eauto.\n contradict n.\n apply In_map_fst_MapIn; eauto.\n Qed.\n\n Lemma overlap_equal : forall T l (m1 m2 : Map.t T),\n Map.Equal m1 m2 ->\n overlap l m1 = overlap l m2.\n Proof.\n induction l; intros; auto; simpl.\n destruct (Map.mem a m1) eqn:?; destruct (Map.mem a m2) eqn:?; auto.\n rewrite H in Heqb; congruence.\n rewrite H in Heqb; congruence.\n Qed.\n\n Instance overlap_proper : forall T,\n Proper (eq ==> Map.Equal ==> eq) (@overlap T).\n Proof.\n unfold Proper, respectful, impl; intros; subst.\n apply overlap_equal; auto.\n Qed.\n\n Lemma nonoverlap_replay_mem_disjoint : forall al ents d,\n overlap al (replay_mem ents d) = false ->\n disjoint al (map fst ents).\n Proof.\n induction al; intuition; simpl in *.\n apply disjoint_nil_l.\n destruct (Map.mem a (replay_mem ents d)) eqn:?; try congruence.\n apply disjoint_cons_l.\n eapply IHal; eauto.\n eapply map_find_replay_mem_not_in.\n rewrite MapFacts.mem_find_b in Heqb.\n destruct (Map.find a (replay_mem ents d)) eqn:?; try congruence.\n eauto.\n Qed.\n\n Lemma replay_mem_nonoverlap_mono : forall al ents m,\n overlap al (replay_mem ents m) = false ->\n overlap al m = false.\n Proof.\n induction al; simpl; intros; auto.\n destruct (Map.mem a m) eqn:?; \n destruct (Map.mem a (replay_mem ents m)) eqn:?; try congruence.\n rewrite MapFacts.mem_find_b in *.\n destruct (Map.find a m) eqn:?; try congruence.\n destruct (Map.find a (replay_mem ents m)) eqn:?; try congruence.\n apply replay_mem_find_none_mono in Heqo0; congruence.\n eapply IHal; eauto.\n Qed.\n\n Lemma replay_disk_vsupd_vecs_disjoint : forall l ents d,\n disjoint (map fst l) (map fst ents) ->\n vsupd_vecs (replay_disk ents d) l =\n replay_disk ents (vsupd_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n destruct (In_dec addr_eq_dec (fst a) (map fst ents)); simpl in *.\n specialize (H (fst a)); simpl in H; intuition.\n rewrite <- IHl.\n unfold vsupd, vsmerge.\n rewrite replay_disk_updN_comm by auto.\n erewrite replay_disk_selN_other; auto.\n unfold disjoint in *; firstorder.\n Qed.\n\n Lemma replay_disk_vssync_vecs_disjoint : forall l ents d,\n disjoint l (map fst ents) ->\n vssync_vecs (replay_disk ents d) l =\n replay_disk ents (vssync_vecs d l).\n Proof.\n induction l; simpl; intros; auto.\n destruct (In_dec addr_eq_dec a (map fst ents)); simpl in *.\n specialize (H a); simpl in H; intuition.\n rewrite <- IHl.\n unfold vssync, vsmerge.\n rewrite replay_disk_updN_comm by auto.\n erewrite replay_disk_selN_other; auto.\n unfold disjoint in *; firstorder.\n Qed.\n\nEnd LogReplay.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/LogReplay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.1397141409914883}} {"text": "(* *********************************************************************)\n(* *)\n(* The Compcert verified compiler *)\n(* *)\n(* Xavier Leroy, INRIA Paris-Rocquencourt *)\n(* *)\n(* Copyright Institut National de Recherche en Informatique et en *)\n(* Automatique. All rights reserved. This file is distributed *)\n(* under the terms of the INRIA Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Zwf Coqlib Maps.\nRequire Import Errors Integers Floats Values AST Memory Globalenvs Events Smallstep.\nRequire Import Ctypes Cop Csyntax Csem.\nRequire Import Initializers.\n\nOpen Scope error_monad_scope.\n\nSection SOUNDNESS.\n\nVariable ge: genv.\n\n(** * Simple expressions and their big-step semantics *)\n\n(** An expression is simple if it contains no assignments and no\n function calls. *)\n\nFixpoint simple (a: expr) : Prop :=\n match a with\n | Eloc _ _ _ _ => True\n | Evar _ _ => True\n | Ederef r _ => simple r\n | Efield l1 _ _ => simple l1\n | Eval _ _ => True\n | Evalof l _ => simple l\n | Eaddrof l _ => simple l\n | Eunop _ r1 _ => simple r1\n | Ebinop _ r1 r2 _ => simple r1 /\\ simple r2\n | Ecast r1 _ => simple r1\n | Eseqand r1 r2 _ => simple r1 /\\ simple r2\n | Eseqor r1 r2 _ => simple r1 /\\ simple r2\n | Econdition r1 r2 r3 _ => simple r1 /\\ simple r2 /\\ simple r3\n | Esizeof _ _ => True\n | Ealignof _ _ => True\n | Eassign _ _ _ => False\n | Eassignop _ _ _ _ _ => False\n | Epostincr _ _ _ => False\n | Ecomma r1 r2 _ => simple r1 /\\ simple r2\n | Ecall _ _ _ => False\n | Ebuiltin _ _ _ _ => False\n | Eparen r1 _ _ => simple r1\n end.\n\n(** A big-step semantics for simple expressions. Similar to the\n big-step semantics from [Cstrategy], with the addition of\n conditionals, comma and paren operators. It is a pity we do not\n share definitions with [Cstrategy], but such sharing raises\n technical difficulties. *)\n\nSection SIMPLE_EXPRS.\n\nVariable e: env.\nVariable m: mem.\n\nInductive eval_simple_lvalue: expr -> block -> ptrofs -> bitfield -> Prop :=\n | esl_loc: forall b ofs bf ty,\n eval_simple_lvalue (Eloc b ofs bf ty) b ofs bf\n | esl_var_local: forall x ty b,\n e!x = Some(b, ty) ->\n eval_simple_lvalue (Evar x ty) b Ptrofs.zero Full\n | esl_var_global: forall x ty b,\n e!x = None ->\n Genv.find_symbol ge x = Some b ->\n eval_simple_lvalue (Evar x ty) b Ptrofs.zero Full\n | esl_deref: forall r ty b ofs,\n eval_simple_rvalue r (Vptr b ofs) ->\n eval_simple_lvalue (Ederef r ty) b ofs Full\n | esl_field_struct: forall r f ty b ofs id co a delta bf,\n eval_simple_rvalue r (Vptr b ofs) ->\n typeof r = Tstruct id a -> ge.(genv_cenv)!id = Some co -> field_offset ge f (co_members co) = OK (delta, bf) ->\n eval_simple_lvalue (Efield r f ty) b (Ptrofs.add ofs (Ptrofs.repr delta)) bf\n | esl_field_union: forall r f ty b ofs id co a delta bf,\n eval_simple_rvalue r (Vptr b ofs) ->\n typeof r = Tunion id a -> ge.(genv_cenv)!id = Some co -> union_field_offset ge f (co_members co) = OK (delta, bf) ->\n eval_simple_lvalue (Efield r f ty) b (Ptrofs.add ofs (Ptrofs.repr delta)) bf\n\nwith eval_simple_rvalue: expr -> val -> Prop :=\n | esr_val: forall v ty,\n eval_simple_rvalue (Eval v ty) v\n | esr_rvalof: forall b ofs bf l ty v,\n eval_simple_lvalue l b ofs bf ->\n ty = typeof l ->\n deref_loc ge ty m b ofs bf E0 v ->\n eval_simple_rvalue (Evalof l ty) v\n | esr_addrof: forall b ofs l ty,\n eval_simple_lvalue l b ofs Full ->\n eval_simple_rvalue (Eaddrof l ty) (Vptr b ofs)\n | esr_unop: forall op r1 ty v1 v,\n eval_simple_rvalue r1 v1 ->\n sem_unary_operation op v1 (typeof r1) m = Some v ->\n eval_simple_rvalue (Eunop op r1 ty) v\n | esr_binop: forall op r1 r2 ty v1 v2 v,\n eval_simple_rvalue r1 v1 -> eval_simple_rvalue r2 v2 ->\n sem_binary_operation ge op v1 (typeof r1) v2 (typeof r2) m = Some v ->\n eval_simple_rvalue (Ebinop op r1 r2 ty) v\n | esr_cast: forall ty r1 v1 v,\n eval_simple_rvalue r1 v1 ->\n sem_cast v1 (typeof r1) ty m = Some v ->\n eval_simple_rvalue (Ecast r1 ty) v\n | esr_sizeof: forall ty1 ty,\n eval_simple_rvalue (Esizeof ty1 ty) (Vptrofs (Ptrofs.repr (sizeof ge ty1)))\n | esr_alignof: forall ty1 ty,\n eval_simple_rvalue (Ealignof ty1 ty) (Vptrofs (Ptrofs.repr (alignof ge ty1)))\n | esr_seqand_true: forall r1 r2 ty v1 v2 v3,\n eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) m = Some true ->\n eval_simple_rvalue r2 v2 ->\n sem_cast v2 (typeof r2) type_bool m = Some v3 ->\n eval_simple_rvalue (Eseqand r1 r2 ty) v3\n | esr_seqand_false: forall r1 r2 ty v1,\n eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) m = Some false ->\n eval_simple_rvalue (Eseqand r1 r2 ty) (Vint Int.zero)\n | esr_seqor_false: forall r1 r2 ty v1 v2 v3,\n eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) m = Some false ->\n eval_simple_rvalue r2 v2 ->\n sem_cast v2 (typeof r2) type_bool m = Some v3 ->\n eval_simple_rvalue (Eseqor r1 r2 ty) v3\n | esr_seqor_true: forall r1 r2 ty v1,\n eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) m = Some true ->\n eval_simple_rvalue (Eseqor r1 r2 ty) (Vint Int.one)\n | esr_condition: forall r1 r2 r3 ty v v1 b v',\n eval_simple_rvalue r1 v1 -> bool_val v1 (typeof r1) m = Some b ->\n eval_simple_rvalue (if b then r2 else r3) v' ->\n sem_cast v' (typeof (if b then r2 else r3)) ty m = Some v ->\n eval_simple_rvalue (Econdition r1 r2 r3 ty) v\n | esr_comma: forall r1 r2 ty v1 v,\n eval_simple_rvalue r1 v1 -> eval_simple_rvalue r2 v ->\n eval_simple_rvalue (Ecomma r1 r2 ty) v\n | esr_paren: forall r tycast ty v v',\n eval_simple_rvalue r v -> sem_cast v (typeof r) tycast m = Some v' ->\n eval_simple_rvalue (Eparen r tycast ty) v'.\n\nEnd SIMPLE_EXPRS.\n\n(** * Correctness of the big-step semantics with respect to reduction sequences *)\n\n(** In this section, we show that if a simple expression [a] reduces to\n some value (with the transition semantics from module [Csem]),\n then it evaluates to this value (with the big-step semantics above). *)\n\nDefinition compat_eval (k: kind) (e: env) (a a': expr) (m: mem) : Prop :=\n typeof a = typeof a' /\\\n match k with\n | LV => forall b ofs bf, eval_simple_lvalue e m a' b ofs bf -> eval_simple_lvalue e m a b ofs bf\n | RV => forall v, eval_simple_rvalue e m a' v -> eval_simple_rvalue e m a v\n end.\n\nLemma lred_simple:\n forall e l m l' m', lred ge e l m l' m' -> simple l -> simple l'.\nProof.\n induction 1; simpl; tauto.\nQed.\n\nLemma lred_compat:\n forall e l m l' m', lred ge e l m l' m' ->\n m = m' /\\ compat_eval LV e l l' m.\nProof.\n induction 1; simpl; split; auto; split; auto; intros bx ofsx bf' EV; inv EV.\n apply esl_var_local; auto.\n apply esl_var_global; auto.\n constructor. constructor.\n eapply esl_field_struct; eauto. constructor. simpl; eauto.\n eapply esl_field_union; eauto. constructor. simpl; eauto.\nQed.\n\nLemma rred_simple:\n forall r m t r' m', rred ge r m t r' m' -> simple r -> simple r'.\nProof.\n induction 1; simpl; intuition. destruct b; auto.\nQed.\n\nLemma rred_compat:\n forall e r m r' m', rred ge r m E0 r' m' ->\n simple r ->\n m = m' /\\ compat_eval RV e r r' m.\nProof.\n intros until m'; intros RED SIMP. inv RED; simpl in SIMP; try contradiction; split; auto; split; auto; intros vx EV.\n inv EV. econstructor. constructor. auto. auto.\n inv EV. econstructor. constructor.\n inv EV. econstructor; eauto. constructor.\n inv EV. econstructor; eauto. constructor. constructor.\n inv EV. econstructor; eauto. constructor.\n inv EV. eapply esr_seqand_true; eauto. constructor.\n inv EV. eapply esr_seqand_false; eauto. constructor.\n inv EV. eapply esr_seqor_true; eauto. constructor.\n inv EV. eapply esr_seqor_false; eauto. constructor.\n inv EV. eapply esr_condition; eauto. constructor.\n inv EV. constructor.\n inv EV. constructor.\n econstructor; eauto. constructor.\n inv EV. econstructor. constructor. auto.\nQed.\n\nLemma compat_eval_context:\n forall e a a' m from to C,\n context from to C ->\n compat_eval from e a a' m ->\n compat_eval to e (C a) (C a') m.\nProof.\n induction 1; intros CE; auto;\n try (generalize (IHcontext CE); intros [TY EV]; red; split; simpl; auto; intros).\n inv H0. constructor; auto.\n inv H0.\n eapply esl_field_struct; eauto. rewrite TY; eauto.\n eapply esl_field_union; eauto. rewrite TY; eauto.\n inv H0. econstructor. eauto. auto. auto.\n inv H0. econstructor; eauto.\n inv H0. econstructor; eauto. congruence.\n inv H0. econstructor; eauto. congruence.\n inv H0. econstructor; eauto. congruence.\n inv H0. econstructor; eauto. congruence.\n inv H0.\n eapply esr_seqand_true; eauto. rewrite TY; auto.\n eapply esr_seqand_false; eauto. rewrite TY; auto.\n inv H0.\n eapply esr_seqor_false; eauto. rewrite TY; auto.\n eapply esr_seqor_true; eauto. rewrite TY; auto.\n inv H0. eapply esr_condition; eauto. congruence.\n inv H0.\n inv H0.\n inv H0.\n inv H0.\n inv H0.\n inv H0.\n red; split; intros. auto. inv H0.\n red; split; intros. auto. inv H0.\n inv H0. econstructor; eauto.\n inv H0. econstructor; eauto. congruence.\nQed.\n\nLemma simple_context_1:\n forall a from to C, context from to C -> simple (C a) -> simple a.\nProof.\n induction 1; simpl; tauto.\nQed.\n\nLemma simple_context_2:\n forall a a', simple a' -> forall from to C, context from to C -> simple (C a) -> simple (C a').\nProof.\n induction 2; simpl; try tauto.\nQed.\n\nLemma compat_eval_steps_aux f r e m r' m' s2 :\n simple r ->\n star step ge s2 nil (ExprState f r' Kstop e m') ->\n estep ge (ExprState f r Kstop e m) nil s2 ->\n exists r1,\n s2 = ExprState f r1 Kstop e m /\\\n compat_eval RV e r r1 m /\\ simple r1.\nProof.\n intros.\n inv H1.\n (* lred *)\n assert (S: simple a) by (eapply simple_context_1; eauto).\n exploit lred_compat; eauto. intros [A B]. subst m'0.\n econstructor; split. eauto. split.\n eapply compat_eval_context; eauto.\n eapply simple_context_2; eauto. eapply lred_simple; eauto.\n (* rred *)\n assert (S: simple a) by (eapply simple_context_1; eauto).\n exploit rred_compat; eauto. intros [A B]. subst m'0.\n econstructor; split. eauto. split.\n eapply compat_eval_context; eauto.\n eapply simple_context_2; eauto. eapply rred_simple; eauto.\n (* callred *)\n assert (S: simple a) by (eapply simple_context_1; eauto).\n inv H8; simpl in S; contradiction.\n (* stuckred *)\n inv H0. destruct H1; inv H0.\nQed.\n\nLemma compat_eval_steps:\n forall f r e m r' m',\n star step ge (ExprState f r Kstop e m) E0 (ExprState f r' Kstop e m') ->\n simple r ->\n m' = m /\\ compat_eval RV e r r' m.\nProof.\n intros.\n remember (ExprState f r Kstop e m) as S1.\n remember E0 as t.\n remember (ExprState f r' Kstop e m') as S2.\n revert S1 t S2 H r m r' m' HeqS1 Heqt HeqS2 H0.\n induction 1; intros; subst.\n (* base case *)\n inv HeqS2. split. auto. red; auto.\n (* inductive case *)\n destruct (app_eq_nil t1 t2); auto. subst. inv H.\n (* expression step *)\n exploit compat_eval_steps_aux; eauto.\n intros [r1 [A [B C]]]. subst s2.\n exploit IHstar; eauto. intros [D E].\n split. auto. destruct B; destruct E. split. congruence. auto.\n (* statement steps *)\n inv H1.\nQed.\n\nTheorem eval_simple_steps:\n forall f r e m v ty m',\n star step ge (ExprState f r Kstop e m) E0 (ExprState f (Eval v ty) Kstop e m') ->\n simple r ->\n m' = m /\\ ty = typeof r /\\ eval_simple_rvalue e m r v.\nProof.\n intros. exploit compat_eval_steps; eauto. intros [A [B C]].\n intuition. apply C. constructor.\nQed.\n\n(** * Soundness of the compile-time evaluator *)\n\n(** A global environment [ge] induces a memory injection mapping\n our symbolic pointers [Vptr id ofs] to run-time pointers\n [Vptr b ofs] where [Genv.find_symbol ge id = Some b]. *)\n\nDefinition inj (b: block) :=\n match Genv.find_symbol ge b with\n | Some b' => Some (b', 0)\n | None => None\n end.\n\nLemma mem_empty_not_valid_pointer:\n forall b ofs, Mem.valid_pointer Mem.empty b ofs = false.\nProof.\n intros. unfold Mem.valid_pointer. destruct (Mem.perm_dec Mem.empty b ofs Cur Nonempty); auto.\n eelim Mem.perm_empty; eauto.\nQed.\n\nLemma mem_empty_not_weak_valid_pointer:\n forall b ofs, Mem.weak_valid_pointer Mem.empty b ofs = false.\nProof.\n intros. unfold Mem.weak_valid_pointer.\n now rewrite !mem_empty_not_valid_pointer.\nQed.\n\nLemma sem_cast_match:\n forall v1 ty1 ty2 m v2 v1' v2',\n sem_cast v1 ty1 ty2 m = Some v2 ->\n do_cast v1' ty1 ty2 = OK v2' ->\n Val.inject inj v1' v1 ->\n Val.inject inj v2' v2.\nProof.\n intros. unfold do_cast in H0. destruct (sem_cast v1' ty1 ty2 Mem.empty) as [v2''|] eqn:E; inv H0.\n exploit (sem_cast_inj inj Mem.empty m).\n intros. rewrite mem_empty_not_weak_valid_pointer in H2. discriminate.\n eexact E. eauto.\n intros [v' [A B]]. congruence.\nQed.\n\nLemma bool_val_match:\n forall v ty b v' m,\n bool_val v ty Mem.empty = Some b ->\n Val.inject inj v v' ->\n bool_val v' ty m = Some b.\nProof.\n intros. eapply bool_val_inj; eauto. intros. rewrite mem_empty_not_weak_valid_pointer in H2; discriminate.\nQed.\n\nLemma add_offset_match:\n forall v b ofs delta,\n Val.inject inj v (Vptr b ofs) ->\n Val.inject inj\n (if Archi.ptr64\n then Val.addl v (Vlong (Int64.repr delta))\n else Val.add v (Vint (Int.repr delta)))\n (Vptr b (Ptrofs.add ofs (Ptrofs.repr delta))).\nProof.\n intros. inv H.\n- rewrite Ptrofs.add_assoc. rewrite (Ptrofs.add_commut (Ptrofs.repr delta0)).\n unfold Val.addl, Val.add; destruct Archi.ptr64 eqn:SF;\n econstructor; eauto; rewrite ! Ptrofs.add_assoc; f_equal; f_equal; symmetry; auto with ptrofs.\n- unfold Val.addl, Val.add; destruct Archi.ptr64; auto.\nQed.\n\n(** Soundness of [constval] with respect to the big-step semantics *)\n\nLemma constval_rvalue:\n forall m a v,\n eval_simple_rvalue empty_env m a v ->\n forall v',\n constval ge a = OK v' ->\n Val.inject inj v' v\nwith constval_lvalue:\n forall m a b ofs bf,\n eval_simple_lvalue empty_env m a b ofs bf ->\n forall v',\n constval ge a = OK v' ->\n bf = Full /\\ Val.inject inj v' (Vptr b ofs).\nProof.\n (* rvalue *)\n induction 1; intros vres CV; simpl in CV; try (monadInv CV).\n (* val *)\n destruct v; monadInv CV; constructor.\n (* rval *)\n assert (constval ge l = OK vres) by (destruct (access_mode ty); congruence).\n exploit constval_lvalue; eauto. intros [A B]. subst bf.\n inv H1; rewrite H3 in CV; congruence.\n (* addrof *)\n eapply constval_lvalue; eauto.\n (* unop *)\n destruct (sem_unary_operation op x (typeof r1) Mem.empty) as [v1'|] eqn:E; inv EQ0.\n exploit (sem_unary_operation_inj inj Mem.empty m).\n intros. rewrite mem_empty_not_weak_valid_pointer in H2; discriminate.\n eexact E. eauto.\n intros [v' [A B]]. congruence.\n (* binop *)\n destruct (sem_binary_operation ge op x (typeof r1) x0 (typeof r2) Mem.empty) as [v1'|] eqn:E; inv EQ2.\n exploit (sem_binary_operation_inj inj Mem.empty m).\n intros. rewrite mem_empty_not_valid_pointer in H3; discriminate.\n intros. rewrite mem_empty_not_weak_valid_pointer in H3; discriminate.\n intros. rewrite mem_empty_not_weak_valid_pointer in H3; discriminate.\n intros. rewrite mem_empty_not_valid_pointer in H3; discriminate.\n eauto. eauto. eauto.\n intros [v' [A B]]. congruence.\n (* cast *)\n eapply sem_cast_match; eauto.\n (* sizeof *)\n auto.\n (* alignof *)\n auto.\n (* seqand *)\n destruct (bool_val x (typeof r1) Mem.empty) as [b|] eqn:E; inv EQ2.\n exploit bool_val_match. eexact E. eauto. instantiate (1 := m). intros E'.\n assert (b = true) by congruence. subst b.\n eapply sem_cast_match; eauto.\n destruct (bool_val x (typeof r1) Mem.empty) as [b|] eqn:E; inv EQ2.\n exploit bool_val_match. eexact E. eauto. instantiate (1 := m). intros E'.\n assert (b = false) by congruence. subst b. inv H2. auto.\n (* seqor *)\n destruct (bool_val x (typeof r1) Mem.empty) as [b|] eqn:E; inv EQ2.\n exploit bool_val_match. eexact E. eauto. instantiate (1 := m). intros E'.\n assert (b = false) by congruence. subst b.\n eapply sem_cast_match; eauto.\n destruct (bool_val x (typeof r1) Mem.empty) as [b|] eqn:E; inv EQ2.\n exploit bool_val_match. eexact E. eauto. instantiate (1 := m). intros E'.\n assert (b = true) by congruence. subst b. inv H2. auto.\n (* conditional *)\n destruct (bool_val x (typeof r1) Mem.empty) as [b'|] eqn:E; inv EQ3.\n exploit bool_val_match. eexact E. eauto. instantiate (1 := m). intros E'.\n assert (b' = b) by congruence. subst b'.\n destruct b; eapply sem_cast_match; eauto.\n (* comma *)\n auto.\n (* paren *)\n eapply sem_cast_match; eauto.\n\n (* lvalue *)\n induction 1; intros v' CV; simpl in CV; try (monadInv CV).\n (* var local *)\n split; auto. unfold empty_env in H. rewrite PTree.gempty in H. congruence.\n (* var_global *)\n split; auto. econstructor. unfold inj. rewrite H0. eauto. auto.\n (* deref *)\n split; eauto.\n (* field struct *)\n rewrite H0 in EQ. monadInv EQ. destruct x0; monadInv EQ2.\n unfold lookup_composite in EQ0; rewrite H1 in EQ0; monadInv EQ0.\n exploit constval_rvalue; eauto. intro MV.\n split. congruence.\n replace x with delta by congruence.\n apply (add_offset_match _ _ _ _ MV).\n (* field union *)\n rewrite H0 in EQ. monadInv EQ. destruct x0; monadInv EQ2.\n unfold lookup_composite in EQ0; rewrite H1 in EQ0; monadInv EQ0.\n exploit constval_rvalue; eauto. intro MV.\n split. congruence.\n replace x with delta by congruence. \n apply (add_offset_match _ _ _ _ MV).\nQed.\n\nLemma constval_simple:\n forall a v, constval ge a = OK v -> simple a.\nProof.\n induction a; simpl; intros vx CV; try (monadInv CV); eauto.\n destruct (access_mode ty); discriminate || eauto.\n intuition eauto.\nQed.\n\n(** Soundness of [constval] with respect to the reduction semantics. *)\n\nTheorem constval_steps:\n forall f r m v v' ty m',\n star step ge (ExprState f r Kstop empty_env m) E0 (ExprState f (Eval v' ty) Kstop empty_env m') ->\n constval ge r = OK v ->\n m' = m /\\ ty = typeof r /\\ Val.inject inj v v'.\nProof.\n intros. exploit eval_simple_steps; eauto. eapply constval_simple; eauto.\n intros [A [B C]]. intuition. eapply constval_rvalue; eauto.\nQed.\n\n(** * Correctness of operations over the initialization state *)\n\n(** ** Properties of the in-memory bytes denoted by initialization data *)\n\nLocal Notation boid := (Genv.bytes_of_init_data (genv_genv ge)).\nLocal Notation boidl := (Genv.bytes_of_init_data_list (genv_genv ge)).\n\nLemma boidl_app: forall il2 il1,\n boidl (il1 ++ il2) = boidl il1 ++ boidl il2.\nProof.\n induction il1 as [ | il il1]; simpl. auto. rewrite app_ass. f_equal; auto.\nQed.\n\nCorollary boidl_rev_cons: forall i il,\n boidl (rev il ++ i :: nil) = boidl (rev il) ++ boid i.\nProof.\n intros. rewrite boidl_app. simpl. rewrite <- app_nil_end. auto.\nQed. \n\nDefinition byte_of_int (n: int) := Byte.repr (Int.unsigned n).\n\nLemma byte_of_int_of_byte: forall b, byte_of_int (int_of_byte b) = b.\nProof.\n intros. unfold int_of_byte, byte_of_int.\n rewrite Int.unsigned_repr, Byte.repr_unsigned. auto.\n assert(Byte.max_unsigned < Int.max_unsigned) by reflexivity.\n generalize (Byte.unsigned_range_2 b). lia.\nQed.\n\nLemma inj_bytes_1: forall n,\n inj_bytes (encode_int 1 n) = Byte (Byte.repr n) :: nil.\nProof.\n intros. unfold encode_int, bytes_of_int, rev_if_be. destruct Archi.big_endian; auto.\nQed.\n\nLemma inj_bytes_byte: forall b,\n inj_bytes (encode_int 1 (Int.unsigned (int_of_byte b))) = Byte b :: nil.\nProof.\n intros. rewrite inj_bytes_1. do 2 f_equal. apply byte_of_int_of_byte.\nQed.\n\nLemma boidl_init_ints8: forall l,\n boidl (map Init_int8 l) = inj_bytes (map byte_of_int l).\nProof.\n induction l as [ | i l]; simpl. auto. rewrite inj_bytes_1; simpl. f_equal; auto.\nQed.\n\nLemma boidl_init_bytes: forall l,\n boidl (map Init_byte l) = inj_bytes l.\nProof.\n induction l as [ | b l]; simpl. auto. rewrite inj_bytes_byte, IHl. auto.\nQed.\n\nLemma boidl_ints8: forall i n,\n boidl (repeat (Init_int8 i) n) = repeat (Byte (byte_of_int i)) n.\nProof.\n induction n; simpl. auto. rewrite inj_bytes_1. simpl; f_equal; auto.\nQed.\n\n(** ** Properties of operations over list of initialization data *)\n\nLemma add_rev_bytes_spec: forall l il,\n add_rev_bytes l il = List.map Init_byte (List.rev l) ++ il.\nProof.\n induction l as [ | b l]; intros; simpl.\n- auto.\n- rewrite IHl. rewrite map_app. simpl. rewrite app_ass. auto.\nQed.\n\nLemma add_rev_bytes_spec': forall l il,\n List.rev (add_rev_bytes l il) = List.rev il ++ List.map Init_byte l.\nProof.\n intros. rewrite add_rev_bytes_spec. rewrite rev_app_distr, map_rev, rev_involutive. auto.\nQed.\n\nLemma add_zeros_spec: forall n il,\n 0 <= n ->\n add_zeros n il = List.repeat (Init_int8 Int.zero) (Z.to_nat n) ++ il.\nProof.\n intros.\n unfold add_zeros; rewrite iter_nat_of_Z by auto; rewrite Zabs2Nat.abs_nat_nonneg by auto.\n induction (Z.to_nat n); simpl. auto. f_equal; auto.\nQed.\n\nLemma decompose_spec: forall il depth bl il',\n decompose il depth = OK (bl, il') ->\n exists nl, il = List.map Init_int8 nl ++ il'\n /\\ bl = List.map byte_of_int (rev nl)\n /\\ List.length nl = Z.to_nat depth.\nProof.\n assert (REC: forall il accu depth bl il',\n decompose_rec accu il depth = OK (bl, il') ->\n exists nl, il = List.map Init_int8 nl ++ il'\n /\\ bl = List.map byte_of_int (rev nl) ++ accu\n /\\ List.length nl = Z.to_nat depth).\n { induction il as [ | i il ]; intros until il'; intros D; simpl in D.\n - destruct (zle depth 0); inv D.\n exists (@nil int); simpl. rewrite Z_to_nat_neg by auto. auto.\n - destruct (zle depth 0). \n + inv D. exists (@nil int); simpl. rewrite Z_to_nat_neg by auto. auto.\n + destruct i; try discriminate.\n apply IHil in D; destruct D as (nl & P & Q & R).\n exists (i :: nl); simpl; split. congruence. split.\n rewrite map_app. simpl. rewrite app_ass. exact Q.\n rewrite R, <- Z2Nat.inj_succ by lia. f_equal; lia.\n }\n intros. apply REC in H. destruct H as (nl & P & Q & R). rewrite app_nil_r in Q.\n exists nl; auto.\nQed.\n\nLemma list_repeat_app: forall (A: Type) (a: A) n2 n1,\n List.repeat a n1 ++ List.repeat a n2 = List.repeat a (n1 + n2)%nat.\nProof.\n induction n1; simpl; congruence.\nQed.\n\nLemma list_rev_repeat: forall (A: Type) (a: A) n,\n rev (List.repeat a n) = List.repeat a n.\nProof.\n induction n; simpl. auto. rewrite IHn. change (a :: nil) with (repeat a 1%nat).\n rewrite list_repeat_app. rewrite Nat.add_comm. auto. \nQed.\n\nLemma normalize_boidl: forall il depth il',\n normalize il depth = OK il' ->\n boidl (rev il') = boidl (rev il).\nProof.\n induction il as [ | i il]; simpl; intros depth il' AT.\n- destruct (zle depth 0); inv AT. auto.\n- destruct (zle depth 0). inv AT. auto.\n destruct i;\n try (monadInv AT; simpl;\n rewrite ? add_rev_bytes_spec', ? boidl_rev_cons, ? boidl_app, ? boidl_init_bytes;\n erewrite IHil by eauto; reflexivity).\n set (n := Z.max 0 z) in *. destruct (zle n depth); monadInv AT.\n + rewrite add_zeros_spec, rev_app_distr, ! boidl_app by lia.\n erewrite IHil by eauto. f_equal.\n rewrite list_rev_repeat. simpl. rewrite app_nil_r, boidl_ints8.\n f_equal. unfold n. apply Z.max_case_strong; intros; auto. rewrite ! Z_to_nat_neg by lia. auto.\n + rewrite add_zeros_spec, rev_app_distr, !boidl_app by lia.\n simpl. rewrite boidl_rev_cons, list_rev_repeat. simpl.\n rewrite app_ass, app_nil_r, !boidl_ints8. f_equal.\n rewrite list_repeat_app. f_equal. rewrite <- Z2Nat.inj_add by lia.\n unfold n. apply Z.max_case_strong; intros; f_equal; lia.\nQed.\n\nLemma trisection_boidl: forall il depth sz bytes1 bytes2 il',\n trisection il depth sz = OK (bytes1, bytes2, il') ->\n boidl (rev il) = boidl (rev il') ++ inj_bytes bytes2 ++ inj_bytes bytes1\n /\\ length bytes1 = Z.to_nat depth\n /\\ length bytes2 = Z.to_nat sz.\nProof.\n unfold trisection; intros. monadInv H.\n apply normalize_boidl in EQ. rewrite <- EQ.\n apply decompose_spec in EQ1. destruct EQ1 as (nl1 & A1 & B1 & C1).\n apply decompose_spec in EQ0. destruct EQ0 as (nl2 & A2 & B2 & C2).\n split.\n- rewrite A1, A2, !rev_app_distr, !boidl_app, app_ass.\n rewrite <- !map_rev, !boidl_init_ints8. rewrite <- B1, <- B2. auto.\n- rewrite B1, B2, !map_length, !rev_length. auto.\nQed. \n\nLemma store_init_data_loadbytes:\n forall m b p i m',\n Genv.store_init_data ge m b p i = Some m' ->\n match i with Init_space _ => False | _ => True end ->\n Mem.loadbytes m' b p (init_data_size i) = Some (boid i).\nProof.\n intros; destruct i; simpl in H; try apply (Mem.loadbytes_store_same _ _ _ _ _ _ H).\n- contradiction.\n- rewrite Genv.init_data_size_addrof. simpl.\n destruct (Genv.find_symbol ge i) as [b'|]; try discriminate.\n rewrite (Mem.loadbytes_store_same _ _ _ _ _ _ H).\n unfold encode_val, Mptr; destruct Archi.ptr64; reflexivity.\nQed.\n\n(** ** Validity and size of initialization data *)\n\nDefinition idvalid (i: init_data) : Prop :=\n match i with\n | Init_addrof symb ofs => exists b, Genv.find_symbol ge symb = Some b\n | _ => True\n end.\n\nFixpoint idlvalid (p: Z) (il: list init_data) {struct il} : Prop :=\n match il with\n | nil => True\n | i1 :: il =>\n (Genv.init_data_alignment i1 | p)\n /\\ idvalid i1\n /\\ idlvalid (p + init_data_size i1) il\n end.\n\nLemma idlvalid_app: forall l2 l1 pos,\n idlvalid pos (l1 ++ l2) <-> idlvalid pos l1 /\\ idlvalid (pos + init_data_list_size l1) l2.\nProof.\n induction l1 as [ | d l1]; intros; simpl.\n- rewrite Z.add_0_r; tauto.\n- rewrite IHl1. rewrite Z.add_assoc. tauto.\nQed.\n\nLemma add_rev_bytes_valid: forall il bl,\n idlvalid 0 (rev il) -> idlvalid 0 (rev (add_rev_bytes bl il)).\nProof.\n intros. rewrite add_rev_bytes_spec, rev_app_distr, idlvalid_app. split; auto.\n generalize (rev bl) (0 + init_data_list_size (rev il)). induction l; simpl; intros.\n auto.\n rewrite idlvalid_app; split; auto. simpl. auto using Z.divide_1_l.\nQed.\n\nLemma add_zeros_valid: forall il n,\n 0 <= n -> idlvalid 0 (rev il) -> idlvalid 0 (rev (add_zeros n il)).\nProof.\n intros. rewrite add_zeros_spec, rev_app_distr, idlvalid_app by auto.\n split; auto.\n generalize (Z.to_nat n) (0 + init_data_list_size (rev il)). induction n0; simpl; intros.\n auto.\n rewrite idlvalid_app; split; auto. simpl. auto using Z.divide_1_l.\nQed.\n\nLemma normalize_valid: forall il depth il',\n normalize il depth = OK il' -> idlvalid 0 (rev il) -> idlvalid 0 (rev il').\nProof.\n induction il as [ | i il]; simpl; intros.\n- destruct (zle depth 0); inv H. simpl. tauto.\n- destruct (zle depth 0). inv H. auto.\n rewrite idlvalid_app in H0; destruct H0.\n destruct i; try (monadInv H; apply add_rev_bytes_valid; eapply IHil; eauto).\n + monadInv H. simpl. rewrite idlvalid_app; split. eauto. simpl; auto using Z.divide_1_l. \n + destruct (zle (Z.max 0 z)); monadInv H.\n * apply add_zeros_valid. lia. eauto.\n * apply add_zeros_valid. lia. simpl. rewrite idlvalid_app; split. auto. simpl; auto using Z.divide_1_l.\nQed.\n\nLemma trisection_valid: forall il depth sz bytes1 bytes2 il',\n trisection il depth sz = OK (bytes1, bytes2, il') ->\n idlvalid 0 (rev il) ->\n idlvalid 0 (rev il').\nProof.\n unfold trisection; intros. monadInv H.\n apply decompose_spec in EQ1. destruct EQ1 as (nl1 & A1 & B1 & C1).\n apply decompose_spec in EQ0. destruct EQ0 as (nl2 & A2 & B2 & C2).\n exploit normalize_valid; eauto. rewrite A1, A2, !rev_app_distr, !idlvalid_app.\n tauto.\nQed.\n\nLemma init_data_size_boid: forall i,\n init_data_size i = Z.of_nat (length (boid i)).\nProof.\n intros. destruct i; simpl; rewrite ?length_inj_bytes, ?encode_int_length; auto.\n- rewrite repeat_length. rewrite Z_to_nat_max; auto.\n- destruct (Genv.find_symbol ge i), Archi.ptr64; reflexivity.\nQed.\n\nLemma init_data_list_size_boidl: forall il,\n init_data_list_size il = Z.of_nat (length (boidl il)).\nProof.\n induction il as [ | i il]; simpl. auto. \n rewrite app_length, init_data_size_boid. lia.\nQed.\n\nLemma init_data_list_size_app: forall l1 l2,\n init_data_list_size (l1 ++ l2) = init_data_list_size l1 + init_data_list_size l2.\nProof.\n induction l1 as [ | i l1]; intros; simpl. auto. rewrite IHl1; lia.\nQed.\n\n(** ** Memory areas that are initialized to zeros *)\n\nDefinition reads_as_zeros (m: mem) (b: block) (from to: Z) : Prop :=\n forall i, from <= i < to -> Mem.loadbytes m b i 1 = Some (Byte Byte.zero :: nil).\n\nLemma reads_as_zeros_mono: forall m b from1 from2 to1 to2,\n reads_as_zeros m b from1 to1 -> from1 <= from2 -> to2 <= to1 ->\n reads_as_zeros m b from2 to2.\nProof.\n intros; red; intros. apply H; lia.\nQed.\n\nRemark reads_as_zeros_unchanged:\n forall (P: block -> Z -> Prop) m b from to m',\n reads_as_zeros m b from to ->\n Mem.unchanged_on P m m' ->\n (forall i, from <= i < to -> P b i) ->\n reads_as_zeros m' b from to.\nProof.\n intros; red; intros. eapply Mem.loadbytes_unchanged_on; eauto.\n intros; apply H1. lia.\nQed.\n\nLemma reads_as_zeros_loadbytes: forall m b from to,\n reads_as_zeros m b from to ->\n forall len pos, from <= pos -> pos + len <= to -> 0 <= len ->\n Mem.loadbytes m b pos len = Some (repeat (Byte Byte.zero) (Z.to_nat len)).\nProof.\n intros until to; intros RZ.\n induction len using (well_founded_induction (Zwf_well_founded 0)).\n intros. destruct (zeq len 0).\n- subst len. rewrite Mem.loadbytes_empty by lia. auto.\n- replace (Z.to_nat len) with (S (Z.to_nat (len - 1))).\n change (repeat (Byte Byte.zero) (S (Z.to_nat (len - 1))))\n with ((Byte Byte.zero :: nil) ++ repeat (Byte Byte.zero) (Z.to_nat (len - 1))).\n replace len with (1 + (len - 1)) at 1 by lia. \n apply Mem.loadbytes_concat; try lia.\n + apply RZ. lia.\n + apply H; unfold Zwf; lia.\n + rewrite <- Z2Nat.inj_succ by lia. f_equal; lia. \nQed.\n\nLemma reads_as_zeros_equiv: forall m b from to,\n reads_as_zeros m b from to <-> Genv.readbytes_as_zero m b from (to - from).\nProof.\n intros; split; intros.\n- red; intros. set (len := Z.of_nat n).\n replace n with (Z.to_nat len) by apply Nat2Z.id.\n eapply reads_as_zeros_loadbytes; eauto. lia. lia.\n- red; intros. red in H. apply (H i 1%nat). lia. lia.\nQed.\n\n(** ** Semantic correctness of state operations *)\n\n(** Semantic interpretation of states. *)\n\nRecord match_state (s: state) (m: mem) (b: block) : Prop := {\n match_range:\n 0 <= s.(curr) <= s.(total_size);\n match_contents:\n Mem.loadbytes m b 0 s.(curr) = Some (boidl (rev s.(init)));\n match_valid:\n idlvalid 0 (rev s.(init));\n match_uninitialized:\n reads_as_zeros m b s.(curr) s.(total_size)\n}.\n\nLemma match_size: forall s m b,\n match_state s m b ->\n init_data_list_size (rev s.(init)) = s.(curr).\nProof.\n intros. rewrite init_data_list_size_boidl.\n erewrite Mem.loadbytes_length by (eapply match_contents; eauto).\n apply Z2Nat.id. eapply match_range; eauto.\nQed.\n\nLemma curr_pad_to: forall s pos,\n curr s <= curr (pad_to s pos) /\\ pos <= curr (pad_to s pos).\nProof.\n unfold pad_to; intros. destruct (zle pos (curr s)); simpl; lia.\nQed.\n\nLemma total_size_pad_to: forall s pos,\n total_size (pad_to s pos) = total_size s.\nProof.\n unfold pad_to; intros. destruct (zle pos (curr s)); auto.\nQed.\n\nLemma pad_to_correct: forall pos s m b,\n match_state s m b -> pos <= s.(total_size) ->\n match_state (pad_to s pos) m b.\nProof.\n intros. unfold pad_to. destruct (zle pos (curr s)); auto.\n destruct H; constructor; simpl; intros.\n- lia.\n- rewrite boidl_rev_cons. simpl.\n replace pos with (s.(curr) + (pos - s.(curr))) at 1 by lia.\n apply Mem.loadbytes_concat; try lia.\n * auto.\n * eapply reads_as_zeros_loadbytes; eauto. lia. lia. lia.\n- rewrite idlvalid_app. split; auto. simpl. intuition auto using Z.divide_1_l.\n- eapply reads_as_zeros_mono; eauto; lia.\nQed.\n\nLemma trisection_correct: forall s m b pos sz bytes1 bytes2 il,\n match_state s m b ->\n trisection s.(init) (s.(curr) - (pos + sz)) sz = OK (bytes1, bytes2, il) ->\n 0 <= pos -> pos + sz <= s.(curr) -> 0 <= sz ->\n Mem.loadbytes m b 0 pos = Some (boidl (rev il))\n /\\ Mem.loadbytes m b pos sz = Some (inj_bytes bytes2)\n /\\ Mem.loadbytes m b (pos + sz) (s.(curr) - (pos + sz)) = Some (inj_bytes bytes1).\nProof.\n intros. apply trisection_boidl in H0. destruct H0 as (A & B & C).\n set (depth := curr s - (pos + sz)) in *.\n pose proof (match_contents _ _ _ H) as D.\n replace (curr s) with ((pos + sz) + depth) in D by lia.\n exploit Mem.loadbytes_split. eexact D. lia. lia.\n rewrite Z.add_0_l. intros (bytes0 & bytes1' & LB0 & LB1 & E1).\n exploit Mem.loadbytes_split. eexact LB0. lia. lia.\n rewrite Z.add_0_l. intros (bytes3 & bytes2' & LB3 & LB2 & E2).\n rewrite A in E1. rewrite <- app_ass in E1.\n exploit list_append_injective_r. eexact E1.\n { unfold inj_bytes; rewrite map_length. erewrite Mem.loadbytes_length; eauto. }\n intros (E3 & E4).\n rewrite E2 in E3.\n exploit list_append_injective_r. eexact E3.\n { unfold inj_bytes; rewrite map_length. erewrite Mem.loadbytes_length; eauto. }\n intros (E5 & E6).\n intuition congruence.\nQed.\n\nRemark decode_int_zero_ext: forall n bytes,\n 0 <= n <= 4 -> n = Z.of_nat (length bytes) ->\n Int.zero_ext (n * 8) (Int.repr (decode_int bytes)) = Int.repr (decode_int bytes).\nProof.\n intros.\n assert (0 <= decode_int bytes < two_p (n * 8)).\n { rewrite H0. replace (length bytes) with (length (rev_if_be bytes)). \n apply int_of_bytes_range.\n apply rev_if_be_length. }\n assert (two_p (n * 8) <= Int.modulus).\n { apply (two_p_monotone (n * 8) 32); lia. } \n unfold Int.zero_ext.\n rewrite Int.unsigned_repr by (unfold Int.max_unsigned; lia).\n rewrite Zbits.Zzero_ext_mod by lia.\n rewrite Zmod_small by auto. auto.\nQed.\n\nTheorem load_int_correct: forall s m b pos isz i v,\n match_state s m b ->\n load_int s pos isz = OK i ->\n Mem.load (chunk_for_carrier isz) m b pos = Some v ->\n v = Vint i.\nProof.\n intros until v; intros MS RI LD.\n exploit Mem.load_valid_access. eauto. intros [PERM ALIGN].\n unfold load_int in RI. \n set (chunk := chunk_for_carrier isz) in *.\n set (sz := size_chunk chunk) in *.\n assert (sz > 0) by (apply size_chunk_pos).\n set (s1 := pad_to s (pos + sz)) in *.\n assert (pos + sz <= curr s1) by (apply curr_pad_to).\n monadInv RI. InvBooleans. destruct x as [[bytes1 bytes2] il].\n assert (MS': match_state s1 m b) by (apply pad_to_correct; auto).\n exploit trisection_correct; eauto. lia.\n intros (L1 & L2 & L3).\n assert (LEN: Z.of_nat (length bytes2) = sz).\n { apply Mem.loadbytes_length in L2. unfold inj_bytes in L2.\n rewrite map_length in L2. rewrite L2. apply Z2Nat.id; lia. }\n exploit Mem.loadbytes_load. eexact L2. exact ALIGN. rewrite LD. \n unfold decode_val. rewrite proj_inj_bytes. intros E; inv E; inv EQ0.\n unfold chunk, chunk_for_carrier; destruct isz; f_equal.\n - apply (decode_int_zero_ext 1). lia. auto.\n - apply (decode_int_zero_ext 2). lia. auto.\n - apply (decode_int_zero_ext 1). lia. auto.\nQed.\n\nRemark loadbytes_concat_3: forall m b ofs1 len1 l1 ofs2 len2 l2 ofs3 len3 l3 len,\n Mem.loadbytes m b ofs1 len1 = Some l1 ->\n Mem.loadbytes m b ofs2 len2 = Some l2 ->\n Mem.loadbytes m b ofs3 len3 = Some l3 ->\n ofs2 = ofs1 + len1 -> ofs3 = ofs2 + len2 -> 0 <= len1 -> 0 <= len2 -> 0 <= len3 ->\n len = len1 + len2 + len3 ->\n Mem.loadbytes m b ofs1 len = Some (l1 ++ l2 ++ l3).\nProof.\n intros. rewrite H7, <- Z.add_assoc. apply Mem.loadbytes_concat. auto.\n apply Mem.loadbytes_concat. rewrite <- H2; auto. rewrite <- H2, <- H3; auto.\n lia. lia. lia. lia.\nQed. \n\nTheorem store_data_correct: forall s m b pos i s' m',\n match_state s m b ->\n store_data s pos i = OK s' ->\n Genv.store_init_data ge m b pos i = Some m' ->\n match i with Init_space _ => False | _ => True end ->\n match_state s' m' b.\nProof.\n intros until m'; intros MS ST SI NOSPACE.\n exploit Genv.store_init_data_aligned; eauto. intros ALIGN.\n assert (VALID: idvalid i).\n { destruct i; simpl; auto. simpl in SI. destruct (Genv.find_symbol ge i); try discriminate. exists b0; auto. }\n unfold store_data in ST.\n set (sz := init_data_size i) in *.\n assert (sz >= 0) by (apply init_data_size_pos).\n set (s1 := pad_to s (pos + sz)) in *.\n monadInv ST. InvBooleans.\n assert (U: Mem.unchanged_on (fun b i => ~(pos <= i < pos + sz)) m m').\n { eapply Genv.store_init_data_unchanged. eauto. tauto. }\n exploit store_init_data_loadbytes; eauto. fold sz. intros D.\n destruct (zle (curr s) pos).\n- inv ST.\n set (il := if zlt (curr s) pos then Init_space (pos - curr s) :: init s else init s).\n assert (IL: boidl (rev il) = boidl (rev (init s)) ++ repeat (Byte Byte.zero) (Z.to_nat (pos - curr s))).\n { unfold il; destruct (zlt (curr s) pos).\n - simpl rev. rewrite boidl_rev_cons. simpl. auto.\n - rewrite Z_to_nat_neg by lia. simpl. rewrite app_nil_r; auto.\n }\n constructor; simpl; intros.\n + lia.\n + rewrite boidl_rev_cons, IL, app_ass.\n apply loadbytes_concat_3 with (len1 := curr s) (ofs2 := curr s) (len2 := pos - curr s) (ofs3 := pos) (len3 := sz); try lia.\n * eapply Mem.loadbytes_unchanged_on; eauto.\n intros. simpl. lia.\n eapply match_contents; eauto.\n * eapply Mem.loadbytes_unchanged_on; eauto.\n intros. simpl. lia.\n eapply reads_as_zeros_loadbytes. eapply match_uninitialized; eauto. lia. lia. lia.\n * exact D.\n * eapply match_range; eauto.\n + rewrite idlvalid_app; split.\n * unfold il; destruct (zlt (curr s) pos).\n ** simpl; rewrite idlvalid_app; split. eapply match_valid; eauto. simpl. auto using Z.divide_1_l.\n ** eapply match_valid; eauto.\n * simpl.\n replace (init_data_list_size (rev il)) with pos. tauto.\n unfold il; destruct (zlt (curr s) pos).\n ** simpl; rewrite init_data_list_size_app; simpl.\n erewrite match_size by eauto. lia.\n ** erewrite match_size by eauto. lia.\n + eapply reads_as_zeros_unchanged; eauto.\n eapply reads_as_zeros_mono. eapply match_uninitialized; eauto. lia. lia.\n intros. simpl. lia.\n- monadInv ST. destruct x as [[bytes1 bytes2] il]. inv EQ0.\n assert (pos + sz <= curr s1) by (apply curr_pad_to).\n assert (MS': match_state s1 m b) by (apply pad_to_correct; auto).\n exploit trisection_correct; eauto. lia.\n intros (L1 & L2 & L3).\n constructor; simpl; intros.\n + eapply match_range; eauto.\n + rewrite add_rev_bytes_spec, rev_app_distr; simpl; rewrite app_ass; simpl.\n rewrite <- map_rev, rev_involutive.\n rewrite boidl_app. simpl. rewrite boidl_init_bytes.\n apply loadbytes_concat_3 with (len1 := pos) (ofs2 := pos) (len2 := sz) (ofs3 := pos + sz)\n (len3 := curr s1 - (pos + sz)); try lia.\n * eapply Mem.loadbytes_unchanged_on; eauto.\n intros. simpl. lia.\n * exact D.\n * eapply Mem.loadbytes_unchanged_on; eauto.\n intros. simpl. lia.\n + apply add_rev_bytes_valid. simpl; rewrite idlvalid_app; split.\n * eapply trisection_valid; eauto. eapply match_valid; eauto.\n * rewrite init_data_list_size_boidl. erewrite Mem.loadbytes_length by eauto.\n rewrite Z2Nat.id by lia. simpl. tauto.\n + eapply reads_as_zeros_unchanged; eauto. eapply match_uninitialized; eauto.\n intros. simpl. lia.\nQed.\n\nCorollary store_int_correct: forall s m b pos isz n s' m',\n match_state s m b ->\n store_int s pos isz n = OK s' ->\n Mem.store (chunk_for_carrier isz) m b pos (Vint n) = Some m' ->\n match_state s' m' b.\nProof.\n intros. eapply store_data_correct; eauto.\n- destruct isz; exact H1.\n- destruct isz; exact I.\nQed.\n\nTheorem init_data_list_of_state_correct: forall s m b il b' m1,\n match_state s m b ->\n init_data_list_of_state s = OK il ->\n Mem.range_perm m1 b' 0 s.(total_size) Cur Writable ->\n reads_as_zeros m1 b' 0 s.(total_size) ->\n exists m2,\n Genv.store_init_data_list ge m1 b' 0 il = Some m2\n /\\ Mem.loadbytes m2 b' 0 (init_data_list_size il) = Mem.loadbytes m b 0 s.(total_size).\nProof.\n intros. unfold init_data_list_of_state in H0; monadInv H0. rename l into LE.\n set (s1 := pad_to s s.(total_size)) in *.\n assert (MS1: match_state s1 m b) by (apply pad_to_correct; auto; lia).\n apply reads_as_zeros_equiv in H2. rewrite Z.sub_0_r in H2.\n assert (R: rev' (init s1) = rev (init s1)).\n { unfold rev'. rewrite <- rev_alt. auto. }\n assert (C: curr s1 = total_size s).\n { unfold s1, pad_to. destruct zle; simpl; lia. }\n assert (A: Genv.init_data_list_aligned 0 (rev (init s1))).\n { exploit match_valid; eauto. generalize (rev (init s1)) 0.\n induction l as [ | i l]; simpl; intuition. }\n assert (B: forall id ofs, In (Init_addrof id ofs) (rev (init s1)) ->\n exists b, Genv.find_symbol ge id = Some b).\n { intros id ofs. exploit match_valid; eauto. generalize (rev (init s1)) 0.\n induction l as [ | i l]; simpl; intuition eauto. subst i; assumption. }\n exploit Genv.store_init_data_list_exists.\n 2: eexact A. 2: eexact B.\n erewrite match_size by eauto. rewrite C. eauto.\n intros (m2 & ST). exists m2; split.\n- rewrite R. auto.\n- rewrite R. transitivity (Some (boidl (rev (init s1)))).\n + eapply Genv.store_init_data_list_loadbytes; eauto.\n erewrite match_size, C by eauto. auto.\n + symmetry. rewrite <- C. eapply match_contents; eauto.\nQed.\n\n(** ** Total size properties *)\n\nLemma total_size_store_data: forall s pos i s',\n store_data s pos i = OK s' -> total_size s' = total_size s.\nProof.\n unfold store_data; intros. monadInv H. destruct (zle (curr s) pos); monadInv H.\n- auto.\n- destruct x as [[bytes1 bytes2] il2]. inv EQ0. simpl. apply total_size_pad_to.\nQed.\n\nLemma total_size_transl_init_bitfield: forall ce s ty sz p w i pos s',\n transl_init_bitfield ce s ty sz p w i pos = OK s' -> total_size s' = total_size s.\nProof.\n unfold transl_init_bitfield; intros. destruct i; monadInv H. destruct x; monadInv EQ0.\n eapply total_size_store_data. eexact EQ2.\nQed.\n\nLemma total_size_transl_init_rec: forall ce s ty i pos s',\n transl_init_rec ce s ty i pos = OK s' -> total_size s' = total_size s\nwith total_size_transl_init_array: forall ce s tyelt il pos s',\n transl_init_array ce s tyelt il pos = OK s' -> total_size s' = total_size s\nwith total_size_transl_init_struct: forall ce s ms il base pos s',\n transl_init_struct ce s ms il base pos = OK s' -> total_size s' = total_size s.\nProof.\n- destruct i; simpl; intros.\n + monadInv H; eauto using total_size_store_data.\n + destruct ty; monadInv H. eauto.\n + destruct ty; monadInv H. destruct (co_su x); try discriminate. eauto.\n + destruct ty; monadInv H. destruct (co_su x); monadInv EQ0. destruct x2.\n * eauto.\n * eauto using total_size_transl_init_bitfield.\n- destruct il; simpl; intros.\n + inv H; auto.\n + monadInv H. transitivity (total_size x); eauto.\n- destruct il; simpl; intros.\n + inv H; auto.\n + revert ms pos H. induction ms; intros.\n * inv H.\n * destruct (member_not_initialized a). eapply IHms; eauto.\n monadInv H. transitivity (total_size x1). eauto.\n destruct x0; eauto using total_size_transl_init_bitfield.\nQed.\n\n(** * Soundness of the translation of initializers *)\n\n(** Soundness for single initializers. *)\n\nInductive exec_assign: mem -> block -> Z -> bitfield -> type -> val -> mem -> Prop :=\n | exec_assign_full: forall m b ofs ty v m' chunk,\n access_mode ty = By_value chunk ->\n Mem.store chunk m b ofs v = Some m' ->\n exec_assign m b ofs Full ty v m'\n | exec_assign_bits: forall m b ofs sz sg sg1 attr pos width ty n m' c,\n type_is_volatile ty = false ->\n 0 <= pos -> 0 < width -> pos + width <= bitsize_intsize sz ->\n sg1 = (if zlt width (bitsize_intsize sz) then Signed else sg) ->\n Mem.load (chunk_for_carrier sz) m b ofs = Some (Vint c) ->\n Mem.store (chunk_for_carrier sz) m b ofs\n (Vint (Int.bitfield_insert (first_bit sz pos width) width c n)) = Some m' ->\n exec_assign m b ofs (Bits sz sg pos width) (Tint sz sg1 attr) (Vint n) m'.\n\nLemma transl_init_single_sound:\n forall ty a data f m v1 ty1 m' v b ofs m'',\n transl_init_single ge ty a = OK data ->\n star step ge (ExprState f a Kstop empty_env m) E0 (ExprState f (Eval v1 ty1) Kstop empty_env m') ->\n sem_cast v1 ty1 ty m' = Some v ->\n exec_assign m' b ofs Full ty v m'' ->\n Genv.store_init_data ge m b ofs data = Some m''\n /\\ match data with Init_space _ => False | _ => True end.\nProof.\n intros until m''; intros TR STEPS CAST ASG.\n monadInv TR. monadInv EQ. \n exploit constval_steps; eauto. intros [A [B C]]. subst m' ty1.\n exploit sem_cast_match; eauto. intros D.\n inv ASG. rename H into A. unfold Genv.store_init_data. inv D.\n- (* int *)\n remember Archi.ptr64 as ptr64. destruct ty; try discriminate EQ0.\n+ destruct i0; inv EQ0.\n destruct s; simpl in A; inv A. rewrite <- Mem.store_signed_unsigned_8; auto. auto.\n destruct s; simpl in A; inv A. rewrite <- Mem.store_signed_unsigned_16; auto. auto.\n simpl in A; inv A. auto.\n simpl in A; inv A. auto.\n+ destruct ptr64; inv EQ0. simpl in A; unfold Mptr in A; rewrite <- Heqptr64 in A; inv A. auto.\n- (* Long *)\n remember Archi.ptr64 as ptr64. destruct ty; monadInv EQ0.\n+ simpl in A; inv A. auto.\n+ simpl in A; unfold Mptr in A; rewrite <- Heqptr64 in A; inv A. auto.\n- (* float *)\n destruct ty; try discriminate.\n destruct f1; inv EQ0; simpl in A; inv A; auto.\n- (* single *)\n destruct ty; try discriminate.\n destruct f1; inv EQ0; simpl in A; inv A; auto.\n- (* pointer *)\n unfold inj in H.\n assert (X: data = Init_addrof b1 ofs1 /\\ chunk = Mptr).\n { remember Archi.ptr64 as ptr64.\n destruct ty; inversion EQ0.\n - destruct i; monadInv H2. unfold Mptr. rewrite <- Heqptr64. inv A; auto.\n - monadInv H2. unfold Mptr. rewrite <- Heqptr64. inv A; auto.\n - inv A; auto.\n }\n destruct X; subst. destruct (Genv.find_symbol ge b1); inv H.\n rewrite Ptrofs.add_zero in H0. auto.\n- (* undef *)\n discriminate.\nQed.\n\n(* Hypothesis ce_consistent: composite_env_consistent ge. *)\n\n(** A semantics for general initializers *)\n\nDefinition dummy_function := mkfunction Tvoid cc_default nil nil Sskip.\n\nFixpoint initialized_fields_of_struct (ms: members) (pos: Z) : res (list (Z * bitfield * type)) :=\n match ms with\n | nil =>\n OK nil\n | m :: ms' =>\n let pos' := next_field ge.(genv_cenv) pos m in\n if member_not_initialized m\n then initialized_fields_of_struct ms' pos'\n else\n do ofs_bf <- layout_field ge.(genv_cenv) pos m;\n do l <- initialized_fields_of_struct ms' pos';\n OK ((ofs_bf, type_member m) :: l)\n end.\n\nInductive exec_init: mem -> block -> Z -> bitfield -> type -> initializer -> mem -> Prop :=\n | exec_init_single_: forall m b ofs bf ty a v1 ty1 m' v m'',\n star step ge (ExprState dummy_function a Kstop empty_env m)\n E0 (ExprState dummy_function (Eval v1 ty1) Kstop empty_env m') ->\n sem_cast v1 ty1 ty m' = Some v ->\n exec_assign m' b ofs bf ty v m'' ->\n exec_init m b ofs bf ty (Init_single a) m''\n | exec_init_array_: forall m b ofs ty sz a il m',\n exec_init_array m b ofs ty sz il m' ->\n exec_init m b ofs Full (Tarray ty sz a) (Init_array il) m'\n | exec_init_struct_: forall m b ofs id a il co flds m',\n ge.(genv_cenv)!id = Some co -> co_su co = Struct ->\n initialized_fields_of_struct (co_members co) 0 = OK flds ->\n exec_init_struct m b ofs flds il m' ->\n exec_init m b ofs Full (Tstruct id a) (Init_struct il) m'\n | exec_init_union_: forall m b ofs id a f i co ty pos bf m',\n ge.(genv_cenv)!id = Some co -> co_su co = Union ->\n field_type f (co_members co) = OK ty ->\n union_field_offset ge f (co_members co) = OK (pos, bf) ->\n exec_init m b (ofs + pos) bf ty i m' ->\n exec_init m b ofs Full (Tunion id a) (Init_union f i) m'\n\nwith exec_init_array: mem -> block -> Z -> type -> Z -> initializer_list -> mem -> Prop :=\n | exec_init_array_nil: forall m b ofs ty sz,\n sz >= 0 ->\n exec_init_array m b ofs ty sz Init_nil m\n | exec_init_array_cons: forall m b ofs ty sz i1 il m' m'',\n exec_init m b ofs Full ty i1 m' ->\n exec_init_array m' b (ofs + sizeof ge ty) ty (sz - 1) il m'' ->\n exec_init_array m b ofs ty sz (Init_cons i1 il) m''\n\nwith exec_init_struct: mem -> block -> Z -> list (Z * bitfield * type) -> initializer_list -> mem -> Prop :=\n | exec_init_struct_nil: forall m b ofs,\n exec_init_struct m b ofs nil Init_nil m\n | exec_init_struct_cons: forall m b ofs pos bf ty l i1 il m' m'',\n exec_init m b (ofs + pos) bf ty i1 m' ->\n exec_init_struct m' b ofs l il m'' ->\n exec_init_struct m b ofs ((pos, bf, ty) :: l) (Init_cons i1 il) m''.\n\nScheme exec_init_ind3 := Minimality for exec_init Sort Prop\n with exec_init_array_ind3 := Minimality for exec_init_array Sort Prop\n with exec_init_struct_ind3 := Minimality for exec_init_struct Sort Prop.\nCombined Scheme exec_init_scheme from exec_init_ind3, exec_init_array_ind3, exec_init_struct_ind3.\n\nRemark exec_init_array_length:\n forall m b ofs ty sz il m',\n exec_init_array m b ofs ty sz il m' -> sz >= 0.\nProof.\n induction 1; lia.\nQed.\n\nLemma transl_init_rec_sound:\n (forall m b ofs bf ty i m',\n exec_init m b ofs bf ty i m' ->\n forall s s',\n match_state s m b ->\n match bf with\n | Full => transl_init_rec ge s ty i ofs\n | Bits sz sg p w => transl_init_bitfield ge s ty sz p w i ofs\n end = OK s' ->\n match_state s' m' b)\n/\\ (forall m b ofs ty sz il m',\n exec_init_array m b ofs ty sz il m' ->\n forall s s',\n match_state s m b ->\n transl_init_array ge s ty il ofs = OK s' ->\n match_state s' m' b)\n/\\ (forall m b ofs flds il m',\n exec_init_struct m b ofs flds il m' ->\n forall s s' ms pos,\n match_state s m b ->\n initialized_fields_of_struct ms pos = OK flds ->\n transl_init_struct ge s ms il ofs pos = OK s' ->\n match_state s' m' b).\nProof.\n apply exec_init_scheme.\n- (* single *)\n intros until m''; intros STEP CAST ASG s s' MS TR. destruct bf; monadInv TR.\n + (* full *)\n exploit transl_init_single_sound; eauto. intros [P Q].\n eapply store_data_correct; eauto. \n + (* bitfield *)\n destruct x; monadInv EQ0. monadInv EQ.\n exploit constval_steps; eauto. intros [A [B C]]. subst m' ty1.\n exploit sem_cast_match; eauto. intros D.\n inv ASG. inv D.\n set (f := first_bit sz pos width) in *.\n assert (E: Vint c = Vint x) by (eapply load_int_correct; eauto).\n inv E.\n eapply store_int_correct; eauto.\n- (* array *)\n intros. monadInv H2. eauto.\n- (* struct *)\n intros. monadInv H5. unfold lookup_composite in EQ. rewrite H in EQ. inv EQ.\n rewrite H0 in EQ0. eauto.\n- (* union *)\n intros. monadInv H6. unfold lookup_composite in EQ. rewrite H in EQ. inv EQ. rewrite H0 in EQ0.\n rewrite H1, H2 in EQ0. simpl in EQ0. eauto.\n- (* array nil *)\n intros. monadInv H1. auto.\n- (* array cons *)\n intros. monadInv H4. eauto.\n- (* struct nil *)\n intros. monadInv H1. auto.\n- (* struct cons *)\n intros. simpl in H5. revert H4 H5. generalize pos0. induction ms as [ | m1 ms]. discriminate.\n simpl. destruct (member_not_initialized m1).\n intros; eapply IHms; eauto.\n clear IHms. intros. monadInv H5. rewrite EQ in H4. monadInv H4. inv EQ0.\n eauto.\nQed.\n\nEnd SOUNDNESS.\n\nTheorem transl_init_sound:\n forall p m b ty i m1 data,\n let sz := sizeof (prog_comp_env p) ty in\n Mem.range_perm m b 0 sz Cur Writable ->\n reads_as_zeros m b 0 sz ->\n exec_init (globalenv p) m b 0 Full ty i m1 ->\n transl_init (prog_comp_env p) ty i = OK data ->\n exists m2,\n Genv.store_init_data_list (globalenv p) m b 0 data = Some m2\n /\\ Mem.loadbytes m2 b 0 (init_data_list_size data) = Mem.loadbytes m1 b 0 sz.\nProof.\n intros.\n set (ge := globalenv p) in *.\n change (prog_comp_env p) with (genv_cenv ge) in *.\n unfold transl_init in H2; monadInv H2.\n fold sz in EQ. set (s0 := initial_state sz) in *.\n assert (match_state ge s0 m b).\n { constructor; simpl.\n - generalize (sizeof_pos ge ty). fold sz. lia.\n - apply Mem.loadbytes_empty. lia.\n - auto.\n - assumption.\n }\n assert (match_state ge x m1 b).\n { eapply (proj1 (transl_init_rec_sound ge)); eauto. }\n assert (total_size x = sz).\n { change sz with s0.(total_size). eapply total_size_transl_init_rec; eauto. }\n rewrite <- H4. eapply init_data_list_of_state_correct; eauto; rewrite H4; auto.\nQed.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/cfrontend/Initializersproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.13971413797326923}} {"text": "Require Import ucos_include.\nRequire Import join_lib_aux.\n(*Require Import ucert.\nRequire Import OSTimeDlyPure.\nRequire Import OSQPostPure.\nRequire Import laby.\nRequire Import mathlib.\n*)\n\nRequire Import os_ucos_h.\nImport DeprecatedTactic.\nOpen Scope code_scope.\nOpen Scope Z_scope.\nOpen Scope int_scope.\n\nLemma p_local_ostcblist_eq_ct:\n forall s P ct v'36 v'37 v'38 v'39 v'40 v'41 ct' v'44 v'48 lg,\n s|= p_local OSLInv ct lg **\n AOSTCBList' v'36 v'37 v'38 (v'39 :: v'40) v'41 ct' v'44 v'48 ** P ->\n ct' = ct.\nProof.\n intros.\n unfold p_local in H.\n unfold AOSTCBList' in H.\n unfold CurTid in H.\n sep normal in H.\n sep destruct H.\n sep lift 3%nat in H.\n apply disj_split in H.\n destruct H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H0;subst.\n sep lifts (3::6::nil)%nat in H.\n eapply read_only_merge_vptr in H.\n destruct H;auto.\n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H0;subst.\n sep lifts (2::6::nil)%nat in H.\n eapply read_only_merge_vptr in H.\n destruct H;auto.\nQed.\n\nDefinition highest_rdy prio rtbl :=\n (Int.unsigned prio < 64) /\\\n prio_in_tbl prio rtbl /\\\n forall prio', 0 <= Int.unsigned prio' < 64-> Int.eq prio prio' = false -> prio_in_tbl prio' rtbl -> Int.ltu prio prio' = true.\n\nLemma get_highest_rdy:\n forall rgrp rtbl x i0 y,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl -> \n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n RL_Tbl_Grp_P rtbl (Vint32 rgrp) ->\n (Int.unsigned rgrp <= 255) ->\n nth_val' (Z.to_nat (Int.unsigned rgrp)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n highest_rdy ((x<<ᵢ$ 3) +ᵢ y) rtbl.\nProof.\n introv Hpro Harr Hlen Hrl Hrg Hnth1 Hnth2 Hnth3.\n lets Has : unmap_inrtbl' Hrg Hnth1 Hnth2 Hnth3; eauto.\n destruct Has.\n unfolds.\n splits; auto.\n introv Hproo Heq Hpri.\n lets Hneq : prio_in_tbl_rgrp_neq_zero Hpro Hrl; try omega; eauto.\n unfold OS_IDLE_PRIO.\n unfold OS_LOWEST_PRIO.\n clear -x.\n int auto.\n unfold Int.ltu.\n rewrite zlt_true; auto.\n clear Hpro.\n unfolds in H0.\n unfolds in Hpri.\n unfolds in Hrl.\n assert (((x<<ᵢ$ 3)+ᵢy)&ᵢ$ 7 = ((x<<ᵢ$ 3)+ᵢy)&ᵢ$ 7 ) by auto.\n assert (Int.shru((x<<ᵢ$ 3)+ᵢy) ($ 3) = Int.shru ((x<<ᵢ$ 3)+ᵢy) ($ 3)) by auto.\n assert ( prio'&ᵢ$ 7 = prio'&ᵢ$ 7) by auto.\n assert (Int.shru prio' ($ 3) = Int.shru prio' ($ 3)) by auto.\n lets Hrs : math_unmap_range Hrg Hnth1.\n lets Hz : nth_val'_imply_nth_val Hnth2.\n simpl in Hlen.\n unfold Pos.to_nat in Hlen; simpl in Hlen.\n rewrite Hlen.\n omega.\n lets Hex : n07_arr_len_ex Hrs Harr Hlen.\n destruct Hex as (xv & Hnth & Hrsa).\n rewrite Hz in Hnth.\n inverts Hnth.\n lets Hbs : math_unmap_range Hrsa Hnth3.\n assert ((Int.unsigned y) < 8).\n eapply nat_8_range_conver; eauto.\n lets Heqb : math_shrl_3_eq H5 Hrs.\n rewrite <- Heqb in Hz.\n lets Hasb : H0 H1 H2 Hz.\n lets Hpra : math_64_le_8 Hproo.\n assert ((0 <= Z.to_nat (Int.unsigned (Int.shru prio' ($ 3))) < 8)%nat).\n eapply nat_8_range_conver; eauto.\n lets Hex : n07_arr_len_ex H6 Harr Hlen.\n destruct Hex as (vy & Hnty & Hnht1).\n lets Hpy : Hpri H3 H4 Hnty.\n assert ( Vint32 rgrp = Vint32 rgrp) by auto.\n lets Hr1 : Hrl Hz H7.\n rewrite Heqb. auto.\n lets Hr2 : Hrl H6 Hnty H7. \n destruct Hr1 as (Hr11 & Hr12).\n clear Hr11.\n destruct Hr2 as (Hr21 & Hr22).\n clear Hr21.\n rewrite nat_elim in *;try rewrite Heqb; try eapply nat_8_range_conver; eauto.\n lets Hl1 : math_and_shf_ltu_true H Hasb.\n apply Hr12 in Hl1.\n lets Hl2 : math_and_shf_ltu_true Hpy. omega.\n apply Hr22 in Hl2.\n clear Hr12 Hr22.\n clear H7.\n lets Heqa : math_8range_eqy Hrs H5;eauto.\n rewrite Heqa in *.\n rewrite Heqb in *.\n pose (Int.eq_spec ((x<<ᵢ$ 3)+ᵢy) prio') as Hnq.\n rewrite Heq in Hnq.\n assert (Int.unsigned ((x<<ᵢ$ 3)+ᵢy) <= Int.unsigned prio').\n assert (xv= $ 0 \\/ xv <> $0) by tauto.\n destruct H7.\n subst xv.\n rewrite Int.and_commut in Hasb.\n rewrite Int.and_zero in Hasb.\n assert ($ 1<<ᵢy <> Int.zero).\n clear - H5.\n mauto.\n tryfalse.\n lets Hrszz : math_highest_prio_select Hnth3 Hnth1 Hz Hnty;eauto; try omega.\n eapply nat_8_range_conver; eauto.\n rewrite Int.and_commut .\n assert (Int.unsigned ($ 7&ᵢprio') <= Int.unsigned ($ 7)).\n apply Int.and_le.\n rewrite Int.unsigned_repr in H8.\n omega.\n clear- x.\n int auto.\n clear -Hnq H7.\n assert (Int.unsigned ((x<<ᵢ$ 3)+ᵢy) < Int.unsigned prio' \\/\n Int.unsigned ((x<<ᵢ$ 3)+ᵢy) = Int.unsigned prio') by omega.\n destruct H; auto.\n clear H7.\n false.\n apply Hnq.\n apply unsigned_inj; auto.\nQed.\n\n\nLemma nth_val'2nth_val':\n forall (rtbl : list val) (n : nat) x,\n nth_val' n rtbl = Vptr x -> nth_val n rtbl = Some (Vptr x).\nProof.\n inductions rtbl;intros;simpl in *.\n destruct n;simpl in H;tryfalse.\n destruct n.\n simpl in H.\n subst;auto.\n simpl in H.\n eapply IHrtbl;eauto.\nQed.\n\nLemma highest_rdy_eq':\n forall prio rtbl ptbl tcbls ct l1 l2 p1 hcurt P s t vhold,\n t <> vhold ->\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n highest_rdy prio rtbl ->\n nth_val' (Z.to_nat (Int.unsigned prio)) ptbl = Vptr t ->\n R_PrioTbl_P ptbl tcbls vhold -> \n s |= AOSTCBList p1 (Vptr ct) l1 l2 rtbl hcurt tcbls ** HTCBList tcbls ** (EX tp, GV OSTCBCur @ (Tptr tp) |-r-> Vptr ct) ** P ->\n s |= GV OSTCBCur @ os_ucos_h.OS_TCB ∗ |-> Vptr ct ** AHprio GetHPrio t ** Atrue.\nProof.\n introv Hnvhold Hpr Har Hlen Hhi Hnth Hr Hs.\n unfolds in Hhi.\n destruct Hhi as (Hpro & Hprt & Hfora).\n unfolds in Hr.\n assert (0<=Int.unsigned prio < 64).\n split; auto.\n clear -s.\n int auto.\n\n lets Hz : nth_val'2nth_val' Hnth.\n destruct Hr as (Hr1 & Hr2).\n lets Hsa : Hr1 H Hz.\n destruct Hsa as (st & m & Hget);auto.\n unfold AOSTCBList in Hs.\n sep normal in Hs.\n sep destruct Hs.\n sep split in Hs.\n simpljoin1.\n sep lifts (4::1::nil)%nat in Hs.\n eapply read_only_merge_vptr in Hs.\n destruct Hs.\n sep cancel 1%nat 1%nat.\n inverts H4.\n assert (s |= HTCBList tcbls ** Atrue).\n sep auto.\n sep cancel 2%nat 2%nat.\n simpl in H4.\n mytac.\n simpl.\n split; auto.\n destruct H10 as [[]].\n simpl in H4.\n simpl.\n unfolds.\n exists tcbls prio st m.\n split; auto.\n subst o.\n rewrite get_sig.\n remember (dec abtcblsid abtcblsid) as Hb.\n destruct Hb; auto.\n destruct n.\n auto.\n split; auto.\n lets Hab : TCBList_get_TCBNode_P Hget H1 H2 H3.\n destruct Hab as (vll & Htnode).\n unfolds in Htnode.\n destruct Htnode as (Hv1 & Hv2 & Hrl & Hrt).\n unfolds in Hrt.\n destruct Hrt as (Hrr1 & Hrr2 & Hrr3 & Hrr4).\n unfolds in Hrr1.\n unfolds in Hrr3.\n destruct Hrr3 as (Hwr1 & Hwr2 & Hwr3).\n unfolds in Hwr1.\n assert (RdyTCBblk vll rtbl prio ).\n unfolds.\n splits; auto.\n apply Hrr1 in H9.\n destruct H9 as (Hvos & Hvtc & Hexx).\n destruct Hexx.\n inverts H9.\n splits; auto.\n unfolds; auto.\n intros.\n unfolds in H12.\n destruct st'; tryfalse.\n lets Hasds : TCBList_get_TCBNode_P H10 H1 H2 H3.\n destruct Hasds as (vvll & Hcp).\n unfolds in Hcp.\n destruct Hcp as (Hcp1 & Hcp2 & Hcpr & Hcprt).\n unfolds in Hcprt.\n destruct Hcprt as (_ & Htas & _).\n unfolds in Htas.\n assert ( (prio', rdy, msg') = (prio', rdy, msg')) by auto.\n apply Htas in H13.\n destruct H13.\n unfolds in H13.\n destruct H13.\n unfolds in Hcpr.\n mytac.\n rewrite Hcp2 in H16.\n inverts H16.\n eapply Hfora; eauto.\n unfolds in H7.\n apply Int.eq_false.\n\n lets Hress : H7 H9 H10 Hget.\n auto.\nQed.\n\n\n\nLemma highest_rdy_eq:\n forall p1 l1 l2 rtbl hcurt tcbls P i x i0 y ptbl s t ct vhold,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl -> \n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold->\n (Int.unsigned i <= 255) ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n nth_val' (Z.to_nat (Int.unsigned ((x<<ᵢ$ 3) +ᵢ y))) ptbl = Vptr t -> \n R_PrioTbl_P ptbl tcbls vhold ->\n s |= AOSTCBList p1 (Vptr ct) l1 l2 rtbl hcurt tcbls ** HTCBList tcbls ** (EX tp,GV OSTCBCur @ tp ∗ |-r-> Vptr ct) ** P ->\n s |= GV OSTCBCur @ os_ucos_h.OS_TCB ∗ |-> Vptr ct ** AHprio GetHPrio t ** Atrue.\nProof.\n intros.\n eapply highest_rdy_eq'; eauto.\n unfolds in H3.\n lets Hx:unmap_inrtbl' H H0 H1 H2.\n lets Hx':Hx H4 H5 H6 H7.\n mytac.\n apply H3 in H12.\n mytac;auto.\n\n apply nth_val_nth_val'_some_eq in H12.\n rewrite H12 in H8;inverts H8.\n auto.\n split;auto.\n clear.\n lets Hx:Int.unsigned_range ((x<<ᵢ$ 3)+ᵢy).\n destruct Hx;auto.\n eapply get_highest_rdy; eauto.\nQed.\n\nLemma hoare_pure_gen : forall P1 P2 (p:Prop) S Q a b c d e f tid,\n (forall s, s |= P1 -> p) ->\n {|a,b,c,d,e,f|} |-tid {{P1 ** P2 ** [|p|]}} S {{Q}} ->\n {|a,b,c,d,e,f|} |-tid {{P1 ** P2}} S {{Q}}.\nProof.\n intros.\n apply backward_rule1 with (p:=(P1 ** P2 ** [|p|])); auto.\n intros.\n sep auto.\n destruct_s s.\n simpl in H1; simpljoin1.\n apply (H (e0, e1, x, i, (i0, i1, c0), x2, a0)); auto.\nQed.\n\nLemma hoare_pure_gen' : forall P (p:Prop) S Q a b c d e f tid,\n (forall s, s |= P -> p) ->\n {|a,b,c,d,e,f|} |-tid {{P ** [|p|]}} S {{Q}} ->\n {|a,b,c,d,e,f|} |-tid {{P}} S {{Q}}.\nProof.\n intros.\n apply backward_rule1 with (p:=(P ** [|p|])); auto.\n intros.\n sep auto.\n eapply H; eauto.\nQed.\n\nLemma sc_isched_step:\n forall P v'0 t ct,\n can_change_aop P ->\n P ==> GV OSTCBCur @ (Tptr OS_TCB) |-> Vptr ct ** AHprio GetHPrio t ** Atrue //\\\\ HCurTCB ct ** [| ct <> t |] ** Atrue ->\n GetHPrio ⊢ <|| (ASSUME sc;;sched);; v'0 ||> ** P ⇒\n <|| (spec_done None;;sched);; v'0 ||> ** P.\nProof.\n intros.\n apply absinfer_seq;auto.\n apply absinfer_seq;auto.\n apply absinfer_assume;auto.\n intros.\n apply H0 in H1.\n unfolds.\n destruct H1.\n exists ct t.\n destruct_s s.\n simpl in H1.\n simpl in H2.\n \n\n mytac;simpl;auto.\n eapply join_sig_get;eauto.\n clear -H24 H23.\n unfold GetHPrio in *.\n mytac.\n do 4 eexists;splits;eauto.\n eapply join_get_l;eauto.\nQed.\n\n\nLemma nsc_isched_step:\n forall P v'0 t ct,\n can_change_aop P ->\n P ==> GV OSTCBCur @ (Tptr OS_TCB) |-> Vptr ct ** AHprio GetHPrio t ** Atrue //\\\\ HCurTCB ct ** [| ct =t |] ** Atrue ->\n GetHPrio ⊢ <|| ASSUME nsc;; v'0 ||> ** P ⇒\n <|| spec_done None;;v'0 ||> ** P.\nProof.\n intros.\n apply absinfer_seq;auto.\n apply absinfer_assume;auto.\n intros.\n apply H0 in H1.\n unfolds.\n destruct H1.\n exists ct t.\n destruct_s s.\n simpl in H1.\n simpl in H2.\n mytac;simpl;auto.\n eapply join_sig_get;eauto.\n clear -H24 H23.\n unfold GetHPrio in *.\n mytac.\n do 4 eexists;splits;eauto.\n eapply join_get_l;eauto.\nQed.\n\n\nLemma tcbjoinsig_set_sub_sub:\n forall t x tcbls tcbls' tls y tls',\n TcbMod.joinsig t x tcbls tcbls' ->\n TcbMod.set tls t y = tls' ->\n TcbMod.sub tcbls' tls ->\n TcbMod.sub tcbls tls'.\nProof.\n intros.\n unfolds; intros.\n unfold TcbMod.joinsig in H.\n unfold TcbMod.sub in H1.\n unfold TcbMod.lookup in *.\n pose proof H a.\n substs.\n rewrite H2 in H3.\n destruct (tidspec.beq t a) eqn : eq1.\n lets Hx: tidspec.beq_true_eq eq1; substs.\n rewrite TcbMod.set_a_get_a; auto.\n rewrite TcbMod.get_sig_some in H3; tryfalse.\n lets Hx: tidspec.beq_false_neq eq1.\n rewrite TcbMod.get_sig_none in H3; auto.\n destruct (TcbMod.get tcbls' a) eqn : eq2; tryfalse.\n apply H1 in eq2; substs.\n rewrite TcbMod.set_a_get_a'; auto.\nQed.\n\nLemma tickstep_eqdomtls:\n forall tls qls tls' qls' tls_sub,\n TcbMod.sub tls_sub tls ->\n tickstep' tls qls tls' qls' tls_sub->\n eqdomtls tls tls'.\nProof.\n intros.\n inductions H0.\n unfolds.\n intros.\n split;intros.\n unfolds;unfolds in H0.\n simpljoin1.\n eexists;eauto.\n unfolds in H0.\n unfolds;simpljoin1;eauto.\n assert (eqdomtls tls tls').\n subst tls'.\n eapply tls_get_set_indom;eauto.\n instantiate (1:=(p, st, msg0)).\n eapply TcbMod.get_sub_get;eauto.\n clear - H0.\n pose proof H0 t.\n rewrite TcbMod.get_sig_some in H.\n destruct (TcbMod.get tls_used' t); tryfalse.\n destruct (TcbMod.get tls_used t); tryfalse.\n subst; auto.\n lets Hx: tcbjoinsig_set_sub_sub H0 H2 H.\n apply IHtickstep' in Hx.\n clear -H4 Hx.\n unfold eqdomtls in *.\n intros.\n lets Ha: H4 tid.\n lets Hb: Hx tid.\n clear H4 Hx.\n split;\n destruct Ha,Hb.\n intros.\n apply H in H3.\n apply H1 in H3;auto.\n intros.\n apply H2 in H3.\n apply H0 in H3.\n auto.\nQed.\n\n(*\nLemma absimp_timetick:\n forall P tls qls tls' qls' curtid tm s,\n can_change_aop P ->\n tickstep tls qls tls' qls' ->\n absinfer ( <|| timetick_spec (|nil|);;s ||>\n ** HECBList qls ** HTCBList tls ** HTime tm ** HCurTCB curtid ** P)\n ( <|| END None;;s ||> ** \n HECBList qls'** HTCBList tls' ** HTime (Int.add tm Int.one) **\n HCurTCB curtid **P).\nProof.\n intros.\n apply absinfer_seq;pauto.\n infer_part1 0%nat.\n eexists; exgamma.\n splits.\n simpl_subst_gamma.\n eapply specstep_merge_emp; constructors.\n unfolds; mytac; try tri_exists_and_solver.\n assert (eqdomO \n (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls'))\n (OSAbstMod.set\n (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls')) ostmid (ostm (tm+ᵢInt.one)))).\n \n \n eapply abst_get_set_eqdom.\n absdata_solver.\n simpl;auto.\n assert (eqdomO (OSAbstMod.set O absecblsid (absecblist qls')) (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls'))).\n eapply abst_get_set_eqdom.\n absdata_solver.\n simpl.\n \n eapply tickstep_eqdomtls;eauto.\n apply TcbMod.sub_refl.\n assert (eqdomO O (OSAbstMod.set O absecblsid (absecblist qls'))).\n eapply abst_get_set_eqdom.\n absdata_solver.\n simpl;auto.\n eapply ruleLib.eqdomO_trans;eauto.\n eapply ruleLib.eqdomO_trans;eauto.\n assert (tidsame (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls'))\n (OSAbstMod.set\n (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls')) ostmid (ostm (tm+ᵢInt.one)))).\n tidsame_solver.\n assert (tidsame O\n (OSAbstMod.set (OSAbstMod.set O absecblsid (absecblist qls'))\n abtcblsid (abstcblist tls'))).\n tidsame_solver.\n eapply tidsame_trans;eauto.\n eapply OSAbstMod.disj_emp_r;eauto.\n repeat simpl_absdata_sep; sep auto.\nQed.\n\n\nLemma absimp_toy:\n forall P tls qls curtid tm s,\n can_change_aop P ->\n absinfer ( <||toyint_spec (|nil|) ;; s||>\n ** HECBList qls ** HTCBList tls ** HTime tm ** HCurTCB curtid ** P)\n ( <||END None;;s ||> ** \n HECBList qls** HTCBList tls ** HTime tm **\n HCurTCB curtid **P).\nProof.\n intros.\n apply absinfer_seq;pauto.\n infer_solver 0%nat.\nQed.\n *)\n\nLemma prio_neq_tid_neq:\n forall p1 l1 l2 rtbl hcurt tcbls P i x i0 y ptbl s t ct vhold\n next pre eptr msg dly st p_ct tcbx tcby tcbbitx tcbbity,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl -> \n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold->\n (Int.unsigned i <= 255) ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n nth_val' (Z.to_nat (Int.unsigned ((x<<ᵢ$ 3) +ᵢ y))) ptbl = Vptr t -> \n R_PrioTbl_P ptbl tcbls vhold ->\n Int.eq ((x<<ᵢ$ 3)+ᵢy) p_ct = false ->\n s |= AOSTCBList p1 (Vptr ct) l1\n ((next\n :: pre\n :: eptr\n :: msg\n :: Vint32 dly\n :: Vint32 st\n :: Vint32 p_ct\n :: Vint32 tcbx\n :: Vint32 tcby\n :: Vint32 tcbbitx :: Vint32 tcbbity :: nil)::l2) rtbl hcurt tcbls ** HTCBList tcbls ** P ->\n ct <> t.\nProof.\n intros.\n intro.\n subst t.\n unfolds in H9.\n destruct H9 as (Ha&Hb&Hc). \n unfolds in H3.\n lets Has : unmap_inrtbl' H H0 H5 H6 H7; eauto.\n destruct Has.\n assert (0<= Int.unsigned ((x<<ᵢ$ 3)+ᵢy)).\n lets Hran: Int.unsigned_range ((x<<ᵢ$ 3)+ᵢy).\n destruct Hran;auto.\n lets Hx: H3 H12.\n split;auto.\n destruct Hx.\n destruct H14.\n lets Hx: nth_val'2nth_val' H8.\n rewrite H14 in Hx.\n inverts Hx.\n lets Hx: Ha H14 H15.\n split;auto.\n destruct Hx.\n destruct H16.\n unfold AOSTCBList in H11.\n sep normal in H11.\n sep destruct H11.\n sep split in H11.\n simpl in H20.\n simpljoin1.\n inverts H20.\n inverts H25.\n unfolds in H23.\n destruct x9.\n destruct p.\n simpljoin1.\n unfolds in H23.\n simpl in H23.\n inverts H23.\n lets Hx:tcbjoin_get_a_my H22.\n lets Hy:TcbMod.join_get_get_r H18 Hx.\n unfold get in H16; simpl in H16.\n rewrite H16 in Hy.\n inverts Hy.\n clear -H10.\n int auto.\nQed.\n\nLemma prio_eq_tid_eq:\n forall p1 l1 l2 rtbl hcurt tcbls P i x i0 y ptbl s t ct vhold\n next pre eptr msg dly st p_ct tcbx tcby tcbbitx tcbbity,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl -> \n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold->\n (Int.unsigned i <= 255) ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n nth_val' (Z.to_nat (Int.unsigned ((x<<ᵢ$ 3) +ᵢ y))) ptbl = Vptr t -> \n R_PrioTbl_P ptbl tcbls vhold ->\n Int.eq ((x<<ᵢ$ 3)+ᵢy) p_ct = true ->\n s |= AOSTCBList p1 (Vptr ct) l1\n ((next\n :: pre\n :: eptr\n :: msg\n :: Vint32 dly\n :: Vint32 st\n :: Vint32 p_ct\n :: Vint32 tcbx\n :: Vint32 tcby\n :: Vint32 tcbbitx :: Vint32 tcbbity :: nil)::l2) rtbl hcurt tcbls ** HTCBList tcbls ** P ->\n ct = t.\nProof.\n intros.\n assert (((x<<ᵢ$ 3)+ᵢy) = p_ct).\n clear -H10.\n lets Hx:Int.eq_spec ((x<<ᵢ$ 3)+ᵢy) p_ct.\n rewrite H10 in Hx;auto.\n subst p_ct.\n unfolds in H9.\n destruct H9 as (Ha&Hb&Hc). \n unfolds in H3.\n lets Has : unmap_inrtbl' H H0 H5 H6 H7; eauto.\n destruct Has.\n assert (0<= Int.unsigned ((x<<ᵢ$ 3)+ᵢy)).\n lets Hran: Int.unsigned_range ((x<<ᵢ$ 3)+ᵢy).\n destruct Hran;auto.\n lets Hx: H3 H12.\n split;auto.\n destruct Hx.\n destruct H14.\n lets Hx:nth_val'2nth_val' H8.\n rewrite H14 in Hx.\n inverts Hx.\n lets Hx: Ha H14 H15.\n split;auto.\n destruct Hx.\n destruct H16.\n unfold AOSTCBList in H11.\n sep normal in H11.\n sep destruct H11.\n sep split in H11.\n simpl in H20.\n simpljoin1.\n inverts H20.\n inverts H25.\n unfolds in H23.\n destruct x9.\n destruct p.\n simpljoin1.\n unfolds in H23.\n simpl in H23.\n inverts H23.\n lets Hx:tcbjoin_get_a_my H22.\n lets Hy:TcbMod.join_get_get_r H18 Hx.\n lets Hm: Hb H16.\n lets Hn: Hb Hy.\n simpljoin1.\n rewrite H28 in H23;inverts H23;auto.\nQed.\n\n\nLemma backward_1 :\n forall P P' Q S spec sd linv I r ri s tid,\n P ==> P' ->\n {|spec , sd, I, linv, r, ri|}|-tid {{P'**Q}}s {{S}} ->\n {|spec , sd, I, linv, r, ri|}|-tid {{P**Q}}s {{S}}. \nProof.\n intros.\n eapply backward_rule1 with (p:=P'**Q).\n intros.\n sep auto.\n auto.\nQed.\n\nLemma gvar_off_zero:\n forall s P l x t,\n s |= G&x @ t == l ** P ->\n exists b, l = (b,Int.zero).\nProof.\n intros.\n destruct_s s.\n destruct l.\n simpl in H;simpljoin1.\n eexists;eauto.\n rewrite <- Int.unsigned_zero in H1.\n apply unsigned_inj in H1.\n subst i2;eauto.\nQed.\n\nLemma dllseg_head_null_elim:\n forall s v'8 v'11 v'13 x y z P,\n s |= dllseg Vnull v'8 v'11 Vnull v'13 x y z ** P -> v'13= nil /\\ v'8 = v'11.\nProof.\n intros.\n unfold dllseg in *.\n destruct v'13.\n sep split in H.\n auto.\n sep split in H.\n tryfalse.\nQed.\n\n\nLemma dllseg_head_isptr' :\n forall l v1 v2 v3 v4 t n p P s, s |= dllseg v1 v2 v3 (Vptr v4) l t n p ** P -> isptr v1.\nProof.\n inductions l. \n intros.\n simpl in H.\n simpljoin1 ; unfolds; simpl; auto.\n right;eexists;auto.\n intros.\n unfold dllseg in H.\n fold dllseg in H.\n sep destroy H.\n right.\n unfold node in H3.\n sep destroy H3.\n simpljoin1.\n eauto.\nQed.\n\nLemma xx:\n forall a b c a' b' c' l l',(logic_isr a\n :: logic_is b\n :: logic_val c::l) = ( logic_isr a'\n :: logic_is b'\n :: logic_val c' :: l')-> c=c'.\nProof.\n intros.\n inverts H;auto.\nQed.\n\n\nLemma xxx:forall P s v'9 v'10,getisr (gettaskst s) = isrupd v'9 0%nat false -> getis (gettaskst s) = 0%nat :: v'10 -> getie (gettaskst s) = false -> ( forall j : nat,\n (0 <= j < gettopis (OSTickISR :: v'10))%nat ->\n isrupd v'9 OSTickISR true j = false) -> s|=P ->s|= (isr_inv //\\\\ Aie false) ** P.\nProof.\n intros.\n destruct_s s.\n simpl.\n\n simpl in H,H0.\n exists empmem m m empabst o o.\n splits;simpljoin1.\n split.\n eexists;splits;simpljoin1.\n splits; eauto.\n unfolds; auto.\n\n exists 0%nat.\n splits;simpljoin1.\n simpl;auto.\n splits; auto.\n unfolds; auto.\n \n intros.\n omega.\n unfolds; auto.\n \n simpl in H1.\n splits; auto.\n unfolds; auto.\n auto.\nQed.\n\nLemma xxxx: forall s P v'10, getis (gettaskst s) = 0%nat :: v'10->\n s |= P ->\n s |= [|hd_error (0%nat :: v'10) = Some 0%nat|] **\n Ais (0%nat :: v'10) ** P.\nProof.\n intros.\n destruct_s s.\n simpl.\n exists empmem m m empabst o o.\n splits;simpljoin1.\n simpl; splits; auto.\n unfolds; auto.\n \n exists empmem m m empabst o o.\n splits; auto.\n apply map_join_comm.\n apply map_join_emp.\n apply map_join_comm.\n apply map_join_emp.\n\n simpl in H; splits; auto.\n unfolds; auto.\nQed.\n\nLemma xxxxx: forall s v'9 P, getisr (gettaskst s) = isrupd v'9 0%nat false -> s|=P ->s\n |= ([|isrupd v'9 0%nat false 0%nat = false|] //\\\\\n Aisr (isrupd v'9 0%nat false)) ** P.\n\nProof.\n intros.\n destruct_s s.\n simpl.\n exists empmem m m empabst o o.\n splits; simpljoin1.\n split.\n unfold isrupd.\n assert (beq_nat 0 0 =true) by auto.\n rewrite H1.\n unfold emposabst.\n auto.\n unfold emposabst; simpl in H;auto.\n auto.\nQed.\n\n\n\nLemma ostcbcur_tp_os_tcb:\n forall P s tp v,\n s |= OSInv ** GV OSTCBCur @ tp ∗ |-r-> Vptr v ** P -> s |= OSInv ** GV OSTCBCur @ OS_TCB ∗ |-r-> Vptr v ** P .\nProof.\n intros.\n unfold OSInv in H.\n unfold AOSTCBList' in H.\n sep normal in H.\n sep destruct H.\n sep lift 9%nat in H.\n apply disj_split in H.\n destruct H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n sep lifts (3::23::nil)%nat in H.\n destruct H0.\n subst x6.\n apply read_only_merge_vptr in H.\n destruct H.\n subst.\n sep cancel 1%nat 2%nat.\n unfold OSInv.\n sep normal.\n sep eexists.\n sep semiauto;eauto.\n unfold AOSTCBList'.\n sep lift 7%nat.\n apply disj_split.\n left.\n sep auto.\n eauto.\n eauto.\n auto.\n sep normal in H.\n sep destruct H.\n sep split in H.\n sep lifts (2::23::nil)%nat in H.\n destruct H0;subst.\n apply read_only_merge_vptr in H.\n destruct H.\n subst.\n sep cancel 1%nat 2%nat.\n unfold OSInv.\n sep normal.\n sep eexists.\n sep semiauto;eauto.\n unfold AOSTCBList'.\n sep lift 7%nat.\n apply disj_split.\n right.\n sep auto.\nQed.\n\n\n\n\nLemma task_del_noexists:\n forall v'9 v'7 v'13 ct v'21 v'10 v'11 P xx xxx, \n dllseg v'7 xx v'13 (Vptr ct) v'9 OS_TCB_flag V_OSTCBPrev V_OSTCBNext **\n dllseg (Vptr ct) v'13 v'21 Vnull (v'10 :: v'11) OS_TCB_flag V_OSTCBPrev\n V_OSTCBNext **\n dllsegflag v'7 xxx (v'9 ++ v'10 :: v'11) V_OSTCBNext ** LINV OSLInv ct (logic_val (V$ 0) :: nil) ** P ==> Afalse.\nProof.\n inductions v'9.\n intros.\n simpl dllseg in H.\n simpl dllsegflag in H.\n unfold LINV in H.\n unfold OSLInv in H.\n unfold node in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H3.\n subst.\n destruct H0.\n inverts H0.\n struct_type_vallist_match_elim.\n unfolds in H2;simpl in H2;unfolds in H4;simpl in H4;unfolds in H5;simpl in H5.\n inverts H3.\n inverts H2.\n inverts H5.\n inverts H6.\n inverts H4.\n unfold get_off_addr in H.\n simpl fst in H.\n sep lift 2%nat in H.\n apply flag_merege_false in H.\n tryfalse.\n\n intros.\n simpl dllseg at 1 in H.\n simpl dllsegflag in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n sep remember (2::4::5::6::7::nil)%nat in H.\n sep remember (6::nil)%nat in H.\n simpl in H.\n mytac.\n sep lifts (2::3::nil)%nat in H11.\n rewrite H1 in H2;inverts H2.\n eapply IHv'9 in H11.\n simpl in H11.\n tryfalse.\nQed.\n\n\nLtac unfolddef:=\n try\n (unfold code in *;unfold cont in *;unfold tid in *;\n unfold Maps.sub in *;unfold disjoint in *;unfold osabst in *).\n\nLemma os_core_common_map1 :\n forall (A B T : Type) (MC : PermMap A B T) tcbls t x x0 x3 x2,\n usePerm = false ->\n get tcbls t = Some x ->\n t <> x0 ->\n join (sig x0 x3) x2 tcbls ->\n get x2 t = Some x.\n hy.\nQed.\n\nLemma tcblist_get_TCBNode_P\n: forall (l: list vallist) (tcbls : TcbMod.map) (head : val) (rtbl : vallist)\n (t : tidspec.A) x ,\n get tcbls t = Some x ->\n TCBList_P head l rtbl tcbls ->\n exists vl, TCBNode_P vl rtbl x.\nProof.\n inductions l.\n intros.\n simpl in H0.\n subst.\n(* ** ac: SearchAbout (get _ _ = None). *)\n rewrite map_emp_get in H.\n tryfalse.\n intros.\n simpl in H0.\n mytac.\n assert (t = x0 \\/ t <> x0) by tauto.\n destruct H0;subst.\n exists a;auto.\n assert (x=x3).\n clear -H H2.\n assert (join (sig x0 x3) x2 tcbls).\n auto.\n clear H2.\n assert (get (sig x0 x3) x0 = Some x3).\n apply map_get_sig.\n eapply join_get_l in H0;eauto.\n unfolddef.\n unfolds in H0.\n simpl in H0.\n unfolds in H.\n simpl in H.\n rewrite H in H0;inverts H0.\n auto.\n subst x3;auto.\n eapply IHl with (tcbls:= x2);eauto.\n instantiate (1:= t).\n clear -H H2 H0.\n assert (join (sig x0 x3) x2 tcbls);auto.\n clear H2.\n\n eapply os_core_common_map1; ica.\nQed. \n\n\nLemma highest_rdy_eq_dead':\n forall prio rtbl ptbl tcbls ct l p1 P s t vhold tail,\n t <> vhold ->\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘OS_RDY_TBL_SIZE->\n highest_rdy prio rtbl ->\n nth_val' (Z.to_nat (Int.unsigned prio)) ptbl = Vptr t ->\n R_PrioTbl_P ptbl tcbls vhold -> \n s |= tcblist p1 Vnull tail Vnull l rtbl tcbls ** HTCBList tcbls ** GV OSTCBCur @ (Tptr OS_TCB) |-> Vptr ct ** P ->\n s |= GV OSTCBCur @ os_ucos_h.OS_TCB ∗ |-> Vptr ct ** AHprio GetHPrio t ** Atrue.\nProof.\n introv Hnvhold Hpr Har Hlen Hhi Hnth Hr Hs.\n unfolds in Hhi.\n destruct Hhi as (Hpro & Hprt & Hfora).\n unfolds in Hr.\n assert (0<=Int.unsigned prio < 64).\n split; auto.\n clear -s.\n int auto.\n\n lets Hz : nth_val'2nth_val' Hnth.\n destruct Hr as (Hr1 & Hr2).\n lets Hsa : Hr1 H Hz.\n destruct Hsa as (st & m & Hget);auto.\n unfold AOSTCBList in Hs.\n sep normal in Hs.\n sep destruct Hs.\n sep split in Hs.\n simpljoin1.\n sep cancel 3%nat 1%nat.\n assert (s |= HTCBList tcbls ** Atrue).\n sep auto.\n sep cancel 2%nat 2%nat.\n simpl in H3.\n mytac.\n simpl.\n split; auto.\n destruct H4 as [[]].\n simpl in H3.\n simpl.\n unfolds.\n exists tcbls prio st m.\n split; auto.\n subst o.\n rewrite get_sig.\n remember (dec abtcblsid abtcblsid) as Hb.\n destruct Hb; auto.\n destruct n.\n auto.\n split; auto.\n\n unfold tcblist in Hs.\n sep normal in Hs.\n sep split in Hs.\n lets Hab : tcblist_get_TCBNode_P Hget H4.\n destruct Hab as (vll & Htnode).\n unfolds in Htnode.\n destruct Htnode as (Hv1 & Hv2 & Hrl & Hrt).\n unfolds in Hrt.\n destruct Hrt as (Hrr1 & Hrr2 & Hrr3 & Hrr4).\n unfolds in Hrr1.\n unfolds in Hrr3.\n destruct Hrr3 as (Hwr1 & Hwr2 & Hwr3).\n unfolds in Hwr1.\n assert (RdyTCBblk vll rtbl prio ).\n unfolds.\n splits; auto.\n apply Hrr1 in H6.\n destruct H6 as (Hvos & Hvtc & Hexx).\n destruct Hexx.\n inverts H6.\n splits; auto.\n unfolds; auto.\n intros.\n unfolds in H8.\n destruct st'; tryfalse.\n lets Hasds : tcblist_get_TCBNode_P H7 H4.\n destruct Hasds as (vvll & Hcp).\n unfolds in Hcp.\n destruct Hcp as (Hcp1 & Hcp2 & Hcpr & Hcprt).\n unfolds in Hcprt.\n destruct Hcprt as (_ & Htas & _).\n unfolds in Htas.\n assert ( (prio', rdy, msg') = (prio', rdy, msg')) by auto.\n apply Htas in H9.\n destruct H9.\n unfolds in H9.\n destruct H9.\n unfolds in Hcpr.\n mytac.\n rewrite Hcp2 in H12.\n inverts H12.\n eapply Hfora; eauto.\n apply Int.eq_false.\n unfolds in H2.\n lets Hress : H2 H6 H7 Hget.\n auto.\nQed.\n\nLemma highest_rdy_eq_dead\n: forall (p1 : val) (l : list vallist) (rtbl : vallist)\n (tcbls : TcbMod.map) (P : asrt) \n (i x i0 y : int32) (ptbl : vallist) (s : RstateOP)\n (t ct vhold : addrval) tail,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘ OS_RDY_TBL_SIZE ->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold ->\n Int.unsigned i <= 255 ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n nth_val' (Z.to_nat (Int.unsigned ((x<<ᵢ$ 3) +ᵢ y))) ptbl = Vptr t ->\n R_PrioTbl_P ptbl tcbls vhold ->\n s\n |= tcblist p1 Vnull tail Vnull l rtbl tcbls **\n HTCBList tcbls ** GV OSTCBCur @ OS_TCB ∗ |-> Vptr ct ** P ->\n s |= GV OSTCBCur @ OS_TCB ∗ |-> Vptr ct ** AHprio GetHPrio t ** Atrue.\nProof.\n intros.\n eapply highest_rdy_eq_dead'; eauto.\n unfolds in H3.\n lets Hx:unmap_inrtbl' H H0 H1 H2.\n lets Hx':Hx H4 H5 H6 H7.\n mytac.\n apply H3 in H12.\n mytac;auto.\n apply nth_val_nth_val'_some_eq in H12.\n rewrite H12 in H8;inverts H8.\n auto.\n split;auto.\n clear.\n lets Hx:Int.unsigned_range ((x<<ᵢ$ 3)+ᵢy).\n destruct Hx;auto.\n eapply get_highest_rdy; eauto.\nQed.\n\nLemma highest_ct_dead_neq\n: forall (p1 : val) (l : list vallist) (rtbl : vallist)\n (tcbls : TcbMod.map) (P : asrt) \n (i x i0 y : int32) (ptbl : vallist) (s : RstateOP)\n (t ct vhold : addrval) tail,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘ OS_RDY_TBL_SIZE ->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold ->\n Int.unsigned i <= 255 ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n nth_val' (Z.to_nat (Int.unsigned ((x<<ᵢ$ 3) +ᵢ y))) ptbl = Vptr t ->\n R_PrioTbl_P ptbl tcbls vhold ->\n s\n |= tcblist p1 Vnull tail Vnull l rtbl tcbls ** TCB_Not_In (Vptr ct) p1 l **\n HTCBList tcbls ** GV OSTCBCur @ OS_TCB ∗ |-> Vptr ct ** P ->\n ct <> t.\nProof.\n intros.\n intro.\n subst t.\n unfold TCB_Not_In in H10.\n sep split in H10.\n mytac.\n inverts H12.\n destruct H11.\n assert (highest_rdy ((x<<ᵢ$ 3) +ᵢ y) rtbl).\n eapply get_highest_rdy;eauto.\n unfolds in H11.\n unfolds in H3.\n mytac.\n unfold tcblist in *.\n sep split in H10.\n clear H10.\n unfolds in H9.\n mytac.\n lets Hx:H3 H12.\n split;auto.\n remember ((x<<ᵢ$ 3) +ᵢ y) as X.\n clear HeqX.\n int auto.\n mytac.\n lets Hx:H9 H16 H17.\n split;auto.\n remember ((x<<ᵢ$ 3) +ᵢ y) as X.\n clear HeqX.\n int auto.\n mytac.\n apply nth_val'_imp_nth_val_vptr in H8.\n rewrite H8 in H16;inverts H16.\n clear -H14 H18.\n gen p1 tcbls.\n inductions l;intros.\n\n simpl in H14.\n subst.\n rewrite map_emp_get in H18.\n tryfalse.\n simpl in H14.\n mytac.\n destruct x1.\n simpl.\n remember (beq_pos x0 b && Int.eq Int.zero i) as X.\n destruct X.\n auto.\n rewrite H0.\n eapply IHl;eauto.\n eapply join_sig_get_neq;eauto.\n Lemma addr_eq_false_neq:\n forall x a y b,\n false = beq_pos x a && Int.eq y b ->\n (x,y)<>(a,b).\n Proof.\n intros.\n intro.\n inverts H0.\n rewrite beq_pos_Pos_eqb_eq in H.\n assert ((a =? a)%positive = true).\n apply Pos.eqb_eq;auto.\n assert (Int.eq b b =true).\n clear;int auto.\n rewrite H0,H1 in H.\n simpl in H;tryfalse.\n Qed.\n eapply addr_eq_false_neq;eauto.\nQed.\n\n\n\nLemma dead_not_ready:\n forall (rtbl : vallist)\n (tcbls : TcbMod.map)\n (i x i0 y : int32) (ptbl : vallist) \n x0,\n prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘ OS_RDY_TBL_SIZE ->\n RL_Tbl_Grp_P rtbl (Vint32 i) ->\n Int.unsigned i <= 255 ->\n nth_val' (Z.to_nat (Int.unsigned i)) OSUnMapVallist = Vint32 x ->\n nth_val' (Z.to_nat (Int.unsigned x)) rtbl = Vint32 i0 ->\n nth_val' (Z.to_nat (Int.unsigned i0)) OSUnMapVallist = Vint32 y ->\n prio_not_in_tbl x0 rtbl ->\n Int.eq ((x<<ᵢ$ 3) +ᵢ y) x0 = false.\nProof.\n intros.\n unfolds in H7.\n apply Int.eq_false.\n intro.\n subst x0.\n assert (Int.unsigned x <= 7).\n apply math_unmap_get_y in H4.\n omega.\n auto.\n assert (((x<<ᵢ$ 3) +ᵢ y)&ᵢ$ 7 = y).\n apply inline_bittblfunctions.ob2.\n apply math_unmap_get_y in H4.\n omega.\n auto.\n apply math_unmap_get_y in H6.\n omega.\n auto.\n lets Hx:symbolic_lemmas.array_type_vallist_match_imp_rule_type_val_match H0.\n rewrite H1.\n instantiate (1:=Z.to_nat (Int.unsigned x)).\n clear -H8.\n apply z_le_7_imp_n.\n auto.\n rewrite H5 in Hx.\n simpl in Hx.\n remember (Int.unsigned i0 <=? Byte.max_unsigned) as X.\n destruct X;tryfalse.\n clear -HeqX.\n unfold Byte.max_unsigned in *.\n unfold Byte.modulus in *.\n unfold Byte.wordsize in *.\n unfold Wordsize_8.wordsize in *.\n simpl in HeqX.\n apply Zle_bool_imp_le;auto.\n symmetry in H9.\n assert (((x<<ᵢ$ 3) +ᵢ y) >>ᵢ $ 3 = x).\n eapply math_shrl_3_eq;eauto.\n apply math_unmap_get_y in H6.\n omega.\n \n lets Hx:symbolic_lemmas.array_type_vallist_match_imp_rule_type_val_match H0.\n rewrite H1.\n instantiate (1:=Z.to_nat (Int.unsigned x)).\n clear -H8.\n apply z_le_7_imp_n.\n auto.\n rewrite H5 in Hx.\n simpl in Hx.\n remember (Int.unsigned i0 <=? Byte.max_unsigned) as X.\n destruct X;tryfalse.\n clear -HeqX.\n unfold Byte.max_unsigned in *.\n unfold Byte.modulus in *.\n unfold Byte.wordsize in *.\n unfold Wordsize_8.wordsize in *.\n simpl in HeqX.\n apply Zle_bool_imp_le;auto.\n clear -H8.\n int auto.\n apply z_le_7_imp_n;auto.\n symmetry in H10.\n\n lets Hx: nth_val'_imp_nth_val_int H5.\n lets Hy:H7 H9 H10 Hx.\n \n assert (prio_in_tbl ($ Int.unsigned((x<<ᵢ$ 3) +ᵢ y)) rtbl).\n eapply unmap_inrtbl;eauto.\n rewrite Int.repr_unsigned in H11.\n unfolds in H11.\n lets Hz:H11 H9 H10 Hx.\n rewrite Hy in Hz.\n assert (Int.unsigned y <= 7).\n \n apply math_unmap_get_y in H6.\n omega.\n auto.\n lets Hw:symbolic_lemmas.array_type_vallist_match_imp_rule_type_val_match H0.\n rewrite H1.\n instantiate (1:=Z.to_nat (Int.unsigned x)).\n clear -H8.\n apply z_le_7_imp_n.\n auto.\n rewrite H5 in Hw.\n simpl in Hw.\n remember (Int.unsigned i0 <=? Byte.max_unsigned) as X.\n destruct X;tryfalse.\n clear -HeqX.\n unfold Byte.max_unsigned in *.\n unfold Byte.modulus in *.\n unfold Byte.wordsize in *.\n unfold Wordsize_8.wordsize in *.\n simpl in HeqX.\n apply Zle_bool_imp_le;auto.\n \n clear -Hz H12.\n mauto.\n destruct H12.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n \n destruct H.\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\n\n unfolds in Hz.\n rewrite H in *.\n simpl in Hz.\n int auto.\nQed.\n\n\nLemma dead_not_in:\n forall s head tail l rtbl tcbls ct P xx,\n s |= tcblist head xx tail Vnull l rtbl tcbls ** TCB_Not_In (Vptr ct) head l ** HTCBList tcbls ** P ->\n s |= HTCBList tcbls ** [|~ indom tcbls ct|] ** Atrue.\nProof.\n intros.\n sep split.\n sep auto.\n intro.\n unfold tcblist in H.\n unfold TCB_Not_In in H.\n sep normal in H.\n sep split in H.\n destruct H2.\n destruct H3.\n inverts H3.\n destruct H2.\n unfold tcbdllseg in *.\n remember ( HTCBList tcbls ** P) as PP.\n clear HeqPP.\n clears.\n remember (x,Int.zero) as y.\n clear Heqy.\n clears.\n gen s head rtbl tcbls PP y tail xx0.\n inductions l;intros.\n simpl dllseg in H.\n sep split in H.\n subst.\n unfolds in H1.\n subst.\n unfolds in H0.\n destruct H0.\n rewrite map_emp_get in H0.\n tryfalse.\n unfold1 TCBList_P in H1.\n mytac.\n unfold1 dllseg in H.\n unfold node in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n rewrite H6 in H2;inverts H2.\n destruct H1;inverts H1.\n struct_type_vallist_match_elim.\n unfolds in H6;simpl in H6;inverts H6.\n unfolds in H1.\n destruct H1;subst.\n assert (l=nil).\n clear -H5.\n destruct l;auto.\n simpl in H5.\n mytac;tryfalse.\n subst l.\n unfolds in H5.\n subst x1.\n assert (y = (x4,Int.zero)).\n clear -H0 H3.\n unfold TcbJoin in *.\n apply join_comm in H3.\n apply join_emp_eq in H3.\n subst.\n\n apply indom_sig_eq in H0.\n auto.\n subst y.\n simpl.\n assert (beq_pos x4 x4 = true).\n rewrite beq_pos_Pos_eqb_eq.\n apply Pos.eqb_eq.\n auto.\n rewrite H1.\n clear;int auto.\n destruct H1;subst x0.\n \n simpl.\n remember (os_inv.beq_addrval y (x4, Int.zero)) as X.\n destruct X;auto.\n\n remember (dllseg (Vptr x) (Vptr (x4, Int.zero)) tail Vnull l OS_TCB_flag\n V_OSTCBPrev V_OSTCBNext ** PP) as X.\n remember (Astruct (x4, Int.zero) OS_TCB_flag\n (Vptr x\n :: x12\n :: x11\n :: x10\n :: Vint32 i5\n :: Vint32 i4\n :: Vint32 i3\n :: Vint32 i2\n :: Vint32 i1 :: Vint32 i0 :: Vint32 i :: nil)) as Y.\n simpl in H.\n mytac.\n eapply IHl in H5;eauto.\n \n clear -H3 H0 H1 HeqX.\n unfolds in H3.\n eapply joinsig_indom_neq;eauto.\n clear -HeqX.\n destruct y;simpl in HeqX.\n assert ((b,i)<>(x4, Int.zero)).\n eapply addr_eq_false_neq;eauto.\n auto.\nQed.\n\n\nLemma tcbld_rtbl_timetci_update_tcbdllflag:\n forall l l' v'28 v'39 v'40 v'41 v'33 x7 v'43,\n tcbls_rtbl_timetci_update l v'28 \n (Vint32 v'39) v'40 v'41 =\n Some (l', v'33, Vint32 x7, v'43) ->\n eq_dllflag l l'.\nProof.\n induction l.\n intros.\n simpl in H.\n inverts H.\n simpl;auto.\n intros.\n Ltac xunfold' H:=\n let M:= fresh in \n match type of H with\n | match ?X with\n | _ => _\n end = Some _ => remember X as M;destruct M;tryfalse;auto\n | _ => idtac\n end.\n\n Ltac xunfold'' H:=\n let M:= fresh in \n match type of H with\n | Some _ = match ?X with\n | _ => _\n end => remember X as M;destruct M;tryfalse;auto\n | _ => idtac\n end.\n\n\n\n Ltac xunfold'''' H:=\n match type of H with\n | (Some ?p) = _\n => destruct p as [[[]]]\n | _ => idtac\n end.\n\n Ltac xunfold''' H:=\n let M:= fresh in \n match type of H with\n | match ?X with\n | _ => _\n end = Some _ => remember X as M eqn:Htick;destruct M;tryfalse;auto;xunfold'''' Htick;inverts H\n | _ => idtac\n end.\n\n Ltac xunfold H :=\n repeat (xunfold' H);\n subst;\n simpl in *;unfold add_option_first in H;(xunfold''' H).\n simpl in H.\n xunfold H.\n splits;auto.\n eapply IHl;eauto.\n splits;auto.\n eapply IHl;eauto.\n splits;auto.\n eapply IHl;eauto.\n splits;auto.\n \n eapply IHl;eauto.\nQed.\n\n\nLemma tcblist_p_rh_curtcb:\n forall l1 l2 l a b p x,\n join l1 l2 l ->\n TCBList_P (Vptr p) (a::x) b l2 ->\n RH_CurTCB p l.\nProof.\n intros.\n unfold1 TCBList_P in *.\n mytac.\n inverts H0.\n clear -H2 H.\n unfolds.\n unfolds in H2.\n destruct x3.\n destruct p.\n do 3 eexists.\n apply join_sig_get in H2.\n eapply join_get_get_r in H;eauto.\n auto.\nQed.\n\n\nLemma inv_change_aux':\n forall p1 p2 tcbl1 tcbcur tcbl2 rtbl tcbls ptfree lfree P t,\n AOSTCBList' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl t tcbls ptfree **\n AOSTCBFreeList' ptfree lfree t tcbls** p_local OSLInv t init_lg ** P <==>\n AOSTCBList_old p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl t tcbls **\n AOSTCBFreeList ptfree lfree ** tcbdllflag p1 (tcbl1 ++ tcbcur :: tcbl2) ** LINV OSLInv t init_lg ** P.\nProof.\n intros.\n split;intros.\n unfold AOSTCBList' in H.\n apply disj_split in H.\n destruct H.\n sep normal in H.\n unfold p_local in H.\n unfold CurTid in H.\n unfold LINV in H.\n unfold OSLInv in H.\n unfold init_lg in H.\n \n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H0.\n inverts H0.\n destruct H1.\n subst p2.\n sep lift 5%nat in H.\n sep lift 3%nat in H.\n sep lift 2%nat in H.\n apply read_only_merge_vptr in H.\n destruct H as (H & Ha).\n unfold LINV.\n sep semiauto.\n eauto.\n unfold AOSTCBList_old.\n sep normal.\n sep eexists.\n sep semiauto.\n sep cancel tcbdllseg.\n sep cancel tcbdllseg.\n unfold AOSTCBFreeList' in H.\n unfold AOSTCBFreeList.\n unfold OSLInv, init_lg.\n sep auto.\n destruct H.\n unfold TCBFree_Not_Eq in H.\n sep auto.\n unfold TCBFree_Eq in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H1.\n tryfalse.\n eauto.\n eauto.\n auto.\n unfold p_local in H.\n unfold CurTid in H.\n unfold LINV in H.\n unfold OSLInv in H.\n unfold TCB_Not_In in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n unfold init_lg in H0.\n inverts H0.\n destruct H1.\n destruct H1.\n subst p2.\n sep lift 4%nat in H.\n sep lift 3%nat in H.\n sep lift 2%nat in H.\n apply read_only_merge_vptr in H.\n destruct H as (H & Ha).\n subst t.\n sep lift 4%nat in H.\n inverts H5.\n sep lift 3%nat in H.\n subst ptfree.\n unfold AOSTCBFreeList' in H.\n destruct H2.\n inverts H2.\n sep normal in H.\n sep lift 7%nat in H.\n apply disj_split in H.\n destruct H.\n unfold TCBFree_Not_Eq in H.\n sep normal in H.\n sep split in H.\n tryfalse.\n unfold TCBFree_Eq in H.\n sep normal in H.\n sep destruct H.\n sep split in H.\n destruct H2.\n destruct H5;subst.\n sep lift 2%nat in H.\n sep lift 5%nat in H.\n eapply flag_merege_false in H.\n tryfalse.\n(****)\n intros.\n unfold p_local, CurTid, LINV, OSLInv.\n unfold AOSTCBList_old in H.\n \n unfold LINV, OSLInv, init_lg in H.\n sep semiauto.\n sep lift 3%nat.\n unfold AOSTCBList'.\n eapply disj_split.\n left.\n sep normal.\n subst p2.\n sep lift 5%nat in H.\n sep lift 6%nat in H.\n lets Hxx : tcbfreelist_disj_tcblist H.\n sep semiauto.\n\n sep cancel 2%nat 4%nat.\n sep cancel 3%nat 1%nat.\n sep lift 3%nat.\n sep cancel tcbdllflag.\n sep lift 4%nat in H.\n apply read_only_merge_vptreq in H.\n unfold AOSTCBFreeList in H.\n sep lift 5%nat.\n unfold AOSTCBFreeList'.\n sep lift 2%nat.\n eapply disj_split.\n left.\n unfold TCBFree_Not_Eq.\n sep auto.\n eauto.\n eauto.\n auto.\n split;auto.\nQed.\n \nLemma inv_change_aux:\n forall p1 p2 tcbl1 tcbcur tcbl2 rtbl tcbls ptfree lfree P t,\n AOSTCBList' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl t tcbls ptfree **\n AOSTCBFreeList' ptfree lfree t tcbls** p_local OSLInv t init_lg ** P <==>\n AOSTCBList p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl t tcbls **\n AOSTCBFreeList ptfree lfree ** tcbdllflag p1 (tcbl1 ++ tcbcur :: tcbl2) ** p_local OSLInv t init_lg ** P.\nProof.\n intros.\n split;intros.\n apply inv_change_aux' in H.\n sep semiauto.\n unfold p_local in *.\n unfold CurTid in *.\n unfold AOSTCBList in *.\n unfold AOSTCBList_old in *.\n sep auto.\n destruct H0;subst.\n sep lift 4%nat.\n apply read_only_merge_vptreq.\n sep auto.\n eauto.\n eauto.\n auto.\n apply inv_change_aux'.\n sep semiauto.\n unfold p_local in *.\n unfold CurTid in *.\n unfold AOSTCBList in *.\n unfold AOSTCBList_old in *.\n sep auto.\n sep lift 4%nat in H.\n destruct H0;subst.\n apply read_only_merge_vptr in H.\n destruct H.\n sep auto.\n eauto.\n eauto.\n auto.\nQed.\n\nDefinition prio_in_tcbdllseg := \nfix prio_in_tcbdllseg (p : int32) (l : list vallist) {struct l} : bool :=\n match l with\n | nil => false\n | h :: l' =>\n match V_OSTCBPrio h with\n | Some (Vint32 p') => (Int.eq p' p) || (prio_in_tcbdllseg p l')\n | _ => prio_in_tcbdllseg p l'\n end\n end.\n\n\n\nLemma tickstep_prio_in_tcbls':\n forall tcbls tcbls' ecbls ecbls' p tcblsx,\n sub tcblsx tcbls ->\n prio_not_in_tcbls p tcbls ->\n tickstep' tcbls ecbls tcbls' ecbls' tcblsx->\n prio_not_in_tcbls p tcbls'.\nProof.\n intros.\n inductions H1.\n auto.\n eapply IHtickstep';eauto.\n eapply joinsig_set_sub_sub;eauto.\n unfolds.\n intro.\n unfolds in H0.\n destruct H0.\n inverts H2;mytac.\n assert (t = x \\/ t <> x ) by tauto.\n destruct H3.\n subst.\n rewrite map_get_set in H2.\n inverts H2.\n exists x x0 x1.\n eapply sub_joinsig_get;eauto.\n rewrite map_get_set' in H2.\n do 3 eexists;eauto.\n auto.\n assert (t = x \\/ t <> x ) by tauto.\n destruct H2.\n subst.\n rewrite map_get_set in H0.\n inverts H0.\n do 3 eexists.\n eapply sub_joinsig_get;eauto.\n rewrite map_get_set' in H0.\n do 3 eexists;eauto.\n auto.\n assert (t = x \\/ t <> x ) by tauto.\n destruct H2.\n subst.\n rewrite map_get_set in H0.\n inverts H0.\n do 3 eexists.\n eapply sub_joinsig_get;eauto.\n rewrite map_get_set' in H0.\n do 3 eexists;eauto.\n auto.\n assert (t = x0 \\/ t <> x0 ) by tauto.\n destruct H3.\n subst.\n rewrite map_get_set in H0.\n inverts H0.\n do 3 eexists.\n eapply sub_joinsig_get;eauto.\n rewrite map_get_set' in H0.\n do 3 eexists;eauto.\n auto.\n assert (t = x0 \\/ t <> x0 ) by tauto.\n destruct H3.\n subst.\n rewrite map_get_set in H2.\n inverts H2.\n do 3 eexists.\n eapply sub_joinsig_get;eauto.\n rewrite map_get_set' in H2.\n do 3 eexists;eauto.\n auto.\nQed.\n\nLemma tickstep_prio_in_tcbls:\n forall tcbls tcbls' ecbls ecbls' p,\n prio_not_in_tcbls p tcbls ->\n tickstep tcbls ecbls tcbls' ecbls' ->\n prio_not_in_tcbls p tcbls'.\nProof.\n intros.\n eapply tickstep_prio_in_tcbls';eauto.\n clear;unfolds;join auto.\nQed.\n\nLemma prio_not_in_hl:\n forall a rtbl tcbls p x3 ,\n TCBList_P p a rtbl tcbls ->\n prio_not_in_tcbls x3 tcbls ->\n prio_in_tcbdllseg x3 a = false.\nProof.\n inductions a.\n intros.\n simpl;auto.\n intros.\n simpl.\n simpl in H.\n mytac.\n remember (V_OSTCBPrio a) as XX.\n destruct XX.\n destruct v.\n eapply IHa;eauto.\n unfolds.\n unfolds in H0.\n intro.\n destruct H0.\n mytac;do 3 eexists.\n eapply join_get_r in H;eauto.\n eapply IHa;eauto.\n unfolds.\n unfolds in H0.\n intro.\n destruct H0.\n mytac;do 3 eexists.\n eapply join_get_r in H;eauto.\n apply orb_false_iff.\n unfolds in H3.\n destruct x2.\n destruct p.\n mytac.\n rewrite H3 in HeqXX.\n inverts HeqXX.\n unfolds in H0.\n remember (Int.eq p x3) as X.\n destruct X;auto.\n destruct H0.\n exists x t m.\n eapply join_get_l;eauto.\n lets Hx: Int.eq_spec p x3.\n rewrite <- HeqX in Hx.\n subst.\n apply map_get_sig;auto.\n eapply IHa;eauto.\n unfolds.\n unfolds in H0.\n intro.\n destruct H0.\n mytac;do 3 eexists.\n eapply join_get_r;eauto.\n eapply IHa;eauto.\n unfolds.\n unfolds in H0.\n intro.\n destruct H0.\n mytac;do 3 eexists.\n eapply join_get_r;eauto.\n eapply IHa;eauto.\n unfolds.\n unfolds in H0.\n intro.\n destruct H0.\n mytac;do 3 eexists.\n eapply join_get_r;eauto.\nQed.\n\nFixpoint tcblist_rl l:=\n match l with\n | nil => True\n | a::l' => RL_TCBblk_P a /\\ tcblist_rl l'\n end.\n\nLemma tcblist_p_rl:\n forall b a c d,\n TCBList_P a b c d -> tcblist_rl b.\nProof.\n inductions b.\n intros;simpl in *;auto.\n intros.\n simpl.\n simpl in H.\n mytac.\n unfolds in H2.\n destruct x2.\n destruct p.\n mytac;auto.\n eapply IHb;eauto.\nQed.\n\nLemma prio_not_in_tcbls_nready:\n forall x0 tcbls ptbl vhold rtbl,\n array_type_vallist_match Int8u rtbl ->\n length rtbl = ∘ OS_RDY_TBL_SIZE ->\n R_PrioTbl_P ptbl tcbls vhold ->\n RL_RTbl_PrioTbl_P rtbl ptbl vhold ->\n Int.unsigned x0 < 64 ->\n prio_not_in_tcbls x0 tcbls ->\n prio_not_in_tbl x0 rtbl.\nProof.\n intros.\n lets Hx : prio_rtbl_dec x0 H H0.\n split;auto.\n clear;int auto.\n destruct Hx;auto.\n unfolds in H4.\n destruct H4.\n unfolds in H1.\n mytac.\n unfolds in H2.\n lets Hx: H2 H5.\n split;auto.\n clear;int auto.\n mytac.\n exists x.\n eapply H1;eauto.\n split;auto.\n clear;int auto.\nQed.\n\n\nLemma tcbfree_eq_tick_hold:\n forall s P ct x tcbls tcbls' ecbls ecbls',\n tickstep tcbls ecbls tcbls' ecbls' ->\n s |= TCBFree_Eq (Vptr ct) ct x tcbls ** P ->\n s |= TCBFree_Eq (Vptr ct) ct x tcbls' ** P.\nProof.\n introv Htickstep.\n intros.\n sep cancel 2%nat 2%nat.\n unfold TCBFree_Eq in *.\n sep auto.\n mytac;auto.\n eexists.\n split;eauto.\n clear -Htickstep H4.\n unfolds in Htickstep.\n Lemma tcbfree_eq_tick_hold':\n forall p tcbls ecbls tcbls' ecbls' tcblsx,\n sub tcblsx tcbls ->\n tickstep' tcbls ecbls tcbls' ecbls' tcblsx ->\n prio_not_in_tcbls p tcbls ->\n prio_not_in_tcbls p tcbls'.\n Proof.\n intros.\n inductions H0.\n auto.\n eapply IHtickstep';eauto.\n eapply joinsig_set_sub_sub;eauto.\n unfold prio_not_in_tcbls in *.\n intro.\n destruct H4.\n mytac.\n assert (x=t \\/ x <> t) by tauto.\n destruct H2.\n subst.\n rewrite map_get_set in H4.\n inverts H4.\n Focus 2.\n rewrite map_get_set' in H4;auto.\n do 3 eexists;eauto.\n exists t st x1.\n eapply sub_joinsig_get;eauto.\n Qed.\n eapply tcbfree_eq_tick_hold';eauto.\n clear;unfolds.\n join auto.\nQed.\n \n\nLemma not_in_tcblist_tick_hold:\n forall a b c d a' b' c' rtbl rtbl' ct head,\n tcbls_rtbl_timetci_update a rtbl \n (Vint32 b) c d =\n Some (a', rtbl', Vint32 b', c') ->\n ~ ptr_in_tcblist (Vptr ct) head a ->\n ~ ptr_in_tcblist (Vptr ct) head a'.\nProof.\n intros.\n intro.\n destruct H0.\n gen b c d a' b' c' rtbl rtbl' ct head.\n inductions a.\n intros.\n simpl in *.\n inverts H;simpl in H1;tryfalse.\n intros.\n simpl.\n simpl in H.\n xunfold H.\n\n simpl in H1.\n destruct head;tryfalse.\n eapply IHa;eauto.\n eapply IHa;eauto.\n eapply IHa;eauto.\n remember (os_inv.beq_addrval ct a) as X.\n destruct X;auto.\n eapply IHa;eauto.\n \n simpl in H1.\n destruct head;tryfalse.\n eapply IHa;eauto.\n eapply IHa;eauto.\n eapply IHa;eauto.\n remember (os_inv.beq_addrval ct a) as X.\n destruct X;auto.\n eapply IHa;eauto.\n simpl in H1.\n destruct head;tryfalse.\n eapply IHa;eauto.\n eapply IHa;eauto.\n eapply IHa;eauto.\n remember (os_inv.beq_addrval ct a) as X.\n destruct X;auto.\n eapply IHa;eauto.\n simpl in H1.\n destruct head;tryfalse.\n eapply IHa;eauto.\n eapply IHa;eauto.\n eapply IHa;eauto.\n remember (os_inv.beq_addrval ct a) as X.\n destruct X;auto.\n eapply IHa;eauto.\nQed.\n\nLemma GoodFrm_dllsegflag:\n forall z x y next,\n GoodFrm (dllsegflag x y z next).\nProof.\n inductions z.\n intros.\n simpl.\n auto.\n intros.\n simpl.\n intros.\n splits;auto.\nQed.\n\nClose Scope code_scope.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/ucos_lib/oscore_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.24508501864634824, "lm_q1q2_score": 0.13966234769750968}} {"text": "From Coq Require Import String Arith ZArith PropExtensionality Lia.\n\nFrom Vyper Require Import Config Calldag.\nFrom Vyper.L10 Require Import Base.\nFrom Vyper.L40 Require Import AST Descend Callset Descend Expr Stmt Interpret.\nFrom Vyper.L40Metered Require Import Interpret Expr Stmt.\n\nLemma call_metering_ok\n {C: VyperConfig}\n {bigger_call_depth_bound smaller_call_depth_bound: nat}\n (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n {max_call_depth: nat}\n (DepthOk: bigger_call_depth_bound <= max_call_depth)\n {cd: calldag}\n (fc: fun_ctx cd bigger_call_depth_bound)\n (builtins: string -> option builtin)\n (world: world_state)\n (arg_values: list uint256):\n let '(world', result) := interpret_call builtins fc world arg_values\n in interpret_call_metered max_call_depth (cd_decls cd) builtins (fun_decl fc)\n world arg_values\n =\n (world', Some result).\nProof.\nrevert smaller_call_depth_bound Ebound fc world arg_values max_call_depth DepthOk.\ninduction bigger_call_depth_bound; intros. { discriminate. }\ninversion Ebound. subst. clear Ebound.\nunfold interpret_call. fold (@interpret_call C smaller_call_depth_bound cd).\nmatch goal with\n|- let '(world', result) :=\n match fun_decl fc as d with\n | FunDecl name arity body => ?X\n end eq_refl\n in _ = _\n =>\n remember (fun name arity body => X) as do_call\nend.\nenough (Q: forall name arity body E,\n let '(world', result) := do_call name arity body E in\n interpret_call_metered max_call_depth (cd_decls cd) builtins\n (FunDecl name arity body) world arg_values\n =\n (world', Some result)).\n{\n clear Heqdo_call.\n destruct (fun_decl fc) as (name, arity, body).\n apply Q.\n}\nintros. subst do_call.\nunfold interpret_call_metered.\ndestruct max_call_depth. { apply Nat.nle_succ_0 in DepthOk. contradiction. }\nsimpl. (* cbn does something weird *)\nfold interpret_call_metered.\nremember (Datatypes.length arg_values =? N.to_nat arity) as arity_ok.\ndestruct arity_ok. 2:reflexivity.\nassert (IH: forall (fc': fun_ctx cd smaller_call_depth_bound)\n (world: world_state)\n (arg_values: list uint256),\n let\n '(world', result) := interpret_call builtins fc' world arg_values in\n interpret_call_metered max_call_depth (cd_decls cd) builtins (fun_decl fc') world arg_values = (world', Some result)).\n{\n intros.\n assert (D := fun_bound_ok fc'). rewrite Nat.ltb_lt in D.\n destruct smaller_call_depth_bound. { apply Nat.nlt_0_r in D. contradiction. }\n apply (IHbigger_call_depth_bound _ eq_refl).\n apply (le_S_n _ _ DepthOk).\n}\nassert (M := let _ := memory_impl in\n block_metering_ok eq_refl fc\n (interpret_call builtins)\n (interpret_call_metered max_call_depth\n (cd_decls cd) builtins)\n IH builtins world (OpenArray.from_list arg_values) nil\n body ((Interpret.interpret_call_helper E))).\ndestruct interpret_block as ((world', loc'), result). rewrite M.\ndestruct result; try easy.\nnow destruct a.\nQed.\n\n(* XXX this is a dup from somewhere else *)\nLemma match_some {T R} {x: option T} {y: T} (E: x = Some y)\n (some_branch: forall z: T, x = Some z -> R)\n (none_branch: x = None -> R):\n match x as x' return x = x' -> _ with\n | Some z => some_branch z\n | None => none_branch\n end eq_refl\n =\n some_branch y E.\nProof.\ndestruct x. 2:discriminate.\ninversion E. subst. f_equal. apply proof_irrelevance.\nQed.\n\nLemma match_none {T R} {x: option T} (E: x = None)\n (some_branch: forall z: T, x = Some z -> R)\n (none_branch: x = None -> R):\n match x as x' return x = x' -> _ with\n | Some z => some_branch z\n | None => none_branch\n end eq_refl\n =\n none_branch E.\nProof.\ndestruct x. 1:discriminate.\ninversion E. subst. f_equal. apply proof_irrelevance.\nQed.\n\nFixpoint max_depth_by_names (m: string -> option nat) (l: list string)\n{struct l}\n: nat\n:= match l with\n | nil => 0\n | (h :: t)%list => match m h with\n | Some n => max n (max_depth_by_names m t)\n | None => max_depth_by_names m t\n end\n end.\n\nDefinition max_depth_in_calldag {C: VyperConfig}\n (cd: calldag)\n:= let _ := string_map_impl in\n max_depth_by_names (cd_depthmap cd)\n (List.map fst (Map.items (cd_decls cd))).\n\nLemma max_depth_in_calldag_ok {C: VyperConfig}\n {cd: calldag}\n {name: string}\n {d: decl}\n {depth: nat}\n (Ok: cd_declmap cd name = Some d)\n (D: cd_depthmap cd name = Some depth):\n depth <= max_depth_in_calldag cd.\nProof.\nunfold cd_declmap in Ok.\nrewrite Map.items_ok in Ok.\nunfold max_depth_in_calldag.\nremember (Map.items (cd_decls cd)) as l. clear Heql.\ninduction l as [|(k,v)]. { easy. }\ncbn in *.\ndestruct string_dec as [E|NE].\n{ subst k. rewrite D. lia. }\nassert (IH := IHl Ok).\ndestruct (cd_depthmap cd k); lia.\nQed.\n\nLemma metering_ok\n {C: VyperConfig}\n {max_call_depth: nat}\n {cd: calldag}\n (DepthOk: max_depth_in_calldag cd < max_call_depth)\n (builtins: string -> option builtin)\n (fun_name: string)\n (world: world_state)\n (args: list uint256):\n let '(world', result) := interpret builtins cd fun_name world args\n in interpret_metered max_call_depth (cd_decls cd) builtins fun_name world args\n =\n (world', Some result).\nProof.\nunfold interpret.\nunfold interpret_metered.\nunfold make_fun_ctx_and_bound.\nunfold cd_declmap. unfold Base.map_lookup.\nrefine (match Map.lookup (cd_decls cd) fun_name as z return _ = z -> _ with\n | Some d => fun E => _\n | None => fun E => _\n end eq_refl).\n2:{ rewrite (match_none E). rewrite E. trivial. }\nrewrite (match_some E).\nrefine (match cd_depthmap cd fun_name as z return _ = z -> _ with\n | Some depth => fun D => _\n | None => fun D => _\n end eq_refl).\n2:{ exfalso. exact (Calldag.make_fun_ctx_helper E D). }\nrewrite (match_some D).\nassert (M' := max_depth_in_calldag_ok E D).\nassert (M: S depth <= max_call_depth) by lia.\nassert (CM := call_metering_ok eq_refl M {|\n fun_name := fun_name;\n fun_depth := depth;\n fun_depth_ok := D;\n fun_decl := d;\n fun_decl_ok := E;\n fun_bound_ok := proj2 (Nat.ltb_lt depth (S depth)) (Nat.lt_succ_diag_r depth)\n |} builtins world args).\ndestruct interpret_call as (world', result).\nrewrite E. apply CM.\nQed.\n", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L40Metered/Call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.23651623106411435, "lm_q1q2_score": 0.13928183431085148}} {"text": "Require Import VST.floyd.proofauto.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import sha.HMAC256_functional_prog.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import compcert.lib.Integers.\nRequire Import sha.general_lemmas. \nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.spec_hmac_drbg.\n\nLemma HMAC256_DRBG_reseed_algorithmWFaux d l y A B zz \n (H: (A, B, zz) = HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_algorithm d l y):\n 0 <= zz < Int.max_signed /\\ Zlength A = 32 /\\ Forall isbyteZ A.\nProof.\n unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_algorithm, HMAC_DRBG_algorithms.HMAC_DRBG_reseed_algorithm in H.\n destruct d as [[? ?] ?]. \n remember (HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256\n (l ++ y) l1 l0) as q; destruct q. inv H. rewrite int_max_signed_eq. split. omega.\n eapply spec_hmac_drbg_pure_lemmas.HMAC_DRBG_update_value; eassumption.\nQed.\n\nLemma HMAC256_DRBG_reseed_functionWFaux a b c s t x y A B zz C D ss \n (H: ENTROPY.success (A, B, zz, C, D) ss =\n HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_function a b c s t x y):\n 0 <= zz < Int.max_signed /\\ Zlength A = 32 /\\ Forall isbyteZ A.\nProof. unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_function, DRBG_functions.DRBG_reseed_function in H.\n destruct t. destruct p.\n remember ((x && negb b0)%bool) as bb; destruct bb; try discriminate.\n remember (Zlength y >? c) as cc; destruct cc; try discriminate.\n remember (get_entropy z a b x s) as dd. destruct dd; try discriminate. inv H.\n eapply HMAC256_DRBG_reseed_algorithmWFaux; eassumption.\nQed.\n\nLemma mbedtls_HMAC256_DRBG_reseed_functionWFaux a s data ss A B zz C D\n (H: mbedtls_HMAC256_DRBG_reseed_function s a data =\n ENTROPY.success (A, B, zz, C, D) ss):\n 0 <= zz < Int.max_signed /\\ Zlength A = 32 /\\ Forall isbyteZ A.\nProof. unfold mbedtls_HMAC256_DRBG_reseed_function in H.\n destruct a; symmetry in H. eapply HMAC256_DRBG_reseed_functionWFaux; eauto. Qed.\n\n\nLemma HMAC_DRBG_updateWF a b c d e:\n (d,e) = HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256 a b c ->\n Zlength e = 32 /\\ Forall isbyteZ e.\nProof. unfold HMAC_DRBG_algorithms.HMAC_DRBG_update.\n destruct a; intros.\n + inversion H; clear H; split. apply hmac_common_lemmas.HMAC_Zlength.\n apply hmac_common_lemmas.isbyte_hmac.\n + inversion H; clear H. rewrite hmac_common_lemmas.HMAC_Zlength.\n split; trivial. apply hmac_common_lemmas.isbyte_hmac.\nQed.\n\nLemma false_zgt z a: false = (z >? a) -> z<=a. \nProof. unfold Z.gtb.\n remember (z ?= a). destruct c. symmetry in Heqc; apply Z.compare_eq in Heqc. subst; intros. omega.\n symmetry in Heqc. destruct (Z.compare_lt_iff z a); intros. apply H in Heqc. omega.\n discriminate.\nQed. \n\nLemma HMAC256_DRBG_generate_algorithmWF a v k rc n l bytes V K RC (N:n >=0)\n (A: 0<= a +1< Int.max_signed) (Rc: 0<=rc) \n (H: DRBG_functions.generate_algorithm_success bytes (V, K, RC) =\n HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a (v,k,rc) n l):\n Zlength V = 32 /\\ 0 <= RC < Int.max_signed /\\ Forall isbyteZ V.\nProof.\n unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm in H.\n unfold HMAC_DRBG_algorithms.HMAC_DRBG_generate_algorithm in H.\n remember (rc >? a) as q; destruct q; try discriminate.\n apply false_zgt in Heqq.\n destruct l.\n + rewrite HMAC_DRBG_algorithms.HMAC_DRBG_generate_helper_Z_equation in H.\n remember (0 >=? n). destruct b.\n - symmetry in Heqb; apply Z.geb_le in Heqb.\n assert (NN: n=0) by omega. subst n; clear N Heqb. simpl in H.\n inversion H; clear H. subst.\n split. apply hmac_common_lemmas.HMAC_Zlength.\n split. split; omega.\n apply hmac_common_lemmas.isbyte_hmac. \n - remember (HMAC_DRBG_algorithms.HMAC_DRBG_generate_helper_Z\n HMAC256_functional_prog.HMAC256 k v (n - Z.of_nat 32)). \n destruct p. \n remember (HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256\n [] k (HMAC256_functional_prog.HMAC256 l k)). \n destruct p. inv H. \n apply HMAC_DRBG_updateWF in Heqp0. destruct Heqp0.\n split; trivial. split; trivial. omega.\n + remember (HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256 (z :: l) k v). \n destruct p.\n rewrite HMAC_DRBG_algorithms.HMAC_DRBG_generate_helper_Z_equation in H.\n remember (0 >=? n) as b; destruct b.\n - symmetry in Heqb. apply Z.geb_le in Heqb.\n assert (NN: n=0) by omega. subst n; clear N Heqb.\n remember (HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256\n (z :: l) l0 l1). \n destruct p. inv H. apply HMAC_DRBG_updateWF in Heqp0. destruct Heqp0.\n split; trivial. split; trivial. omega.\n - remember (HMAC_DRBG_algorithms.HMAC_DRBG_generate_helper_Z\n HMAC256_functional_prog.HMAC256 l0 l1 (n - Z.of_nat 32)).\n destruct p.\n remember (HMAC_DRBG_algorithms.HMAC_DRBG_update HMAC256_functional_prog.HMAC256\n (z :: l) l0 (HMAC256_functional_prog.HMAC256 l2 l0)). \n destruct p. inv H. apply HMAC_DRBG_updateWF in Heqp1. destruct Heqp1.\n split; trivial. split; trivial. omega.\nQed.\n\nLemma HMAC256_DRBG_generate_functionWF f a b c s v k rc d pr n e l V K RC z PR ss bytes\n (A: 0<= a+1 < Int.max_signed) (N: n>=0) (Rc: 0<=rc)\n (F: forall s d z b x y zz A B C D ss, ENTROPY.success (A, B, zz, C, D) ss = f s (d, z, b) x y -> 0<=zz)\n (H : ENTROPY.success (bytes, (V, K, RC, z, PR)) ss =\n HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_function f a b c s (v, k, rc, d, pr) n e pr l):\nZlength V = 32 /\\ 0 <= RC < Int.max_signed /\\ Forall isbyteZ V.\nProof.\n unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_function in H.\n unfold DRBG_functions.DRBG_generate_function in H.\n remember (n >? b) as q1; destruct q1; try discriminate.\n remember (e >? d) as q2; destruct q2; try discriminate.\n remember (Zlength l >? c) as q3; destruct q3; try discriminate.\n assert (P: (pr && negb pr)%bool = false). { destruct pr; trivial. }\n rewrite P in H; clear P.\n remember (DRBG_functions.DRBG_generate_function_helper\n (HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a) f s\n (v, k, rc, d, pr) n pr l pr 1). \n destruct r; try discriminate.\n destruct p. symmetry in H; inv H.\n unfold DRBG_functions.DRBG_generate_function_helper in Heqr.\n destruct PR.\n + remember (f s (v, k, rc, z, true) true l). \n destruct r; try discriminate.\n destruct p. destruct p. apply false_zgt in Heqq1. apply false_zgt in Heqq2. apply false_zgt in Heqq3.\n remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a p n []).\n destruct d.\n * remember (f s0 (p, z0, b0) true [] ). \n destruct r; try discriminate.\n destruct p0. destruct p0.\n remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a p0 n []).\n destruct d; try discriminate.\n symmetry in Heqr; inv Heqr. destruct p0 as [[XX yy] zz].\n apply HMAC256_DRBG_generate_algorithmWF in Heqd0; trivial.\n apply F in Heqr1; trivial.\n * symmetry in Heqr; inv Heqr.\n destruct p as [[? ?] ?]. apply HMAC256_DRBG_generate_algorithmWF in Heqd; trivial.\n apply F in Heqr0; trivial.\n + remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a\n (v, k, rc) n l).\n destruct d.\n - remember (f s (v, k, rc, z, false) false l). destruct r; try discriminate.\n destruct p. destruct p.\n remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_generate_algorithm a p n\n []).\n destruct d; try discriminate. symmetry in Heqr; inv Heqr.\n destruct p as [[? ?] ?]. apply HMAC256_DRBG_generate_algorithmWF in Heqd0; trivial.\n apply F in Heqr0; trivial.\n - symmetry in Heqr; inv Heqr. apply HMAC256_DRBG_generate_algorithmWF in Heqd; trivial.\nQed.\n\n\nLemma mbedtls_HMAC256_DRBG_generate_functionWF_success s k v rc el pr rsi n l bytes V K RC z PR ss\n (N: n>=0) (Rc: 0<=rc) (HRSI: 0 <= rsi+1 < Int.max_signed)\n (H: ENTROPY.success (bytes, (V, K, RC, z, PR)) ss =\n mbedtls_HMAC256_DRBG_generate_function s (HMAC256DRBGabs k v rc el pr rsi) n l):\nZlength V = 32 /\\ 0 <= RC < Int.max_signed /\\ Forall isbyteZ V.\nProof. unfold mbedtls_HMAC256_DRBG_generate_function, hmac256drbgabs_generate in H.\n apply HMAC256_DRBG_generate_functionWF in H; trivial.\n intros. eapply HMAC256_DRBG_reseed_functionWFaux; eassumption.\nQed.\n\nLemma hmac256drbgabs_generateWF I s n l K V RC el PR rsi (N:n>=0)\n (HI: Zlength (hmac256drbgabs_value I) = 32 /\\ \n 0 <= hmac256drbgabs_reseed_counter I < Int.max_signed /\\\n Forall isbyteZ (hmac256drbgabs_value I)) (HRSI: 0 <= rsi +1< Int.max_signed)\n (G: hmac256drbgabs_generate I s n l = HMAC256DRBGabs K V RC el PR rsi):\n Zlength V = 32 /\\ 0 <= RC < Int.max_signed /\\ Forall isbyteZ V.\nProof. unfold hmac256drbgabs_generate in G. destruct I; simpl in HI.\n remember ( mbedtls_HMAC256_DRBG_generate_function s\n (HMAC256DRBGabs key V0 reseed_counter entropy_len\n prediction_resistance reseed_interval) n l). \n destruct r.\n + destruct p. destruct d. destruct p. destruct d. destruct p.\n inv G. apply mbedtls_HMAC256_DRBG_generate_functionWF_success in Heqr; trivial. omega.\n + inv G. trivial.\nQed. \n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/hmacdrbg/verif_hmac_drbg_WF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.13919948270199065}} {"text": "Require Import msl.msl_standard.\nRequire Import msl.seplog.\nRequire Import veric.base.\nRequire Import veric.compcert_rmaps.\nRequire Import veric.juicy_mem.\nRequire Import veric.juicy_mem_lemmas.\nRequire Import veric.juicy_mem_ops.\nRequire Import veric.juicy_extspec.\nRequire Import veric.tycontext.\nRequire Import veric.expr2.\nRequire Import veric.semax.\nRequire Import veric.semax_call.\nRequire Import veric.semax_ext.\nRequire Import veric.semax_ext_oracle.\nRequire Import veric.juicy_safety.\nRequire Import veric.Clight_new.\nRequire Import veric.res_predicates.\nRequire Import veric.SeparationLogic.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.extspec.\nRequire Import sepcomp.step_lemmas.\nRequire Import floyd.reptype_lemmas.\nRequire Import floyd.field_at.\nRequire Import floyd.nested_field_lemmas.\nRequire Import floyd.client_lemmas.\nRequire Import floyd.jmeq_lemmas.\nRequire Import concurrency.lksize.\nRequire Import concurrency.semax_conc_pred.\n\n(*+ About this file *)\n\n(* This file shows that, with our current notion of safety for\nexternal calls (see the definition of safeN_), there is no need to\nhave an oracle that predicts the nondeterminism of release. We define\nbelow specifications of acquire/release with and without oracle, and\nwe prove that safety without implies safety with. *)\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDefinition _f := 1%positive. (* alpha-convertible *)\nDefinition _args := 2%positive. (* alpha-convertible *)\nDefinition _lock := 1%positive. (* alpha-convertible *)\nDefinition _cond := 2%positive. (* alpha-convertible *)\nDefinition _lock_t := 2%positive. (* number given by clightgen when threads.h is included first *)\n\nDefinition voidstar_funtype := Tfunction (Tcons (tptr tvoid) Tnil) (tptr tvoid) cc_default.\nDefinition tlock := (Tarray (Tpointer Tvoid noattr) 1 noattr).\n\n(*+ Deep embedding of [mpred]s *)\n\nInductive Pred :=\n | Mapsto : Share.t -> type -> val -> val -> Pred\n | Mapsto_ : Share.t -> type -> val -> Pred\n | Data_at : forall cs : compspecs, Share.t -> forall t : type, reptype t -> val -> Pred\n | Data_at_ : forall cs : compspecs, Share.t -> type -> val -> Pred\n | Field_at : forall cs : compspecs, Share.t ->\n forall t : type, forall gfs : list gfield, reptype (nested_field_type t gfs) -> val -> Pred\n | Lock_inv : Share.t -> val -> Pred -> Pred\n | Pred_prop : Prop -> Pred\n | Exp : forall A : Type, (A -> Pred) -> Pred\n | Later : Pred -> Pred\n | Pred_list : list Pred -> Pred.\n\nFixpoint Interp (p : Pred) : mpred :=\n match p with\n | Mapsto a b c d => mapsto a b c d\n | Mapsto_ a b c => mapsto_ a b c\n | Data_at a b c d e => @data_at a b c d e\n | Data_at_ a b c d => @data_at_ a b c d\n | Field_at a b c d e f => @field_at a b c d e f\n | Lock_inv a b c => lock_inv a b (Interp c)\n | Pred_prop a => (!!a && emp)%logic\n | Exp a b => exp (fun x => Interp (b x))\n | Later a => later (Interp a)\n | Pred_list l => fold_right sepcon emp (map Interp l)\n end.\n\n(*+ Type of the oracle *)\n\nDefinition Oracle := list rmap.\n\n(*+ Specification of each concurrent primitive *)\n\nDefinition acquire_spec :=\n WITH v : val, sh : share, R : Pred\n PRE [ _lock OF tptr Tvoid ]\n PROP (readable_share sh)\n LOCAL (temp _lock v)\n SEP (lock_inv sh v (Interp R))\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (lock_inv sh v (Interp R); Interp R).\n\nDefinition acquire_oracular_spec :=\n mk_funspecOracle\n Oracle\n (* ARGS *)\n ((_lock, tptr Tvoid) :: nil, tvoid)\n cc_default\n (* WITH *)\n (Prop * Oracle * val * share * Pred)\n (* PRE *)\n (fun (x : Prop * Oracle * val * share * Pred) (oracle : Oracle) =>\n match x with\n | (ok, oracle_x, v, sh, R) =>\n PROP (readable_share sh;\n (match oracle with\n | nil => ~ok\n | cons mlock oracle' => oracle' = oracle_x /\\ (app_pred (Interp R) mlock <-> ok)\n end))\n LOCAL (temp _lock v)\n SEP (lock_inv sh v (Interp R))\n end)\n (* POST *)\n (fun (x : Prop * Oracle * val * share * Pred) (oracle : Oracle) =>\n match x with\n (ok, oracle_x, v, sh, R) =>\n PROP (oracle = oracle_x; ok)\n LOCAL ()\n SEP (lock_inv sh v (Interp R); Interp R)\n end).\n\nDefinition release_spec :=\n WITH v : val, sh : share, R : Pred\n PRE [ _lock OF tptr Tvoid ]\n PROP (readable_share sh; precise (Interp R); positive_mpred (Interp R))\n LOCAL (temp _lock v)\n SEP (lock_inv sh v (Interp R); Interp R)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (lock_inv sh v (Interp R)).\n\nDefinition release_oracular_spec :=\n mk_funspecOracle\n Oracle\n (* ARGS *)\n ((_lock, tptr Tvoid) :: nil, tvoid)\n cc_default\n (* WITH *)\n (Oracle * val * share * Pred)\n (* PRE *)\n (fun (x : Oracle * val * share * Pred) (oracle : Oracle) =>\n match x with\n (oracle_x, v, sh, R) =>\n PROP (oracle = oracle_x; readable_share sh)\n LOCAL (temp _lock v)\n SEP (lock_inv sh v (Interp R); Interp R)\n end)\n (* POST *)\n (fun (x : Oracle * val * share * Pred) (oracle : Oracle) =>\n match x with\n (oracle_x, v, sh, R) =>\n PROP (oracle = oracle_x; readable_share sh)\n LOCAL ()\n SEP (lock_inv sh v (Interp R))\n end).\n\n(*+ Adding the specifications to a void ext_spec *)\n\n(*! The void ext_spec *)\nDefinition void_spec T : external_specification juicy_mem external_function T :=\n Build_external_specification\n juicy_mem external_function T\n (fun ef => False)\n (fun ef Hef ge tys vl m z => False)\n (fun ef Hef ge ty vl m z => False)\n (fun rv m z => False).\n\nDefinition ok_void_spec (T : Type) : OracleKind.\n refine (Build_OracleKind T (Build_juicy_ext_spec _ (void_spec T) _ _ _)).\nProof.\n simpl; intros; contradiction.\n simpl; intros; contradiction.\n simpl; intros; intros ? ? ? ?; contradiction.\nDefined.\n\nDefinition concurrent_oracular_specs (cs : compspecs) (ext_link : string -> ident) :=\n (ext_link \"acquire\"%string, acquire_oracular_spec) ::\n (ext_link \"release\"%string, release_oracular_spec) ::\n nil.\n\nDefinition concurrent_simple_specs (cs : compspecs) (ext_link : string -> ident) :=\n (ext_link \"acquire\"%string, acquire_spec) ::\n (ext_link \"release\"%string, release_spec) ::\n nil.\n\nDefinition concurrent_oracular_ext_spec (cs : compspecs) (ext_link : string -> ident) :=\n add_funspecsOracle_rec\n ext_link\n (ok_void_spec (list rmap)).(@OK_ty)\n (ok_void_spec (list rmap)).(@OK_spec)\n (concurrent_oracular_specs cs ext_link).\n\nDefinition concurrent_simple_ext_spec Z (cs : compspecs) (ext_link : string -> ident) :=\n add_funspecs_rec\n ext_link\n (ok_void_spec Z).(@OK_ty)\n (ok_void_spec Z).(@OK_spec)\n (concurrent_simple_specs cs ext_link).\n\nDefinition Concurrent_Oracular_Espec cs ext_link :=\n Build_OracleKind\n (list rmap)\n (concurrent_oracular_ext_spec cs ext_link).\n\nDefinition Concurrent_Simple_Espec Z cs ext_link :=\n Build_OracleKind\n Z\n (concurrent_simple_ext_spec Z cs ext_link).\n\nLemma strong_nat_ind (P : nat -> Prop) (IH : forall n, (forall i, lt i n -> P i) -> P n) n : P n.\nProof.\n apply IH; induction n; intros i li; inversion li; eauto.\nQed.\n\nSet Printing Implicit.\n\nLemma at_external_not_halted (G C M : Type) (csem : semantics.CoreSemantics G C M) (q : C) :\n semantics.at_external csem q <> None -> semantics.halted csem q = None.\nProof.\n destruct (@semantics.at_external_halted_excl G C _ csem q); tauto.\nQed.\n\nTheorem oracular_refinement cs ext_link ge n oracle c m :\n jsafeN (Concurrent_Simple_Espec unit cs ext_link).(@OK_spec) ge n tt c m ->\n jsafeN (Concurrent_Oracular_Espec cs ext_link).(@OK_spec) ge n oracle c m.\nProof.\n revert oracle c m; induction n as [n InductionHypothesis] using strong_nat_ind; intros oracle c m.\n intros Safe; induction Safe as [ | | n z_unit c m e args x E Pre Post | ].\n all: swap 3 4.\n - (* safeN_0 *)\n now eapply safeN_0; eauto.\n\n - (* safeN_step *)\n eapply safeN_step; eauto.\n now apply InductionHypothesis; auto.\n\n - (* safeN_halted *)\n now eapply safeN_halted; eauto.\n\n - (* safeN_external *)\n destruct c as [ | ef_ args_ lid ve te k ]; [ discriminate | ].\n simpl in E; injection E as -> -> .\n\n (* We need to know which of the externals we are talking about *)\n (* paragraph below: ef has to be an EF_external *)\n assert (Hef : match e with EF_external _ _ => True | _ => False end).\n {\n match goal with x : ext_spec_type _ _ |- _ => clear -x end.\n destruct e eqn:Ee; [ apply I | .. ]; simpl in x;\n repeat match goal with\n _ : context [ oi_eq_dec ?x ?y ] |- _ =>\n destruct (oi_eq_dec x y); try discriminate; try tauto\n end.\n }\n\n assert (Ex : exists name sig, e = EF_external name sig) by (destruct e; eauto; tauto).\n destruct Ex as (name & sg & ->); clear Hef.\n\n Unset Printing Implicit.\n revert x Pre Post.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspec2pre, funspec2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [ H_acquire | notacquire ].\n\n { (* case 1 : acquire *)\n intros [phi_x [ts [[vx shx] Rx]]] [Hargsty Pre] Post.\n simpl in Pre, Post; clear ts.\n destruct oracle as [ | phi_oracle oracle ].\n\n - simpl.\n\n (* this is the x parameter for the WITH clause, but it has the wrong type. *)\n pose (xwith := (phi_x, (False, @nil rmap, vx, shx, Rx))).\n assert ((rmap * (Prop * list rmap * val * share * Pred) =\n @ext_spec_type\n juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))\n )%type as EqT.\n { simpl. unfold ef_sig in *.\n rewrite H_acquire. simpl. if_tac;[ reflexivity | congruence ]. }\n\n (* getting a JMeq-copy of x of the correct type *)\n remember xwith as x2.\n assert (JMeq xwith x2). subst. apply JMeq_refl.\n clear Heqx2.\n revert x2 H.\n pattern (rmap * (Prop * list rmap * val * share * Pred))%type at 1 3.\n cut (\n (fun T : Type =>\n forall x2 : T,\n @JMeq (rmap * (Prop * list rmap * val * share * Pred)) xwith T x2 ->\n @jsafeN (list rmap) (concurrent_oracular_ext_spec cs ext_link) ge (S n) nil\n (Clight_new.ExtCall (EF_external name sg) args lid ve te k) m)\n (@ext_spec_type juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))).\n {\n assert (APP : forall P Q : Prop, P = Q -> P -> Q) by (intros ? ? -> ; auto).\n apply APP.\n rewrite <- EqT.\n reflexivity.\n }\n intros x2 E2.\n\n Set Printing All.\n (* The following is strange, it fails to typecheck even though\n it is provided as a quote from one of the types. *)\n Fail apply safeN_external with\n (e := EF_external name sg)\n (x := x2).\n Fail\n set (qwdq := @ext_spec_type juicy_mem external_function (list rmap)\n (JE_spec (list rmap) (concurrent_oracular_ext_spec cs ext_link))\n acquire_oracular_spec).\n Unset Printing All.\n\n eapply safeN_external with\n (e := EF_external name sg)\n (x := x2).\n + reflexivity.\n + simpl.\n\n revert x2 E2.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n 2:congruence.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n unfold xwith; simpl in Pre |- *. (* done with JMeq.. for this +bullet. *)\n\n destruct Pre as [phi0 [phi1 [Hj [[[? ?] [[? ?] ?]] ?]]]].\n exists phi0, phi1; repeat split; auto.\n\n + intros ret m' z' n' _ (* Hargsty *) Hretty Hn Hr.\n specialize (Post ret m' tt n' Hargsty Hretty Hn Hr).\n\n revert x2 E2.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n 2:congruence. clear e.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n\n intros [phi0 [phi1 [Hj PLS]]].\n destruct PLS as [[[? [FALSE ?]] ?] ?].\n exfalso; tauto.\n\n - simpl.\n\n (* this is the x parameter for the WITH clause, but it has the wrong type. *)\n pose (xwith := (phi_x, (app_pred (Interp Rx) phi_oracle, oracle, vx, shx, Rx))).\n assert ((rmap * (Prop * list rmap * val * share * Pred) =\n @ext_spec_type\n juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))\n )%type as EqT.\n { simpl. unfold ef_sig in *.\n rewrite H_acquire. simpl. if_tac;[ reflexivity | congruence ]. }\n\n (* getting a JMeq-copy of x of the correct type *)\n remember xwith as x2.\n assert (JMeq xwith x2). subst. apply JMeq_refl.\n clear Heqx2.\n revert x2 H.\n pattern (rmap * (Prop * list rmap * val * share * Pred))%type at 1 3.\n cut (\n (fun T : Type =>\n forall x2 : T,\n @JMeq (rmap * (Prop * list rmap * val * share * Pred)) xwith T x2 ->\n @jsafeN (list rmap) (concurrent_oracular_ext_spec cs ext_link) ge (S n) (phi_oracle :: oracle)\n (Clight_new.ExtCall (EF_external name sg) args lid ve te k) m)\n (@ext_spec_type juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))).\n {\n assert (APP : forall P Q : Prop, P = Q -> P -> Q) by (intros ? ? -> ; auto).\n apply APP.\n rewrite <- EqT.\n reflexivity.\n }\n intros x2 E2.\n\n eapply safeN_external with\n (e := EF_external name sg)\n (x := x2).\n + reflexivity.\n + simpl.\n\n revert x2 E2.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n 2:congruence. clear e.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n\n unfold xwith; simpl in Pre |- *.\n\n destruct Pre as [phi0 [phi1 [Hj [[[? ?] [[? ?] ?]] ?]]]].\n exists phi0, phi1; repeat split; auto.\n\n + intros ret m' z' n' _ (* Hargsty *) Hretty Hn Hr.\n specialize (Post ret m' tt n' Hargsty Hretty Hn Hr).\n\n revert x2 E2.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n 2:congruence. clear e.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n\n intros [phi0 [phi1 [Hj [[? [? Sep]] NC]]]].\n destruct Post as [c' [Ae Post]].\n { exists phi0, phi1; repeat split; auto. }\n exists c'; split; [ now auto | ].\n apply InductionHypothesis. omega.\n hnf.\n destruct z_unit. (* only unit (can be replaced with a universal quantification) *)\n apply Post.\n }\n\n unfold JE_spec.\n unfold funspec2jspec, funspec2extspec.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspec2pre, funspec2post, ext_spec_type, ext_spec_pre, ext_spec_post, release_spec.\n simpl.\n if_tac [ H_release | notrelease ].\n { (* case 2: release *)\n intros [phi_x [ts [[vx shx] Rx]]] [Hargsty Pre] Post.\n simpl in Pre, Post; clear ts.\n simpl.\n\n (* this is the x parameter for the WITH clause, but it has the wrong type. *)\n pose (xwith := (phi_x, (oracle, vx, shx, Rx))).\n assert ((rmap * (list rmap * val * share * Pred) =\n @ext_spec_type\n juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))\n )%type as EqT.\n simpl in *.\n { rewrite H_release. simpl. if_tac. congruence. if_tac. reflexivity. congruence. }\n\n (* getting a JMeq-copy of x of the correct type *)\n remember xwith as x2.\n assert (JMeq xwith x2). subst. apply JMeq_refl.\n clear Heqx2.\n revert x2 H.\n simpl OK_ty.\n pattern (rmap * (list rmap * val * share * Pred))%type at 1 3.\n cut (\n (fun T : Type =>\n forall x2 : T,\n @JMeq (rmap * (list rmap * val * share * Pred)) xwith T x2 ->\n @jsafeN (list rmap) (concurrent_oracular_ext_spec cs ext_link) ge (S n) oracle\n (Clight_new.ExtCall (EF_external name sg) args lid ve te k) m)\n (@ext_spec_type juicy_mem external_function (@OK_ty (Concurrent_Oracular_Espec cs ext_link))\n (@OK_spec (Concurrent_Oracular_Espec cs ext_link)) (EF_external name sg))).\n {\n assert (APP : forall P Q : Prop, P = Q -> P -> Q) by (intros ? ? -> ; auto).\n apply APP.\n rewrite <- EqT.\n reflexivity.\n }\n intros x2 E2.\n\n eapply safeN_external with\n (e := EF_external name sg)\n (x := x2).\n + reflexivity.\n + simpl.\n revert x2 E2.\n\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n now congruence.\n simpl (JE_spec _ _).\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e0|e0].\n 2:intros []. clear e.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n\n unfold xwith; simpl in Pre |- *.\n\n destruct Pre as [phi0 [phi1 [Hj [[[? ?] [[? ?] ?]] ?]]]].\n exists phi0, phi1; repeat split; auto.\n\n + intros ret m' z' n' _ (* Hargsty *) Hretty Hn Hr.\n specialize (Post ret m' tt n' Hargsty Hretty Hn Hr).\n\n revert x2 E2.\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e|e].\n now congruence.\n simpl (JE_spec _ _).\n simpl (ext_spec_pre _); simpl (ext_spec_post _); simpl (ext_spec_type _).\n unfold funspecOracle2pre, funspecOracle2post, ext_spec_type, ext_spec_pre, ext_spec_post.\n if_tac [e0|e0].\n 2:intros []. clear e.\n intros x2 E2. apply JMeq_eq in E2. subst x2.\n\n intros [phi0 [phi1 [Hj [[? [? Sep]] NC]]]].\n destruct Post as [c' [Ae Post]].\n { exists phi0, phi1; repeat split; auto. }\n exists c'; split; [ now auto | ].\n apply InductionHypothesis. omega.\n hnf.\n destruct z_unit.\n apply Post.\n }\n\n { (* remaining of cases *)\n intros x; exfalso; tauto.\n }\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/oracular_refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.13916724696049504}} {"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Common.Types.\nRequire Import Common.Bisimulation.\nRequire Import Common.AllDiff.\nRequire Import Bag.Bag2.\nRequire Import FwOF.FwOFSignatures.\nRequire FwOF.FwOFWellFormednessLemmas.\n\nLocal Open Scope list_scope.\nLocal Open Scope bag_scope.\n\nModule Make (Import RelationDefinitions : RELATION_DEFINITIONS) <: RELATION.\n\n Module RelationDefinitions := RelationDefinitions.\n Import AtomsAndController.\n Import Machine.\n Import Atoms.\n Module Import Lemmas := FwOF.FwOFWellFormednessLemmas.Make (RelationDefinitions).\n\n Hint Resolve OfLinksHaveSrc_pres1 OfLinksHaveSrc_pres2 OfLinksHaveSrc_pres3.\n Hint Unfold UniqSwIds.\n Hint Resolve P_entails_FlowTablesSafe step_preserves_P.\n Hint Resolve DevicesFromTopo_pres0 DevicesFromTopo_pres1 SwitchesHaveOpenFlowLinks_pres0\n SwitchesHaveOpenFlowLinks_pres1.\n Hint Resolve LinksHaveSrc_untouched.\n Hint Resolve LinksHaveDst_untouched.\n Hint Resolve FlowTablesSafe_untouched.\n Hint Resolve UniqSwIds_pres.\n Hint Resolve FlowTablesSafe_PacketOut.\n Hint Resolve AllDiff_preservation.\n Hint Resolve NoBarriersInCtrlm_preservation.\n\n Ltac sauto := solve[eauto with datatypes].\n\n Lemma simpl_step : forall (st1 st2 : state) obs\n (tblsOk1 : FlowTablesSafe (switches st1))\n (linksTopoOk1 : ConsistentDataLinks (links st1))\n (haveSrc1 : LinksHaveSrc (switches st1) (links st1))\n (haveDst1 : LinksHaveDst (switches st1) (links st1))\n (uniqSwIds1 : UniqSwIds (switches st1))\n (P0 : P (switches st1) (ofLinks st1) (ctrl st1))\n (uniqOfLinkIds1 : AllDiff of_to (ofLinks st1))\n (ofLinksHaveSw1 : OFLinksHaveSw (switches st1) (ofLinks st1))\n (devsFromTopo1 : DevicesFromTopo st1)\n (swsHaveOFLinks1 : SwitchesHaveOpenFlowLinks (switches st1) (ofLinks st1))\n (noBarriersInCtrlm1 : NoBarriersInCtrlm (switches st1)),\n step st1 obs st2 ->\n exists tblsOk2 linksTopoOk2 haveSrc2 haveDst2 uniqSwIds2 P1\n uniqOfLinkIds2 ofLinksHaveSw2 devsFromTopo2 swsHaveOFLinks2\n noBarriersInCtrlm2,\n concreteStep\n (ConcreteState st1 tblsOk1 linksTopoOk1 haveSrc1 haveDst1 uniqSwIds1\n P0 uniqOfLinkIds1 ofLinksHaveSw1 devsFromTopo1\n swsHaveOFLinks1 noBarriersInCtrlm1)\n obs\n (ConcreteState st2 tblsOk2 linksTopoOk2 haveSrc2 haveDst2 uniqSwIds2\n P1 uniqOfLinkIds2 ofLinksHaveSw2 devsFromTopo2\n swsHaveOFLinks2 noBarriersInCtrlm2).\n Proof with simpl;eauto with datatypes.\n intros.\n unfold concreteStep.\n simpl.\n { inversion H; subst; simpl in *.\n (* Case 1. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 2: processed a buffered FlowMod *)\n + eexists.\n unfold FlowTablesSafe.\n intros.\n apply Bag.in_union in H0. simpl in H0.\n { destruct H0 as [[HIn | HContra] | HIn]; \n [idtac | solve[inversion HContra] | idtac].\n (* interesting case, where the flow table has been modified *)\n - inversion HIn; subst; clear HIn.\n assert (FlowModSafe swId1 tbl0 (({|FlowMod fm|}) <+> ctrlm1)) as J.\n { unfold FlowTablesSafe in tblsOk1.\n eapply tblsOk1.\n apply Bag.in_union. left. simpl... }\n inversion J; subst.\n * assert (NotFlowMod (FlowMod fm)) as Hcontra.\n { apply H0. apply Bag.in_union; simpl... }\n inversion Hcontra.\n * assert (FlowMod fm = FlowMod f /\\ ctrlm1 = ctrlm0) as HEq.\n { eapply Bag.singleton_union_disjoint.\n apply Bag.union_from_ordered in H0...\n intros.\n assert (NotFlowMod (FlowMod fm)) as X...\n inversion X. }\n destruct HEq as [HEq HEq0].\n inversion HEq; subst...\n apply NoFlowModsInBuffer...\n - unfold FlowTablesSafe in tblsOk1.\n eapply tblsOk1.\n apply Bag.in_union... } \n eexists...\n eexists...\n eexists...\n eexists...\n eexists...\n eexists...\n eexists...\n eexists. sauto.\n eexists. sauto.\n eexists.\n { unfold NoBarriersInCtrlm in *.\n intros.\n apply Bag.in_union in H0; simpl in H0.\n destruct H0 as [[H0|H0]|H0].\n + refine (noBarriersInCtrlm1 (Switch swId0 pts0 tbl0 inp0 outp0 (({|FlowMod fm|}) <+> ctrlm0) switchm0) _ _ _).\n - apply Bag.in_union. simpl...\n - apply Bag.in_union.\n rewrite <- H0 in H1.\n simpl in H1.\n right...\n + inversion H0.\n + refine (noBarriersInCtrlm1 sw _ _ _)...\n apply Bag.in_union... }\n sauto.\n (* Case 4. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. \n { unfold NoBarriersInCtrlm in *.\n intros.\n apply Bag.in_union in H0; simpl in H0.\n destruct H0 as [[H0|H0]|H0].\n + refine (noBarriersInCtrlm1 (Switch swId0 pts0 tbl0 inp0 outp0 (({|PacketOut pt pk|}) <+> ctrlm0) switchm0) _ _ _).\n - apply Bag.in_union. simpl...\n - apply Bag.in_union.\n rewrite <- H0 in H1.\n simpl in H1.\n right...\n + inversion H0.\n + refine (noBarriersInCtrlm1 sw _ _ _)...\n apply Bag.in_union... }\n sauto.\n (* Case 5. *)\n + eexists. sauto.\n exists (LinkTopoOK_inv pks0 (pk::pks0) linksTopoOk1).\n exists (LinksHaveSrc_inv pks0 (pk::pks0) (LinksHaveSrc_untouched haveSrc1)).\n exists (LinksHaveDst_inv pks0 (pk::pks0) (LinksHaveDst_untouched haveDst1)).\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 6. *)\n + eexists. sauto.\n exists (LinkTopoOK_inv (pks0 ++ [pk]) pks0 linksTopoOk1).\n exists \n (LinksHaveSrc_inv (pks0 ++ [pk]) pks0 (LinksHaveSrc_untouched haveSrc1)).\n exists \n (LinksHaveDst_inv (pks0 ++ [pk]) pks0 (LinksHaveDst_untouched haveDst1)).\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 7. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 8. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. \n { eapply AllDiff_preservation.\n exact uniqOfLinkIds1.\n do 2 rewrite -> map_app... }\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 9. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists.\n { eapply AllDiff_preservation.\n exact uniqOfLinkIds1.\n do 2 rewrite -> map_app... }\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 10. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists.\n { eapply AllDiff_preservation.\n exact uniqOfLinkIds1.\n do 2 rewrite -> map_app... }\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n (* Case 11. *)\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists.\n { eapply AllDiff_preservation.\n exact uniqOfLinkIds1.\n do 2 rewrite -> map_app... }\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n sauto.\n + eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists.\n { eapply AllDiff_preservation.\n exact uniqOfLinkIds1.\n do 2 rewrite -> map_app... }\n eexists. sauto.\n eexists. sauto.\n eexists. sauto.\n eexists. \n { unfold NoBarriersInCtrlm in *.\n intros.\n apply Bag.in_union in H1; simpl in H1.\n destruct H1 as [[H1|H1]|H1].\n + rewrite <- H1 in H2.\n simpl in H2.\n apply Bag.in_union in H2. simpl in H2.\n destruct H2 as [[H2|H2]|H2].\n * subst. exact H0.\n * inversion H2.\n * refine (noBarriersInCtrlm1 (Switch swId0 pts0 tbl0 inp0 outp0 ctrlm0 switchm0) _ _ _).\n apply Bag.in_union. simpl...\n simpl... \n + inversion H1.\n + refine (noBarriersInCtrlm1 sw _ _ _)...\n apply Bag.in_union... }\n sauto.\n (* epic fail of a proof script *)\n Grab Existential Variables. \n eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n eauto. eauto. eauto. eauto. eauto. eauto. eauto. \n eauto. eauto. \n }\n Qed.\n\n Lemma simpl_multistep' : forall (st1 st2 : state) obs\n (tblsOk1 : FlowTablesSafe (switches st1))\n (linksTopoOk1 : ConsistentDataLinks (links st1))\n (haveSrc1 : LinksHaveSrc (switches st1) (links st1))\n (haveDst1 : LinksHaveDst (switches st1) (links st1))\n (uniqSwIds1 : UniqSwIds (switches st1))\n (P1 : P (switches st1) (ofLinks st1) (ctrl st1))\n (uniqOfLinkIds1 : AllDiff of_to (ofLinks st1))\n (ofLinksHaveSw1 : OFLinksHaveSw (switches st1) (ofLinks st1))\n (devsFromTopo1 : DevicesFromTopo st1)\n (swsHaveOFLinks1 : SwitchesHaveOpenFlowLinks (switches st1) (ofLinks st1))\n (noBarriersInCtrlm1 : NoBarriersInCtrlm (switches st1)),\n multistep step st1 obs st2 ->\n exists tblsOk2 linksTopoOk2 haveSrc2 haveDst2 uniqSwIds2 P2\n uniqOfLinkIds2 ofLinksHaveSw2 devsFromTopo2 swsHaveOFLinks2\n noBarriersInCtrlm2,\n multistep concreteStep\n (ConcreteState st1 tblsOk1 linksTopoOk1 haveSrc1 haveDst1 \n uniqSwIds1 P1 uniqOfLinkIds1\n ofLinksHaveSw1 devsFromTopo1 swsHaveOFLinks1\n noBarriersInCtrlm1)\n obs\n (ConcreteState st2 tblsOk2 linksTopoOk2 haveSrc2 haveDst2 \n uniqSwIds2 P2 uniqOfLinkIds2\n ofLinksHaveSw2 devsFromTopo2 swsHaveOFLinks2\n noBarriersInCtrlm2).\n Proof with eauto with datatypes.\n intros.\n induction H.\n (* zero steps. *)\n + solve [ eauto 13 ].\n (* tau step *)\n + destruct (simpl_step tblsOk1 linksTopoOk1 haveSrc1 haveDst1 \n uniqSwIds1 P1 uniqOfLinkIds1 ofLinksHaveSw1\n devsFromTopo1 swsHaveOFLinks1\n noBarriersInCtrlm1\n H)\n as [tblsOk2 [linksTopoOk2 [haveSrc2 [haveDst2 [uniqSwIds2 \n [P2 [uniqOfLinkIds2 [ofLinksHaveSw2 \n [devsFromTopo2 [swsHaveOFLinks2 \n [noBarriersInCtrlm2 step]]]]]]]]]]].\n destruct (IHmultistep tblsOk2 linksTopoOk2 haveSrc2 haveDst2 \n uniqSwIds2 P2 uniqOfLinkIds2 ofLinksHaveSw2\n devsFromTopo2 swsHaveOFLinks2 noBarriersInCtrlm2)\n as [tblsOk3 [linksTopoOk3 [haveSrc3 [haveDst3\n [uniqSwIds3 [PN [uniqOfLinkIdsN [ofLinksHaveSwN \n [devsFromTopoN [swsHaveOFLinksN [noBarriersInCtrlmN stepN]]]]]]]]]]].\n solve [ eauto 13 ].\n (* The script below is an identical copy of the case above. *)\n + destruct (simpl_step tblsOk1 linksTopoOk1 haveSrc1 haveDst1 \n uniqSwIds1 P1 uniqOfLinkIds1 ofLinksHaveSw1\n devsFromTopo1 swsHaveOFLinks1\n noBarriersInCtrlm1\n H)\n as [tblsOk2 [linksTopoOk2 [haveSrc2 [haveDst2 [uniqSwIds2 \n [P2 [uniqOfLinkIds2 [ofLinksHaveSw2 \n [devsFromTopo2 [swsHaveOFLinks2 \n [noBarriersInCtrlm2 step]]]]]]]]]]].\n destruct (IHmultistep tblsOk2 linksTopoOk2 haveSrc2 haveDst2 \n uniqSwIds2 P2 uniqOfLinkIds2 ofLinksHaveSw2\n devsFromTopo2 swsHaveOFLinks2 noBarriersInCtrlm2)\n as [tblsOk3 [linksTopoOk3 [haveSrc3 [haveDst3\n [uniqSwIds3 [PN [uniqOfLinkIdsN [ofLinksHaveSwN \n [devsFromTopoN [swsHaveOFLinksN [noBarriersInCtrlmN stepN]]]]]]]]]]].\n solve [ eauto 13 ].\n Qed.\n\n Lemma simpl_multistep : forall (st1 : concreteState) (devs2 : state) obs,\n multistep step (devices st1) obs devs2 ->\n exists (st2 : concreteState),\n devices st2 = devs2 /\\\n multistep concreteStep st1 obs st2.\n Proof with simpl;auto.\n intros.\n destruct st1.\n destruct (simpl_multistep' concreteState_flowTableSafety0\n concreteState_consistentDataLinks0 linksHaveSrc0 linksHaveDst0\n uniqSwIds0 ctrlP0 uniqOfLinkIds0 ofLinksHaveSw0 devicesFromTopo0\n swsHaveOFLinks0 noBarriersInCtrlm0 H) as [v0 [v1 [v2 [v3 [v4 [v5 [v6 [v7 [v8 [v9 [v10 Hstep]]]]]]]]]]].\n exists (ConcreteState devs2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10)...\n Qed.\n\n Lemma relate_step_simpl_tau : forall st1 st2,\n concreteStep st1 None st2 ->\n relate (devices st1) = relate (devices st2).\n Proof with eauto with datatypes.\n intros.\n inversion H; subst.\n (* Case 2. *)\n idtac \"Proving relate_step_simpl_tau (Case 2 of 11)...\".\n destruct st1. destruct st2. subst. unfold relate. simpl.\n autorewrite with bag using simpl.\n bag_perm 100.\n (* 3. PacketOut case. *)\n idtac \"Proving relate_step_simpl_tau (Case 3 of 11)...\".\n destruct st1. destruct st2. subst. unfold relate. simpl.\n autorewrite with bag using simpl.\n bag_perm 100.\n (* 4. SendDataLink case. *)\n idtac \"Proving relate_step_simpl_tau (Case 4 of 11)...\".\n destruct st1. destruct st2. subst. unfold relate. simpl.\n autorewrite with bag using simpl.\n destruct dst0.\n rewrite -> Bag.from_list_cons.\n assert (topo (src (DataLink (swId0, pt) pks0 (s,p))) =\n Some (dst (DataLink (swId0, pt) pks0 (s,p)))) as Jtopo.\n {\n unfold ConsistentDataLinks in concreteState_consistentDataLinks0.\n apply concreteState_consistentDataLinks0.\n simpl in H1.\n rewrite <- H1.\n simpl... }\n simpl in Jtopo.\n rewrite -> Jtopo.\n bag_perm 100.\n (* 5. RecvDataLink case. *)\n idtac \"Proving relate_step_simpl_tau (Case 5 of 11)...\".\n destruct st1. destruct st2. subst. unfold relate. simpl.\n autorewrite with bag using simpl.\n bag_perm 100.\n (* 6. Controller steps *)\n idtac \"Proving relate_step_simpl_tau (Case 6 of 11)...\".\n unfold relate.\n simpl.\n rewrite -> (ControllerRemembersPackets H2).\n reflexivity.\n (* 7. Controller receives. *)\n idtac \"Proving relate_step_simpl_tau (Case 7 of 11)...\".\n unfold relate.\n simpl.\n repeat rewrite -> map_app.\n simpl.\n repeat rewrite -> unions_app.\n autorewrite with bag using simpl.\n rewrite -> (ControllerRecvRemembersPackets H2).\n bag_perm 100.\n (* 8. Controller sends *)\n idtac \"Proving relate_step_simpl_tau (Case 8 of 11)...\".\n unfold relate.\n simpl.\n repeat rewrite -> map_app.\n simpl.\n repeat rewrite -> unions_app.\n autorewrite with bag using simpl.\n rewrite -> (ControllerSendForgetsPackets H2).\n bag_perm 100.\n (* 9. Switch sends to controller *)\n idtac \"Proving relate_step_simpl_tau (Case 9 of 11)...\".\n unfold relate.\n simpl.\n repeat rewrite -> map_app.\n simpl.\n repeat rewrite -> unions_app.\n autorewrite with bag using simpl.\n bag_perm 100.\n (* 10. Switch receives a barrier. *)\n idtac \"Proving relate_step_simpl_tau (Case 10 of 11)...\".\n unfold relate.\n simpl.\n repeat rewrite -> map_app.\n simpl.\n repeat rewrite -> unions_app.\n autorewrite with bag using simpl.\n bag_perm 100.\n (* 11. Switch receives a non-barrier. *)\n idtac \"Proving relate_step_simpl_tau (Case 11 of 11)...\".\n unfold relate.\n simpl.\n repeat rewrite -> map_app.\n simpl.\n repeat rewrite -> unions_app.\n autorewrite with bag using simpl.\n bag_perm 100.\n Qed.\n\n Lemma relate_multistep_simpl_tau : forall st1 st2,\n multistep concreteStep st1 nil st2 ->\n relate (devices st1) = relate (devices st2).\n Proof with eauto.\n intros.\n remember nil.\n induction H...\n + apply relate_step_simpl_tau in H.\n rewrite -> H...\n + inversion Heql.\n Qed.\n\n Lemma relate_step_simpl_obs : forall sw pt pk lps st1 st2,\n relate (devices st1) = ({| (sw,pt,pk) |} <+> lps) ->\n concreteStep st1 (Some (sw,pt,pk)) st2 ->\n relate (devices st2) = \n (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps).\n Proof with eauto with datatypes.\n intros.\n inversion H0.\n destruct st1.\n destruct st2.\n destruct devices0.\n destruct devices1.\n subst.\n simpl in *.\n inversion H1; subst; clear H1.\n inversion H6; subst; clear H6.\n assert (FlowTableSafe sw tbl0) as Z.\n { assert (FlowModSafe sw tbl0 ctrlm0) as Z.\n { unfold FlowTablesSafe in concreteState_flowTableSafety0.\n eapply concreteState_flowTableSafety0...\n apply Bag.in_union; simpl... }\n unfold FlowTableSafe in Z.\n inversion Z... }\n remember (Z pt pk outp' pksToCtrl H3) as Y eqn:X. clear X Z.\n rewrite <- Y. clear Y.\n\n unfold relate in *.\n simpl in *.\n autorewrite with bag using simpl.\n apply (Bag.pop_union_r _ ({|(sw,pt,pk)|})).\n repeat rewrite -> Bag.union_assoc.\n rewrite -> (Bag.union_comm _ lps).\n rewrite <- H.\n simpl.\n autorewrite with bag using simpl.\n bag_perm 100.\n Qed.\n\n Lemma relate_multistep_simpl_obs : forall sw pt pk lps st1 st2,\n relate (devices st1) = ({| (sw,pt,pk) |} <+> lps) ->\n multistep concreteStep st1 [(sw,pt,pk)] st2 ->\n relate (devices st2) = \n (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps).\n Proof with eauto.\n intros.\n remember [(sw,pt,pk)] as obs.\n induction H0; subst.\n inversion Heqobs.\n apply IHmultistep...\n apply relate_step_simpl_tau in H0.\n symmetry in H0.\n rewrite -> H0...\n destruct obs; inversion Heqobs.\n subst.\n clear Heqobs.\n apply relate_multistep_simpl_tau in H1.\n apply relate_step_simpl_obs with (lps := lps) in H0 .\n rewrite <- H0.\n symmetry...\n trivial.\n Qed.\n\n Lemma simpl_weak_sim : forall st1 devs2 sw pt pk lps,\n multistep step (devices st1) [(sw,pt,pk)] devs2 ->\n relate (devices st1) = ({| (sw,pt,pk) |} <+> lps) ->\n abstractStep\n ({| (sw,pt,pk) |} <+> lps)\n (Some (sw,pt,pk))\n (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps) ->\n exists st2 : concreteState,\n inverse_relation \n bisim_relation\n (unions (map (transfer sw) (abst_func sw pt pk)) <+> lps)\n st2 /\\\n multistep concreteStep st1 [(sw,pt,pk)] st2.\n Proof with eauto.\n intros.\n destruct (simpl_multistep st1 H) as [st2 [Heq Hmultistep]]. \n assert (relate (devices st1) = ({| (sw,pt,pk) |} <+> lps)) as Hrel.\n subst. simpl...\n exists st2.\n split.\n unfold inverse_relation.\n unfold bisim_relation.\n symmetry...\n exact (relate_multistep_simpl_obs Hrel Hmultistep).\n trivial.\n Qed.\n\nEnd Make.\n", "meta": {"author": "frenetic-lang", "repo": "featherweight-openflow", "sha": "4470518794e3ed867919d30500be2d0128b1de1c", "save_path": "github-repos/coq/frenetic-lang-featherweight-openflow", "path": "github-repos/coq/frenetic-lang-featherweight-openflow/featherweight-openflow-4470518794e3ed867919d30500be2d0128b1de1c/coq/FwOF/FwOFWellFormedness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.13912372902014838}} {"text": "Require Export CalculusSM_tacs.\n\n\nSection CalculusSM_derived.\n\n Context { pd : @Data }.\n Context { pn : @Node }.\n Context { pk : @Key }.\n Context { pm : @Msg }.\n Context { qc : @Quorum_context pn}.\n Context { pat : @AuthTok }.\n Context { paf : @AuthFun pn pk pat pd }.\n Context { pda : @DataAuth pd pn }.\n Context { cad : @ContainedAuthData pd pat pm }.\n Context { dtc : @DTimeContext }.\n Context { iot : @IOTrustedFun }.\n Context { ctp : @ComponentTrust pd pn pat qc iot }.\n Context { cap : @ComponentAuth pd pn pk pat pm dtc iot }.\n\n Local Open Scope eo.\n Local Open Scope proc.\n\n\n Context { base_fun_io : baseFunIO }.\n Context { base_state_fun : baseStateFun }.\n Context { trusted_state_fun : trustedStateFun }.\n Context { pkc : KnowledgeComponents }.\n\n Local Open Scope kn.\n\n\n\n (************************************************************************************************)\n Definition DERIVED_RULE_KLD_implies_or_owns {eo : EventOrdering} e R H d :=\n MkRule1\n (fun e' =>\n [⟬R⟭ H ⊢ ASSUMPTION_knew_or_learns_or_gen d @ e'])\n (⟬R⟭ H ⊢ ASSUMPTION_learns_or_owns d @ e).\n\n Lemma DERIVED_RULE_KLD_implies_or_owns_true :\n forall {eo : EventOrdering} e R H d,\n rule_true (DERIVED_RULE_KLD_implies_or_owns e R H d).\n Proof.\n start_proving_derived st.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (ASSUMPTION_knows_implies_learned_or_gen d @ e)).\n { LOCKapply DERIVED_RULE_KLD_implies_or_true; inst_hyp e0 w. }\n\n LOCKintro1 \"y\".\n LOCKelim \"x\"; try LOCKauto.\n\n LOCKelim \"x\".\n { LOCKintro 0; try LOCKauto. }\n\n LOCKintro 1.\n LOCKapply@ \"x\" (DERIVED_RULE_unlocal_before_eq_hyp_true \"u\").\n LOCKelim \"x\" \"z\".\n LOCKapply@ \"u\" DERIVED_RULE_owns_change_localle_true; try LOCKauto.\n Qed.\n\n\n (***********************************************************)\n Definition DERIVED_RULE_owns_dec {eo : EventOrdering} e d R H :=\n MkRule0\n []\n (⟬R⟭ H ⊢ KE_OR (KE_OWNS d) (KE_NOT (KE_OWNS d)) @ e).\n\n Lemma DERIVED_RULE_owns_dec_true :\n forall {eo : EventOrdering} e d R H,\n rule_true (DERIVED_RULE_owns_dec e d R H).\n Proof.\n start_proving_derived st.\n destruct (implies_ex_node e) as [n cond].\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (KE_OR (KE_HAS_OWNER d n) (KE_NOT (KE_HAS_OWNER d n)) @ e)).\n { LOCKapply PRIMITIVE_RULE_has_owner_dec_true. }\n LOCKelim \"x\".\n { LOCKintro 0.\n LOCKapply (PRIMITIVE_RULE_exists_node_intro_true n).\n LOCKintro; try LOCKauto. }\n LOCKintro 1.\n LOCKintro \"o\".\n LOCKelim \"x\"; try LOCKauto.\n LOCKapply@ \"o\" PRIMITIVE_RULE_exists_node_elim_true.\n LOCKapply@ \"o\" (PRIMITIVE_RULE_and_elim_true \"o\" \"x\").\n LOCKapply (PRIMITIVE_RULE_subst_node_in_has_owner_true n0); try LOCKauto.\n LOCKapply (PRIMITIVE_RULE_cut_true \"a\" (KE_AT n @ e)); try LOCKauto.\n LOCKapply PRIMITIVE_RULE_at_implies_same_node_true; try LOCKauto.\n Qed.\n\n\n (***************************************************************************)\n Definition DERIVED_RULE_disseminate_if_learned_and_disseminated\n p a {eo : EventOrdering} e R H d :=\n MkRule1\n (fun e' =>\n [⟬R⟭ H ⊢ ASSUMPTION_disseminate_if_knows d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_knew_or_learns_or_gen d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_learns_if_gen d @ e',\n ⟬R⟭ H ⊢ KE_AT a @ e,\n ⟬R⟭ H ⊢ KE_DISS d @ e,\n ⟬R⟭ H ⊢ KE_HAS_OWNER d p @ e,\n ⟬R⟭ H ⊢ KE_NOT (KE_NODE_EQ p a) @ e])\n (⟬R⟭ H ⊢ KE_HAPPENED_BEFORE (KE_DISS_OWN d) @ e).\n\n Lemma DERIVED_RULE_disseminate_if_learned_and_disseminated_true :\n forall p a {eo : EventOrdering} (e : EventN) R H (d : kc_data),\n rule_true(DERIVED_RULE_disseminate_if_learned_and_disseminated p a e R H d).\n Proof.\n start_proving_derived st.\n inst_hyp e w.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"ass\" (ASSUMPTION_learned_if_gen d @ e)).\n { LOCKapply DERIVED_RULE_implies_learned_if_gen_true; inst_hyp e0 q. }\n\n LOCKelim \"ass\"; try LOCKauto.\n LOCKapply (DERIVED_RULE_knows_and_not_owns_implies_learns2_true p a).\n { LOCKapply DERIVED_RULE_KLD_implies_or_owns_true; inst_hyp e0 w. }\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"ass\" (ASSUMPTION_disseminate_if_knows d @ e)).\n\n LOCKelim \"ass\"; try LOCKauto.\n LOCKintro; try LOCKauto.\n Qed.\n\n\n (***************************************************************************)\n Definition ASSUMPTION_disseminate_if_knows_trusted (d : kc_data) : KExpression :=\n KE_IMPLIES\n (KE_ANDS\n [KE_DISS d,\n KE_NODE,\n KE_LOCAL_CORRECT_TRACE_BEFORE])\n (KE_EX_TRUST\n (fun t =>\n KE_AND\n (KE_TKNOWS t)\n (KE_GEN_FOR d t))).\n\n Definition ASSUMPTION_trusted_learned_if_gen (t : kc_trust) :=\n KE_IMPLIES\n (KE_TLEARNED t)\n (KE_HAPPENED_BEFORE (KE_TDISS_OWN t)).\n\n\n (***************************************************************************)\n Definition DERIVED_RULE_disseminate_if_learned_and_disseminated2\n {eo : EventOrdering} e R H d :=\n MkRule1\n (fun e' =>\n [⟬R⟭ H ⊢ KE_ALL_DATA ASSUMPTION_disseminate_if_knows_trusted @ e',\n ⟬R⟭ H ⊢ KE_ALL_DATA ASSUMPTION_knew_or_learns_or_gen @ e',\n ⟬R⟭ H ⊢ KE_ALL_TRUST ASSUMPTION_trusted_learns_if_gen @ e',\n ⟬R⟭ H ⊢ KE_LOCAL_CORRECT_TRACE_BEFORE @ e,\n ⟬R⟭ H ⊢ KE_DISS d @ e])\n (⟬R⟭ H ⊢ KE_EX_TRUST (fun t =>\n KE_ANDS\n [KE_GEN_FOR d t,\n KE_TKNOWS t,\n KE_OR\n (KE_HAPPENED_BEFORE (KE_TDISS_OWN t))\n (KE_TOWNS t)]) @ e).\n\n Lemma DERIVED_RULE_disseminate_if_learned_and_disseminated2_true :\n forall {eo : EventOrdering} (e : EventN) R H (d : kc_data),\n rule_true (DERIVED_RULE_disseminate_if_learned_and_disseminated2 e R H d).\n Proof.\n start_proving_derived st.\n inst_hyp e w.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"ass\" (KE_ALL_DATA ASSUMPTION_disseminate_if_knows_trusted @ e)).\n LOCKapply@ \"ass\" (PRIMITIVE_RULE_all_data_elim_true \"ass\" d).\n LOCKelim \"ass\"; repeat LOCKintro; try LOCKauto.\n LOCKapply@ \"ass\" PRIMITIVE_RULE_exists_trust_elim_true.\n LOCKelim \"ass\" \"kn\".\n LOCKapply (PRIMITIVE_RULE_exists_trust_intro_true t).\n repeat LOCKintro; try LOCKauto.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"o\" (KE_OR (KE_TOWNS t) (KE_NOT (KE_TOWNS t)) @ e)).\n { LOCKapply DERIVED_RULE_owns_dec_true. }\n\n LOCKelim \"o\".\n { LOCKintro 1; try LOCKauto. }\n LOCKintro 0.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"lrn\" (KE_TLEARNED t @ e)).\n { LOCKapply DERIVED_RULE_knows_and_not_owns_implies_learns_true; try LOCKauto.\n LOCKapply DERIVED_RULE_KLD_implies_or_owns_true.\n inst_hyp e0 z.\n repeat LOCKclear.\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (KE_ALL_DATA ASSUMPTION_knew_or_learns_or_gen @ e0)).\n LOCKapply@ \"x\" (PRIMITIVE_RULE_all_data_elim_true \"x\" (kc_trust2data t)); LOCKauto. }\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"lid\" (ASSUMPTION_trusted_learned_if_gen t @ e)).\n { repeat LOCKclear.\n LOCKapply DERIVED_RULE_implies_learned_if_gen_true.\n inst_hyp e0 z.\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (KE_ALL_TRUST ASSUMPTION_trusted_learns_if_gen @ e0)).\n LOCKapply@ \"x\" (PRIMITIVE_RULE_all_trust_elim_true \"x\" t); LOCKauto. }\n\n LOCKelim \"lid\"; try LOCKauto.\n Qed.\n\n\n (***************************************************************************)\n Definition DERIVED_RULE_knows_if_learned_and_disseminated\n p a {eo : EventOrdering} e R H d :=\n MkRule1\n (fun e' =>\n [⟬R⟭ H ⊢ ASSUMPTION_disseminate_if_knows d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_knew_or_learns_or_gen d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_learns_if_gen d @ e',\n ⟬R⟭ H ⊢ KE_AT a @ e,\n ⟬R⟭ H ⊢ KE_DISS d @ e,\n ⟬R⟭ H ⊢ KE_HAS_OWNER d p @ e,\n ⟬R⟭ H ⊢ KE_NOT (KE_NODE_EQ p a) @ e])\n (⟬R⟭ H ⊢ KE_HAPPENED_BEFORE (KE_KNOWS_OWN d) @ e).\n\n Lemma DERIVED_RULE_knows_if_learned_and_disseminated_true :\n forall p a {eo : EventOrdering} (e : EventN) R H (d : kc_data),\n rule_true (DERIVED_RULE_knows_if_learned_and_disseminated p a e R H d).\n Proof.\n start_proving_derived st.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (KE_HAPPENED_BEFORE (KE_DISS_OWN d) @ e)).\n { LOCKapply (DERIVED_RULE_disseminate_if_learned_and_disseminated_true p a); inst_hyp e0 q. }\n LOCKapply@ \"x\" (PRIMITIVE_RULE_unhappened_before_hyp_true \"u\").\n LOCKapply@ \"u\" PRIMITIVE_RULE_unhappened_before_if_causal_true.\n LOCKelim \"x\" \"y\".\n\n LOCKintro; try LOCKauto.\n\n LOCKapply (PRIMITIVE_RULE_cut_true \"ass\" (ASSUMPTION_disseminate_if_knows d @ e0)).\n { inst_hyp e0 h.\n LOCKclear \"x\".\n LOCKclear \"y\".\n LOCKclear \"u\". }\n\n LOCKelim \"ass\"; try LOCKauto.\n LOCKintro; try LOCKauto.\n Qed.\n\n\n (***************************************************************************)\n Definition DERIVED_RULE_knows_if_learned_and_disseminated2\n p {eo : EventOrdering} e R H d :=\n MkRule1\n (fun e' =>\n [⟬R⟭ H ⊢ ASSUMPTION_disseminate_if_knows d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_knew_or_learns_or_gen d @ e',\n ⟬R⟭ H ⊢ ASSUMPTION_learns_if_gen d @ e',\n ⟬R⟭ H ⊢ KE_DISS d @ e,\n ⟬R⟭ H ⊢ KE_HAS_OWNER d p @ e])\n (⟬R⟭ H ⊢ KE_HAPPENED_BEFORE_EQ (KE_KNOWS_OWN d) @ e).\n\n Lemma DERIVED_RULE_knows_if_learned_and_disseminated2_true :\n forall p {eo : EventOrdering} (e : EventN) R H (d : kc_data),\n rule_true (DERIVED_RULE_knows_if_learned_and_disseminated2 p e R H d).\n Proof.\n start_proving_derived st.\n LOCKapply (PRIMITIVE_RULE_cut_true \"y\" (KE_OR (KE_OWNS d) (KE_NOT (KE_OWNS d)) @ e)).\n { LOCKapply DERIVED_RULE_owns_dec_true. }\n LOCKelim \"y\".\n { LOCKintro 1; try LOCKintro; try LOCKauto.\n LOCKintro; try LOCKauto.\n LOCKapply (PRIMITIVE_RULE_cut_true \"x\" (ASSUMPTION_disseminate_if_knows d @ e)).\n { LOCKclear \"y\"; inst_hyp e h. }\n LOCKelim \"x\"; try LOCKauto.\n LOCKintro; try LOCKauto.\n LOCKclear \"y\"; inst_hyp e h. }\n\n destruct (implies_ex_node e) as [n cond].\n\n LOCKintro 0.\n LOCKapply (DERIVED_RULE_knows_if_learned_and_disseminated_true p n); try LOCKauto;\n try (complete (LOCKclear \"y\"; inst_hyp e0 h)).\n LOCKintro \"o\".\n LOCKelim \"y\"; try LOCKauto.\n LOCKapply (PRIMITIVE_RULE_exists_node_intro_true n); try LOCKintro; try LOCKauto.\n LOCKapply (PRIMITIVE_RULE_subst_node_in_has_owner_true p); try LOCKauto.\n LOCKclear \"o\"; inst_hyp e h.\n Qed.\n\nEnd CalculusSM_derived.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/model/CalculusSM_derived.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.1386715540035824}} {"text": "(* *********************************************************************)\n(* *)\n(* The Compcert verified compiler *)\n(* *)\n(* Xavier Leroy, INRIA Paris-Rocquencourt *)\n(* *)\n(* Copyright Institut National de Recherche en Informatique et en *)\n(* Automatique. All rights reserved. This file is distributed *)\n(* under the terms of the INRIA Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n\n(** Type system for the Mach intermediate language. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import Mach.\n\n(** * Typing rules *)\n\nInductive wt_instr : instruction -> Prop :=\n | wt_Mlabel:\n forall lbl,\n wt_instr (Mlabel lbl)\n | wt_Mgetstack:\n forall ofs ty r,\n mreg_type r = ty ->\n wt_instr (Mgetstack ofs ty r)\n | wt_Msetstack:\n forall ofs ty r,\n mreg_type r = ty ->\n wt_instr (Msetstack r ofs ty)\n | wt_Mgetparam:\n forall ofs ty r,\n mreg_type r = ty ->\n wt_instr (Mgetparam ofs ty r)\n | wt_Mopmove:\n forall r1 r,\n mreg_type r1 = mreg_type r ->\n wt_instr (Mop Omove (r1 :: nil) r)\n | wt_Mop:\n forall op args res,\n op <> Omove ->\n (List.map mreg_type args, mreg_type res) = type_of_operation op ->\n wt_instr (Mop op args res)\n | wt_Mload:\n forall chunk addr args dst,\n List.map mreg_type args = type_of_addressing addr ->\n mreg_type dst = type_of_chunk chunk ->\n wt_instr (Mload chunk addr args dst)\n | wt_Mstore:\n forall chunk addr args src,\n List.map mreg_type args = type_of_addressing addr ->\n mreg_type src = type_of_chunk chunk ->\n wt_instr (Mstore chunk addr args src)\n | wt_Mcall:\n forall sig ros,\n match ros with inl r => mreg_type r = Tint | inr s => True end ->\n wt_instr (Mcall sig ros)\n | wt_Mtailcall:\n forall sig ros,\n tailcall_possible sig ->\n match ros with inl r => mreg_type r = Tint | inr s => True end ->\n wt_instr (Mtailcall sig ros)\n | wt_Mbuiltin:\n forall ef args res,\n List.map mreg_type args = (ef_sig ef).(sig_args) ->\n mreg_type res = proj_sig_res (ef_sig ef) ->\n wt_instr (Mbuiltin ef args res)\n | wt_Mannot:\n forall ef args,\n ef_reloads ef = false ->\n wt_instr (Mannot ef args)\n | wt_Mgoto:\n forall lbl,\n wt_instr (Mgoto lbl)\n | wt_Mcond:\n forall cond args lbl,\n List.map mreg_type args = type_of_condition cond ->\n wt_instr (Mcond cond args lbl)\n | wt_Mjumptable:\n forall arg tbl,\n mreg_type arg = Tint ->\n list_length_z tbl * 4 <= Int.max_unsigned ->\n wt_instr (Mjumptable arg tbl)\n | wt_Mreturn: \n wt_instr Mreturn.\n\nRecord wt_function (f: function) : Prop := mk_wt_function {\n wt_function_instrs:\n forall instr, In instr f.(fn_code) -> wt_instr instr;\n wt_function_stacksize:\n 0 <= f.(fn_stacksize) <= Int.max_unsigned\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n | wt_fundef_external: forall ef,\n wt_fundef (External ef)\n | wt_function_internal: forall f,\n wt_function f ->\n wt_fundef (Internal f).\n\nDefinition wt_program (p: program) : Prop :=\n forall i f, In (i, f) (prog_funct p) -> wt_fundef f.\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/backend/Machtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.13863956852546505}} {"text": "Require Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import EquivDec.\nRequire Import RelationClasses.\nRequire Import Bool.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingIR Require Import Time.\nFrom PromisingIR Require Import View.\nFrom PromisingIR Require Import BoolMap.\nFrom PromisingIR Require Import Promises.\nFrom PromisingIR Require Import Cell.\nFrom PromisingIR Require Import Memory.\nFrom PromisingIR Require Import TView.\nFrom PromisingIR Require Import Global.\nFrom PromisingIR Require Import Local.\nFrom PromisingIR Require Import Thread.\nFrom PromisingIR Require Import Configuration.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\n\nRequire Import PromisingArch.promising.Promising.\nRequire Import PromisingArch.mapping.RMWLang.\nRequire Import PromisingArch.mapping.RMWPromising.\nRequire Import PromisingArch.mapping.PSLang.\nRequire Import PromisingArch.mapping.PStoRMWUtils.\nRequire Import PromisingArch.mapping.PStoRMWDef.\n\nSet Implicit Arguments.\n\n\nModule PStoRMWThread.\n Variant sim_val: forall (val_ps: Const.t) (val_arm: Val.t), Prop :=\n | sim_val_num\n v:\n sim_val (Const.num v) v\n (* | sim_val_undef *)\n (* v: *)\n (* sim_val Const.undef v *)\n .\n #[export] Hint Constructors sim_val: core.\n\n Definition sim_regs (regs_ps: RegFile.t) (regs_arm: RMap.t (A:=View.t (A:=unit))): Prop :=\n forall r, sim_val (IdentFun.find r regs_ps) (RMap.find r regs_arm).(ValA.val).\n\n Variant sim_program_event: forall (e_ps: ProgramEvent.t) (e_arm: RMWEvent.t (A:=View.t (A:=unit))), Prop :=\n | sim_program_event_internal:\n sim_program_event ProgramEvent.silent RMWEvent.internal\n | sim_program_event_control\n ctrl:\n sim_program_event ProgramEvent.silent (RMWEvent.control ctrl)\n | sim_program_event_read\n loc_ps val_ps ord_ps\n ord_arm loc_arm val_arm\n (LOC: loc_arm.(ValA.val) = Zpos loc_ps)\n (VAL: sim_val val_ps val_arm.(ValA.val))\n (ORD: ord_arm = ps_to_rmw_ordr ord_ps)\n :\n sim_program_event (ProgramEvent.read loc_ps val_ps ord_ps)\n (RMWEvent.read ord_arm loc_arm val_arm)\n | sim_program_event_write\n loc_ps val_ps ord_ps\n ord_arm loc_arm val_arm\n (LOC: loc_arm.(ValA.val) = Zpos loc_ps)\n (VAL: sim_val val_ps val_arm.(ValA.val))\n (ORD: ord_arm = ps_to_rmw_ordw ord_ps)\n :\n sim_program_event (ProgramEvent.write loc_ps val_ps ord_ps)\n (RMWEvent.write ord_arm loc_arm val_arm)\n | sim_program_event_fadd\n loc_ps vold_ps vnew_ps ordr_ps ordw_ps\n ordr_arm ordw_arm loc_arm vold_arm vnew_arm\n (LOC: loc_arm.(ValA.val) = Zpos loc_ps)\n (VOLD: sim_val vold_ps vold_arm.(ValA.val))\n (VNEW: sim_val vnew_ps vnew_arm.(ValA.val))\n (ORDR: ordr_arm = ps_to_rmw_ordr ordr_ps)\n (ORDW: ordw_arm = ps_to_rmw_ordw ordw_ps)\n :\n sim_program_event (ProgramEvent.update loc_ps vold_ps vnew_ps ordr_ps ordw_ps)\n (RMWEvent.fadd ordr_arm ordw_arm loc_arm vold_arm vnew_arm)\n | sim_program_event_dmb\n ordr_ps ordw_ps\n rr rw wr ww\n (RR: rr = Ordering.le Ordering.acqrel ordr_ps || Ordering.le Ordering.seqcst ordw_ps)\n (RW: rw = Ordering.le Ordering.acqrel ordr_ps || Ordering.le Ordering.acqrel ordw_ps)\n (WR: wr = Ordering.le Ordering.seqcst ordw_ps)\n (WW: ww = Ordering.le Ordering.acqrel ordw_ps):\n sim_program_event (ProgramEvent.fence ordr_ps ordw_ps)\n (RMWEvent.dmb rr rw wr ww)\n .\n #[export] Hint Constructors sim_program_event: core.\n\n Variant sim_state (st_ps: State.t) (st_arm: RMWState.t (A:=View.t (A:=unit))): Prop :=\n | sim_state_intro\n (STMTS: RMWState.stmts st_arm = ps_to_rmw_stmts (State.stmts st_ps))\n (REGS: sim_regs st_ps.(State.regs) st_arm.(RMWState.rmap))\n .\n #[export] Hint Constructors sim_state: core.\n\n Variant sim_tview (tview: PSTView.t) (lc_arm: Local.t (A:=unit)): Prop :=\n | sim_tview_intro\n (REL: forall loc loc',\n PSTime.le\n ((tview.(PSTView.rel) loc).(View.rlx) loc')\n (ntt (View.ts (join lc_arm.(Local.vwn) (lc_arm.(Local.coh) (Zpos loc))))))\n (CUR: forall loc,\n PSTime.le\n (tview.(PSTView.cur).(View.rlx) loc)\n (ntt (View.ts (join lc_arm.(Local.vrn) (lc_arm.(Local.coh) (Zpos loc))))))\n (ACQ: forall loc,\n PSTime.le\n (tview.(PSTView.acq).(View.rlx) loc)\n (ntt (View.ts (join (join lc_arm.(Local.vrn) lc_arm.(Local.vro)) (lc_arm.(Local.coh) (Zpos loc))))))\n (VNEW: le lc_arm.(Local.vrn) lc_arm.(Local.vwn))\n .\n #[export] Hint Constructors sim_tview: core.\n\n Variant sim_memory (tid: Ident.t) (n: Time.t)\n (lc_ps: PSLocal.t) (gprm_ps: BoolMap.t) (mem_ps: PSMemory.t)\n (lc_arm: Local.t (A:=unit)) (mem_arm: Memory.t): Prop :=\n | sim_memory_intro\n (PRM_SOUND: forall ts (PROMISED_ARM: Promises.lookup ts lc_arm.(Local.promises)),\n exists msg_arm loc_ps from,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (< lc_ps.(PSLocal.promises) loc_ps = true>>))\n (PRM_COMPLETE: forall loc (PROMISED_PS: lc_ps.(PSLocal.promises) loc = true),\n exists ts msg_arm,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>))\n (MEM_SOUND: forall ts msg_arm\n (GET_ARM: Memory.get_msg ts mem_arm = Some msg_arm),\n exists loc_ps from msg_ps,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (__guard__ (\n (<>) \\/\n exists fts fval ftid,\n (<>) /\\\n (<>) /\\\n (<>))) /\\\n (__guard__ (\n (<>) /\\\n (< msg_arm.(Msg.tid) = tid>>) /\\\n (<\n (<>) /\\\n (< msg_arm.(Msg.tid) = tid>>)>>) \\/\n exists val_ps released na,\n (<>) /\\\n (<>) /\\\n (<>))))\n (MEM_COMPLETE: forall loc_ps from to msg_ps\n (TO: PSTime.lt PSTime.bot to)\n (GET_PS: PSMemory.get loc_ps to mem_ps = Some (from, msg_ps)),\n exists ts msg_arm,\n (<>) /\\\n (<>) /\\\n (<>))\n (FWD: forall loc loc_ps ts\n (LOC: loc = Zpos loc_ps)\n (FWD: (lc_arm.(Local.fwdbank) loc).(FwdItem.ts) = ts),\n exists from val released na,\n (<>) /\\\n (<>) /\\\n (<>))\n (RELEASED: forall loc from to val released na\n (GET: PSMemory.get loc to mem_ps = Some (from, Message.message val released na)),\n forall loc', PSTime.le ((View.unwrap released).(View.rlx) loc') to)\n .\n\n Variant sim_thread (tid: Ident.t) (n: Time.t)\n (th_ps: PSThread.t lang_ps) (eu: RMWExecUnit.t (A:=unit)): Prop :=\n | sim_thread_intro\n (SIM_STATE: sim_state (PSThread.state th_ps) (RMWExecUnit.state eu))\n (SIM_TVIEW: sim_tview (PSLocal.tview (PSThread.local th_ps)) (RMWExecUnit.local eu))\n (SIM_MEM: sim_memory tid n\n (PSThread.local th_ps)\n (PSGlobal.promises (PSThread.global th_ps))\n (PSGlobal.memory (PSThread.global th_ps))\n (RMWExecUnit.local eu) (RMWExecUnit.mem eu))\n .\n\n Lemma sim_val_eq_inv\n val1 val2 val_arm\n (VAL1: sim_val val1 val_arm)\n (VAL2: sim_val val2 val_arm):\n val1 = val2.\n Proof.\n inv VAL1. inv VAL2. ss.\n Qed.\n\n Lemma sim_regs_eval_expr\n regs_ps regs_arm e\n (SIM: sim_regs regs_ps regs_arm):\n sim_val (RegFile.eval_expr regs_ps e) (sem_expr regs_arm (ps_to_rmw_expr e)).(ValA.val).\n Proof.\n induction e; ss.\n - destruct op. ss.\n inv IHe; ss. condtac; econs.\n - destruct op; inv IHe1; inv IHe2; ss.\n Qed.\n\n Lemma sim_regs_add\n regs_ps regs_arm\n r val_ps (val_arm: ValA.t (A:=View.t (A:=unit)))\n (SIM: sim_regs regs_ps regs_arm)\n (VAL: sim_val val_ps val_arm.(ValA.val)):\n sim_regs (IdentFun.add r val_ps regs_ps)\n (RMap.add r val_arm regs_arm).\n Proof.\n ii. rewrite IdentFun.add_spec, RMap.add_o.\n condtac; ss; subst.\n - condtac; ss. congr.\n - condtac; ss.\n Qed.\n\n Lemma sim_state_step\n st1_ps st1_arm e_arm st2_arm\n (SIM1: sim_state st1_ps st1_arm)\n (STEP: RMWState.step e_arm st1_arm st2_arm):\n exists e_ps st2_ps,\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n destruct st1_ps as [regs1_ps stmts1_ps].\n destruct st1_arm as [stmts1_arm regs1_arm].\n destruct st2_arm as [stmts2_arm regs2_arm].\n inv SIM1. ss.\n destruct stmts1_ps; ss; subst; [inv STEP|].\n destruct t; ss; cycle 1.\n { (* ite *)\n inv STEP. condtac.\n - esplits; [econs 2|..]; ss.\n + des_ifs.\n exploit sim_regs_eval_expr; eauto.\n rewrite Heq. ii. inv x0. congr.\n + econs; ss. rewrite <- List.map_app. ss.\n - esplits; [econs 3|..]; ss.\n + des_ifs.\n exploit sim_regs_eval_expr; eauto.\n rewrite Heq. ii. inv x0. congr.\n + econs; ss. rewrite <- List.map_app. ss.\n }\n { (* dowhile *)\n inv STEP. esplits; [econs 4|..]; ss.\n econs; ss. unfold ps_to_rmw_stmts.\n rewrite List.map_app. ss.\n }\n\n destruct i; ss; inv STEP.\n { (* skip *)\n esplits; [econs 1; econs 1|..]; ss.\n }\n { (* assign *)\n esplits; [econs 1; econs 2|..]; ss.\n econs; ss.\n apply sim_regs_add; ss.\n apply sim_regs_eval_expr; ss.\n }\n { (* load *)\n esplits; [econs 1; econs 3|..]; eauto.\n econs; ss.\n apply sim_regs_add; ss.\n }\n { (* store *)\n esplits; [econs 1; econs 4|..]; eauto.\n econs; ss.\n apply sim_regs_eval_expr; ss.\n }\n { (* fadd *)\n esplits; [econs 1; econs 5|..]; eauto.\n - econs; ss. s.\n exploit sim_regs_eval_expr; eauto. i.\n inv x0. rewrite <- H0. ss.\n - econs; ss.\n apply sim_regs_add; ss.\n }\n { (* dmb *)\n esplits; [econs 1; econs 6|..]; eauto.\n }\n Qed.\n\n Lemma sim_tview_le\n tview lc1_arm lc2_arm\n (SIM: sim_tview tview lc1_arm)\n (LE: Local.le lc1_arm lc2_arm)\n (VNEW2: le lc2_arm.(Local.vrn) lc2_arm.(Local.vwn)):\n sim_tview tview lc2_arm.\n Proof.\n inv SIM. econs; ss; i.\n - etrans; eauto. apply le_ntt.\n eapply join_le; try apply Time.order; try apply LE.\n - etrans; eauto. apply le_ntt.\n eapply join_le; try apply Time.order; try apply LE.\n - etrans; eauto. apply le_ntt.\n repeat eapply join_le; try apply Time.order; try apply LE.\n Qed.\n\n Lemma sim_memory_latest_le\n tid n lc_ps gprm_ps mem_ps prm_ps mem_arm\n ts loc loc_ps view val ts_ps\n (SIM: sim_memory tid n lc_ps gprm_ps mem_ps prm_ps mem_arm)\n (LOC: loc = Zpos loc_ps)\n (LATEST: Memory.latest loc ts view mem_arm)\n (READ: Memory.read loc ts mem_arm = Some val)\n (LE: PSTime.le ts_ps (ntt view))\n (CLOSED: exists from msg,\n PSMemory.get loc_ps ts_ps mem_ps = Some (from, msg)):\n PSTime.le ts_ps (ntt ts).\n Proof.\n des. destruct (TimeFacts.le_lt_dec ts_ps PSTime.bot).\n { etrans; eauto. apply PSTime.bot_spec. }\n destruct (TimeFacts.le_lt_dec ts_ps (ntt ts)); ss.\n inv SIM. exploit MEM_COMPLETE; eauto. i. des. subst.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE RELEASED.\n unfold Memory.get_msg in *. destruct ts0; ss.\n exploit LATEST; try exact GET_ARM; ss.\n - apply ntt_lt. ss.\n - apply ntt_le. ss.\n Qed.\n\n Lemma sim_tview_readable\n tid n lc_ps gprm_ps mem_ps lc_arm mem_arm\n loc loc_ps ts view_pre val\n ord\n (TVIEW: sim_tview lc_ps.(PSLocal.tview) lc_arm)\n (MEM: sim_memory tid n lc_ps gprm_ps mem_ps lc_arm mem_arm)\n (TVIEW_WF: TView.wf lc_ps.(PSLocal.tview))\n (TVIEW_CLOSED: TView.closed lc_ps.(PSLocal.tview) mem_ps)\n (LOC: loc = Zpos loc_ps)\n (VIEW_PRE: le lc_arm.(Local.vrn) view_pre)\n (LATEST_COH: Memory.latest loc ts (lc_arm.(Local.coh) loc).(View.ts) mem_arm)\n (LATEST_PRE: Memory.latest loc ts view_pre.(View.ts) mem_arm)\n (READ: Memory.read loc ts mem_arm = Some val):\n PSTView.readable (PSTView.cur lc_ps.(PSLocal.tview)) loc_ps (ntt ts) ord.\n Proof.\n cut (PSTime.le (View.rlx (PSTView.cur (PSLocal.tview lc_ps)) loc_ps) (ntt ts)).\n { i. econs; ss. etrans; eauto. apply TVIEW_WF. }\n inv TVIEW. clear REL ACQ.\n specialize (CUR loc_ps). ss.\n eapply sim_memory_latest_le; try exact CUR; eauto.\n - apply Memory.latest_join; ss.\n eapply Memory.latest_mon2; try exact LATEST_PRE. apply VIEW_PRE.\n - inv TVIEW_CLOSED. inv CUR0. specialize (RLX loc_ps). des. eauto.\n Qed.\n\n Lemma sim_memory_read\n tid n lc_ps gprm_ps mem_ps lc_arm mem_arm\n loc loc_ps ts ord val_arm\n (MEM: sim_memory tid n lc_ps gprm_ps mem_ps lc_arm mem_arm)\n (INHABITED: PSMemory.inhabited mem_ps)\n (LE: le (FwdItem.read_view (Local.fwdbank lc_arm loc) ts ord).(View.ts) n)\n (LOC: loc = Zpos loc_ps)\n (READ: Memory.read loc ts mem_arm = Some val_arm):\n (<>) \\/\n (<>) /\\\n (<>) \\/\n exists from val released na,\n (<>) /\\\n (<>) /\\\n (<\n if (lc_arm.(Local.fwdbank) loc).(FwdItem.ex)\n then forall loc, PSTime.le\n ((PSView.unwrap released).(View.rlx) loc)\n (ntt (View.ts (join (join lc_arm.(Local.vrn) lc_arm.(Local.vro))\n (lc_arm.(Local.coh) (Zpos loc)))))\n else PSView.le (View.unwrap released) (lc_ps.(PSLocal.tview).(PSTView.rel) loc_ps)>>).\n Proof.\n unfold Memory.read in *. destruct ts; ss.\n { inv READ. right. right. esplits; eauto.\n condtac; ss; i.\n - apply PSTime.bot_spec.\n - apply PSView.bot_spec.\n }\n revert READ.\n destruct (List.nth_error mem_arm ts) eqn:Heq; ss.\n condtac; ss. destruct t. ss. r in e. i. inv READ. clear X.\n inv MEM. exploit MEM_SOUND; eauto.\n { instantiate (2:=S ts). eauto. }\n s. i. des. inv LOC.\n revert LE. unfold FwdItem.read_view. condtac; ss; i.\n - right. right.\n apply andb_prop in X. des.\n revert X. unfold proj_sumbool.\n condtac; ss. i. r in e.\n exploit FWD; try exact e; eauto. i. des. ss.\n rewrite GET_PS in *. inv GET_PS0.\n esplits; try exact GET_PS0; ss.\n unguardH x0. des; ss. inv MSG. ss.\n - unguardH x0. des; subst.\n + exploit PROMISED; ss. i. des.\n destruct (Id.eq_dec tid0 tid); subst; auto.\n right. left. splits; ss.\n destruct (PSLocal.promises lc_ps loc_ps0) eqn:Y; ss.\n exploit PROMISED_PS; ss.\n + right. right. esplits; eauto. i.\n exploit FWD; eauto. s. i. des.\n rewrite GET_PS0 in *. inv GET_PS. ss.\n Qed.\n\n Lemma wf_arm_fwd\n tid mem_arm\n ts loc ord lc_arm\n (WF: RMWLocal.wf (A:=unit) tid lc_arm mem_arm):\n ts <= View.ts (Local.coh lc_arm loc) \\/\n ts <= View.ts (FwdItem.read_view (Local.fwdbank lc_arm loc) ts ord).\n Proof.\n inv WF. clear - FWD.\n unfold FwdItem.read_view. condtac; ss.\n - left. apply andb_prop in X. des.\n destruct (FwdItem.ts (Local.fwdbank lc_arm loc) == ts); ss.\n etrans; [|apply FWD].\n rewrite e. ss.\n - right. ss.\n Qed.\n\n Lemma sim_read\n tid n\n lc1_ps gl1_ps\n ord loc\n ex ord_arm (vloc: ValA.t (A:=View.t (A:=unit))) res ts lc1_arm mem_arm lc2_arm\n (TVIEW1: sim_tview (PSLocal.tview lc1_ps) lc1_arm)\n (MEM1: sim_memory tid n lc1_ps (Global.promises gl1_ps) (Global.memory gl1_ps) lc1_arm mem_arm)\n (LC_WF1_PS: PSLocal.wf lc1_ps gl1_ps)\n (GL_WF1_PS: PSGlobal.wf gl1_ps)\n (WF1_ARM: RMWLocal.wf tid lc1_arm mem_arm)\n (ORD: ord_arm = ps_to_rmw_ordr ord)\n (LOC: vloc.(ValA.val) = Zpos loc)\n (VRO: le lc2_arm.(Local.vro).(View.ts) n)\n (STEP: Local.read ex ord_arm vloc res ts lc1_arm mem_arm lc2_arm):\n (<>) \\/\n (exists val released lc2_ps,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>)) \\/\n (exists val,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>)).\n Proof.\n exploit (Local.read_incr (A:=unit)); eauto. i.\n inv STEP.\n exploit sim_memory_read; eauto; try apply GL_WF1_PS.\n { ss. etrans; try exact VRO. ets. }\n i. des; auto.\n { (* race with a promise *)\n ss. right. right.\n esplits; eauto.\n - eapply sim_tview_le; try exact TVIEW1; ss; i.\n eapply join_le; try apply View.order; try refl. apply TVIEW1.\n - econs; s; try apply MEM1. i.\n guardH FWD.\n dup MEM1. inv MEM0.\n exploit FWD0; try exact FWD; eauto.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD0 RELEASED.\n unguardH FWD. i. des.\n esplits; eauto. condtac; ss. i.\n etrans; [apply REL_FWD|]. apply le_ntt.\n eapply join_le; [apply Time.order|..].\n + eapply join_le; try apply Time.order.\n + unfold fun_add. condtac; ets. ss.\n rewrite e. ss. ets.\n }\n\n { (* normal read *)\n exploit sim_tview_readable; try exact LATEST; eauto; try apply LC_WF1_PS.\n { apply joins_le. right. left. ss. }\n ss. i. des.\n right. left. esplits.\n { econs; eauto; try refl. }\n { ss. }\n\n { econs; s; i.\n { (* rel view *)\n etrans; [apply TVIEW1|]. apply le_ntt. ss.\n eapply join_le; try apply Time.order. apply x0.\n }\n\n { (* cur view *)\n repeat apply PSTime.join_spec.\n { etrans; [apply TVIEW1|]. apply le_ntt. ss.\n eapply join_le; try apply Time.order. apply x0.\n }\n { replace (View.rlx (View.singleton_ur_if (Ordering.le Ordering.relaxed ord) loc (ntt ts)) loc0)\n with (TimeMap.singleton loc (ntt ts) loc0); cycle 1.\n { unfold View.singleton_ur_if. condtac; ss. }\n unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n unfold fun_add. condtac; ss; try apply PSTime.bot_spec.\n subst. rewrite LOC. condtac; ss; try congr. apply le_ntt.\n etrans; [|apply join_r].\n exploit (wf_arm_fwd ts); eauto. i. des; ets.\n }\n { condtac; ss; try apply PSTime.bot_spec.\n unfold FwdItem.read_view. condtac; ss.\n - apply andb_prop in X0. des.\n revert X0. unfold proj_sumbool. condtac; ss. r in e. i. clear X2.\n rewrite negb_true_iff in X1.\n exploit REL_FWD; ss. condtac; i.\n + rewrite andb_true_l in X1.\n apply orb_false_elim in X1. des.\n destruct ord; ss.\n + etrans; [apply x2|].\n etrans; [apply LC_WF1_PS|].\n etrans; [apply TVIEW1|].\n apply le_ntt. ss.\n eapply join_le; try apply Time.order.\n unfold fun_add. condtac; ss.\n rewrite e0. apply join_l.\n - unfold ifc. repeat (condtac; try by destruct ord; ss).\n inv MEM1. exploit RELEASED; eauto. i.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED.\n etrans; try apply x2. apply le_ntt. ets.\n }\n }\n\n { (* acq view *)\n repeat apply PSTime.join_spec.\n { etrans; [apply TVIEW1|]. apply le_ntt. ss.\n eapply join_le; [apply Time.order|..]; try apply x0.\n eapply join_le; try apply Time.order.\n }\n { replace (View.rlx (View.singleton_ur_if (Ordering.le Ordering.relaxed ord) loc (ntt ts)) loc0)\n with (TimeMap.singleton loc (ntt ts) loc0); cycle 1.\n { unfold View.singleton_ur_if. condtac; ss. }\n unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n unfold fun_add. condtac; ss; try apply PSTime.bot_spec.\n subst. rewrite LOC. condtac; ss; try congr. apply le_ntt.\n etrans; [|apply join_r].\n exploit (wf_arm_fwd ts); eauto. i. des.\n - etrans; [|apply join_l]. apply x2.\n - etrans; [|apply join_r]. etrans; [|apply join_r]. apply x2.\n }\n { condtac; ss; try apply PSTime.bot_spec.\n unfold FwdItem.read_view. condtac; ss.\n - apply andb_prop in X0. des.\n revert X0. unfold proj_sumbool. condtac; ss. r in e. i. clear X2.\n rewrite negb_true_iff in X1.\n exploit REL_FWD; ss. condtac; i.\n + etrans; [apply x2|]. apply le_ntt.\n eapply join_le; [apply Time.order|..].\n * eapply join_le; try apply Time.order.\n * unfold fun_add. condtac; ss.\n rewrite e0. apply join_l.\n + etrans; [apply x2|].\n etrans; [apply LC_WF1_PS|].\n etrans; [apply LC_WF1_PS|].\n etrans; [apply TVIEW1|].\n apply le_ntt. ss.\n eapply join_le; [apply Time.order|..].\n * eapply join_le; apply Time.order.\n * unfold fun_add. condtac; ss.\n rewrite e0. apply join_l.\n - unfold ifc. repeat (condtac; try by destruct ord; ss).\n + inv MEM1. exploit RELEASED; eauto. i.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED.\n etrans; try apply x2. apply le_ntt. ets.\n + inv MEM1. exploit RELEASED; eauto. i.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED.\n etrans; try apply x2. apply le_ntt. ets.\n }\n }\n\n { (* VNEW *)\n eapply join_le; try apply View.order; try refl. apply TVIEW1.\n }\n }\n\n { inv MEM1. econs; s; eauto. i.\n exploit FWD; eauto. i. des.\n esplits; eauto.\n - etrans; try exact CUR.\n unfold TimeMap.join.\n etrans; [|apply PSTime.join_l].\n apply PSTime.join_l.\n - condtac; ss. i.\n etrans; eauto. i. apply le_ntt.\n eapply join_le; [apply Time.order|..].\n + eapply join_le; try apply Time.order.\n + unfold fun_add. condtac; ss. rewrite e. ets.\n }\n }\n Qed.\n\n Lemma sim_tview_writable\n tview lc_arm\n loc loc_ps ts view_pre\n ord\n (TVIEW: sim_tview tview lc_arm)\n (LOC: loc = Zpos loc_ps)\n (VIEW_PRE: le lc_arm.(Local.vwn) view_pre)\n (COH: lt (lc_arm.(Local.coh) loc).(View.ts) ts)\n (EXT: lt view_pre.(View.ts) ts):\n PSTView.writable (PSTView.cur tview) loc_ps (ntt ts) ord.\n Proof.\n subst. econs.\n eapply TimeFacts.le_lt_lt; [apply TVIEW|].\n apply lt_ntt. ss.\n apply Time.max_lub_lt; ss.\n eapply Time.le_lt_trans; try exact EXT.\n etrans; [|apply VIEW_PRE].\n apply TVIEW.\n Qed.\n\n Lemma sim_fulfill\n tid n\n lc1_ps gl1_ps\n ord loc\n (ex: bool) ord_arm (vloc: ValA.t (A:=View.t (A:=unit))) vval res ts view_pre lc1_arm mem_arm lc2_arm\n releasedm\n (TVIEW1: sim_tview (PSLocal.tview lc1_ps) lc1_arm)\n (MEM1: sim_memory tid n lc1_ps (Global.promises gl1_ps) (Global.memory gl1_ps) lc1_arm mem_arm)\n (LC_WF1_PS: PSLocal.wf lc1_ps gl1_ps)\n (GL_WF1_PS: PSGlobal.wf gl1_ps)\n (WF1_ARM: RMWLocal.wf tid lc1_arm mem_arm)\n (ORD: ord_arm = ps_to_rmw_ordw ord)\n (ORD_NA: le ts n -> Ordering.le ord Ordering.na)\n (LOC: vloc.(ValA.val) = Zpos loc)\n (RELEASEDM_WF: View.opt_wf releasedm)\n (RELEASEDM1: if ex\n then forall loc, PSTime.le\n ((PSView.unwrap releasedm).(View.rlx) loc)\n (ntt (View.ts (join (join lc1_arm.(Local.vrn) lc1_arm.(Local.vro))\n (lc1_arm.(Local.coh) (Zpos loc)))))\n else releasedm = None)\n (RELEASEDM2: forall loc', PSTime.le ((View.unwrap releasedm).(View.rlx) loc') (ntt ts))\n (STEP: Local.fulfill ex ord_arm vloc vval res ts tid view_pre lc1_arm mem_arm lc2_arm):\n exists from lc2_ps gl2_ps,\n (<>) /\\\n exists released lc3_ps gl3_ps,\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n exploit (Local.fulfill_incr (A:=unit)); eauto. intro INCR.\n inv STEP. dup MEM1. inv MEM0.\n exploit MEM_SOUND; eauto. s. i. des.\n rewrite LOC in LOC0. symmetry in LOC0. inv LOC0.\n unguardH x0. des; try congr. subst.\n exploit PRM_SOUND; eauto. s. i. des.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED TID.\n rewrite MSG in *. inv GET_ARM. ss.\n rewrite LOC in LOC0. symmetry in LOC0. inv LOC0.\n dup LC_WF1_PS. inv LC_WF1_PS0.\n exploit RESERVES; eauto. i.\n rewrite GET_PS in x0. symmetry in x0. inv x0.\n clear TVIEW_WF TVIEW_CLOSED PROMISES PROMISES_FINITE RESERVES RESERVES_ONLY RESERVES_FINITE.\n exploit PSMemory.remove_exists; try exact RESERVED. i. des.\n rename mem2 into rsv2.\n exploit PSMemory.remove_exists; try exact GET_PS. i. des.\n destruct lc1_ps as [tview1 prm1 rsv1].\n destruct gl1_ps as [sc1 gprm1 mem1]. ss.\n do 3 eexists. split; [eauto|]. s.\n\n exploit (@PSMemory.add_exists\n mem2 loc from (ntt ts)\n (Message.message (ValA.val vval) (TView.write_released tview1 loc (ntt ts) releasedm ord) (Ordering.le ord Ordering.na))); ss.\n { i. revert GET2. erewrite Memory.remove_o; eauto.\n condtac; ss. guardH o. i.\n exploit PSMemory.remove_get0; try exact x2. i. des.\n exploit PSMemory.get_disjoint; [exact GET|exact GET2|]. i. des; ss.\n subst. unguard. des; ss.\n }\n { econs.\n exploit TViewFacts.write_future0; try apply LC_WF1_PS; try exact RELEASEDM_WF. s. i. des.\n apply WF_RELEASED.\n }\n i. des.\n\n assert (exists prm2 gprm2,\n (<>) /\\\n (<\n exists ts' msg_arm,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>))>>)).\n { destruct (prm1 loc) eqn:GETP; cycle 1.\n { esplits; [econs 1; eauto|].\n split; i; try congr. des.\n apply Promises.unset_le in H0.\n inv MEM1. exploit PRM_SOUND; try exact H0; try eassumption. s. i. des.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE RELEASED.\n rewrite GET_ARM in *. inv H1.\n rewrite LOC0 in *. inv H2. auto.\n }\n destruct (classic (\n exists ts' msg_arm,\n le ts' n /\\\n Promises.lookup ts' (Promises.unset ts (Local.promises lc1_arm)) /\\\n Memory.get_msg ts' mem_arm = Some msg_arm /\\\n msg_arm.(Msg.loc) = Zpos loc)).\n - des. esplits; [econs 1; eauto|].\n split; i; ss. esplits; eauto.\n - exploit BoolMap.remove_exists; try exact GETP. i. des.\n exploit BoolMap.remove_exists; try eapply LC_WF1_PS; try exact GETP. s. i. des.\n esplits; [econs 2; eauto|].\n + apply ORD_NA. destruct (le_lt_dec ts n); ss. exfalso.\n inv MEM1. exploit PRM_COMPLETE; eauto. i. des.\n apply H. esplits; try exact LE; eauto.\n rewrite Promises.unset_o. condtac; ss.\n inversion e. subst.\n exploit Nat.le_lt_trans; try apply LE; try exact l. nia.\n + split; i; try congr.\n exploit BoolMap.remove_get0; try exact x4. i. des. congr.\n }\n des.\n\n esplits.\n { (* step *)\n econs; try exact FULFILL; eauto.\n inv WRITABLE.\n eapply sim_tview_writable; [..|exact COH|exact EXT]; eauto.\n apply joins_le. right. right. right. left. ss.\n }\n\n { (* sim_tview *)\n s. clear x1 PROMISED PROMISED_PS rsv2 x0 mem2 x2 mem0 x3 prm2 gprm2 FULFILL PROMISED0.\n inv WRITABLE. econs; s; try apply TVIEW1; i.\n { unfold LocFun.add. condtac; ss; cycle 1.\n { etrans; [apply TVIEW1|]. apply le_ntt. ss.\n eapply join_le; try apply Time.order; try refl. apply INCR.\n }\n subst. unfold fun_add. rewrite LOC.\n do 2 (condtac; ss; try congr).\n - rewrite ntt_join. etrans; [|eapply PSTime.join_r].\n apply PSTime.join_spec.\n + etrans; [apply TVIEW1|].\n apply le_ntt. ss. apply join_spec.\n * etrans; try apply TVIEW1.\n etrans; [|apply Nat.lt_le_incl; exact EXT].\n do 3 (etrans; [|apply join_r]). apply join_l.\n * etrans; [apply WF1_ARM|].\n etrans; [|apply Nat.lt_le_incl; exact EXT].\n unfold ifc. do 2 (condtac; try by (destruct ord; ss)).\n do 4 (etrans; [|apply join_r]). ss.\n eapply join_le; try apply Time.order. refl.\n + unfold TimeMap.singleton, LocFun.add.\n condtac; try refl. apply PSTime.bot_spec.\n - apply PSTime.join_spec.\n + etrans; [apply TVIEW1|]. apply le_ntt. ss.\n apply join_spec; try apply join_l.\n rewrite LOC in *.\n etrans; [apply Nat.lt_le_incl; apply COH|].\n apply join_r.\n + rewrite ntt_join. etrans; [|apply PSTime.join_r].\n unfold TimeMap.singleton, LocFun.add.\n condtac; try refl. apply PSTime.bot_spec.\n }\n\n { rewrite ntt_join. apply PSTime.join_spec.\n - etrans; [apply TVIEW1|]. s. rewrite ntt_join.\n apply PSTime.join_spec; [apply PSTime.join_l|].\n rewrite <- ntt_join. apply le_ntt.\n etrans; [|apply join_r]. apply INCR.\n - unfold TimeMap.singleton, LocFun.add.\n condtac; try apply PSTime.bot_spec.\n subst. unfold fun_add. rewrite LOC. condtac; try congr. s.\n apply PSTime.join_r.\n }\n { rewrite ntt_join. apply PSTime.join_spec.\n - etrans; [apply TVIEW1|]. s. rewrite ntt_join.\n apply PSTime.join_spec; [apply PSTime.join_l|].\n rewrite <- ntt_join. apply le_ntt.\n etrans; [|apply join_r]. apply INCR.\n - unfold TimeMap.singleton, LocFun.add.\n condtac; try apply PSTime.bot_spec.\n subst. unfold fun_add. rewrite LOC. condtac; try congr. s.\n apply PSTime.join_r.\n }\n }\n\n { (* sim_memory *)\n s. clear INCR. inv MEM1. econs; s; i.\n { (* PRM_SOUND *)\n revert PROMISED_ARM1.\n rewrite Promises.unset_o. condtac; ss. i.\n exploit PRM_SOUND; try exact PROMISED_ARM1. i. des.\n esplits; try eassumption.\n - erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n des. clear X0. apply ntt_inj in a0. subst. congr.\n - i. exploit PROMISED_PS0; try eassumption. i.\n inv FULFILL; ss.\n erewrite BoolMap.remove_o; try eassumption. condtac; ss. subst.\n inv PROMISED0. exploit H1.\n { esplits; try exact H; eauto.\n rewrite Promises.unset_o. condtac; ss.\n }\n i. exploit BoolMap.remove_get0; try exact REMOVE. i. des. congr.\n }\n { (* PRM_COMPLETE *)\n destruct (PSLoc.eq_dec loc0 loc).\n { subst. inv PROMISED0. eauto. }\n exploit (PRM_COMPLETE loc0).\n { inv FULFILL; ss. revert PROMISED_PS0.\n erewrite BoolMap.remove_o; eauto. condtac; ss.\n }\n i. des. esplits; eauto.\n erewrite Promises.unset_o. condtac; ss. inversion e. subst.\n rewrite GET_ARM in *. inv MSG. ss.\n rewrite LOC in *. inv LOC0. ss.\n }\n\n { (* MEM_SOUND *)\n destruct (Nat.eq_dec ts0 ts); subst.\n - rewrite GET_ARM in *. inv MSG.\n exploit PSMemory.add_get0; try exact x3. i. des.\n esplits; try exact GET0; ss.\n right. esplits; ss.\n rewrite Promises.unset_o. condtac; ss. congr.\n - exploit MEM_SOUND; eauto. i. des.\n exploit Memory.remove_get1; try exact GET_PS0; eauto. i. des.\n { apply ntt_inj in x8. congr. }\n exploit Memory.add_get1; try exact x6; eauto. i.\n esplits; eauto. unguardH x4. des; subst.\n + left. splits; ss.\n { erewrite Promises.unset_o. condtac; ss. }\n i. exploit PROMISED1; eauto. i. des.\n inv FULFILL; auto.\n erewrite (@BoolMap.remove_o prm2); try eassumption.\n erewrite (@BoolMap.remove_o gprm2); try eassumption.\n condtac; subst.\n { exploit BoolMap.remove_get0; try exact REMOVE. i. des.\n move PROMISED0 at bottom. inv PROMISED0.\n exploit H1; try congr.\n esplits; try exact H; eauto.\n rewrite Promises.unset_o. condtac; ss. auto.\n }\n splits; auto.\n + right. esplits; eauto.\n rewrite Promises.unset_o. condtac; ss.\n }\n\n { (* MEM_COMPLETE *)\n revert GET_PS0.\n erewrite PSMemory.add_o; eauto. condtac; ss.\n - i. des. inv GET_PS0. esplits; eauto.\n - erewrite Memory.remove_o; eauto. condtac; ss. eauto.\n }\n\n { (* FWD *)\n revert FWD0. unfold fun_add. condtac; ss.\n - i. r in e. clear X. subst.\n rewrite LOC in e. inv e.\n exploit PSMemory.add_get0; try exact x3. i. des.\n esplits; try exact GET0.\n { unfold TimeMap.join, TimeMap.singleton, LocFun.add.\n condtac; ss. apply PSTime.join_r.\n }\n condtac.\n + i. unfold TView.write_released.\n condtac; try apply PSTime.bot_spec. ss.\n apply PSTime.join_spec.\n * etrans; try apply RELEASEDM1. apply le_ntt.\n eapply join_le; [apply Time.order|..]; try refl.\n condtac; ss. rewrite e. inv WRITABLE. nia.\n * unfold LocFun.add. condtac; ss.\n condtac; ss; apply PSTime.join_spec.\n { etrans; [apply LC_WF1_PS|].\n etrans; [apply TVIEW1|].\n apply le_ntt. s.\n eapply join_le; [apply Time.order|..]; try refl.\n condtac; ss. rewrite e0. inv WRITABLE. nia.\n }\n { unfold TimeMap.singleton, LocFun.add, LocFun.init.\n condtac; try apply PSTime.bot_spec. subst.\n rewrite LOC. condtac; ss; try congr.\n apply le_ntt. ets.\n }\n { etrans; [apply LC_WF1_PS|]. s.\n etrans; [apply LC_WF1_PS|]. s.\n etrans; [apply TVIEW1|]. apply le_ntt. s.\n eapply join_le; [apply Time.order|..]; try refl.\n condtac; ss. rewrite e0. inv WRITABLE. nia.\n }\n { unfold TimeMap.singleton, LocFun.add, LocFun.init.\n condtac; try apply PSTime.bot_spec. subst.\n rewrite LOC. condtac; ss; try congr.\n apply le_ntt. ets.\n }\n + subst.\n unfold TView.write_released.\n condtac; ss; try apply View.bot_spec.\n unfold LocFun.add. condtac; ss.\n condtac; ss; apply PSView.join_spec; try apply PSView.bot_spec; try refl.\n - i. exploit FWD; eauto. i. des.\n exploit PSMemory.remove_get1; try exact GET_PS0; eauto. i. des; ss.\n exploit PSMemory.add_get1; try exact x4; eauto. i.\n esplits; try exact x5; ss.\n { etrans; try exact CUR. apply PSTime.join_l. }\n condtac.\n + etrans; try apply REL_FWD. apply le_ntt.\n eapply join_le; [apply Time.order|..]; try refl.\n condtac; ss. rewrite e. inv WRITABLE. nia.\n + etrans; try apply REL_FWD. condtac.\n * unfold LocFun.add. condtac; try refl.\n etrans; [|apply PSView.join_l]. apply LC_WF1_PS.\n * unfold LocFun.add. condtac; try refl.\n subst. apply PSView.join_l.\n }\n\n { (* RELEASED *)\n revert GET.\n erewrite PSMemory.add_o; eauto. condtac; ss.\n - i. des. inv GET.\n unfold TView.write_released.\n condtac; ss; try apply PSTime.bot_spec.\n apply PSTime.join_spec; ss.\n unfold LocFun.add. condtac; ss.\n condtac; ss; apply PSTime.join_spec.\n + etrans; [apply TVIEW1|]. apply le_ntt. s.\n inv WRITABLE. apply join_spec.\n * etrans; [apply TVIEW1|].\n etrans; [|apply Nat.lt_le_incl; apply EXT]. s.\n do 3 (etrans; [|apply join_r]). apply join_l.\n * etrans; [apply WF1_ARM|].\n etrans; [|apply Nat.lt_le_incl; apply EXT]. s.\n do 4 (etrans; [|apply join_r]).\n unfold ifc. do 2 (condtac; try by (destruct ord; ss)).\n eapply join_le; try apply Time.order. refl.\n + unfold TimeMap.singleton. unfold LocFun.add.\n condtac; try refl. apply PSTime.bot_spec.\n + etrans; [apply TVIEW1|]. apply le_ntt. s.\n inv WRITABLE. apply join_spec.\n * etrans; [|apply Nat.lt_le_incl; apply EXT]. s.\n do 3 (etrans; [|apply join_r]). apply join_l.\n * rewrite LOC in *. apply Nat.lt_le_incl. ss.\n + unfold TimeMap.singleton. unfold LocFun.add.\n condtac; try refl. apply PSTime.bot_spec.\n - erewrite Memory.remove_o; eauto. condtac; ss. eauto.\n }\n }\n Qed.\n\n Lemma sim_dmb\n tid n\n lc1_ps gl1_ps lc1_arm mem_arm\n ordr ordw\n rr rw wr ww lc2_arm\n (TVIEW1: sim_tview (PSLocal.tview lc1_ps) lc1_arm)\n (SC1: forall loc, PSTime.le (gl1_ps.(PSGlobal.sc) loc) (ntt n))\n (MEM1: sim_memory tid n lc1_ps (Global.promises gl1_ps) (Global.memory gl1_ps) lc1_arm mem_arm)\n (LC_WF1_PS: PSLocal.wf lc1_ps gl1_ps)\n (GL_WF1_PS: PSGlobal.wf gl1_ps)\n (WF1_ARM: RMWLocal.wf tid lc1_arm mem_arm)\n (RR: rr = (Ordering.le Ordering.acqrel ordr: bool) || Ordering.le Ordering.seqcst ordw)\n (RW: rw = Ordering.le Ordering.acqrel ordr || Ordering.le Ordering.acqrel ordw)\n (WR: wr = Ordering.le Ordering.seqcst ordw)\n (WW: ww = Ordering.le Ordering.acqrel ordw)\n (DMBSY: Ordering.le Ordering.seqcst ordw ->\n (join lc1_arm.(Local.vro) lc1_arm.(Local.vwo)).(View.ts) = n)\n (FULFILLABLE: RMWLocal.fulfillable lc2_arm mem_arm)\n (STEP: Local.dmb rr rw wr ww lc1_arm lc2_arm):\n exists lc2_ps gl2_ps,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n exploit (Local.dmb_incr (A:=unit)); eauto. i.\n destruct lc1_ps as [tview1 prm1 rsv1].\n destruct gl1_ps as [sc1 gprm1 mem1]. ss.\n inv STEP. esplits.\n { econs; eauto. s. i.\n extensionality loc.\n destruct (prm1 loc) eqn:PRM; ss.\n inv MEM1. exploit PRM_COMPLETE; try eassumption. s. i. des.\n exploit FULFILLABLE; try eassumption. s. i. des.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE RELEASED LT_VCAP LT_COH.\n replace (Ordering.le Ordering.acqrel ordw)\n with true in * by (destruct ordw; ss).\n rewrite orb_true_r in LT_VWN. ss.\n cut (ts < ts); try by nia.\n eapply le_lt_trans; try apply LT_VWN.\n etrans; try apply LE.\n rewrite <- DMBSY; ss.\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n }\n\n { econs; ss; i.\n { (* rel view *)\n repeat condtac; s.\n - unfold TView.write_fence_sc.\n rewrite X0, orb_true_r. ss.\n apply PSTime.join_spec.\n + etrans; try apply SC1. rewrite <- DMBSY; ss. apply le_ntt.\n etrans; [|apply join_l].\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n + condtac.\n * etrans; [apply TVIEW1|]. apply le_ntt. s.\n repeat apply join_spec.\n { etrans; [|apply join_l].\n etrans; [|apply join_l].\n apply TVIEW1.\n }\n { etrans; [|apply join_l].\n etrans; [|apply join_r].\n apply join_l.\n }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n * etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n { etrans; [apply TVIEW1|].\n repeat (etrans; [|apply join_l]; try refl).\n }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n - etrans; [apply TVIEW1|]. apply le_ntt. s.\n repeat apply join_spec.\n + etrans; [|apply join_l].\n etrans; [|apply join_l].\n apply TVIEW1.\n + etrans; [|apply join_l].\n etrans; [|apply join_r].\n apply join_l.\n + etrans; [apply WF1_ARM|]. s.\n etrans; [|apply join_l].\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n - etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n + etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n + etrans; [apply WF1_ARM|]. s.\n etrans; [|apply join_l].\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n - etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n + etrans; [|apply join_l]. apply join_l.\n + apply join_r.\n }\n\n { (* cur *)\n repeat condtac; s.\n - unfold TView.write_fence_sc.\n rewrite X, orb_true_r. ss.\n apply PSTime.join_spec.\n + etrans; try apply SC1. rewrite <- DMBSY; ss. apply le_ntt.\n etrans; [|apply join_l].\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n + condtac.\n * etrans; [apply TVIEW1|]. apply le_ntt. s.\n repeat apply join_spec.\n { etrans; [|apply join_l]. apply join_l. }\n { etrans; [|apply join_l].\n etrans; [|apply join_r].\n apply join_l.\n }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n * etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n { etrans; [|apply join_l]. apply join_l. }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n - etrans; [apply TVIEW1|]. apply le_ntt. s.\n repeat apply join_spec.\n + etrans; [|apply join_l]. apply join_l.\n + etrans; [|apply join_l].\n etrans; [|apply join_r].\n apply join_l.\n + apply join_r.\n - etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n + etrans; [|apply join_l]. apply join_l.\n + apply join_r.\n }\n\n { (* acq *)\n apply PSTime.join_spec.\n { etrans; [apply TVIEW1|]. apply le_ntt. s.\n eapply join_le; [apply Time.order|..]; try refl.\n eapply join_le; try apply Time.order. refl.\n }\n condtac; try apply PSTime.bot_spec. s.\n unfold TView.write_fence_sc.\n rewrite X, orb_true_r. ss.\n apply PSTime.join_spec.\n - etrans; try apply SC1. rewrite <- DMBSY; ss. apply le_ntt.\n etrans; [|apply join_l].\n etrans; [|apply join_l].\n etrans; [|apply join_r].\n eapply join_le; try apply Time.order. refl.\n - condtac.\n + etrans; [apply TVIEW1|]. apply le_ntt. s.\n repeat apply join_spec.\n { do 2 (etrans; [|apply join_l]). apply join_l. }\n { etrans; [|apply join_l].\n etrans; [|apply join_r].\n refl.\n }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n + etrans; [apply TVIEW1|]. apply le_ntt. s. apply join_spec.\n { do 2 (etrans; [|apply join_l]). apply join_l. }\n { etrans; [apply WF1_ARM|].\n etrans; [|apply join_l].\n etrans; [|apply join_l].\n etrans; [|apply join_r]. s.\n eapply join_le; try apply Time.order. refl.\n }\n }\n\n { (* vnew *)\n apply join_spec.\n - etrans; [|apply join_l]. apply TVIEW1.\n - etrans; [|apply join_r]. apply join_spec.\n + etrans; [|apply join_l]. unfold ifc.\n condtac; try apply bot_spec. condtac; try refl.\n destruct ordr, ordw; ss.\n + etrans; [|apply join_r]. unfold ifc.\n condtac; try apply bot_spec. condtac; try refl.\n destruct ordr, ordw; ss.\n }\n }\n\n { (* sc *)\n s. i. unfold TView.write_fence_sc. condtac; ss.\n apply PSTime.join_spec; ss.\n exploit DMBSY; ss. i. rewrite <- x1.\n condtac.\n - etrans; [apply TVIEW1|]. apply le_ntt. ss.\n (repeat apply join_spec); try apply WF1_ARM. apply join_l.\n - etrans; [apply TVIEW1|]. apply le_ntt. ss.\n repeat apply join_spec; apply WF1_ARM.\n }\n\n { (* mem *)\n inv MEM1. ss. econs; s; eauto. i.\n exploit FWD; eauto. i. des.\n esplits; eauto.\n { etrans; try exact CUR.\n repeat condtac; ss; try refl; try apply LC_WF1_PS.\n unfold TView.write_fence_sc. unfold TimeMap.join.\n repeat (condtac; ss); try apply PSTime.join_r.\n etrans; [|apply PSTime.join_r]. apply LC_WF1_PS.\n }\n condtac; ss.\n - i. etrans; eauto. apply le_ntt.\n eapply join_le; [apply Time.order|..]; try refl.\n apply join_spec; ets.\n - etrans; eauto. condtac; ss; try refl.\n repeat (condtac; ss); cycle 1.\n { etrans; [apply LC_WF1_PS|]. apply LC_WF1_PS. }\n { apply LC_WF1_PS. }\n unfold TView.write_fence_sc.\n condtac; try by (destruct ordw; ss). s.\n econs; s.\n + etrans; [|apply TimeMap.join_r]. condtac; ss.\n * etrans; [apply LC_WF1_PS|]. s.\n etrans; [apply LC_WF1_PS|]. s.\n apply LC_WF1_PS.\n * etrans; [apply LC_WF1_PS|]. s.\n apply LC_WF1_PS.\n + etrans; [|apply TimeMap.join_r]. condtac; ss.\n * etrans; [apply LC_WF1_PS|]. s.\n apply LC_WF1_PS.\n * apply LC_WF1_PS.\n }\n Qed.\n\n Lemma sim_control\n tid n\n lc1_ps gl1_ps lc1_arm mem_arm\n ctrl lc2_arm\n (TVIEW1: sim_tview (PSLocal.tview lc1_ps) lc1_arm)\n (MEM1: sim_memory tid n lc1_ps (Global.promises gl1_ps) (Global.memory gl1_ps) lc1_arm mem_arm)\n (STEP: Local.control ctrl lc1_arm lc2_arm):\n (<>) /\\\n (<>).\n Proof.\n exploit (Local.control_incr (A:=unit)); eauto. i.\n inv STEP. split.\n - eapply sim_tview_le; eauto. s. apply TVIEW1.\n - inv MEM1. ss.\n Qed.\n\n Lemma update_empty_loc\n tid (lc1 lc2 lc3: Local.t (A:=unit)) mem\n ordr vlocr vold ts_old\n ordw vlocw vnew res ts_new view_pre\n (WF: RMWLocal.wf tid lc1 mem)\n (READ: Local.read true ordr vlocr vold ts_old lc1 mem lc2)\n (FULFILL: Local.fulfill true ordw vlocw vnew res ts_new tid view_pre lc2 mem lc3)\n (LOC: vlocr.(ValA.val) = vlocw.(ValA.val))\n (FULFILLABLE: RMWLocal.fulfillable lc3 mem):\n empty_loc vlocr.(ValA.val) ts_old ts_new mem.\n Proof.\n assert (EX: Memory.exclusive tid (ValA.val vlocr) ts_old ts_new mem).\n { inv READ. inv FULFILL. inv WRITABLE. ss.\n exploit EX; ss. i. des. inv TSX. ss.\n rewrite LOC. auto.\n }\n ii. destruct msg.\n destruct (Id.eq_dec tid0 tid); cycle 1.\n { eapply EX; eauto. nia. }\n ss. subst.\n dup WF. inv WF0. clear COH VRN VWN FWD PRM.\n exploit (PRM_COH (S ts)); eauto; s.\n { clear - READ TS1 MSG.\n inv READ.\n destruct (le_lt_dec (S ts) (View.ts (Local.coh lc1 (ValA.val vlocr)))); ss.\n exfalso.\n eapply COH; eauto.\n }\n intro PROMISED. clear PRM_COH.\n assert (PROMISED2: Promises.lookup (S ts) (Local.promises lc3)).\n { inv READ. inv FULFILL. ss.\n rewrite Promises.unset_o. condtac; ss.\n r in e. subst. nia.\n }\n exploit FULFILLABLE; eauto. i. des.\n exploit LT_COH; eauto. s. i.\n clear - LOC FULFILL TS2 x0.\n inv FULFILL. inv WRITABLE. ss.\n revert x0. unfold fun_add. condtac; try congr. s. i. nia.\n Qed.\n\n Lemma sim_memory_exclusive\n told tnew\n tid n lc_ps gprm_ps mem_ps lc_arm mem_arm\n loc vold msg loc_ps\n from\n (SIM: sim_memory tid n lc_ps gprm_ps mem_ps lc_arm mem_arm)\n (TS: told < tnew)\n (OLD: Memory.read loc told mem_arm = Some vold)\n (NEW: Memory.get_msg tnew mem_arm = Some msg)\n (EX: empty_loc loc told tnew mem_arm)\n (LOC1: msg.(Msg.loc) = loc)\n (LOC2: loc = Zpos loc_ps)\n (RESERVED: PSMemory.get loc_ps (ntt tnew) mem_ps = Some (from, Message.reserve)):\n from = ntt told.\n Proof.\n dup SIM. inv SIM0.\n exploit MEM_SOUND; eauto. i. des.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED x0.\n rewrite LOC in *. inv LOC2.\n rewrite GET_PS in *. inv RESERVED.\n unguard. des; subst.\n { destruct told; ss.\n unfold Memory.read in OLD. ss. des_ifs.\n inv SIM. exploit (MEM_SOUND (S told)); eauto. i. des.\n clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE FWD RELEASED x0.\n rewrite e in LOC0. inv LOC0.\n exploit PSMemory.get_disjoint; [exact GET_PS|exact GET_PS0|]. i. des.\n { apply ntt_inj in x0. subst. nia. }\n exfalso. apply (x0 (ntt (S told))); econs; ss; try refl.\n - eapply TimeFacts.le_lt_lt; try apply PSTime.bot_spec.\n apply PSTime.incr_spec.\n - exploit lt_ntt; try exact TS. s. i. timetac.\n }\n { apply ntt_lt in TS0.\n destruct (le_lt_dec fts told); cycle 1.\n { unfold Memory.get_msg in GET_FROM_ARM.\n destruct fts; ss.\n exploit EX; try apply GET_FROM_ARM; ss; try nia.\n }\n inv l; ss. exfalso.\n unfold Memory.read in OLD. ss. des_ifs.\n exploit EMPTY; try exact Heq; ss; try nia.\n }\n Qed.\n\n Lemma sim_thread_step\n tid n th1_ps eu1 eu2\n (SIM1: sim_thread tid n th1_ps eu1)\n (SC1: forall loc, PSTime.le (th1_ps.(PSThread.global).(PSGlobal.sc) loc) (ntt n))\n (LC_WF1_PS: PSLocal.wf (PSThread.local th1_ps) (PSThread.global th1_ps))\n (GL_WF1_PS: PSGlobal.wf (PSThread.global th1_ps))\n (WF1_ARM: RMWLocal.wf tid eu1.(RMWExecUnit.local) eu1.(RMWExecUnit.mem))\n (STEP_ARM: RMWExecUnit.state_step_dmbsy_exact (Some n) n tid eu1 eu2)\n (VRO: le eu2.(RMWExecUnit.local).(Local.vro).(View.ts) n)\n (FULFILLABLE: RMWLocal.fulfillable eu2.(RMWExecUnit.local) eu2.(RMWExecUnit.mem)):\n exists th2_ps,\n (<>) /\\\n ((<>) /\\\n (<>) \\/\n exists e_ps th3_ps,\n (<>) /\\\n (<>)).\n Proof.\n destruct th1_ps as [st1_ps lc1_ps gl1_ps].\n destruct eu1 as [st1_arm lc1_arm mem1_arm].\n destruct eu2 as [st2_arm lc2_arm mem2_arm].\n inv SIM1. inv STEP_ARM. inv STEP. ss. subst.\n exploit sim_state_step; eauto. i. des.\n inv LOCAL; inv EVENT.\n { (* internal *)\n esplits.\n - econs 2; try refl.\n econs 1; [econs 2; [|econs 1]|]; eauto.\n - left. ss.\n }\n\n { (* read *)\n exploit sim_read; try exact STEP; eauto.\n i. des.\n - exfalso.\n exploit (FULFILLABLE ts); try by (inv STEP; ss). i. des.\n dup WF1_ARM. inv WF1_ARM0.\n exploit PRM; eauto. i. des.\n clear COH VRN VWN FWD PRM.\n exploit LT_COH; eauto. i.\n exploit (read_ts_coh (A:=unit)); eauto. i.\n clear - STEP GET x0 x1.\n inv STEP. ss.\n unfold Memory.get_msg in *. destruct ts; ss.\n revert MSG. unfold Memory.read. ss.\n rewrite GET. condtac; ss. i.\n rewrite e in *.\n eapply Nat.lt_strorder.\n eapply Nat.lt_le_trans; [exact x0|]. apply x1.\n - exploit sim_val_eq_inv; [exact VAL|exact VAL0|]. i. subst.\n esplits.\n + econs 2; try refl.\n econs 1; [econs 2; [|econs 2]|]; eauto.\n + left. ss.\n - exploit sim_val_eq_inv; [exact VAL|exact VAL0|]. i. subst.\n esplits.\n + econs 2; try refl.\n econs 1; [econs 2; [|econs 8]|]; eauto.\n + left. ss.\n }\n\n { (* fulfill *)\n exploit sim_fulfill; try exact STEP; eauto; ss.\n { Transparent Ordering.le.\n i. apply PF in H. destruct ord_ps; ss.\n }\n { i. apply PSTime.bot_spec. }\n i. des. inv VAL.\n esplits.\n - econs 2.\n { econs 1; [econs 1; econs 3|]; eauto. }\n econs 2; try refl.\n econs 1; [econs 2; [|econs 3]|]; eauto.\n - left. splits; ss. i.\n inv CANCEL_PS. inv STEP_PS0. ss.\n }\n\n { (* fadd *)\n exploit (update_ts (A:=unit)); eauto. intro TS.\n exploit sim_read; try exact STEP_READ; eauto.\n { exploit (Local.control_incr (A:=unit)); eauto. i.\n exploit (Local.fulfill_incr (A:=unit)); eauto. i.\n etrans; [apply x1|]. etrans; [apply x0|]. ss.\n }\n i. des.\n { (* read message is a promise *)\n exfalso.\n exploit (FULFILLABLE ts_old).\n { inv STEP_CONTROL; ss.\n inv STEP_FULFILL; ss.\n rewrite Promises.unset_o.\n condtac; try by (inv STEP_READ; ss); ss.\n r in e. subst. nia.\n }\n i. des.\n dup WF1_ARM. inv WF1_ARM0.\n exploit PRM; eauto. i. des.\n clear COH VRN VWN FWD PRM.\n exploit LT_COH; eauto. i.\n eapply Nat.lt_strorder.\n etrans; try exact x0.\n eapply Nat.lt_le_trans; try exact TS.\n exploit (Local.control_incr (A:=unit)); eauto. i.\n etrans; [|apply x1].\n replace (Msg.loc msg) with (ValA.val vloc); cycle 1.\n { clear - STEP_READ GET.\n inv STEP_READ. ss.\n revert GET. unfold Memory.get_msg. destruct ts_old; ss. i.\n revert MSG. unfold Memory.read. s. rewrite GET. condtac; ss.\n }\n clear - STEP_FULFILL.\n inv STEP_FULFILL. ss.\n unfold fun_add. condtac; ss. congr.\n }\n\n { (* normal read *)\n exploit PSLocal.read_step_future; try exact STEP_PS0; eauto. i. des.\n exploit (RMWLocal.read_wf (A:=unit)); eauto. i.\n exploit sim_fulfill; try exact STEP_FULFILL; eauto; ss.\n { Transparent Ordering.le.\n i. apply PF in H. destruct ordw_ps; ss.\n }\n { clear - LOC SIM_TVIEW SIM_MEM LC_WF1_PS STEP_READ STEP_PS0 TVIEW2 MEM2.\n i. inv STEP_READ. ss.\n unfold FwdItem.read_view. condtac; s.\n - apply andb_prop in X. des.\n revert X. unfold proj_sumbool. condtac; ss. r in e. i. clear X0 X X1.\n inv SIM_MEM. clear PRM_SOUND PRM_COMPLETE MEM_SOUND MEM_COMPLETE RELEASED.\n exploit (FWD (Zpos loc_ps)); eauto. i. des.\n rewrite LOC in *.\n inv STEP_PS0. rewrite GET_PS in *. inv GET.\n revert REL_FWD. condtac; i.\n + etrans; try apply REL_FWD. apply le_ntt. s.\n eapply join_le; [apply Time.order|..].\n * eapply join_le; [apply Time.order|..]; ets.\n * unfold fun_add. condtac; ss. rewrite e. ets.\n + etrans; try apply REL_FWD.\n etrans; [apply LC_WF1_PS|].\n etrans; [apply LC_WF1_PS|].\n etrans; [apply SIM_TVIEW|].\n apply le_ntt. s.\n eapply join_le; [apply Time.order|..].\n * eapply join_le; [apply Time.order|..]; ets.\n * unfold fun_add. condtac; ss. rewrite e. ets.\n - inv STEP_PS0. ss.\n inv MEM2. exploit RELEASED; eauto. i.\n etrans; eauto. apply le_ntt. ets.\n }\n { i. inv STEP_PS0. ss.\n inv SIM_MEM. exploit RELEASED; eauto.\n etrans; try apply x1. econs.\n apply lt_ntt. ss.\n }\n i. des.\n exploit reorder_read_cancel; eauto. i. des.\n exploit sim_val_eq_inv; [exact VAL|exact VOLD|]. i. subst.\n exploit (@sim_memory_exclusive ts_old ts_new); try exact SIM_MEM.\n { clear - WF1_ARM STEP_READ STEP_FULFILL.\n eapply le_lt_trans; cycle 1.\n { inv STEP_FULFILL. inv WRITABLE. apply COH. }\n clear STEP_FULFILL. inv STEP_READ. ss.\n unfold FwdItem.read_view. condtac.\n - apply andb_prop in X. des.\n revert X. unfold proj_sumbool. condtac; ss.\n r in e. i. clear X X0 X1. subst.\n inv WF1_ARM. etrans; try apply FWD.\n unfold fun_add. condtac; try congr. s.\n apply join_l.\n - unfold fun_add. condtac; ss; try congr. ets.\n }\n { instantiate (1:=vold.(ValA.val)).\n instantiate (1:=vloc.(ValA.val)).\n inv STEP_READ. ss.\n }\n { instantiate (1:=Msg.mk vloc.(ValA.val) vnew.(ValA.val) tid).\n inv STEP_FULFILL. ss.\n }\n { hexploit update_empty_loc; try exact STEP_READ; try exact STEP_FULFILL; ss.\n eapply RMWLocal.control_fulfillable; eauto.\n }\n { ss. }\n { eauto. }\n { instantiate (1:=from).\n inv CANCEL_PS. inv CANCEL.\n exploit PSMemory.remove_get0; try exact MEM. i. des. ss.\n }\n i. subst. esplits.\n + econs 2.\n { econs; [econs 1; econs 3|]; eauto. }\n econs 2; try refl.\n econs; [econs 2; [|econs 4]|]; eauto.\n inv VNEW. eauto.\n + left. splits.\n * econs; ss.\n { exploit (Local.control_incr (A:=unit)); eauto. i.\n eapply sim_tview_le; eauto.\n inv STEP_CONTROL. ss. apply TVIEW0.\n }\n { inv STEP_CONTROL. inv MEM0. econs; ss. }\n * i. inv STEP_PS0. inv CANCEL_PS. inv STEP_PS1. ss.\n }\n\n { (* racy read *)\n inv STEP_PS0. esplits; try refl.\n right. esplits.\n - econs 2; [|econs 10]; eauto.\n - ss.\n }\n }\n\n { (* dmb *)\n exploit sim_dmb; try exact STEP; eauto.\n { i. apply DMBSY. rewrite H.\n destruct ordr_ps, ordw_ps; ss.\n }\n i. des. esplits.\n - econs 2; try refl.\n econs; [econs 2; [|econs 5]|]; eauto.\n - left. ss.\n }\n\n { (* control *)\n exploit sim_control; try exact LC; eauto. i. des.\n esplits.\n - econs 2; try refl.\n econs; [econs 2; [|econs 1]|]; eauto.\n - left. ss.\n }\n Qed.\n\n Lemma sim_thread_rtc_step\n tid n th1_ps eu1 eu2\n (SIM1: sim_thread tid n th1_ps eu1)\n (SC1: forall loc, PSTime.le (th1_ps.(PSThread.global).(PSGlobal.sc) loc) (ntt n))\n (LC_WF1_PS: PSLocal.wf (PSThread.local th1_ps) (PSThread.global th1_ps))\n (GL_WF1_PS: PSGlobal.wf (PSThread.global th1_ps))\n (WF1_ARM: RMWLocal.wf tid (RMWExecUnit.local eu1) (RMWExecUnit.mem eu1))\n (STEPS_ARM: rtc (RMWExecUnit.state_step_dmbsy_exact (Some n) n tid) eu1 eu2)\n (VRO: le eu2.(RMWExecUnit.local).(Local.vro).(View.ts) n)\n (FULFILLABLE: RMWLocal.fulfillable eu2.(RMWExecUnit.local) eu2.(RMWExecUnit.mem)):\n exists th2_ps,\n (<>) /\\\n ((<>) /\\\n (<>) \\/\n exists e_ps th3_ps,\n (<>) /\\\n (<>)).\n Proof.\n revert th1_ps SIM1 SC1 LC_WF1_PS GL_WF1_PS.\n induction STEPS_ARM; i.\n { esplits; eauto. }\n hexploit (RMWExecUnit.rtc_state_step_fulfillable (A:=unit)); try exact FULFILLABLE;\n try eapply rtc_mon; try exact STEPS_ARM; i.\n { inv H0. econs. eauto. }\n exploit (RMWExecUnit.rtc_state_step_incr (A:=unit));\n try eapply rtc_mon; try exact STEPS_ARM; i.\n { inv H1. econs. eauto. }\n exploit sim_thread_step; eauto.\n { etrans; try apply x1. ss. }\n i. des; cycle 1.\n { esplits; eauto. }\n exploit PSThread.rtc_tau_step_future; try exact STEPS_PS; eauto. i. des.\n exploit (RMWExecUnit.state_step_rmw_wf (A:=unit)); i.\n { inv H. econs. eauto. }\n { ss. }\n exploit IHSTEPS_ARM; eauto. i. des.\n - esplits; [|eauto]. etrans; eauto.\n - esplits; [|eauto]. etrans; eauto.\n Qed.\n\n Variant sim_thread_exec (tid: Ident.t) (n: Time.t) (after_sc: bool)\n (th_ps: PSThread.t lang_ps) (eu eu_final: RMWExecUnit.t (A:=unit)): Prop :=\n | sim_thread_exec_intro\n sc eu1\n (STEPS1: rtc (RMWExecUnit.state_step None tid) eu eu1)\n (SIM_THREAD: sim_thread tid n th_ps eu1)\n (SC: sc = if after_sc then S n else n)\n (STEPS2: rtc (RMWExecUnit.state_step_dmbsy_over (Some n) sc tid) eu1 eu_final)\n (PROMISES: eu_final.(RMWExecUnit.local).(Local.promises) = bot)\n (STATE: RMWState.is_terminal eu_final.(RMWExecUnit.state))\n .\nEnd PStoRMWThread.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-to-promising-arm", "sha": "1e16f948ec5549a55cde3497036feade3946e1f2", "save_path": "github-repos/coq/snu-sf-promising-ir-to-promising-arm", "path": "github-repos/coq/snu-sf-promising-ir-to-promising-arm/promising-ir-to-promising-arm-1e16f948ec5549a55cde3497036feade3946e1f2/src/mapping/PStoRMWThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.13813057486606478}} {"text": "Require Import floyd.proofauto.\nRequire Import concurrency.semax_conc.\n\nModule Type threadlib_args.\n Parameter CompSpecs : compspecs.\n Parameter ext_link : string -> ident.\nEnd threadlib_args.\n\nModule threadlib (args : threadlib_args).\nImport args.\n\nLocal Open Scope logic.\n\nDefinition makelock_spec R :=\n WITH v : val, sh : share\n PRE [ _lock OF tptr tlock ]\n PROP (writable_share sh)\n LOCAL (temp _lock v)\n SEP (data_at_ sh tlock v)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (lock_inv sh v R).\n\nDefinition freelock_spec R :=\n WITH v : val, sh : share\n PRE [ _lock OF tptr tlock ]\n PROP (writable_share sh)\n LOCAL (temp _lock v)\n SEP (R; lock_inv sh v R)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (R; data_at_ sh tlock v).\n\nDefinition acquire_spec R :=\n WITH v : val, sh : share\n PRE [ _lock OF tptr tlock ]\n PROP (readable_share sh)\n LOCAL (temp _lock v)\n SEP (lock_inv sh v R)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (lock_inv sh v R; R).\n\nDefinition release_spec R :=\n WITH v : val, sh : share\n PRE [ _lock OF tptr tlock ]\n PROP (readable_share sh)\n LOCAL (temp _lock v)\n SEP (lock_inv sh v R; R)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (lock_inv sh v R).\n\nDefinition voidstar_funtype :=\n Tfunction\n (Tcons (tptr tvoid) Tnil)\n (tptr tvoid)\n cc_default.\n\nDefinition spawn_thread_spec (PrePost: (val ->mpred * mpred)) :=\n WITH f : val, b : val\n PRE [_f OF tptr voidstar_funtype, _args OF tptr tvoid]\n PROP ()\n LOCAL (temp _args b)\n SEP ((EX _y : ident, func_ptr'\n (WITH y : val\n PRE [ _y OF tptr tvoid ]\n PROP ()\n LOCAL (temp _y y)\n SEP (fst (PrePost y))\n POST [tptr tvoid]\n PROP ()\n LOCAL ()\n SEP (snd (PrePost y))\n )\n f);\n (fst (PrePost b)))\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (emp).\n\nDefinition exit_thread_spec (_ : unit) :=\n WITH u:unit\n PRE [ ]\n PROP ()\n LOCAL ()\n SEP (emp)\n POST [ tvoid ]\n PROP ()\n LOCAL ()\n SEP (FF).\n\n(* We list the specifications that we assume. In the future,\n identifier for those functions would be strings instead of\n positives. *)\n\nVariable ext_link : string -> ident.\n\nDefinition threadlib_specs : list (ident * {x : Type & x -> funspec}) := [\n (ext_link \"acquire\" , existT _ mpred acquire_spec);\n (ext_link \"release\" , existT _ mpred release_spec);\n (ext_link \"makelock\", existT _ mpred makelock_spec);\n (ext_link \"freelock\", existT _ mpred freelock_spec);\n (ext_link \"spawn\" , existT _ ((val->mpred * mpred)) spawn_thread_spec)\n].\n\nFixpoint find_in_list {A B} (D:forall x y : A, {x = y} + {x <> y})\n (a : A) (l : list (A * B)) : option B :=\n match l with\n | nil => None\n | (a', b) :: l => if D a a' then Some b else find_in_list D a l\n end.\n\nDefinition find_in_threadlib_specs id := find_in_list peq id threadlib_specs.\n\nLemma semax_acquire:\n forall {cs: compspecs} (Frame : list mpred) (Delta : tycontext)\n (P : list Prop) (Q : list localdef) (bl : list expr) (ResInv : mpred)\n (witness: val*share) argsig\n (Pre Post: val*share -> environ -> mpred) ,\n argsig = [(_lock, tptr tlock)] ->\n Pre witness = (let (v,sh) := witness in\n (PROP (readable_share sh)\n LOCAL (temp _lock v) SEP (lock_inv sh v ResInv))) ->\n Post witness = (let (v,sh) := witness in\n (PROP ( ) LOCAL () SEP (lock_inv sh v ResInv; ResInv))) ->\n@semax cs (Concurrent_Espec unit cs ext_link) Delta\n (tc_exprlist Delta (argtypes [(_lock, tptr tlock)]) bl &&\n (` (Pre witness) (make_args' (argsig, Tvoid)\n (eval_exprlist (argtypes argsig) bl)) *\n PROPx P (LOCALx Q (SEPx Frame))))\n (Scall None\n (Evar (ext_link \"acquire\")\n (Tfunction (type_of_params [(_lock, tptr tlock)]) Tvoid\n cc_default)) bl)\n (normal_ret_assert\n (` (Post witness)\n (make_args [] []) * PROPx P (LOCALx Q (SEPx Frame)))).\nProof.\nintros.\nrewrite H0,H1; clear H0 H1. subst argsig. clear.\ndestruct witness as [v sh].\n(* rewrite semax.semax_fold_unfold. *)\nAbort.\n\n\nLemma semax_call_00_helper: (* This lemma's proof almost identical to semax_call_id00_wow *)\nforall (Frame : list mpred) (cs : compspecs) (Delta : tycontext)\n (P : list Prop) (Q : list localdef) (R : list mpred) (bl : list expr)\n (Ppre : list Prop) (Qpre : list localdef) (Qtemp Qpre_temp : PTree.t val)\n (Qvar Qpre_var : PTree.t vardesc)\n (B : Type) (Ppost : B -> list Prop) (Rpre : list mpred)\n (Rpost : B -> list mpred)\n (vl : list val)\n (witness' : mpred)\n (argsig: list (ident * type))\n (A: Type)\n (witness : A)\n (Pre Post : A -> environ -> mpred)\n (PTREE : local2ptree Q = (Qtemp, Qvar, [], []))\n (PTREE' : local2ptree Qpre = (Qpre_temp, Qpre_var, [], []))\n (CHECKVAR : ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- !! Forall (check_one_var_spec Qvar)\n (PTree.elements Qpre_var))\n (FRAME : fold_right sepcon emp R\n |-- fold_right sepcon emp Rpre * fold_right sepcon emp Frame)\n (PPRE : fold_right_and True Ppre)\n (GLBL : (var_types Delta) ! (ext_link \"acquire\") = None)\n (TC1 : ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- tc_exprlist Delta (argtypes argsig) bl)\n (MSUBST : force_list\n (map (msubst_eval_expr Qtemp Qvar)\n (explicit_cast_exprlist (argtypes argsig) bl)) =\n Some vl)\n (CHECKTEMP : ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- !! Forall\n (check_one_temp_spec\n (pTree_from_elements\n (combine (var_names argsig) vl)))\n (PTree.elements Qpre_temp))\n (PRE1 : Pre witness = PROPx Ppre (LOCALx Qpre (SEPx Rpre)))\n (POST1 : Post witness =\n (EX vret : B, PROPx (Ppost vret) LOCAL () (SEPx (Rpost vret)))%assert),\n\n@semax cs (Concurrent_Espec unit cs ext_link) Delta\n (tc_exprlist Delta (argtypes argsig) bl &&\n (` (Pre witness) (make_args' (argsig, Tvoid)\n (eval_exprlist (argtypes argsig) bl)) *\n PROPx P (LOCALx Q (SEPx Frame))))\n (Scall None\n (Evar (ext_link \"acquire\")\n (Tfunction (type_of_params argsig) Tvoid\n cc_default)) bl)\n (normal_ret_assert\n (` (Post witness)\n (make_args [] []) * PROPx P (LOCALx Q (SEPx Frame)))) ->\n @semax cs (Concurrent_Espec unit cs ext_link) Delta (PROPx P (LOCALx Q (SEPx R)))\n (Scall None\n (Evar (ext_link \"acquire\")\n (Tfunction (type_of_params argsig) Tvoid cc_default)) bl)\n (normal_ret_assert\n (EX vret : B,\n PROPx (P ++ Ppost vret) (LOCALx Q (SEPx (Rpost vret ++ Frame))))%assert).\nProof.\nintros.\neapply semax_pre_post; [ | | apply H].\n*\n apply andp_right; auto.\n rewrite PRE1.\n match goal with |- ?D && PROPx ?A ?B |-- ?C =>\n apply derives_trans with (D && PROPx ((length (argtypes argsig) = length bl) :: A) B);\n [ rewrite <- insert_prop | ]\n end.\n apply andp_right; [apply andp_left1; auto | ].\n apply andp_right; [| apply andp_left2; auto].\n eapply derives_trans; [apply TC1 | ].\n clear. go_lowerx.\n unfold tc_exprlist.\n revert bl; induction (argtypes argsig); destruct bl;\n simpl; try apply @FF_left.\n apply prop_right; auto.\n repeat rewrite denote_tc_assert_andp. apply andp_left2.\n eapply derives_trans; [ apply IHl | ]. normalize.\napply derives_extract_PROP; intro LEN.\n clear - PTREE LEN PTREE' MSUBST CHECKVAR FRAME PPRE CHECKTEMP.\n normalize.\n progress (autorewrite with norm1 norm2); normalize.\n eapply derives_trans.\n apply andp_right. apply andp_right. apply CHECKVAR. apply CHECKTEMP. apply derives_refl.\n rewrite andp_assoc. apply derives_extract_prop; intro CVAR.\n apply derives_extract_prop; intro CTEMP.\n clear CHECKTEMP CHECKVAR.\nrewrite PROP_combine.\nrewrite (andp_comm (local (fold_right _ _ _))).\napply andp_right.\napply andp_right.\napply andp_left2.\napply andp_left1.\nrewrite fold_right_and_app_low.\napply prop_derives; intros; split; auto.\n clear - PPRE.\n revert PPRE; induction Ppre; simpl; intuition.\napply andp_left2.\napply andp_left2.\napply andp_derives.\napply derives_refl.\nintro rho; unfold SEPx.\n rewrite fold_right_sepcon_app.\n assumption.\n apply (local2ptree_soundness P _ R) in PTREE.\n simpl app in PTREE.\n apply msubst_eval_exprlist_eq with (P:=P)(R:=R)(Q:=nil) in MSUBST.\n rewrite PTREE.\n intro rho.\n unfold local, lift1. unfold_lift. simpl.\n apply andp_left2.\n eapply derives_trans. apply andp_right. apply MSUBST. apply derives_refl.\n clear MSUBST.\n apply (local2ptree_soundness nil _ (TT::nil)) in PTREE'.\n simpl app in PTREE'.\n rewrite !isolate_LOCAL_lem1 in PTREE'.\n unfold local at 1, lift1.\n simpl.\n apply derives_extract_prop; intro. unfold_lift in H. subst vl.\n unfold PROPx, LOCALx, SEPx. simpl.\napply andp_left2. apply andp_left1.\n assert (LEN': length (var_names argsig) = length (eval_exprlist (argtypes argsig) bl rho)).\n clear - LEN.\n revert bl LEN; induction argsig as [ | [? ?]]; destruct bl;\n simpl; intros; auto.\n inv LEN.\n forget (argtypes argsig) as tys.\n cut (local (fold_right `and `True (map locald_denote (LocalD Qtemp Qvar nil))) rho |--\n `(local (fold_right `and `True (map locald_denote Qpre)))\n (fun rho => (make_args (var_names argsig) (eval_exprlist tys bl rho) rho)) rho).\n intro. eapply derives_trans; [apply H |].\n unfold make_args'. simpl @fst. change (map fst argsig) with (var_names argsig).\n clear. unfold_lift. unfold local, lift1. apply prop_derives.\n induction Qpre; simpl; auto. intros [? ?]. split; auto.\n rewrite PTREE'. clear PTREE' Qpre.\n apply prop_derives; intro. forget (var_names argsig) as fl.\n forget (eval_exprlist tys bl rho) as vl.\n eapply check_specs_lemma; try eassumption.\n*\n clear CHECKVAR CHECKTEMP TC1 PRE1 PPRE.\n intros.\n unfold normal_ret_assert. normalize.\n simpl exit_tycon. rewrite POST1; clear POST1.\n unfold ifvoid.\n go_lowerx. normalize.\n apply exp_right with x.\n normalize.\n apply andp_right.\n apply prop_right.\n rewrite fold_right_and_app_low.\n split; auto.\n rewrite fold_right_sepcon_app. auto.\nQed.\n\n(* Same lemma as [semax_call_id00_wow] but it concerns only the\n functions listed in [threadlib_specs], which, in addition to being\n external, need an additional parameter [witness'] of type, for\n example, [mpred], on which quantifying directly in the WITH clause\n would result in a universe inconsistency. *)\n\n\n\nLemma semax_call_id00_wow_threads:\n forall {A} {A'} (witness: A) (witness' : A')\n (Frame: list mpred)\n (* Espec *) {cs: compspecs} Delta P Q R id (paramty: typelist) (bl: list expr)\n (argsig: list (ident * type)) (retty: type) cc (Pre Post: A -> environ -> mpred)\n ffunspec\n (Post2: environ -> mpred)\n (Ppre: list Prop)\n (Qpre: list localdef)\n (Qtemp Qactuals Qpre_temp : PTree.t _)\n (Qvar Qpre_var: PTree.t vardesc)\n (B: Type)\n (Ppost: B -> list Prop)\n (Rpre: list mpred)\n (Rpost: B -> list mpred)\n (vl : list val)\n (GLBL: (var_types Delta) ! id = None)\n (NAME: find_in_threadlib_specs id = Some (existT (fun x => x -> funspec) A' ffunspec))\n (FUNSPEC: ffunspec witness' = mk_funspec (argsig, Tvoid) cc A Pre Post)\n (* (GLOBS: (glob_specs Delta) ! id = Some (mk_funspec (argsig,Tvoid) cc A Pre Post)) *)\n (* (GLOBT: (glob_types Delta) ! id = Some (type_of_funspec (mk_funspec (argsig,retty) cc A Pre Post))) *)\n (RETTY: retty = Tvoid)\n (H: paramty = type_of_params argsig)\n (PTREE: local2ptree Q = (Qtemp, Qvar, nil, nil))\n (TC1: ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- (tc_exprlist Delta (argtypes argsig) bl))\n (PRE1: Pre witness = PROPx Ppre (LOCALx Qpre (SEPx Rpre)))\n (PTREE': local2ptree Qpre = (Qpre_temp, Qpre_var, nil, nil))\n (MSUBST: force_list (map (msubst_eval_expr Qtemp Qvar)\n (explicit_cast_exprlist (argtypes argsig) bl))\n = Some vl)\n (PTREE'': pTree_from_elements (List.combine (var_names argsig) vl) = Qactuals)\n (CHECKTEMP: ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- !! Forall (check_one_temp_spec Qactuals) (PTree.elements Qpre_temp))\n (CHECKVAR: ENTAIL Delta, PROPx P (LOCALx Q (SEPx R))\n |-- !! Forall (check_one_var_spec Qvar) (PTree.elements Qpre_var))\n (FRAME: fold_right sepcon emp R |-- fold_right sepcon emp Rpre * fold_right sepcon emp Frame)\n (POST1: Post witness = (EX vret:B, PROPx (Ppost vret) (LOCALx nil (SEPx (Rpost vret)))))\n (POST2: Post2 = EX vret:B, PROPx (P++ Ppost vret ) (LOCALx Q\n (SEPx (Rpost vret ++ Frame))))\n (PPRE: fold_right_and True Ppre),\n @semax cs (Concurrent_Espec unit cs ext_link) Delta (PROPx P (LOCALx Q (SEPx R)))\n (Scall None\n (Evar id (Tfunction paramty Tvoid cc))\n bl)\n (normal_ret_assert Post2).\nProof.\n\nintros.\nsubst.\nunfold find_in_threadlib_specs, threadlib_specs in NAME.\nsimpl in NAME.\nrepeat if_tac in NAME.\n\n* (* acquire *)\n subst id.\n injection NAME.\n intros.\n revert FUNSPEC.\n subst A'.\n apply inj_pair2 in H; subst ffunspec. clear NAME.\n intros.\n unfold acquire_spec in FUNSPEC.\n revert PRE1 POST1.\n inv FUNSPEC.\n intros.\n apply inj_pair2 in H3.\n apply inj_pair2 in H4.\n eapply semax_call_00_helper; try eassumption.\n (* eapply semax_acquire; auto; try assumption. *)\n (* rewrite <- H3; reflexivity. *)\n (* rewrite <- H4; reflexivity. *)\nAbort.\n\n(* We need different tactics for them, if only because we have an\n additional witness, which would conflict with the intropattern\n notation. *)\n\n(* tactics from branch concurrency *)\n\n(*\nLtac forward_call_id00_wow_threadlib witness witness' :=\nlet Frame := fresh \"Frame\" in\n evar (Frame: list (mpred));\n eapply (semax_call_id00_wow_threadlib witness witness' Frame);\n [ reflexivity | reflexivity | reflexivity | reflexivity\n | prove_local2ptree | repeat constructor\n | try apply local_True_right; entailer!\n | reflexivity\n | prove_local2ptree | repeat constructor\n | reflexivity | reflexivity\n | Forall_pTree_from_elements\n | Forall_pTree_from_elements\n | unfold fold_right at 1 2; cancel\n | cbv beta iota;\n repeat rewrite exp_uncurry;\n try rewrite no_post_exists0;\n first [reflexivity | extensionality; simpl; reflexivity]\n | intros; try match goal with |- extract_trivial_liftx ?A _ =>\n (has_evar A; fail 1) || (repeat constructor)\n end\n | unify_postcondition_exps\n | unfold fold_right_and; repeat rewrite and_True; auto\n ].\n\nLtac fwd_call'_threadlib witness witness' :=\n try match goal with\n | |- semax _ _ (Scall _ _ _) _ => rewrite -> semax_seq_skip\n end;\n first [\n revert witness;\n match goal with |- let _ := ?A in _ => intro; fwd_call'_threadlib A witness'\n end\n | eapply semax_seq';\n [first [forward_call_id1_wow witness\n | forward_call_id1_x_wow witness\n | forward_call_id1_y_wow witness\n | forward_call_id01_wow witness ]\n | after_forward_call\n ]\n | eapply semax_seq'; [forward_call_id00_wow_threadlib witness witness'\n | after_forward_call ]\n | rewrite <- seq_assoc; fwd_call'_threadlib witness witness'\n ].\n\nTactic Notation \"forward_call_threadlib\" constr(witness) constr(witness') simple_intropattern_list(v) :=\n (* (* we don't need this check (as our specs are canonical),\n and it stack overflows *)\n check_canonical_call; *)\n check_Delta;\n fwd_call'_threadlib witness witness';\n [ ..\n | first\n [ (* body of uniform_intros tactic *)\n (((assert True by (intros v; apply I);\n assert (forall a: unit, True) by (intros v; apply I);\n fail 1)\n || intros v)\n || idtac);\n (* end body of uniform_intros tactic *)\n match goal with\n | |- semax _ _ _ _ => idtac\n | |- unit -> semax _ _ _ _ => intros _\n end;\n repeat (apply semax_extract_PROP; intro);\n abbreviate_semax;\n try fwd_skip\n | complain_intros\n ]\n ].\n*)\nEnd threadlib.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/semax_sync_call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.13762179700456517}} {"text": "(* Step-indexed logical relations for LambdaANF closure conversion. Part of the CertiCoq project.\n * Author: Anonymized, 2016\n *)\n\nRequire Import Coq.NArith.BinNat Coq.Relations.Relations Coq.MSets.MSets Coq.MSets.MSetRBT\n Coq.Lists.List Coq.micromega.Lia Coq.Sets.Ensembles.\nRequire Import LambdaANF.cps LambdaANF.eval LambdaANF.cps_util LambdaANF.identifiers LambdaANF.ctx LambdaANF.set_util\n LambdaANF.Ensembles_util LambdaANF.List_util LambdaANF.size_cps LambdaANF.tactics LambdaANF.algebra. \nRequire Export LambdaANF.logical_relations.\nRequire Import compcert.lib.Coqlib.\n\nImport ListNotations.\n\nClose Scope Z_scope.\n\nSection LogRelCC.\n\n Variable (pr : prims).\n Variable (cenv : ctor_env).\n \n (* Tag for closure records *)\n Variable (clo_tag : ctor_tag). \n\n Context {fuel : Type} {Hf : @fuel_resource fuel} {trace : Type} {Ht : @trace_resource trace}.\n\n Section Exp_rel. \n\n Variable (cc_approx_val : nat -> @PostGT fuel trace -> val -> val -> Prop).\n \n Definition cc_approx_res (k : nat) (P2 : PostGT) (r1 r2 : res) := \n match r1, r2 with \n | OOT, OOT => True \n | Res v1, Res v2 => cc_approx_val k P2 v1 v2\n | _, _ => False\n end.\n\n Definition cc_approx_exp' (k : nat) (P1 : @PostGT fuel trace) (P2 : @PostGT fuel trace) (p1 p2 : exp * env) : Prop :=\n let '(e1, rho1) := p1 in\n let '(e2, rho2) := p2 in\n forall v1 cin1 cout1,\n to_nat cin1 <= k -> bstep_fuel cenv rho1 e1 cin1 v1 cout1 -> \n (* @not_stuck cenv fuel _ trace _ rho1 e1 -> *)\n exists v2 cin2 cout2,\n bstep_fuel cenv rho2 e2 cin2 v2 cout2 /\\\n (* extra invariants for cost *)\n P1 (e1, rho1, cin1, cout1) (e2, rho2, cin2, cout2) /\\\n cc_approx_res (k - to_nat cin1) P2 v1 v2.\n\n End Exp_rel. \n\n (** step-indexed relation on cps terms. Relates terms with open function with closure-converted terms *)\n\n Fixpoint cc_approx_val (k : nat) (PG : PostGT) (v1 v2 : val) {struct k} : Prop :=\n let fix cc_approx_val_aux (v1 v2 : val) {struct v1} : Prop :=\n let fix Forall2_aux vs1 vs2 :=\n match vs1, vs2 with\n | [], [] => True\n | v1 :: vs1, v2 :: vs2 =>\n cc_approx_val_aux v1 v2 /\\ Forall2_aux vs1 vs2\n | _, _ => False\n end\n in\n match v1, v2 with\n | Vfun rho1 defs1 f1,\n Vconstr tag ((Vfun rho2 defs2 f2) :: (Vconstr tag' fvs) :: []) =>\n tag = clo_tag /\\\n forall (vs1 vs2 : list val) (j : nat) (t : fun_tag) \n (xs1 : list var) (e1 : exp) (rho1' : env),\n List.length vs1 = List.length vs2 ->\n find_def f1 defs1 = Some (t, xs1, e1) ->\n Some rho1' = set_lists xs1 vs1 (def_funs defs1 defs1 rho1 rho1) ->\n exists (Γ : var) (xs2 : list var) (e2 : exp) (rho2' : env),\n find_def f2 defs2 = Some (t, Γ :: xs2, e2) /\\ \n Some rho2' = set_lists (Γ :: xs2) ((Vconstr tag' fvs) :: vs2)\n (def_funs defs2 defs2 rho2 rho2) /\\\n match k with\n | 0 => True\n | S k =>\n let R := cc_approx_val (k - (k-j)) PG in\n j < S k ->\n Forall2 R vs1 vs2 ->\n cc_approx_exp' cc_approx_val (k - (k - j)) PG PG\n (e1, rho1') (e2, rho2')\n end\n | Vconstr t1 vs1, Vconstr t2 vs2 =>\n t1 = t2 /\\ Forall2_aux vs1 vs2\n | Vint n1, Vint n2 => n1 = n2\n | Vprim p1, Vprim p2 => p1 = p2\n | _, _ => False\n end\n in cc_approx_val_aux v1 v2.\n\n \n (** More compact definition of the value relation *)\n Definition cc_approx_val' (k : nat) (P : PostGT) (v1 v2 : val) : Prop :=\n match v1, v2 with\n | Vfun rho1 defs1 f1,\n Vconstr tag ((Vfun rho2 defs2 f2) :: (Vconstr tag' fvs) :: []) =>\n tag = clo_tag /\\\n forall (vs1 vs2 : list val) (j : nat) (t : fun_tag) \n (xs1 : list var) (e1 : exp) (rho1' : env),\n List.length vs1 = List.length vs2 ->\n find_def f1 defs1 = Some (t, xs1, e1) ->\n Some rho1' = set_lists xs1 vs1 (def_funs defs1 defs1 rho1 rho1) ->\n exists (Γ : var) (xs2 : list var) (e2 : exp) (rho2' : env),\n find_def f2 defs2 = Some (t, Γ :: xs2, e2) /\\\n Some rho2' = set_lists (Γ :: xs2) ((Vconstr tag' fvs) :: vs2)\n (def_funs defs2 defs2 rho2 rho2) /\\\n (j < k -> Forall2 (cc_approx_val j P) vs1 vs2 ->\n cc_approx_exp' cc_approx_val j P P (e1, rho1') (e2, rho2'))\n | Vconstr t1 vs1, Vconstr t2 vs2 =>\n t1 = t2 /\\ Forall2 (cc_approx_val k P) vs1 vs2\n | Vint n1, Vint n2 => n1 = n2\n | Vprim p1, Vprim p2 => p1 = p2\n | _, _ => False\n end.\n \n (** Correspondence of the two definitions *)\n Lemma cc_approx_val_eq (k : nat) P (v1 v2 : val) :\n cc_approx_val k P v1 v2 <-> cc_approx_val' k P v1 v2.\n Proof.\n destruct k as [ | k ]; destruct v1; destruct v2;\n eauto; try (split; intros H; (now simpl in H; inv H)).\n - split.\n * revert l0; induction l as [| x xs IHxs];\n intros l2; destruct l2 as [| y ys ];\n try (now intros [H1 H2]; split; eauto; inv H2).\n intros H; split; destruct H as [H1 [H2 H3]]; eauto.\n constructor; [ now eauto | now eapply IHxs ].\n * revert l0; induction l as [| x xs IHxs];\n intros l2; destruct l2 as [| y ys ];\n try (now intros [H1 H2]; split; eauto; inv H2).\n intros H; split; inv H; eauto. inv H1.\n split; [ now eauto | now eapply IHxs ].\n - split; intros Hpre; simpl; destruct l; try contradiction;\n destruct v0; try contradiction; destruct l; try contradiction;\n destruct l; try contradiction; destruct v1; try contradiction;\n destruct Hpre as [Heq Hpre]; subst; split; eauto;\n intros; edestruct (Hpre vs1 vs2 0) as [Γ [xs2 [e2 [rho' [H1' [H2' H3']]]]]];\n eauto; subst; do 4 eexists; repeat split; eauto; intros Hc; exfalso; lia.\n - split.\n * revert l0; induction l as [| x xs IHxs];\n intros l2; destruct l2 as [| y ys ];\n try (now intros [H1 H2]; split; eauto; inv H2).\n intros H; split; destruct H as [H1 [H2 H3]]; eauto. constructor. eauto.\n eapply IHxs. simpl. eauto.\n * revert l0; induction l as [| x xs IHxs];\n intros l2; destruct l2 as [| y ys ];\n try (now intros [H1 H2]; split; eauto; inv H2).\n intros H; split; inv H; eauto. inv H1.\n split; [now eauto | now apply IHxs].\n - split; intros Hpre; simpl; destruct l; try contradiction;\n destruct v0; try contradiction; destruct l; try contradiction;\n destruct l; try contradiction; destruct v1; try contradiction;\n destruct Hpre as [Heq Hpre]; subst;\n split; eauto; intros;\n edestruct (Hpre vs1 vs2 j) as [Γ [xs2 [e2 [rho' [H1' [H2' H3']]]]]];\n eauto; do 4 eexists; repeat split; eauto; intros Hleq Hf' v1 c1 Hleq' Hstep;\n (assert (Heq' : k - (k - j) = j) by lia);\n rewrite Heq' in *; eapply H3'; eauto.\n Qed.\n\n Global Opaque cc_approx_val.\n\n Notation cc_approx_exp := (cc_approx_exp' cc_approx_val).\n\n (** Environment relation for a single point (i.e. variable) : \n * ρ1 ~_k^x ρ2 iff ρ1(x) = Some v -> ρ2(x) = Some v' /\\ v ~_k v' *)\n Definition cc_approx_var_env (k : nat) P (rho1 rho2 : env) (x y : var) : Prop :=\n forall v1, \n M.get x rho1 = Some v1 -> \n exists v2, M.get y rho2 = Some v2 /\\ cc_approx_val k P v1 v2.\n\n (** Environment relation for a set of points (i.e. predicate over variables) : \n * ρ1 ~_k^S ρ2 iff \n * forall x, S x -> ρ1(x) = Some v -> ρ2(x) = Some v' /\\ v ~_k v' *)\n Definition cc_approx_env_P (S : Ensemble var) k P rho1 rho2 :=\n forall (x : var), S x -> cc_approx_var_env k P rho1 rho2 x x.\n\n (** Environment relation for the whole domain of definition :\n * ρ1 ~_k ρ2 iff forall x, ρ1(x) = v => ρ2(x) = v' /\\ v ~_k v' *)\n Definition cc_approx_env (k : nat) P (rho1 rho2 : env) : Prop :=\n cc_approx_env_P (fun _ => True) k P rho1 rho2.\n \n (** Lemmas about extending the environment *)\n Lemma cc_approx_var_env_extend_eq :\n forall (rho1 rho2 : env) (k : nat) P (x : var) (v1 v2 : val),\n cc_approx_val k P v1 v2 ->\n cc_approx_var_env k P (M.set x v1 rho1) (M.set x v2 rho2) x x.\n Proof.\n intros rho1 rho2 k P x v1 v2 Hval x' Hget.\n rewrite M.gss in Hget. inv Hget. eexists. rewrite M.gss. split; eauto.\n Qed.\n\n Lemma cc_approx_var_env_extend_neq :\n forall (rho1 rho2 : env) (k : nat) P (x y : var) (v1 v2 : val),\n cc_approx_var_env k P rho1 rho2 y y ->\n y <> x ->\n cc_approx_var_env k P (M.set x v1 rho1) (M.set x v2 rho2) y y.\n Proof.\n intros rho1 rho2 k P x y v1 v2 Hval Hneq x' Hget.\n rewrite M.gso in *; eauto.\n Qed.\n\n Lemma cc_approx_var_env_extend :\n forall (rho1 rho2 : env) (k : nat) P (x y : var) (v1 v2 : val),\n cc_approx_var_env k P rho1 rho2 y y ->\n cc_approx_val k P v1 v2 ->\n cc_approx_var_env k P (M.set x v1 rho1) (M.set x v2 rho2) y y.\n Proof.\n intros rho1 rho2 k P x y v1 v2 Henv Hval.\n destruct (peq y x); subst.\n - apply cc_approx_var_env_extend_eq; eauto.\n - apply cc_approx_var_env_extend_neq; eauto.\n Qed.\n\n (** The environment relation is antimonotonic in the set\n * of free variables *) \n Lemma cc_approx_env_P_antimon (S1 S2 : var -> Prop) P k rho1 rho2 :\n cc_approx_env_P S2 k P rho1 rho2 ->\n S1 \\subset S2 ->\n cc_approx_env_P S1 k P rho1 rho2.\n Proof.\n intros Hpre Hin x HP2. eapply Hpre; eapply Hin; eauto.\n Qed.\n\n Lemma cc_approx_exp_rel_mon (P1 P1' : PostT) P2 k e1 rho1 e2 rho2 :\n cc_approx_exp k P1 P2 (e1, rho1) (e2, rho2) ->\n inclusion _ P1 P1' ->\n cc_approx_exp k P1' P2 (e1, rho1) (e2, rho2).\n Proof.\n intros Hcc Hin v1 c1 cout1 Hleq Hstep.\n edestruct Hcc as [v2 [c2 [cout2 [Hstep2 [HP Hval]]]]]; eauto.\n repeat eexists; eauto.\n Qed.\n\n Lemma cc_approx_exp_same_rel_IH (P1 : PostT) P2 P2' k e1 rho1 e2 rho2 :\n (forall m v1 v2,\n m <= k ->\n cc_approx_val m P2 v1 v2 ->\n cc_approx_val m P2' v1 v2) ->\n cc_approx_exp k P1 P2 (e1, rho1) (e2, rho2) ->\n same_relation _ P2 P2' ->\n cc_approx_exp k P1 P2' (e1, rho1) (e2, rho2).\n Proof.\n intros IH Hcc Hin v1 c1 cout1 Hleq Hstep.\n edestruct Hcc as [v2 [c2 [cout2 [Hstep2 [HP Hval]]]]]; eauto.\n repeat eexists; eauto. \n destruct v1; destruct v2; try contradiction; eauto.\n eapply IH; eauto. lia.\n Qed.\n \n Lemma cc_approx_val_same_rel (k : nat) P1 P2 v1 v2 :\n cc_approx_val k P1 v1 v2 ->\n same_relation _ P1 P2 ->\n cc_approx_val k P2 v1 v2.\n Proof.\n revert v1 v2 P1 P2.\n induction k using lt_wf_rec1.\n intros x; induction x using val_ind'; simpl; eauto;\n intros v2 P1 P2 Hval Hin; rewrite cc_approx_val_eq in *;\n destruct v2; try contradiction. \n - destruct Hval as [Heq Hall]; subst; simpl; eauto.\n inv Hall. split; eauto.\n - destruct Hval as [Heq Hall]; subst; simpl; eauto.\n inv Hall. split; eauto. constructor; eauto.\n assert\n (Hsuf :\n cc_approx_val' k P2 (Vconstr c l) (Vconstr c l')).\n { rewrite <- cc_approx_val_eq. eapply IHx0; eauto. \n rewrite cc_approx_val_eq. split; eauto. }\n now inv Hsuf.\n - destruct l; try contradiction.\n destruct v0; try contradiction.\n destruct l; try contradiction.\n destruct v1; try contradiction.\n destruct l; try contradiction.\n destruct Hval as [Heq Hval]; subst; split; eauto.\n intros vs1 vs2 i t1 xs1 e1 rho1' Hlen Hdef Hset.\n edestruct Hval as [Gamma [xs2 [e2 [rho2' [Hdef' [Hset' Hi]]]]]]; eauto.\n do 4 eexists; repeat split; eauto. intros Hlt Hall.\n eapply cc_approx_exp_same_rel_IH; [| | eassumption ].\n intros; eapply H; eauto; lia.\n eapply cc_approx_exp_rel_mon.\n eapply Hi; eauto. eapply Forall2_monotonic; [| eassumption ].\n intros. eapply H; eauto. now firstorder. now firstorder.\n - eauto.\n - eauto.\n Qed.\n\n Lemma cc_approx_exp_same_rel (P : PostT) P1 P2 k e1 rho1 e2 rho2 :\n cc_approx_exp k P P1 (e1, rho1) (e2, rho2) ->\n same_relation _ P1 P2 ->\n cc_approx_exp k P P2 (e1, rho1) (e2, rho2).\n Proof.\n intros Hcc Hin v1 c1 c2 Hleq Hstep.\n edestruct Hcc as [v2 [c2' [cout2 [Hstep2 [HP Hval]]]]]; eauto.\n repeat eexists; eauto. \n destruct v1; destruct v2; try contradiction; eauto. simpl in *.\n eapply cc_approx_val_same_rel; eauto.\n Qed.\n\n Global Instance cc_approx_env_proper_set :\n Proper (Same_set var ==> Logic.eq ==> Logic.eq ==> Logic.eq ==> Logic.eq ==> iff)\n cc_approx_env_P.\n Proof.\n intros s1 s2 [H1 H2]; split; intros Hpre;\n eapply cc_approx_env_P_antimon; subst; eauto.\n Qed.\n\n (** Lemmas about the sets that index the environment relation *)\n Lemma cc_approx_env_Empty_set k P (rho1 rho2 : env) :\n cc_approx_env_P (Empty_set var) k P rho1 rho2.\n Proof.\n intros x H. inv H.\n Qed.\n\n Lemma cc_approx_env_P_union (P1 P2 : Ensemble var) k P rho1 rho2 :\n cc_approx_env_P P1 k P rho1 rho2 ->\n cc_approx_env_P P2 k P rho1 rho2 ->\n cc_approx_env_P (Union var P1 P2) k P rho1 rho2.\n Proof.\n intros Hpre1 Hpre2 x HP2. inv HP2; eauto.\n Qed.\n\n Lemma cc_approx_env_P_inter_l (P1 P2 : Ensemble var) k P rho1 rho2 :\n cc_approx_env_P P1 k P rho1 rho2 ->\n cc_approx_env_P (Intersection var P1 P2) k P rho1 rho2.\n Proof.\n intros Hpre x HP2. inv HP2; eauto.\n Qed.\n \n Lemma cc_approx_env_P_inter_r (P1 P2 : Ensemble var) k P rho1 rho2 :\n cc_approx_env_P P2 k P rho1 rho2 ->\n cc_approx_env_P (Intersection var P1 P2) k P rho1 rho2.\n Proof.\n intros Hpre x HP2. inv HP2; eauto.\n Qed.\n \n (** Extend the related environments with a single point *)\n Lemma cc_approx_env_P_extend :\n forall S (rho1 rho2 : env) (k : nat) P (x : var) (v1 v2 : val),\n cc_approx_env_P (Setminus var S (Singleton var x)) k P rho1 rho2 ->\n cc_approx_val k P v1 v2 ->\n cc_approx_env_P S k P (M.set x v1 rho1) (M.set x v2 rho2).\n Proof.\n intros S rho1 rho2 k P x v1 v2 Henv Hval x' HP v1' Hget.\n rewrite M.gsspec in Hget. destruct (peq x' x); subst.\n - inv Hget. eexists. rewrite M.gss. split; eauto.\n - apply Henv in Hget; eauto. destruct Hget as [v2' [Heq Hpre]].\n eexists; split; eauto. rewrite M.gso; eauto. constructor; eauto.\n intros Hin. inv Hin. congruence.\n Qed.\n\n (** Extend the related environments with a list *)\n Lemma cc_approx_env_P_set_lists_l:\n forall (P1 P2 : Ensemble var) (rho1 rho2 rho1' rho2' : env)\n (k : nat) P (xs : list var) (vs1 vs2 : list val),\n cc_approx_env_P P1 k P rho1 rho2 ->\n (forall x, ~ List.In x xs -> P2 x -> P1 x) ->\n Forall2 (cc_approx_val k P) vs1 vs2 ->\n set_lists xs vs1 rho1 = Some rho1' ->\n set_lists xs vs2 rho2 = Some rho2' ->\n cc_approx_env_P P2 k P rho1' rho2'.\n Proof.\n intros P1 P2 rho1' rho2' rho1 rho2 k P xs vs1 vs2 Hpre Hyp Hall Hset1 Hset2\n x HP v Hget.\n destruct (in_dec var_dec x xs).\n - edestruct (@set_lists_Forall2_get val) as [v1 [v2 [Hget1 [Hget2 HP']]]]; eauto.\n rewrite Hget in Hget1. inv Hget1. repeat eexists; eauto.\n - erewrite <- set_lists_not_In in Hget; eauto.\n edestruct Hpre as [v2 [Hget' Hpre']]; eauto.\n repeat eexists; eauto. erewrite <- set_lists_not_In; eauto.\n Qed.\n\n Lemma cc_approx_var_env_get_list (rho1 rho2 : env) (k : nat) P\n (xs ys : list var) (vs1 : list val) :\n Forall2 (cc_approx_var_env k P rho1 rho2) xs ys ->\n get_list xs rho1 = Some vs1 ->\n exists vs2,\n get_list ys rho2 = Some vs2 /\\ Forall2 (cc_approx_val k P) vs1 vs2.\n Proof.\n revert ys vs1. induction xs as [| x xs IHxs]; intros ys vs2 Hall Hget.\n - destruct ys; inv Hall. inv Hget. eexists. split; simpl; eauto.\n - simpl in Hget.\n destruct (M.get x rho1) eqn:Heq1; try discriminate.\n destruct (get_list xs rho1) eqn:Heq2; try discriminate. inv Hget.\n destruct ys as [| y ys]; inv Hall. \n destruct (IHxs ys l H4 eq_refl) as [vs2 [Hget HAll]].\n destruct (H2 _ Heq1) as [v2 [Heq Hpre]].\n eexists. split; simpl; eauto. rewrite Hget, Heq. eauto.\n Qed.\n\n Lemma cc_approx_env_P_get_list_l (P : var -> Prop) (rho1 rho2 : env) (k : nat) S\n (xs : list var) (vs1 : list val) :\n cc_approx_env_P P k S rho1 rho2 ->\n Included _ (FromList xs) P ->\n get_list xs rho1 = Some vs1 ->\n exists vs2,\n get_list xs rho2 = Some vs2 /\\ Forall2 (cc_approx_val k S) vs1 vs2.\n Proof.\n intros Henv. revert vs1.\n induction xs as [| x xs IHxs]; intros vs1 Hp Hget.\n - inv Hget. eexists. split; simpl; eauto.\n - simpl in Hget. destruct (M.get x rho1) eqn:Heq1; try discriminate.\n destruct (get_list xs rho1) eqn:Heq2; try discriminate. inv Hget.\n edestruct (IHxs l) as [vs2 [Hget HAll]]; eauto.\n + intros x' Hin. eapply Hp. constructor 2; eauto.\n + eapply Henv in Heq1. destruct Heq1 as [v2 [H1 H2]].\n eexists. split; simpl; eauto. rewrite H1. rewrite Hget.\n constructor. apply Hp. now constructor.\n Qed.\n\n Corollary cc_approx_env_get_list_l (rho1 rho2 : env) (k : nat) S\n (xs : list var) (vs1 : list val) :\n cc_approx_env k S rho1 rho2 ->\n get_list xs rho1 = Some vs1 ->\n exists vs2,\n get_list xs rho2 = Some vs2 /\\ Forall2 (cc_approx_val k S) vs1 vs2.\n Proof.\n intros. eapply cc_approx_env_P_get_list_l; eauto.\n intros x H'; simpl; eauto.\n Qed.\n \n Corollary cc_approx_env_extend (rho1 rho2 : env) (k : nat) S\n (x : var) (v1 v2 : val) :\n cc_approx_env k S rho1 rho2 ->\n cc_approx_val k S v1 v2 ->\n cc_approx_env k S (M.set x v1 rho1) (M.set x v2 rho2).\n Proof.\n intros H1 Hval. apply cc_approx_env_P_extend; eauto.\n eapply cc_approx_env_P_antimon; eauto. intros x' H; simpl; eauto.\n Qed.\n\n Corollary cc_approx_env_set_lists_l (rho1 rho2 rho1' rho2' : env) (k : nat)\n S (xs : list var) (vs1 vs2 : list val) :\n cc_approx_env k S rho1 rho2 ->\n Forall2 (cc_approx_val k S) vs1 vs2 ->\n set_lists xs vs1 rho1 = Some rho1' ->\n set_lists xs vs2 rho2 = Some rho2' ->\n cc_approx_env k S rho1' rho2'.\n Proof.\n intros. eapply cc_approx_env_P_set_lists_l; eauto.\n Qed.\n\n Lemma cc_approx_env_P_set_not_in_P_r P k S rho rho' x v :\n cc_approx_env_P P k S rho rho' ->\n ~ x \\in P ->\n cc_approx_env_P P k S rho (M.set x v rho').\n Proof. \n intros Hcc Hnin y Py v' Hget.\n edestruct Hcc as [v'' [Hget' Happrox]]; eauto.\n exists v''. rewrite M.gsspec.\n destruct (peq y x); subst.\n - contradiction.\n - eauto.\n Qed.\n\n Lemma cc_approx_env_P_def_funs_not_In_P_l k S rho1 rho2 P B B' :\n Disjoint _ S (name_in_fundefs B') ->\n cc_approx_env_P S k P rho1 rho2 ->\n cc_approx_env_P S k P (def_funs B B' rho1 rho1) rho2.\n Proof.\n intros Hd Hcc x HS v Hget. eapply Hcc; eauto. \n erewrite <- def_funs_neq. eassumption. \n intros Hc. eapply Hd; constructor; eauto.\n Qed.\n \n Lemma cc_approx_env_P_def_funs_not_In_P_r k P rho1 rho2 S B B' :\n Disjoint _ S (name_in_fundefs B') ->\n cc_approx_env_P S k P rho1 rho2 ->\n cc_approx_env_P S k P rho1 (def_funs B B' rho2 rho2).\n Proof.\n intros Hd Hcc x HS v Hget.\n edestruct Hcc as [v' [Hget' Hcc']]; eauto.\n eexists; split; eauto.\n rewrite def_funs_neq. eassumption.\n intros Hc. eapply Hd; constructor; eauto.\n Qed.\n \n (** * Index Monotonicity Properties *)\n\n (** The value relation is monotonic in the step index *)\n Lemma cc_approx_val_monotonic (k : nat) P :\n (forall v1 v2 j,\n cc_approx_val k P v1 v2 -> j <= k -> cc_approx_val j P v1 v2).\n Proof.\n intros v1 v2 h Hpre Hleq. try rewrite cc_approx_val_eq in *.\n revert v2 Hpre; induction v1 using val_ind'; intros v2 Hpre;\n destruct v2; try (simpl; contradiction); eauto.\n - destruct l; try now inv Hpre.\n - inv Hpre. inv H0.\n split; auto. constructor; rewrite cc_approx_val_eq in *.\n now eapply IHv1; eauto.\n destruct (IHv0 ((Vconstr c l'))) as [Heq Hpre']; eauto.\n now split; eauto.\n - destruct l; try contradiction. destruct v0; try contradiction. \n destruct l; try contradiction. destruct v1; try contradiction. \n destruct l; try contradiction.\n destruct Hpre as [Heq1 Hpre]; subst; split; eauto.\n intros vs1 vs2 j t1' xs e1 rho1' Hlen Hf' Heq.\n edestruct Hpre as [Γ [xs2 [e2 [rho2' [H1 [H2 H3]]]]]]; eauto.\n subst. do 4 eexists; repeat split; eauto. intros Hleq' Hall.\n eapply H3; eauto. lia.\n Qed.\n\n Lemma cc_approx_res_monotonic (k : nat) P :\n (forall v1 v2 j,\n cc_approx_res cc_approx_val k P v1 v2 -> j <= k -> cc_approx_res cc_approx_val j P v1 v2).\n Proof.\n intros [|] [|] j H; try contradiction; eauto. \n eapply cc_approx_val_monotonic; eauto.\n Qed.\n\n (** The expression relation is monotonic in the step index *)\n Lemma cc_approx_exp_monotonic (k j : nat) P1 P2 rho1 e1 rho2 e2 :\n cc_approx_exp k P1 P2 (rho1, e1) (rho2, e2) ->\n j <= k ->\n cc_approx_exp j P1 P2 (rho1, e1) (rho2, e2).\n Proof.\n intros Hpre Hleq v1 c1 cout1 Hlt Hstep.\n edestruct (Hpre v1 c1) as [v2 [c2 [cout2 [H1 [H2 H3]]]]]; eauto. lia.\n do 3 eexists; repeat split; eauto.\n eapply cc_approx_res_monotonic; eauto. lia.\n Qed.\n \n (** The environment relations are monotonic in the step index *)\n Lemma cc_approx_env_P_monotonic :\n forall P (k j : nat) S (rho1 rho2 : env),\n j <= k -> cc_approx_env_P P k S rho1 rho2 -> cc_approx_env_P P j S rho1 rho2.\n Proof.\n intros P k j S rho1 rho2 Hleq Hpre x HP v Hget.\n edestruct Hpre as [v2 [Heq Hpre2]]; eauto.\n eexists; split; eauto. eapply cc_approx_val_monotonic; eauto.\n Qed.\n\n Lemma cc_approx_env_monotonic k j S rho1 rho2 :\n j <= k -> cc_approx_env k S rho1 rho2 -> cc_approx_env j S rho1 rho2.\n Proof.\n intros Hleq H. eapply cc_approx_env_P_monotonic; eauto.\n Qed.\n \n (* Closure projection before application application *)\n Definition AppClo f f' Γ :=\n Eproj_c f' clo_tag 0%N f\n (Eproj_c Γ clo_tag 1%N f Hole_c). \n\n Open Scope alg_scope.\n \n Definition post_app_compat_cc' x t ys rho1 (P : @PostT fuel trace) (PG : @PostGT fuel trace):=\n forall e1 xs f2 Γ x' t' ys' e2 rho2 rhoc1 rhoc2 fl f vs rhoc1' cin1 cin2 cout1 cout2, \n \n map_util.M.get x rho1 = Some (Vfun rhoc1 fl f) ->\n get_list ys rho1 = Some vs ->\n find_def f fl = Some (t, xs, e1) ->\n set_lists xs vs (def_funs fl fl rhoc1 rhoc1) = Some rhoc1' ->\n \n (* for simplicity don't model the semantics of the target since it doesn't matter *)\n PG (e1, rhoc1', cin1, cout1) (e2, rhoc2, cin2, cout2) -> \n P (Eapp x t ys, rho1, cin1 <+> one (Eapp x t ys), cout1 <+> one (Eapp x t ys))\n (AppClo f2 x' Γ |[ Eapp x' t' (Γ :: ys') ]|, rho2,\n cin2 <+> one (Eapp x' t' (Γ :: ys)) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eapp x' t' (Γ :: ys))) <+>\n one (AppClo f2 x' Γ |[ Eapp x' t' (Γ :: ys') ]|),\n cout2 <+> one (Eapp x' t' (Γ :: ys)) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eapp x' t' (Γ :: ys))) <+>\n one (AppClo f2 x' Γ |[ Eapp x' t' (Γ :: ys') ]|)).\n\n \n Definition post_letapp_compat_cc' x f t ys e1 rho1 (P1 P2 : @PostT fuel trace) (PG : @PostGT fuel trace) :=\n forall xs e_b1 v1 f2 Γ x' f' t' ys' e2 e_b2\n rho2 rho2' rhoc1 rhoc2 fl h vs rhoc1' cin1 cin1' cin2 cin2' cout1 cout2 cout1' cout2', \n \n map_util.M.get f rho1 = Some (Vfun rhoc1 fl h) ->\n get_list ys rho1 = Some vs ->\n find_def h fl = Some (t, xs, e_b1) ->\n set_lists xs vs (def_funs fl fl rhoc1 rhoc1) = Some rhoc1' ->\n bstep_fuel cenv rhoc1' e_b1 cin1 (Res v1) cout1 -> \n (* Will need to prove that the size of the returned val is *)\n\n (* for simplicity don't model the semantics of the target since it doesn't matter *)\n PG (e_b1, rhoc1', cin1, cout1) (e_b2, rhoc2, cin2, cout2) -> \n P1 (e1, M.set x v1 rho1, cin1', cout1') (e2, rho2', cin2', cout2') ->\n P2 (Eletapp x f t ys e1, rho1, cin1 <+> cin1' <+> one (Eletapp x f t ys e1), cout1 <+> cout1' <+> one (Eletapp x f t ys e1))\n (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|, rho2,\n cin2 <+> cin2' <+> one (Eletapp x' f' t' (Γ :: ys') e2) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eletapp x' f' t' (Γ :: ys') e2)) <+>\n one (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|),\n cout2 <+> cout2' <+> one (Eletapp x' f' t' (Γ :: ys') e2) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eletapp x' f' t' (Γ :: ys') e2)) <+>\n one (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|) ).\n\n Definition post_letapp_compat_cc_OOT' x f t ys e1 rho1 (P2 : @PostT fuel trace) (PG : @PostGT fuel trace):=\n forall xs e_b1 f2 Γ x' f' t' ys' e2 e_b2 \n rho2 rhoc1 rhoc2 fl h vs rhoc1' cin1 cout1 cin2 cout2, \n \n map_util.M.get f rho1 = Some (Vfun rhoc1 fl h) ->\n get_list ys rho1 = Some vs ->\n find_def h fl = Some (t, xs, e_b1) ->\n set_lists xs vs (def_funs fl fl rhoc1 rhoc1) = Some rhoc1' ->\n\n (* for simplicity don't model the semantics of the target since it doesn't matter *)\n PG (e_b1, rhoc1', cin1, cout1) (e_b2, rhoc2, cin2, cout2) -> \n P2 (Eletapp x f t ys e1, rho1, cin1 <+> one (Eletapp x f t ys e1), cout1 <+> one (Eletapp x f t ys e1))\n (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|, rho2,\n cin2 <+> one (Eletapp x' f' t' (Γ :: ys') e2) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eletapp x' f' t' (Γ :: ys') e2)) <+>\n one (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|),\n cout2 <+> one (Eletapp x' f' t' (Γ :: ys') e2) <+>\n one (Eproj Γ clo_tag 1%N f2 (Eletapp x' f' t' (Γ :: ys') e2)) <+>\n one (AppClo f2 f' Γ |[ Eletapp x' f' t' (Γ :: ys') e2 ]|)).\n\n Definition post_app_compat_cc P PG := forall x t xs rho1, post_app_compat_cc' x t xs rho1 P PG.\n\n Definition post_letapp_compat_cc P1 P2 PG := forall x f t xs e1 rho1, post_letapp_compat_cc' x f t xs e1 rho1 P1 P2 PG.\n\n Definition post_letapp_compat_cc_OOT P2 PG := forall x f t xs e1 rho1, post_letapp_compat_cc_OOT' x f t xs e1 rho1 P2 PG.\n\n\n \n Section Compat.\n \n Context (P1 P2 : @PostT fuel trace) (* Local *)\n (PG : @PostGT fuel trace). (* Global *)\n \n \n Lemma cc_approx_exp_constr_compat k \n rho1 rho2 x t ys1 ys2 e1 e2 :\n post_constr_compat' x t ys1 e1 rho1 x t ys2 e2 rho2 P1 P2 ->\n post_OOT' (Econstr x t ys1 e1) rho1 (Econstr x t ys2 e2) rho2 P2 ->\n (* For application *)\n Forall2 (cc_approx_var_env k PG rho1 rho2) ys1 ys2 ->\n (forall vs1 vs2 : list val,\n (* needed by cost proof *)\n get_list ys1 rho1 = Some vs1 ->\n Forall2 (cc_approx_val k PG) vs1 vs2 ->\n cc_approx_exp k P1 PG (e1, M.set x (Vconstr t vs1) rho1)\n (e2, M.set x (Vconstr t vs2) rho2)) ->\n cc_approx_exp k P2 PG (Econstr x t ys1 e1, rho1) (Econstr x t ys2 e2, rho2).\n Proof.\n intros Hpost Hoot Hall Hpre v1 c1 cout Hleq1 Hstep1. inv Hstep1. \n - (* OOT *) \n exists OOT, c1, <0>. split. constructor; eauto. \n split; [| now eauto ]. eapply Hoot; eassumption. \n - inv H. \n edestruct (cc_approx_var_env_get_list rho1 rho2) as [vs2' [Hget' Hpre']];\n [| eauto |]; eauto.\n rewrite to_nat_add in *.\n assert (Hg := to_nat_one (exp_to_fin (Econstr x t ys1 e1))). unfold one in *.\n \n edestruct Hpre as [v2 [c2 [cout' [Hstep [HS Hval]]]]]; [| | | eassumption | ]; eauto.\n lia. \n \n eexists. exists (c2 <+> one (Econstr x t ys2 e2)); repeat eexists. \n econstructor 2; eauto. econstructor; eauto.\n eapply Hpost; eauto.\n eapply cc_approx_res_monotonic. eassumption. \n simpl in *. lia.\n Qed.\n \n Lemma cc_approx_exp_proj_compat k rho1 rho2 x tau n y1 y2 e1 e2 :\n post_proj_compat' x tau n y1 e1 rho1 x tau n y2 e2 rho2 P1 P2 ->\n post_OOT' (Eproj x tau n y1 e1) rho1 (Eproj x tau n y2 e2) rho2 P2 ->\n cc_approx_var_env k PG rho1 rho2 y1 y2 ->\n (forall v1 v2 c vs,\n (* needed for cost proof *)\n M.get y1 rho1 = Some (Vconstr c vs) ->\n List.In v1 vs ->\n cc_approx_val k PG v1 v2 -> \n cc_approx_exp k P1 PG (e1, M.set x v1 rho1)\n (e2, M.set x v2 rho2)) ->\n cc_approx_exp k P2 PG (Eproj x tau n y1 e1, rho1) (Eproj x tau n y2 e2, rho2).\n Proof.\n intros Hpost Hoot Henv Hexp v1 cin cout Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, cin, <0>. split. constructor; eassumption.\n split; [| now eauto ]. eapply Hoot; eassumption. \n - inv H. edestruct Henv as [v' [Hget Hpre]]; eauto.\n destruct v'; rewrite cc_approx_val_eq in Hpre; simpl in Hpre; try contradiction.\n inv Hpre.\n\n rewrite to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Eproj x c n y1 e1))). unfold one in *.\n \n edestruct (Forall2_nthN (cc_approx_val k PG) vs l) as [v2 [Hnth Hval]]; eauto.\n edestruct Hexp as [v2' [cin' [cout' [Hstep [HS Hval']]]]];\n [| | | | eassumption | ]; eauto.\n now eapply nthN_In; eauto. lia.\n\n do 3 eexists. split; [| split ]. \n econstructor 2; eauto. econstructor; eauto.\n \n eapply Hpost; try eassumption.\n eapply cc_approx_res_monotonic. eassumption. \n simpl in *. lia.\n Qed.\n\n (** Let Application compatibility *)\n Lemma cc_approx_exp_letapp_compat (k : nat) \n (rho1 rho2 : env) (x f1 : var) (xs1 : list var) \n (f2 f' Γ : var) (xs2 : list var) (t : fun_tag) (e1 e2 : exp) : \n post_letapp_compat_cc' x f1 t xs1 e1 rho1 P1 P2 PG ->\n post_letapp_compat_cc_OOT' x f1 t xs1 e1 rho1 P2 PG ->\n post_OOT' (Eletapp x f1 t xs1 e1) rho1 (AppClo f2 f' Γ |[ Eletapp x f' t (Γ :: xs2) e2 ]|) rho2 P2 -> \n ~ Γ \\in (f2 |: [set f'] :|: FromList xs2) ->\n ~ f' \\in (f2 |: FromList xs2) ->\n cc_approx_var_env k PG rho1 rho2 f1 f2 ->\n Forall2 (cc_approx_var_env k PG rho1 rho2) xs1 xs2 ->\n (forall m v1 v2 rho2',\n m <= k ->\n cc_approx_val m PG v1 v2 -> \n ctx_to_rho (AppClo f2 f' Γ) rho2 rho2' ->\n cc_approx_exp m P1 PG (e1, M.set x v1 rho1) (e2, M.set x v2 rho2')) ->\n \n cc_approx_exp k P2 PG (Eletapp x f1 t xs1 e1, rho1)\n (AppClo f2 f' Γ |[ Eletapp x f' t (Γ :: xs2) e2 ]|, rho2).\n Proof.\n intros Hpost Hpostoot Hoot Hnin1 Hnin2 Henv Hall Hexp v1 cin cout Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, cin, <0>. split; [| split ].\n + econstructor. unfold one. erewrite one_eq. eassumption.\n + eapply Hoot; eauto. \n + simpl; eauto. \n - inv H.\n + (* App terminates *)\n edestruct Henv as [v' [Hget Hpre]]; eauto.\n destruct v'; rewrite cc_approx_val_eq in Hpre; simpl in Hpre; try contradiction.\n destruct l as [| ? [|] ]; try contradiction;\n destruct v0; try contradiction;\n destruct v2; try contradiction.\n destruct l; try contradiction;\n \n destruct Hpre as [Heq Hpre]; subst.\n edestruct cc_approx_var_env_get_list as [vs' [Hgetl2 Hvall]]; eauto.\n\n rewrite !to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Eletapp x f1 t xs1 e1))). unfold one in *. \n \n edestruct Hpre with (j := k - 1) as [G [xs2' [e2' [rho2'' [Hfdef [Hseteq Hcc]]]]]].\n eapply Forall2_length. eassumption. eassumption. now eauto.\n subst. assert (Hevalb := H13).\n eapply Hcc in H13;\n [| | eapply Forall2_monotonic; [| eassumption ] | ]; try (unfold one in *; simpl in *; lia).\n * destruct H13 as (v2' & c2 & c2' & Hstep2 & Hge & Hccv).\n destruct v2' as [ | v2' ]; try contradiction. \n edestruct (Hexp (k - to_nat (cin1 <+> (one_i (exp_to_fin (Eletapp x f1 t xs1 e1)))))) as [v3' [cin2' [cout2' [Hstep [HS Hval']]]]];\n [| | | | eassumption | ]; eauto. simpl in *; lia.\n \n eapply cc_approx_val_monotonic. eapply Hccv. rewrite to_nat_add. unfold one in *; simpl in *. lia.\n \n econstructor. eassumption. reflexivity. econstructor. rewrite M.gso. eassumption.\n intros Hc; eapply Hnin2; subst; eauto. reflexivity. now econstructor. \n\n rewrite !to_nat_add. unfold one in *; simpl in *. lia. \n\n destruct (set_lists xs2' vs' (def_funs f f t0 t0)) eqn:Hgetl; try congruence.\n repeat subst_exp. inv Hseteq. \n do 3 eexists. split; [| split].\n -- constructor 2. econstructor; eauto. simpl. reflexivity.\n constructor 2. econstructor; eauto. \n rewrite M.gso. eassumption. intros Hc; subst. eapply Hnin2; eauto.\n simpl. reflexivity.\n constructor 2. econstructor. \n rewrite M.gso. rewrite M.gss. reflexivity.\n intros Hc. subst; now eapply Hnin1; eauto. \n simpl. rewrite M.gss. rewrite get_list_set_neq. rewrite get_list_set_neq, Hgetl2.\n reflexivity. intros Hc1. now eapply Hnin2; eauto. \n intros Hc2. now eapply Hnin1; eauto. eassumption.\n simpl. rewrite Hgetl. reflexivity. eassumption. eassumption.\n -- eapply Hpost; eassumption.\n -- eapply cc_approx_res_monotonic; eauto. simpl. rewrite to_nat_add. unfold one in *; simpl in *; lia.\n * intros. eapply cc_approx_val_monotonic; eauto. lia. \n + edestruct Henv as [v' [Hget Hpre]]; eauto.\n destruct v'; rewrite cc_approx_val_eq in Hpre; simpl in Hpre; try contradiction.\n destruct l as [| [] [|] ]; try contradiction.\n destruct v0; try contradiction. destruct l; try contradiction. destruct Hpre as [HEq Hpre].\n edestruct cc_approx_var_env_get_list as [vs' [Hgetl2 Hvall]]; eauto. \n edestruct Hpre with (j := k - 1) as [G [xs2' [e2' [rho2' [Hfdef [Hseteq Hcc]]]]]].\n eapply Forall2_length. eassumption. eassumption. now eauto.\n subst.\n rewrite !to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Eletapp x f1 t xs1 e1))). unfold one in *.\n\n eapply Hcc in H13;\n [| | eapply Forall2_monotonic; [| eassumption ] | ]; try (simpl in *; lia).\n 2:{ intros; eapply cc_approx_val_monotonic; eauto. lia. }\n destruct (set_lists xs2' vs' (def_funs f f t0 t0)) as [rho2'' | ] eqn:Hsets; inv Hseteq. \n repeat subst_exp.\n destruct H13 as (v2' & c2 & c2' & Hstep2 & Hge & Hccv).\n destruct v2' as [ | v2' ]; try contradiction. simpl in *. \n do 3 eexists; split; [| split; eauto ].\n * constructor 2. econstructor; eauto. simpl; reflexivity. \n constructor 2. econstructor; eauto. rewrite M.gso. eassumption.\n intros Hc; subst; eapply Hnin2; eauto. \n reflexivity. \n constructor 2. eapply BStept_letapp_oot; eauto.\n rewrite M.gso. rewrite M.gss. reflexivity.\n intros Hc1; subst. now eapply Hnin1; eauto.\n simpl. rewrite M.gss. \n rewrite get_list_set_neq. rewrite get_list_set_neq, Hgetl2.\n reflexivity. intros Hc1. now eapply Hnin2; eauto. \n intros Hc2. now eapply Hnin1; eauto.\n simpl. rewrite Hsets. reflexivity.\n * eapply Hpostoot; eassumption.\n * eauto.\n Qed.\n\n (** Application compatibility *)\n\n Lemma cc_approx_exp_app_compat (k : nat) \n (rho1 rho2 : env) (f1 : var) (xs1 : list var) \n (f2 f' Γ : var) (xs2 : list var) (t : fun_tag) :\n post_app_compat_cc' f1 t xs1 rho1 P2 PG ->\n post_OOT' (Eapp f1 t xs1) rho1 (AppClo f2 f' Γ |[ Eapp f' t (Γ :: xs2) ]|) rho2 P2 ->\n ~ Γ \\in (f2 |: [set f'] :|: FromList xs2) ->\n ~ f' \\in (f2 |: FromList xs2) ->\n\n cc_approx_var_env k PG rho1 rho2 f1 f2 ->\n Forall2 (cc_approx_var_env k PG rho1 rho2) xs1 xs2 -> \n cc_approx_exp k P2 PG (Eapp f1 t xs1, rho1)\n (AppClo f2 f' Γ |[ Eapp f' t (Γ :: xs2) ]|, rho2).\n Proof.\n intros Hpost Hoot Hnin1 Hnin2 Hvar Hall v1 cin cout Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, cin, <0>. split; [| split ].\n + econstructor. unfold one. erewrite one_eq. eassumption.\n + eapply Hoot; eauto. \n + simpl; eauto.\n - inv H. edestruct Hvar as [v2' [Hget Hpre]]; eauto.\n destruct v2'; rewrite cc_approx_val_eq in Hpre; simpl in Hpre; try contradiction.\n destruct l as [| ? [|] ]; try contradiction;\n destruct v; try contradiction.\n destruct v0; try contradiction. \n edestruct cc_approx_var_env_get_list as [vs' [Hgetl2 Hvall]]; eauto. \n destruct l; try contradiction.\n destruct Hpre as [Heq Hpre]; subst. \n edestruct Hpre with (j := k - 1) as [G [xs2' [e2' [rho2'' [Hfdef [Hseteq Hcc]]]]]]; try eassumption.\n eapply Forall2_length. eassumption. now eauto. \n rewrite !to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Eapp f1 t xs1))). unfold one in *.\n \n subst. \n destruct (set_lists xs2' vs' (def_funs f f t0 t0)) eqn:Hgetl; try congruence. inv Hseteq.\n repeat subst_exp. assert (Heval := H11). \n eapply Hcc in H11;\n [| | eapply Forall2_monotonic; [| eassumption ] | ]; try (simpl in *; lia).\n + destruct H11 as (v2' & c2 & cout2' & Hstep2 & Hge & Hccv).\n edestruct Hcc as [v4 [c4 [c5 [Hstep4 [Hpg4 Hrel4]]]]]; [ | | | eassumption | ].\n simpl in *; lia.\n eapply Forall2_monotonic; [| eassumption ].\n intros. eapply cc_approx_val_monotonic. eassumption. lia. simpl in *; lia.\n\n do 3 eexists. split; [| split].\n * simpl. econstructor 2. econstructor; eauto. reflexivity.\n econstructor 2. econstructor; eauto. \n rewrite M.gso. eassumption.\n intros Hc. subst; now eapply Hnin2; eauto. reflexivity.\n econstructor 2. econstructor; eauto. \n rewrite M.gso. rewrite M.gss. reflexivity.\n intros Hc. subst. now eapply Hnin1; eauto.\n simpl. rewrite M.gss.\n rewrite get_list_set_neq. rewrite get_list_set_neq. rewrite Hgetl2. reflexivity.\n intros Hc. now eapply Hnin2; eauto.\n intros Hc. now eapply Hnin1; eauto. \n simpl. rewrite Hgetl. reflexivity.\n * eapply Hpost; eauto.\n * eapply cc_approx_res_monotonic; eauto. simpl in *; lia.\n + intros. eapply cc_approx_val_monotonic; eauto. lia.\n Qed.\n\n Lemma cc_approx_exp_fun_compat k rho1 rho2 B B' e1 e2 :\n post_fun_compat' B e1 rho1 B' e2 rho2 P1 P2 ->\n post_OOT' (Efun B e1) rho1 (Efun B' e2) rho2 P2 ->\n cc_approx_exp (k - 1) P1 PG (e1, def_funs B B rho1 rho1)\n (e2, def_funs B' B' rho2 rho2) ->\n cc_approx_exp k P2 PG (Efun B e1, rho1) (Efun B' e2, rho2).\n Proof.\n intros Hyp Hpost Hexp v1 c1 c2 Hleq1 Hstep1. inv Hstep1. \n - (* OOT *) \n exists OOT, c1, <0>. split. constructor; eassumption.\n split. eapply Hpost. eassumption.\n simpl; eauto.\n - inv H.\n rewrite !to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Efun B e1))). unfold one in *.\n \n edestruct Hexp as [v2' [c3 [c4 [Hstepv2' [Hprev2' Hpost']]]]]; [ | eassumption | ]; eauto.\n\n simpl in *; lia.\n \n eexists v2', (c3 <+> one (Efun B' e2)). repeat eexists.\n econstructor 2; eauto. econstructor; eauto.\n eapply Hyp. eassumption.\n eapply cc_approx_res_monotonic. eassumption. simpl in *; lia.\n Qed.\n\n Lemma cc_approx_exp_case_nil_compat k rho1 rho2 x1 x2 :\n post_OOT' (Ecase x1 []) rho1 (Ecase x2 []) rho2 P2 ->\n cc_approx_exp k P2 PG (Ecase x1 [], rho1) (Ecase x2 [], rho2).\n Proof.\n intros Hoot v1 c1 c2 Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, c1, <0>. split. constructor; eauto. simpl in *.\n split; [| now eauto ]. eapply Hoot; eauto.\n - inv H. inv H5. \n Qed.\n\n Lemma cc_approx_exp_case_cons_compat k rho1 rho2 x1 x2 t e1 e2 B1 B2 :\n post_OOT' (Ecase x1 ((t, e1) :: B1)) rho1 (Ecase x2 ((t, e2) :: B2)) rho2 P2 ->\n post_case_compat_hd' x1 t e1 B1 rho1 x2 t e2 B2 rho2 P1 P2 ->\n post_case_compat_tl' x1 t e1 B1 rho1 x2 t e2 B2 rho2 P2 P2 ->\n\n Forall2 (fun p1 p2 => fst p1 = fst p2) B1 B2 ->\n cc_approx_var_env k PG rho1 rho2 x1 x2 ->\n (forall m, m < k -> cc_approx_exp k P1 PG (e1, rho1) (e2, rho2)) ->\n cc_approx_exp k P2 PG (Ecase x1 B1, rho1) (Ecase x2 B2, rho2) ->\n cc_approx_exp k P2 PG (Ecase x1 ((t, e1) :: B1), rho1) (Ecase x2 ((t, e2) :: B2), rho2).\n Proof.\n intros Hoot Hposthd Hposttl Hall Henv Hexp_hd Hexp_tl v1 c1 c2 Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, c1, <0>. split. constructor; eauto. simpl in *.\n split; [| now eauto ]. eapply Hoot; eauto.\n - inv H.\n rewrite !to_nat_add in *. assert (Hg := to_nat_one (exp_to_fin (Ecase x1 ((t, e1) :: B1)))). unfold one in *.\n inv H3. destruct (var_dec t t0). \n + inv H5; [| contradiction ]; subst.\n edestruct (Hexp_hd (k - 1)) as [v2 [c2 [c2' [Hstep2 [Hpost Hpre2]]]]];\n [ | | eassumption | ]; eauto. simpl in *; lia. simpl in *; lia.\n\n edestruct Henv as [v2' [Hget Hpre]]; eauto.\n rewrite cc_approx_val_eq in Hpre.\n destruct v2'; try (now simpl in Hpre; contradiction). inv Hpre. \n \n repeat eexists.\n * econstructor 2; eauto. econstructor; eauto. econstructor; eauto.\n eapply caseConsistent_same_ctor_tags. eassumption. eassumption.\n now constructor. \n * eapply Hposthd; eauto.\n * eapply cc_approx_res_monotonic. eassumption. \n simpl in *; lia.\n + inv H5. contradiction.\n edestruct Hexp_tl with (cin1 := cin <+> one (Ecase x1 B1)) as [v2 [c2 [c3 [Hstep2 [Hpost2 Hpre2]]]]].\n * rewrite to_nat_add. unfold one in *; simpl in *; lia. \n * econstructor 2; eauto. econstructor; eauto. \n * eapply Henv in H2. destruct H2 as [v2' [Hgetx2 Hval]]. \n assert (Hval' := Hval). rewrite cc_approx_val_eq in Hval'. \n destruct v2'; try contradiction. simpl in Hval'. inv Hval'. \n inv Hstep2. \n -- destruct v1; try contradiction. \n exists OOT, c2, <0>. split; [| split ]. constructor 1. \n simpl in *; eassumption. eapply Hposttl; eassumption. eauto.\n -- inv H. repeat subst_exp.\n do 3 eexists. split; [| split ].\n econstructor 2. econstructor; eauto. econstructor; eauto. \n now econstructor; eauto.\n eapply Hposttl. eassumption.\n simpl. rewrite to_nat_add in Hpre2. unfold one in *. eassumption. \n Qed. \n\n Lemma cc_approx_exp_halt_compat k rho1 rho2 x1 x2 :\n post_OOT' (Ehalt x1) rho1 (Ehalt x2) rho2 P2 ->\n post_base' x1 rho1 x2 rho2 P2 ->\n cc_approx_var_env k PG rho1 rho2 x1 x2 ->\n cc_approx_exp k P2 PG (Ehalt x1, rho1) (Ehalt x2, rho2).\n Proof.\n intros Hoot Hbase Hvar v1 c1 c2 Hleq1 Hstep1. inv Hstep1.\n - (* ΟΟΤ *)\n exists OOT, c1, <0>. split. constructor; eauto.\n split; [| now eauto ]. eapply Hoot; eauto.\n - inv H. edestruct Hvar as [v2' [Hget Hpre]]; eauto.\n repeat eexists. econstructor 2; eauto. econstructor. eassumption.\n rewrite !plus_zero.\n now eapply Hbase; eauto.\n eapply cc_approx_val_monotonic. eassumption. lia.\n Qed.\n\n Lemma cc_approx_exp_prim_val_compat k rho1 rho2 x1 x2 p e1 e2 :\n post_OOT' (Eprim_val x1 p e1) rho1 (Eprim_val x2 p e2) rho2 P2 ->\n cc_approx_exp k P2 PG (Eprim_val x1 p e1, rho1) (Eprim_val x2 p e2, rho2).\n Proof.\n intros Hoot v1 cin cout Hleq1 Hstep1. inv Hstep1.\n - (* OOT *) \n exists OOT, cin, <0>. split. constructor; eassumption. \n split; [| now eauto ]. eapply Hoot; eauto.\n - inv H. \n(* edestruct cc_approx_var_env_get_list as [vs2 [Hget' Hpre']]; [| eassumption | ]; eauto.\n edestruct Prim_axiom_cc as [v2 [Heq Hprev2]]; eauto.\n edestruct (Hpre (k - 1)) as [v2' [c2 [Hstepv2' [Hpost2 Hprev2']]]]; [ | | | | | | eassumption | ]; eauto.\n simpl in *; lia. simpl in *; lia. \n eexists. exists (c2 + cost (Eprim x2 f ys2 e2)). split; [| split ].\n econstructor 2; eauto. lia. \n econstructor; eauto.\n replace (c2 + cost (Eprim x2 f ys2 e2) - cost (Eprim x2 f ys2 e2)) with c2 by lia. \n eassumption.\n replace cin with (cin - cost (Eprim x1 f ys1 e1) + cost (Eprim x2 f ys2 e2)).\n 2:{ simpl in *. eapply Forall2_length in Hall. rewrite Hall. lia. } \n eapply HPost. eassumption.\n eapply cc_approx_res_monotonic. eassumption. \n simpl in *. lia. *)\n Qed.\n \n\n Axiom Prim_axiom_cc :\n forall f f' v1,\n M.get f pr = Some f' ->\n forall k S vs1 vs2,\n Forall2 (cc_approx_val k S) vs1 vs2 ->\n f' vs1 = Some v1 ->\n exists v2,\n f' vs2 = Some v2 /\\ \n cc_approx_val k S v1 v2.\n \n Lemma cc_approx_exp_prim_compat k rho1 rho2 x1 x2 f ys1 ys2 e1 e2 :\n post_OOT' (Eprim x1 f ys1 e1) rho1 (Eprim x2 f ys2 e2) rho2 P2 ->\n Forall2 (cc_approx_var_env k PG rho1 rho2) ys1 ys2 ->\n (* (forall m v1 v2 vs f',\n m < k ->\n (* needed by the cost proof *)\n get_list ys1 rho1 = Some vs ->\n M.get f pr = Some f' ->\n f' vs = Some v1 ->\n cc_approx_val k PG v1 v2 -> \n cc_approx_exp k P1 PG (e1, M.set x1 v1 rho1)\n (e2, M.set x2 v2 rho2)) -> *)\n cc_approx_exp k P2 PG (Eprim x1 f ys1 e1, rho1) (Eprim x2 f ys2 e2, rho2).\n Proof.\n intros Hoot Hall v1 cin cout Hleq1 Hstep1. inv Hstep1.\n - (* OOT *) \n exists OOT, cin, <0>. split. constructor; eassumption. \n split; [| now eauto ]. eapply Hoot; eauto.\n - inv H. \n(* edestruct cc_approx_var_env_get_list as [vs2 [Hget' Hpre']]; [| eassumption | ]; eauto.\n edestruct Prim_axiom_cc as [v2 [Heq Hprev2]]; eauto.\n edestruct (Hpre (k - 1)) as [v2' [c2 [Hstepv2' [Hpost2 Hprev2']]]]; [ | | | | | | eassumption | ]; eauto.\n simpl in *; lia. simpl in *; lia. \n eexists. exists (c2 + cost (Eprim x2 f ys2 e2)). split; [| split ].\n econstructor 2; eauto. lia. \n econstructor; eauto.\n replace (c2 + cost (Eprim x2 f ys2 e2) - cost (Eprim x2 f ys2 e2)) with c2 by lia. \n eassumption.\n replace cin with (cin - cost (Eprim x1 f ys1 e1) + cost (Eprim x2 f ys2 e2)).\n 2:{ simpl in *. eapply Forall2_length in Hall. rewrite Hall. lia. } \n eapply HPost. eassumption.\n eapply cc_approx_res_monotonic. eassumption. \n simpl in *. lia. *)\n Qed.\n \n End Compat.\n\n (** Lift a value predicate to a subset of an environment *)\n Definition lift_P_env (S : Ensemble var) (P : Ensemble val) (rho : env) :=\n forall x v, S x -> M.get x rho = Some v -> P v.\n \n Lemma lift_P_env_antimon S S' P rho :\n Included _ S S' ->\n lift_P_env S' P rho ->\n lift_P_env S P rho.\n Proof.\n intros H Henv x v HS Hget.\n eapply Henv; eauto. eapply H; eauto.\n Qed.\n\n Global Instance lift_P_env_proper : Proper (Same_set var ==> eq ==> eq ==> iff) lift_P_env.\n Proof.\n intros S1 S2 Heq B1 B2 Heq' rho1 rho2 Heq''; subst.\n split; intros H x v Hi Hget; (eapply H; [ | now eauto ]);\n now eapply Heq.\n Qed.\n\n Lemma lift_P_env_Union_l S1 S2 P rho :\n lift_P_env (Union _ S1 S2) P rho ->\n lift_P_env S1 P rho.\n Proof.\n intros H. eapply lift_P_env_antimon; [| now eauto ].\n now apply Included_Union_l.\n Qed.\n\n Lemma lift_P_env_Union_r S1 S2 P rho :\n lift_P_env (Union _ S1 S2) P rho ->\n lift_P_env S2 P rho.\n Proof.\n intros H. eapply lift_P_env_antimon; [| now eauto ].\n now apply Included_Union_r.\n Qed.\n\n Lemma lift_P_env_Emtpy_set P rho :\n lift_P_env (Empty_set _) P rho.\n Proof.\n intros x v H. inv H.\n Qed.\n\n Lemma lift_P_env_extend S P rho x v :\n lift_P_env (Setminus _ S (Singleton _ x)) P rho ->\n P v ->\n lift_P_env S P (M.set x v rho). \n Proof.\n intros H Hp x' v' HS Hget.\n rewrite M.gsspec in Hget.\n destruct (peq x' x); subst.\n - now inv Hget.\n - eapply H; [| eassumption ].\n constructor; eauto. intros Hc. inv Hc. congruence.\n Qed.\n\n Lemma lift_P_env_set_lists S P rho rho' xs vs :\n lift_P_env (Setminus _ S (FromList xs)) P rho ->\n Forall P vs ->\n set_lists xs vs rho = Some rho' ->\n lift_P_env S P rho'. \n Proof.\n revert S xs rho rho'. induction vs; intros S xs rho rho' Henv Hall Hset.\n - destruct xs; inv Hset.\n rewrite FromList_nil, Setminus_Empty_set_neut_r in Henv.\n eapply Henv; now eauto.\n - destruct xs; try discriminate. inv Hall.\n simpl in Hset. destruct (set_lists xs vs rho) eqn:Heq ; try discriminate.\n inv Hset. eapply lift_P_env_extend; eauto.\n eapply IHvs; eauto.\n now rewrite FromList_cons, <- Setminus_Union in Henv.\n Qed.\n\n Lemma lift_P_env_def_funs S P B B' rho :\n lift_P_env (Setminus _ S (name_in_fundefs B)) P rho ->\n (forall f, P (Vfun rho B' f)) ->\n lift_P_env S P (def_funs B' B rho rho). \n Proof.\n revert S rho. induction B; intros S rho Henv Hfun.\n - simpl. eapply lift_P_env_extend; [| now eauto ].\n eapply IHB; [| eassumption ].\n eapply lift_P_env_antimon; [| eassumption ].\n rewrite Setminus_Union. now eapply Included_refl.\n - now rewrite Setminus_Empty_set_neut_r in Henv. \n Qed.\n\n Lemma lift_P_env_get S P rho x v :\n lift_P_env S P rho ->\n Included _ (Singleton _ x) S ->\n M.get x rho = Some v ->\n P v.\n Proof.\n intros Henv HS Hget. eapply Henv; eauto. \n now eapply HS; eauto. \n Qed.\n\n Lemma lift_P_env_get_list S P rho xs vs :\n lift_P_env S P rho ->\n Included _ (FromList xs) S ->\n get_list xs rho = Some vs ->\n Forall P vs.\n Proof.\n revert S xs rho. induction vs; intros S xs rho Henv Hincl Hget.\n - eauto.\n - destruct xs; try discriminate. simpl in Hget.\n destruct (M.get v rho) eqn:Heq; try discriminate.\n destruct (get_list xs rho) eqn:Heq'; try discriminate.\n inv Hget. rewrite FromList_cons in Hincl.\n constructor.\n + eapply lift_P_env_get; eauto.\n eapply Included_trans; [| now eauto ].\n eapply Included_Union_l.\n + eapply IHvs; eauto.\n eapply Included_trans; [| now eauto ].\n eapply Included_Union_r.\n Qed.\n\n Lemma Forall_nthN {A} (R : A -> Prop) l n v :\n Forall R l ->\n nthN l n = Some v ->\n R v.\n Proof.\n revert n. induction l; intros n Hall Hnth; [ discriminate |].\n inv Hall. simpl in Hnth.\n destruct n. \n - inv Hnth; eauto.\n - eapply IHl; eauto. \n Qed.\n\n Section Compose.\n\n Context (P1 P2 : @PostT fuel trace) (* Local *)\n (PG : @PostGT fuel trace) (* Global *)\n (Hprops : Post_properties cenv PG PG PG)\n (HGPost : inclusion _ (comp P1 P2) PG)\n (Hp1 : inclusion _ PG P1)\n (Hp2 : inclusion _ PG P2).\n\n \n Lemma cc_approx_res_respects_preord_exp_r_pre (k : nat) r1 r2 r3 :\n (forall j v1 v2 v3,\n j <= k ->\n cc_approx_val j PG v1 v2 ->\n (forall k, preord_val cenv PG k v2 v3) ->\n cc_approx_val j PG v1 v3) ->\n cc_approx_res cc_approx_val k PG r1 r2 ->\n (forall k', preord_res (preord_val cenv) PG k' r2 r3) ->\n cc_approx_res cc_approx_val k PG r1 r3.\n Proof.\n intros Hyp H1 H2;\n assert (H2' := H2 0); destruct r1; destruct r2; destruct r3; try contradiction; eauto.\n simpl. eapply Hyp; eauto.\n Qed.\n\n Lemma cc_approx_exp_respects_preord_exp_r_pre (k : nat)\n (rho1 rho2 rho3 : env) (e1 e2 e3 : exp) :\n (forall j v1 v2 v3,\n j <= k ->\n cc_approx_val j PG v1 v2 ->\n (forall k, preord_val cenv PG k v2 v3) ->\n cc_approx_val j PG v1 v3) ->\n cc_approx_exp k P1 PG (e1, rho1) (e2, rho2) ->\n (forall k', preord_exp cenv P2 PG k' (e2, rho2) (e3, rho3)) ->\n cc_approx_exp k (comp P1 P2) PG (e1, rho1) (e3, rho3).\n Proof.\n intros IH Hexp1 Hexp2 v1 c Hleq1 Hstep1 Hns.\n edestruct Hexp1 as [v2 [c2 [c2' [Hstep2 [HS Hpre2]]]]]; eauto.\n edestruct (Hexp2 (to_nat c2)) as [v3 [c3 [c3' [Hstep3 [HS' Hpre3]]]]]; [| eassumption | ].\n lia. do 3 eexists; repeat split; eauto. eexists; split; eauto.\n eapply cc_approx_res_respects_preord_exp_r_pre.\n intros. eapply IH; eauto. lia. eassumption.\n intros m.\n edestruct (Hexp2 (m + to_nat c2)) with (cin := c2)\n as [v3' [c4 [c4' [Hstep3' [Hpost3 Hpre3']]]]]; [| eauto |]. lia.\n destruct v1; destruct v2; destruct v3; destruct v3'; try contradiction; eauto.\n eapply bstep_fuel_deterministic in Hstep3; [| eapply Hstep3' ]. inv Hstep3.\n eapply preord_val_monotonic. eauto. lia.\n Qed.\n\n (* TODO move *)\n Lemma occurs_free_closed_fundefs f tau xs e B :\n fun_in_fundefs B (f, tau, xs, e) ->\n closed_fundefs B ->\n Included _ (occurs_free e) (Union _ (FromList xs) (name_in_fundefs B)).\n Proof.\n intros H Hcl.\n eapply Included_trans. now eapply occurs_free_in_fun; eauto.\n unfold closed_fundefs in Hcl. rewrite Hcl, Union_Empty_set_neut_r.\n eapply Included_refl.\n Qed.\n\n Lemma cc_approx_val_respects_preord_val_r (k : nat) (v1 v2 v3 : val) :\n cc_approx_val k PG v1 v2 ->\n (forall k, preord_val cenv PG k v2 v3) ->\n cc_approx_val k PG v1 v3.\n Proof.\n revert v1 v2 v3. induction k using lt_wf_rec.\n induction v1 using val_ind'; intros v2 v3 Happrox Hpre;\n assert (Hpre' := Hpre k);\n rewrite cc_approx_val_eq, preord_val_eq in *.\n - destruct v2; try contradiction.\n destruct v3; try contradiction.\n inv Happrox; inv Hpre'. inv H1; inv H2. split; eauto.\n - destruct v2; try contradiction.\n destruct v3; try contradiction.\n destruct l0; [now inv Happrox; inv H1 |].\n destruct l1; [now inv Hpre'; inv H1 |].\n inv Hpre'; inv Happrox. inv H1; inv H2; split; eauto.\n constructor; eauto.\n + eapply IHv1; [ now eauto |].\n intros k'. specialize (Hpre k').\n rewrite preord_val_eq in Hpre. inv Hpre. now inv H1.\n + assert (Hsuf : cc_approx_val' k PG (Vconstr c0 l) (Vconstr c0 l1)).\n { rewrite <- cc_approx_val_eq.\n eapply IHv0 with (v2 := Vconstr c0 l0).\n - rewrite cc_approx_val_eq. now split; eauto.\n - intros k'. specialize (Hpre k'). rewrite preord_val_eq in Hpre.\n inv Hpre. inv H1. rewrite preord_val_eq. now split; eauto. }\n now inv Hsuf.\n - destruct v2, v3; try contradiction.\n destruct l; try contradiction.\n destruct v0, l; try contradiction.\n destruct v1; try contradiction.\n inversion Hpre' as [Hleq Hall]. clear Hpre'. inv Hall.\n rewrite preord_val_eq in H2. inv H4.\n rewrite preord_val_eq in H3.\n destruct y, y0; try contradiction. simpl.\n destruct l; try contradiction. \n destruct Happrox as [Heq1 Happrox]; subst. inv H6. split; eauto.\n intros vs1 vs2 j t1' xs1 e1 rho1 Heq1 Hfind1 Hset1.\n edestruct (Happrox vs1 vs2) as [Γ [xs2 [e2 [rho2' [Hfind2 [Hset2 Heval2]]]]]]; eauto.\n subst.\n edestruct (H2 (Vconstr c1 l1 :: vs2) (Vconstr c l0 :: vs2)) with (j := 0) as\n [xs3' [e3 [rho3 [Hfind3 [Hset3 _]]]]]; eauto.\n edestruct xs3' as [| Γ' xs3]; try discriminate.\n do 4 eexists. repeat split; eauto.\n intros Hlt Hall.\n eapply cc_approx_exp_rel_mon.\n eapply cc_approx_exp_respects_preord_exp_r_pre\n with (e2 := e2) (rho2 := rho2').\n + intros. eapply H; [ lia | eassumption | eassumption ].\n + eapply cc_approx_exp_rel_mon.\n eapply Heval2. lia. assumption.\n intros ? ? ?. eauto.\n + intros k'. specialize (Hpre (k'+1)). rewrite preord_val_eq in Hpre.\n inversion Hpre as [_ Hall']. clear Hpre. inv Hall'.\n rewrite preord_val_eq in H5.\n edestruct (H5 (Vconstr c1 l1 :: vs2) (Vconstr c l0 :: vs2)) as\n [xs3'' [e3' [rho4 [Hfind3' [Hset3' Heval3']]]]]; eauto.\n rewrite Hfind3' in Hfind3. inv Hfind3.\n rewrite <- Hset3 in Hset3'. inv Hset3'.\n eapply preord_exp_post_monotonic; [| eapply Heval3' ].\n intros ? ? ?. eauto.\n lia. inv H7. constructor.\n eapply preord_val_monotonic. eassumption. lia.\n eapply List_util.Forall2_refl. eapply preord_val_refl; eauto.\n + eauto.\n - destruct v2; try contradiction.\n destruct v3; try contradiction. inv Happrox.\n inv Hpre'. reflexivity.\n - destruct v2; try contradiction.\n destruct v3; try contradiction. inv Happrox.\n inv Hpre'. reflexivity.\n Qed.\n\n Corollary cc_approx_exp_respects_preord_exp_r (k : nat)\n (rho1 rho2 rho3 : env) (e1 e2 e3 : exp) :\n cc_approx_exp k P1 PG (e1, rho1) (e2, rho2) ->\n (forall k', preord_exp cenv P2 PG k' (e2, rho2) (e3, rho3)) ->\n cc_approx_exp k (comp P1 P2) PG (e1, rho1) (e3, rho3).\n Proof.\n eapply cc_approx_exp_respects_preord_exp_r_pre.\n now intros; eapply cc_approx_val_respects_preord_val_r; eauto.\n Qed.\n\n\n (* Sadly, composing with the preord relation on the left doesn't seem provable *)\n\n Lemma cc_approx_exp_respects_preord_exp_l (rho1 rho2 rho3 : env) (e1 e2 e3 : exp) k:\n (forall k, preord_exp cenv P1 PG k (e1, rho1) (e2, rho2)) ->\n cc_approx_exp k P2 PG (e2, rho2) (e3, rho3) ->\n cc_approx_exp k (comp P1 P2) PG (e1, rho1) (e3, rho3).\n Proof.\n intros Hyp1 Hyp2 v c1 c2 Hleq Hstep1.\n edestruct (Hyp1 k) as (v2 & c3 & c4 & Hstep2 & Hpost & Hv2). eassumption. eassumption.\n Abort.\n \n Lemma cc_approx_val_respects_preord_val_l (v1 v2 v3 : val) :\n (forall k, preord_val cenv PG k v1 v2) ->\n (forall k, cc_approx_val k PG v2 v3) ->\n (forall k, cc_approx_val k PG v1 v3).\n Proof.\n intros H1 H2 k. \n revert v1 v2 v3 H1 H2. induction k as [k IHK] using lt_wf_rec.\n induction v1 using val_ind'; intros v2 v3 Hpre Happrox;\n assert (Hpre' := Hpre k);\n assert (Happrox' := Happrox k); \n rewrite cc_approx_val_eq, preord_val_eq in *. \n - admit.\n - admit.\n - destruct v2; try contradiction.\n destruct v3; try contradiction.\n destruct l. now inv Happrox'.\n simpl in Happrox'.\n destruct v1; try contradiction.\n destruct l. now inv Happrox'.\n destruct v2; try contradiction.\n(* \n intros vs1 vs2 i t2 xs1 e1 rho1 Hleneq Hfdef Hset. \n simpl in Hpre'. \n edestruct (Hpre' vs1 vs1) as [xs2' [e2 [rho2 [Hfind2 [Hset2 _]]]]]; eauto.\n edestruct (Happrox' vs1 vs2) with (j := i)\n as [Γ [xs3' [e3 [rho3 [Heq [Hfind3 [Hset3 Heval3]]]]]]]; eauto.\n subst.\n do 4 eexists. split; [| split; [| split ] ]; eauto.\n intros Hlt Hall. \n*)\n \n Abort.\n\n \n End Compose.\n\n Section Divergence.\n \n \n Lemma cc_approx_exp_preserves_divergence\n (P : @PostT fuel trace)\n (PG : @PostGT fuel trace) e1 rho1 e2 rho2\n (Hrel : post_upper_bound P) :\n (forall k, cc_approx_exp k P PG (e1, rho1) (e2, rho2)) ->\n @diverge cenv fuel _ trace _ rho1 e1 -> \n @diverge cenv fuel _ trace _ rho2 e2.\n Proof.\n intros Hexp Hdiv. assert (Hdiv' := Hdiv).\n specialize (Hrel e1 rho1 e2 rho2). inv Hrel.\n intros c2.\n specialize (Hdiv (x c2)). destructAll.\n edestruct Hexp as [v2 [c2' [cout2 [Hs2 [Hp Hval]]]]].\n reflexivity. eassumption.\n destruct v2; try contradiction. \n eapply H in Hp. inv Hp. \n eapply bstep_fuel_OOT_monotonic in Hs2. destructAll. eexists. eassumption.\n Qed.\n \n Lemma cc_approx_exp_preserves_not_stuck\n (P : @PostT fuel trace)\n (PG : @PostGT fuel trace) e1 rho1 e2 rho2\n (Hrel : post_upper_bound P) :\n (forall k, cc_approx_exp k P PG (e1, rho1) (e2, rho2)) ->\n @not_stuck cenv fuel _ trace _ rho1 e1 -> \n @not_stuck cenv fuel _ trace _ rho2 e2.\n Proof.\n intros Hexp Hns. assert (Hns' := Hns). inv Hns.\n - destructAll.\n edestruct Hexp as [v2 [c2' [cout' [Hs2 [Hp Hval]]]]].\n reflexivity. eassumption.\n\n destruct v2; try contradiction.\n left. now eauto.\n - right. eapply cc_approx_exp_preserves_divergence; eassumption.\n Qed.\n\n End Divergence.\n\n\n (* More environment lemmas *)\n \n Lemma cc_approx_val_cc_appox_var_env k P rho1 rho2 x y v1 v2 :\n M.get x rho1 = Some v1 -> M.get y rho2 = Some v2 ->\n cc_approx_val k P v1 v2 ->\n cc_approx_var_env k P rho1 rho2 x y.\n Proof.\n intros Hget1 Hget2 Hcc.\n intros v1' Hget1'. rewrite Hget1 in Hget1'. inv Hget1'.\n firstorder.\n Qed.\n\n Lemma Forall2_cc_approx_var_env k P rho1 rho2 l1 l2 vs1 vs2 :\n get_list l1 rho1 = Some vs1 ->\n get_list l2 rho2 = Some vs2 ->\n Forall2 (cc_approx_val k P) vs1 vs2 ->\n Forall2 (cc_approx_var_env k P rho1 rho2) l1 l2.\n Proof.\n revert vs1 l2 vs2; induction l1; intros vs1 l2 vs2 Hget1 Hget2 Hall.\n - destruct vs1; try discriminate.\n inv Hall. destruct l2; try discriminate.\n now constructor.\n simpl in Hget2. destruct (M.get e rho2); try discriminate.\n destruct (get_list l2 rho2); try discriminate.\n - simpl in Hget1.\n destruct (M.get a rho1) eqn:Hgeta; try discriminate.\n destruct (get_list l1 rho1) eqn:Hgetl; try discriminate.\n inv Hget1.\n inv Hall.\n destruct l2; try discriminate. simpl in Hget2.\n destruct (M.get e rho2) eqn:Hgeta'; try discriminate.\n destruct (get_list l2 rho2) eqn:Hgetl'; try discriminate.\n inv Hget2. constructor; eauto.\n eapply cc_approx_val_cc_appox_var_env; eauto.\n Qed.\n\n (** Lemmas about evaluation contexts *)\n\n (** [(e1, ρ1) < (C [ e2 ], ρ2)] if [(e1, ρ1) < (e2, ρ2')], where [ρ2'] is the\n interpretation of [C] in [ρ2] *)\n Lemma ctx_to_rho_cc_approx_exp k (P : nat -> PostT) boundG rho1 rho2 rho2' C e e' m :\n (forall n e1 rho1 cin1 cout1 e2 rho2 rho2' cin2 cout2 C, \n ctx_to_rho C rho2 rho2' ->\n P (n + to_nat (one_ctx C)) (e1, rho1, cin1, cout1) (e2, rho2', cin2, cout2) ->\n P n (e1, rho1, cin1, cout1) (C|[ e2 ]|, rho2, cin2 <+> one_ctx C, cout2 <+> one_ctx C)) ->\n\n ctx_to_rho C rho2 rho2' -> \n cc_approx_exp k (P (m + exp_ctx_len C)) boundG (e, rho1) (e', rho2') ->\n cc_approx_exp k (P m) boundG (e, rho1) (C |[ e' ]|, rho2).\n Proof. \n intros H1 Hctx Hcc. revert m Hcc; induction Hctx; intros m Hcc.\n - intros v1' c1 Hleq1 Hstep1 Hns.\n edestruct Hcc as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; try eassumption.\n simpl in *. rewrite Nat_as_OT.add_0_r in *. firstorder. \n - intros v1 c1 Hleq1 Hstep1 Hns.\n edestruct IHHctx as [v2 [c2 [c3 [Hstep2 [HP Hcc2]]]]]; try eassumption.\n simpl exp_ctx_len in Hcc.\n replace (m + S (exp_ctx_len C)) with ((m + 1) + (exp_ctx_len C)) in Hcc by lia.\n eassumption.\n eexists. eexists (c2 <+> one (Eproj_c y t N Γ C |[ e' ]|)). eexists. split; [| split ].\n constructor 2; eauto. econstructor; eauto.\n simpl. eapply H1 with (C := Eproj_c y t N Γ Hole_c); eauto.\n econstructor; eauto. now econstructor. \n simpl. unfold one_ctx. simpl. rewrite to_nat_one. eassumption. \n eassumption.\n - intros v1' c1 Hleq1 Hstep1 Hns.\n edestruct IHHctx as [v2' [c2 [c3 [Hstep2 [Hub Hcc2]]]]]; try eassumption.\n\n simpl exp_ctx_len in Hcc.\n replace (m + S (exp_ctx_len C)) with ((m + 1 + exp_ctx_len C)) in Hcc by lia.\n eassumption. \n eexists. eexists (c2 <+> one (Econstr_c x t ys C |[ e' ]|)). eexists. split; [| split ].\n constructor 2; eauto. econstructor; eauto. \n simpl. eapply H1 with (C := Econstr_c x t ys Hole_c); eauto.\n econstructor; eauto. now econstructor.\n unfold one_ctx. rewrite to_nat_one. simpl. eassumption. eassumption.\n - intros v1' c1 Hleq1 Hstep1 Hns. \n edestruct IHHctx as [v2' [c2 [c3 [Hstep2 [Hub Hcc2]]]]]; try eassumption. \n\n simpl exp_ctx_len in Hcc.\n replace (m + S (exp_ctx_len C)) with (m + 1 + exp_ctx_len C) in Hcc by lia. \n eassumption.\n\n eexists. eexists (c2 <+> one (Efun1_c B C |[ e' ]|)). eexists. split; [| split ].\n constructor 2; eauto. econstructor; eauto. \n simpl. eapply H1 with (C := Efun1_c B Hole_c); eauto.\n econstructor; eauto. now econstructor.\n unfold one_ctx. rewrite to_nat_one. simpl. eassumption. eassumption.\n Qed.\n \n Lemma cc_approx_exp_ctx_to_rho k (P : nat -> @PostT fuel trace) boundG rho1 rho2 rho2' C e e' m :\n (forall n e1 rho1 e2 rho2 rho2' (cin1 cin2 : fuel) (cout1 cout2 : trace) C, \n ctx_to_rho C rho2 rho2' ->\n P n (e1, rho1, cin1, cout1) (C|[ e2 ]|, rho2, cin2 <+> one_ctx C, cout2 <+> one_ctx C) ->\n P (n + to_nat (one_ctx C)) (e1, rho1, cin1, cout1) (e2, rho2', cin2, cout2)) ->\n (forall m e2 rho2 rho2' (cin1 cin2 : fuel) (cout1 cout2 : trace) C,\n ctx_to_rho C rho2 rho2' ->\n P m (e, rho1, cin1, cout1) (C |[ e2 ]|, rho2, cin2, cout2) ->\n P (m + to_nat (one_ctx C)) (e, rho1, cin1, cout1) (e2, rho2', cin2, cout2)) ->\n ctx_to_rho C rho2 rho2' -> \n cc_approx_exp k (P m) boundG (e, rho1) (C |[ e' ]|, rho2) ->\n cc_approx_exp k (P (m + exp_ctx_len C)) boundG (e, rho1) (e', rho2').\n Proof.\n intros H1 H2 Hctx Hcc. revert m Hcc; induction Hctx; intros m Hcc.\n - intros v1' c1 c1' Hleq1 Hstep1.\n edestruct Hcc as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; try eassumption.\n simpl in *. rewrite Nat_as_OT.add_0_r in *. firstorder.\n - simpl exp_ctx_len.\n replace (m + S (exp_ctx_len C)) with ((m + 1) + (exp_ctx_len C)) by lia.\n eapply IHHctx; eauto.\n + intros v1 c1 c1' Hleq1 Hstep1.\n edestruct Hcc as [v2 [c2 [c2' [Hstep2 [Hub Hcc2]]]]]; try eassumption.\n inv Hstep2; repeat subst_exp.\n * destruct v1; try contradiction.\n (* eapply lt_zero_one in H3. subst. *)\n eexists OOT, c2, <0>. split. econstructor; eauto.\n unfold one; erewrite one_eq. eassumption.\n split.\n -- erewrite <- (@to_nat_one _ fuel _). eapply H2 with (C := Eproj_c y t N Γ Hole_c); try eassumption.\n econstructor; eauto. now econstructor.\n -- simpl. eassumption. \n * inv H3. do 3 eexists. repeat subst_exp.\n split. eassumption. split.\n erewrite <- (@to_nat_one _ fuel _).\n eapply H1 with (C := Eproj_c y t N Γ Hole_c); try eassumption.\n econstructor; eauto. now econstructor. eassumption.\n - simpl . \n replace (m + S (exp_ctx_len C)) with ((m + 1) + (exp_ctx_len C)) by lia.\n eapply IHHctx; eauto.\n intros v1' c1' Hleq1 Hstep1 Hns.\n edestruct Hcc as [v2' [c2' [c3' [Hstep2 [Hub Hcc2]]]]]; try eassumption.\n inv Hstep2; simpl in *; repeat subst_exp.\n + destruct v1'; try contradiction. \n eexists OOT, c2', <0>. split. econstructor; eauto. unfold one. erewrite one_eq. eassumption.\n split.\n erewrite <- (@to_nat_one _ fuel _). eapply H2 with (C := Econstr_c x t ys Hole_c).\n econstructor; eauto. now econstructor.\n simpl. eassumption. eassumption. \n + inv H0. repeat subst_exp. do 3 eexists. split. eassumption.\n split.\n erewrite <- (@to_nat_one _ fuel). eapply H1 with (C := Econstr_c x t ys Hole_c); try eassumption.\n econstructor; eauto. now econstructor. simpl.\n eassumption.\n - simpl exp_ctx_len.\n replace (m + S (exp_ctx_len C)) with (m + 1 + exp_ctx_len C) by lia. \n eapply IHHctx; eauto. \n intros v1' c1' c2' Hleq1 Hstep1.\n edestruct Hcc as [v2' [c3 [c3' [Hstep2 [Hub Hcc2]]]]]; try eassumption.\n inv Hstep2; simpl in *; repeat subst_exp.\n + destruct v1'; try contradiction. \n eexists OOT, c3, <0>. split. econstructor; eauto. unfold one. erewrite one_eq. eassumption.\n\n split.\n erewrite <- to_nat_one. eapply H2 with (C := Efun1_c B Hole_c).\n econstructor; eauto. now econstructor.\n simpl. eassumption. \n simpl; eauto. \n + inv H. repeat subst_exp. do 3 eexists. split. eassumption.\n split.\n erewrite <- to_nat_one. eapply H1 with (C := Efun1_c B Hole_c); try eassumption.\n econstructor; eauto. now econstructor. simpl.\n eassumption.\n \n Qed.\n\n Lemma leq_sum_exists A B C:\n A <= B + C ->\n exists B' C', A = B' + C' /\\ B' <= B /\\ C' <= C.\n Proof.\n revert B C. induction A; intros B C Hleq.\n - eexists 0, 0. split; eauto. split; lia. \n - destruct B; destruct C.\n + lia.\n + assert (Hleq' : A <= 0 + C) by lia.\n edestruct IHA as [B' [C' [Heq1 [Hl1 Hl2]]]]. eassumption.\n subst. eexists 0. eexists (S C'). split; lia.\n + assert (Hleq' : A <= B + 0) by lia.\n edestruct IHA as [B' [C' [Heq1 [Hl1 Hl2]]]]. eassumption.\n subst. eexists (S B'). eexists 0. destruct C'; try lia.\n + assert (Hleq' : A <= S B + C) by lia.\n edestruct IHA as [B' [C' [Heq1 [Hl1 Hl2]]]]. eassumption.\n subst. eexists B'. eexists (S C').\n split; try lia.\n Qed. \n\n (*\n Lemma ctx_to_rho_cc_approx_exp_left_weak k P1 P2 boundG rho1 rho1' rho2 C e e' :\n (* This is very specific to what holds currently for CC *)\n (* forall c1 c2 m a b, b <= 7 * a -> P m c1 c2 -> P (m + b) (c1 + a) c2) -> *)\n ctx_to_rho C rho1 rho1' ->\n cc_approx_exp k P1 boundG (e, rho1') (e', rho2) ->\n cc_approx_exp k P2 boundG (C|[ e ]|, rho1) (e', rho2).\n Proof. \n intros Hctx. induction Hctx.\n - intros H1. eapply cc_approx_exp_rel_mon. eassumption.\n admit.\n - intros v1 c1 Hleq1 Hstep1.\n edestruct Hcc as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; try eassumption.\n simpl in *. do 2 eexists; split; eauto. split; eauto.\n rewrite (plus_n_O c1). eapply H1; eauto.\n - intros v1 c1 Hleq1 Hstep1. simpl in Hstep1. inv Hstep1; repeat subst_exp.\n + assert (Hc1 : c1 = 0) by (simpl in *; lia); subst. \n eexists OOT, 0. split. constructor; eauto. eapply cost_gt_0.\n split. eapply \n assert (Heq' : exists B D, A = B + D /\\ B <= 7 * exp_ctx_len C /\\ D <= 7).\n { revert Hleq. clear. intros Hleq.\n destruct A. eexists 0, 0. split; eauto. split; lia.\n assert (Heq : A <= 7 * (exp_ctx_len C) + 6) by (simpl in *; lia).\n destruct (Nat_as_DT.le_decidable A (7 * (exp_ctx_len C))). \n + eexists A, 1. split; eauto. lia. split; eauto.\n lia.\n + eexists (7 * exp_ctx_len C).\n eexists (S A - 7 * exp_ctx_len C).\n split. lia. split. lia. lia. }\n edestruct Heq' as [B [D [Heq [HeqB HleqD]]]]. subst.\n edestruct IHHctx with (A := B) as [v2 [c2 [Hstep2 [HP Hcc2]]]];\n [ | | | | eassumption | ]. \n intros. now eapply H1; eauto.\n simpl in *. lia.\n eassumption.\n lia. \n repeat eexists. eassumption. \n replace (m + (B + D)) with (m + B + D) by lia. eapply H1; eauto.\n eapply cc_approx_val_monotonic. eassumption. lia. \n - intros v1' c1 Hleq1 Hstep1. inv Hstep1. repeat subst_exp.\n assert (Heq'' : exists B D, A = B + D /\\ B <= 7 * exp_ctx_len C /\\ D <= 7 + 7 * @List.length var ys).\n { eapply leq_sum_exists. simpl in *; lia. } \n destruct Heq'' as [B [D [Heq [Hleqb Hleqd]]]]. subst.\n \n edestruct IHHctx with (A := B)\n as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; [ eassumption | | eassumption | | eassumption | ].\n eassumption. lia.\n repeat eexists. eassumption.\n rewrite (plus_assoc m). rewrite <- (plus_assoc c).\n eapply H1. eauto. lia. eassumption.\n eapply cc_approx_val_monotonic. eassumption. lia.\n - intros v1' c1 Hleq1 Hstep1. inv Hstep1. repeat subst_exp.\n simpl in Hleq.\n pose (cost := 1 + PS.cardinal (fundefs_fv B)).\n assert (Heq'' : exists B D, A = B + D /\\ B <= 7 * exp_ctx_len C /\\ D <= 7*cost).\n { eapply leq_sum_exists. simpl in *; lia. }\n destruct Heq'' as [B' [D [Heq [Hleqb Hleqd]]]]. subst.\n \n edestruct IHHctx with (A := B')\n as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; [ eassumption | | eassumption | | eassumption | ].\n eassumption. lia.\n repeat eexists. eassumption.\n rewrite (plus_assoc m).\n eapply H1; eauto.\n eapply cc_approx_val_monotonic. eassumption. lia.\n Qed.\n \n Lemma ctx_to_rho_cc_approx_exp_left k (P : nat -> relation nat) boundG rho1 rho1' rho2 C e e' m A :\n (* This is very specific to what holds currently for CC *)\n (forall c1 c2 m a b, a <= b <= 7 * a -> P m c1 c2 -> P (m + b) (c1 + a) c2) ->\n ctx_to_rho C rho1 rho1' ->\n exp_ctx_len C <= A <= 7 * exp_ctx_len C ->\n cc_approx_exp k (P m) boundG (e, rho1') (e', rho2) ->\n cc_approx_exp k (P (m + A)) boundG (C|[ e ]|, rho1) (e', rho2).\n Proof. \n intros H1 Hctx Hcc; revert m A rho2 H1 Hcc; induction Hctx;\n intros m A rho2 H1 Hleq Hcc.\n - intros v1 c1 Hleq1 Hstep1.\n edestruct Hcc as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; try eassumption.\n simpl in *. do 2 eexists; split; eauto. split; eauto.\n rewrite (plus_n_O c1). eapply H1; eauto.\n - intros v1 c1 Hleq1 Hstep1. simpl in Hstep1. inv Hstep1. repeat subst_exp.\n assert (Heq' : exists B D, A = B + D /\\ exp_ctx_len C <= B <= 7 * exp_ctx_len C /\\ 1 <= D <= 7).\n { revert Hleq. clear. intros Hleq.\n destruct A; try (simpl in *; lia). simpl in Hleq. \n assert (Heq : exp_ctx_len C <= A <= 7 * (exp_ctx_len C) + 6) by lia.\n clear Hleq.\n destruct (Nat_as_DT.le_decidable A (7 * (exp_ctx_len C))). \n + eexists A, 1. split; eauto. lia. split; eauto.\n lia. lia.\n + eexists (7 * exp_ctx_len C).\n eexists (S A - 7 * exp_ctx_len C).\n split. lia. split. lia. lia. }\n edestruct Heq' as [B [D [Heq [HeqB HleqD]]]]. subst.\n edestruct IHHctx with (A := B) as [v2 [c2 [Hstep2 [HP Hcc2]]]];\n [ | | | | eassumption | ]. \n intros. now eapply H1; eauto.\n simpl in *. lia.\n eassumption.\n lia. \n repeat eexists. eassumption. \n replace (m + (B + D)) with (m + B + D) by lia. eapply H1; eauto.\n eapply cc_approx_val_monotonic. eassumption. lia. \n - intros v1' c1 Hleq1 Hstep1. inv Hstep1. repeat subst_exp.\n assert (Heq' : exists B, A = B + (1 + @List.length var ys)). \n { simpl in *. eexists (A - S (Datatypes.length ys)).\n rewrite NPeano.Nat.sub_add. lia. simpl in *. lia. }\n destruct Heq' as [B' Hbeq].\n assert (Heq'' : exists B D, A = B + D /\\ exp_ctx_len C <= B <= 7 * exp_ctx_len C /\\\n 1 + @List.length var ys <= D <= 7 + 7 * @List.length var ys).\n { revert Hbeq Hleq. clear. intros Hbeq Hleq. subst.\n assert (Heq : exp_ctx_len C <= B' <= 7 * (exp_ctx_len C) + (6 + 6 * @List.length var ys))\n by (simpl in *; lia).\n clear Hleq.\n destruct (Nat_as_DT.le_decidable B' (7 * (exp_ctx_len C))). \n + eexists B'. eexists. split; eauto. split. lia. lia.\n + eexists (7 * exp_ctx_len C).\n eexists (1 + @List.length var ys + B' - 7 * exp_ctx_len C).\n split. lia. split. lia. lia. }\n clear Hbeq.\n destruct Heq'' as [B [D [Heq [Hleqb Hleqd]]]]. subst.\n \n edestruct IHHctx with (A := B)\n as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; [ eassumption | | eassumption | | eassumption | ].\n eassumption. lia.\n repeat eexists. eassumption.\n rewrite (plus_assoc m). rewrite <- (plus_assoc c).\n eapply H1. eauto. lia. eassumption.\n eapply cc_approx_val_monotonic. eassumption. lia.\n - intros v1' c1 Hleq1 Hstep1. inv Hstep1. repeat subst_exp.\n simpl in Hleq.\n pose (cost := 1 + PS.cardinal (fundefs_fv B)).\n assert (Heq' : exists B, A = B + cost). \n { simpl in *. eexists (A - cost).\n rewrite NPeano.Nat.sub_add. lia. lia. }\n assert (Heq'' : exists B D, A = B + D /\\ exp_ctx_len C <= B <= 7 * exp_ctx_len C /\\\n cost <= D <= 7*cost).\n { destruct Heq' as [B' Hbeq].\n revert Hbeq Hleq. clear. intros Hbeq Hleq. subst.\n assert (Heq : exp_ctx_len C <= B' <= 7 * (exp_ctx_len C) + 6*cost)\n by (simpl in *; lia).\n clear Hleq.\n destruct (Nat_as_DT.le_decidable B' (7 * (exp_ctx_len C))). \n + eexists B'. eexists. split; eauto. split. lia. lia.\n + eexists (7 * exp_ctx_len C).\n eexists (cost + B' - 7 * exp_ctx_len C).\n split. lia. split. lia. lia. }\n clear Heq'.\n destruct Heq'' as [B' [D [Heq [Hleqb Hleqd]]]]. subst.\n \n edestruct IHHctx with (A := B')\n as [v2' [c2 [Hstep2 [Hub Hcc2]]]]; [ eassumption | | eassumption | | eassumption | ].\n eassumption. lia.\n repeat eexists. eassumption.\n rewrite (plus_assoc m).\n eapply H1; eauto.\n eapply cc_approx_val_monotonic. eassumption. lia.\n Qed.\n*) \n\n (*\n Lemma cc_approx_exp_rel_conj k P1 P2 P rho1 rho2 e1 e2 :\n cc_approx_exp k P1 P (e1, rho1) (e2, rho2) ->\n cc_approx_exp k P2 P (e1, rho1) (e2, rho2) ->\n cc_approx_exp k (fun c1 c2 => P1 c1 c2 /\\ P2 c1 c2) P (e1, rho1) (e2, rho2).\n Proof. \n intros Hcc1 Hcc2 v c Hlt Hstep.\n edestruct Hcc1 as [v1 [c1 [Hstep1 [HP1 Hv1]]]]; eauto.\n edestruct Hcc2 as [v2 [c2 [Hstep2 [HP2 Hv2]]]]; eauto.\n destruct v; destruct v2; try contradiction.\n - destruct v1; try contradiction. do 2 eexists. split. eassumption. split; eauto.\n split; eauto.\n\n eapply bstep_fuel_deterministic in Hstep1. ; eauto. inv Hstep1.\n firstorder.\n Qed. *)\n\n (* The following are obsolete *)\n (* TODO: move to identifiers.v *)\n Inductive closed_fundefs_in_val : val -> Prop :=\n | Vconstr_closed :\n forall t vs,\n Forall closed_fundefs_in_val vs ->\n closed_fundefs_in_val (Vconstr t vs)\n | Vfun_closed :\n forall rho B f,\n closed_fundefs B ->\n closed_fundefs_in_fundefs B ->\n (* fun_in_fundefs B (f, tau, xs, e) -> *)\n (* Included _ (occurs_free e) (Union _ (FromList xs) (name_in_fundefs B)) -> *)\n closed_fundefs_in_val (Vfun rho B f)\n | Vint_closed :\n forall z, closed_fundefs_in_val (Vint z)\n | Vprim_closed : forall p, closed_fundefs_in_val (Vprim p).\n\n Definition closed_fundefs_in_env (S : Ensemble var) rho : Prop :=\n lift_P_env S closed_fundefs_in_val rho.\n\n Lemma fun_in_fundefs_funs_in_fundef B B' f t xs e :\n fun_in_fundefs B (f, t, xs, e) ->\n funs_in_exp B' e ->\n funs_in_fundef B' B.\n Proof.\n induction B; intros Hin Hfuns.\n - inv Hin.\n + inv H. now eauto.\n + constructor 2. eapply IHB; eauto.\n - inv Hin.\n Qed.\n\n Axiom prims_closed_fundefs :\n forall (f : prim) (f' : list val -> option val) vs v,\n M.get f pr = Some f' ->\n Forall closed_fundefs_in_val vs ->\n f' vs = Some v ->\n closed_fundefs_in_val v.\n\n Lemma bstep_e_preserves_closed_fundefs rho e v c :\n bstep_e pr cenv rho e v c ->\n closed_fundefs_in_env (occurs_free e) rho ->\n closed_fundefs_in_exp e ->\n closed_fundefs_in_val v.\n Proof.\n intros Hstep Hcl1 Hcl2. induction Hstep.\n - eapply IHHstep.\n + subst. eapply lift_P_env_extend. \n * eapply lift_P_env_antimon; [| now eauto ].\n rewrite occurs_free_Econstr.\n eapply Included_Union_r.\n * constructor. eapply lift_P_env_get_list; eauto.\n rewrite occurs_free_Econstr. eapply Included_Union_l.\n + intros B Hin. eauto.\n - eapply IHHstep.\n + subst. eapply lift_P_env_extend. \n * eapply lift_P_env_antimon; [| now eauto ].\n rewrite occurs_free_Eproj.\n eapply Included_Union_r.\n * eapply Forall_nthN; [| eassumption ].\n eapply lift_P_env_get in H; [| eassumption |].\n now inv H. \n rewrite occurs_free_Eproj. eapply Included_Union_l.\n + intros B Hin. eauto.\n - eapply IHHstep.\n + eapply lift_P_env_antimon; [| now eauto ].\n eapply occurs_free_Ecase_Included.\n eapply findtag_In_patterns. eassumption.\n + intros B Hin. eapply Hcl2.\n econstructor; eauto. apply findtag_In_patterns. eassumption.\n - eapply IHHstep.\n + eapply Hcl1 in H; [| now eauto ]. inv H.\n apply find_def_correct in H1. \n eapply lift_P_env_antimon. eapply occurs_free_in_fun.\n eassumption.\n unfold closed_fundefs in H5. rewrite H5, Union_Empty_set_neut_r.\n eapply lift_P_env_set_lists; [| | now eauto ].\n * rewrite Setminus_Union_distr, Setminus_Same_set_Empty_set, Union_Empty_set_neut_l.\n eapply lift_P_env_def_funs.\n rewrite Setminus_Included_Empty_set. now apply lift_P_env_Emtpy_set.\n eauto with Ensembles_DB.\n intros f''. now constructor. \n * eapply lift_P_env_get_list; [ eassumption | | eassumption ].\n rewrite occurs_free_Eapp. eapply Included_Union_l.\n + intros B Hin.\n eapply Hcl1 in H; [| now eauto ].\n eapply find_def_correct in H1.\n inv H. eapply H7. eapply fun_in_fundefs_funs_in_fundef; eassumption.\n - admit. (* TODO fill in letapp case *)\n - eapply IHHstep.\n + eapply lift_P_env_def_funs.\n * eapply lift_P_env_antimon; [| eassumption ].\n rewrite occurs_free_Efun. eapply Included_Union_r.\n * intros f. constructor. now eapply Hcl2.\n intros B H. eapply Hcl2. now eauto.\n + intros B Hin. eauto.\n - eapply IHHstep.\n + subst. eapply lift_P_env_extend. \n * eapply lift_P_env_antimon; [| now eauto ].\n rewrite occurs_free_Eprim_val. reflexivity.\n * constructor.\n + intros B Hin. eauto.\n - eapply IHHstep.\n + subst. eapply lift_P_env_extend. \n * eapply lift_P_env_antimon; [| now eauto ].\n rewrite occurs_free_Eprim. eapply Included_Union_r.\n * eapply prims_closed_fundefs; [ eassumption | | eassumption ].\n eapply lift_P_env_get_list; [ eassumption | | eassumption ].\n rewrite occurs_free_Eprim. eapply Included_Union_l.\n + intros B Hin. eauto.\n - eapply Hcl1. now constructor. eassumption.\n Abort.\n\nEnd LogRelCC.\n\nNotation cc_approx_exp := (fun cenv ct => (cc_approx_exp' cenv (cc_approx_val cenv ct))).\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/LambdaANF/logical_relations_cc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.13743039196867818}} {"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gmap agree auth numbers frac_auth.\nFrom iris.algebra.lib Require Import excl_auth mono_nat.\nFrom iris.base_logic.lib Require Import invariants mono_nat saved_prop.\nFrom stdpp Require Import namespaces countable.\nFrom aneris.prelude Require Import strings.\nFrom aneris.aneris_lang.lib.serialization Require Export serialization_proof.\nFrom aneris.aneris_lang Require Import proofmode resources.\nFrom aneris.examples.reliable_communication Require Import user_params.\nFrom aneris.examples.reliable_communication.resources Require Import chan_session_resources.\n\n(** Socket Interpretation. *)\nSection SocketInterp.\n Context `{!anerisG Mdl Σ, !chanG Σ, !server_ghost_names}.\n Context `{!Reliable_communication_service_params}.\n\n (* ------------------------------------------------------------------------- *)\n (** Persistent components of the resources transferred over the network. *)\n (* ------------------------------------------------------------------------- *)\n\n (** Initialization persistent resources. *)\n (** If the side is Right, then the sender is the client, in which case, the server\n must always receive a session token starting from the 2nd step of the connection. *)\n Definition init_interp_pers clt_addr (str : string) (s : side) (i : nat) : iProp Σ :=\n match s with\n Left => (⌜str = \"INIT-ACK\"⌝ ∗ ∃ (γs : session_name), session_token clt_addr γs) ∨\n (⌜str = \"COOKIE-ACK\"⌝ ∗ ∃ (γs : session_name), session_connected clt_addr γs)\n | Right =>\n (⌜str = \"INIT\"⌝ ∗ ⌜i = 0⌝) ∨\n (⌜str = \"COOKIE\"⌝ ∗ ∃ (γs : session_name), session_token clt_addr γs)\n end.\n\n (** Sequence id persistent resources. *)\n Definition idmsg_interp_pers clt_addr (i : nat) (v : val) (s : side) : iProp Σ :=\n ∃ (γs : session_name),\n session_token clt_addr γs ∗\n ses_idx (chan_session_escrow_name (session_chan_name γs)) (dual_side s) i v ∗\n mono_nat_lb_own (side_elim s (session_srv_idx_name γs)\n (session_clt_idx_name γs)) (i+1).\n\n (** Acknowledgement persistent resources. *)\n Definition ack_interp_pers clt_addr (i : nat) (s : side) : iProp Σ :=\n ∃ (γs : session_name),\n session_token clt_addr γs ∗\n mono_nat_lb_own (side_elim s (session_clt_idx_name γs)\n (session_srv_idx_name γs)) i.\n\n\n (* ------------------------------------------------------------------------- *)\n (** Client socket interpretation. *)\n (* ------------------------------------------------------------------------- *)\n\n Definition client_init_interp clt_addr (s : string) (n : nat) : iProp Σ :=\n (⌜s = \"INIT-ACK\"⌝ ∗ CookieRes clt_addr n) ∨\n (⌜s = \"COOKIE-ACK\"⌝ ∗ ∃ γs, can_init γs clt_addr RCParams_protocol Left ∗\n session_connected clt_addr γs).\n\n Definition client_interp : message → iProp Σ :=\n λ m, (∃ (mval : val),\n ⌜(m_sender m) = RCParams_srv_saddr⌝ ∗\n ⌜(s_is_ser (msg_serialization RCParams_srv_ser)) mval (m_body m)⌝ ∗\n ((∃ s i, ⌜mval = InjLV (#(LitString s), #(LitInt i))⌝ ∗\n ∃ (n : nat) (γs : session_name), ⌜Z.of_nat n = i⌝ ∗\n session_token (m_destination m) γs ∗\n client_init_interp (m_destination m) s n) ∨\n ((∃ γs, session_connected (m_destination m) γs) ∗\n ((∃ ackid, ⌜mval = InjRV (InjLV ackid)⌝ ∗\n ∃ (n : nat), ⌜ackid = #n⌝ ∗\n ack_interp_pers (m_destination m) n Left) ∨\n (∃ i w, ⌜mval = InjRV (InjRV (#(LitInt i), w))⌝ ∗\n ∃ (n : nat), ⌜Z.of_nat n = i⌝ ∗\n idmsg_interp_pers (m_destination m) n w Left)))))%I.\n\n\n (* ------------------------------------------------------------------------- *)\n (** Server socket interpretation. *)\n (* ------------------------------------------------------------------------- *)\n\n Definition server_init_interp\n (clt_addr : socket_address)\n (s r : string) (i : nat) : iProp Σ :=\n (* INIT PHASE *)\n (⌜s = \"INIT\"⌝ ∗ ⌜r = \"INIT-ACK\"⌝ ∗ ⌜i = 0⌝ ∗\n (∀ (m' : message),\n (∃ (cookie : nat) (γs: session_name),\n ⌜s_is_ser\n (msg_serialization RCParams_srv_ser)\n (InjLV (#r, #cookie)%V) (m_body m')⌝ ∗\n ⌜m_sender m' = RCParams_srv_saddr⌝ ∗\n ⌜m_destination m' = clt_addr⌝ ∗\n session_token clt_addr γs ∗\n CookieRes clt_addr cookie) -∗\n client_interp m')) ∨\n (* COOKIE PHASE *)\n (⌜s = \"COOKIE\"⌝ ∗ ⌜r = \"COOKIE-ACK\"⌝ ∗\n CookieRes clt_addr i ∗\n (∃ (γs: session_name), session_token clt_addr γs) ∗\n (∀ (m' : message) (n : nat),\n (∃ (γs: session_name),\n ⌜s_is_ser (msg_serialization RCParams_srv_ser)\n (InjLV (#r, #n)%V) (m_body m')⌝ ∗\n ⌜m_sender m' = RCParams_srv_saddr⌝ ∗\n ⌜m_destination m' = clt_addr⌝ ∗\n session_token clt_addr γs ∗\n session_connected clt_addr γs ∗\n can_init γs clt_addr RCParams_protocol Left) -∗\n client_interp m')).\n\n Definition server_interp : message → iProp Σ :=\n λ m, (∃ (mval : val),\n ⌜(s_is_ser (msg_serialization RCParams_clt_ser)) mval (m_body m)⌝ ∗\n (m_sender m) ⤇ client_interp ∗\n ((∃ s r i, ⌜mval = InjLV (#(LitString s), #(LitInt i))⌝ ∗\n ∃ (n : nat), ⌜Z.of_nat n = i⌝ ∗\n server_init_interp (m_sender m) s r n) ∨\n ((∃ γs, session_connected (m_sender m) γs) ∗\n ((∃ ackid, ⌜mval = InjRV (InjLV ackid)⌝ ∗\n ∃ (n : nat), ⌜ackid = #n⌝ ∗ ack_interp_pers (m_sender m) n Right) ∨\n (∃ i w, ⌜mval = InjRV (InjRV (#(LitInt i), w))⌝ ∗\n ∃ (n : nat), ⌜Z.of_nat n = i⌝ ∗\n idmsg_interp_pers (m_sender m) n w Right)))))%I.\n\n (** Persistent resources transferred over the network. *)\n Definition client_server_interp_pers (s : side) : message → iProp Σ :=\n λ m, (∃ (mval : val),\n (match s with\n Left => ⌜(m_sender m) = RCParams_srv_saddr⌝\n | Right => (m_sender m) ⤇ client_interp\n end) ∗\n ⌜(s_is_ser (msg_serialization\n (side_elim s RCParams_srv_ser RCParams_clt_ser)))\n mval (m_body m)⌝ ∗\n ((∃ str (i: nat),\n ⌜mval = InjLV (#(LitString str), #(LitInt i))⌝ ∗\n init_interp_pers (side_elim s (m_destination m) (m_sender m)) str s i) ∨\n ((∃ γs, session_connected (side_elim s (m_destination m) (m_sender m)) γs) ∗\n ((∃ ackid,\n ⌜mval = InjRV (InjLV ackid)⌝ ∗\n ∃ (n : nat), ⌜ackid = #n⌝ ∗\n ack_interp_pers\n (side_elim s (m_destination m) (m_sender m)) n s) ∨\n (∃ i w,\n ⌜mval = InjRV (InjRV (#(LitInt i), w)%V)⌝ ∗\n ∃ n : nat, ⌜Z.of_nat n = i⌝ ∗\n idmsg_interp_pers\n (side_elim s (m_destination m) (m_sender m)) n w s)))))%I.\n\n Global Instance client_server_interp_pers_persistent s m :\n Persistent (client_server_interp_pers s m).\n Proof. destruct s; apply _. Qed.\n\n (** We can always obtain the persistent part of the network resources. *)\n Lemma client_interp_le m :\n client_interp m -∗ client_server_interp_pers Left m.\n Proof.\n iDestruct 1 as (mval Heq Hser) \"H\".\n iExists mval. iSplit; [done|]. iSplit; [done|].\n iDestruct \"H\" as \"[H | H]\".\n { iDestruct \"H\" as (s i ->) \"H\". iLeft; simpl.\n iDestruct \"H\" as (n γs Hn) \"(#Hs & [(-> & H)|(-> & (%y & H1 & H2))])\"; subst; eauto.\n - iExists _, _. iSplit; [done|]. iLeft. eauto.\n - iExists _, _. iSplit; eauto. }\n iDestruct \"H\" as \"(Hmd & [H | H])\".\n { iDestruct \"H\" as (ackid) \"[-> [%n [-> H]]]\". iRight. subst; iSplit; first subst; eauto.\n iLeft. iExists _.\n iSplit; [done|]. iExists _. by iFrame. }\n iDestruct \"H\" as (i w ->) \"H\".\n iRight. iSplit; first done. iRight. iExists _, _. iSplit; done.\n Qed.\n\n Lemma server_interp_le m :\n server_interp m -∗ client_server_interp_pers Right m.\n Proof.\n iDestruct 1 as (mval Hser) \"[Hinterp H]\".\n iExists mval. iSplit; first eauto.\n iSplit; [done|].\n iDestruct \"H\" as \"[H | H]\".\n { iDestruct \"H\" as (s r i ->) \"H\". iLeft; simpl.\n iDestruct \"H\" as (n Hn) \"[( -> & -> & -> & Hasn)|(-> & -> & Hck & (%γs & Hγs) & H)]\".\n - iExists \"INIT\", _. subst; eauto.\n - iExists \"COOKIE\", n. iSplit; first subst; eauto. }\n iDestruct \"H\" as \"(Hmd & [H | H])\".\n { iDestruct \"H\" as (ackid) \"[-> [%n [-> H]]]\". iRight. iSplit; first done.\n iLeft. iExists _.\n iSplit; [done|]. iExists _. by iFrame. }\n iDestruct \"H\" as (i w ->) \"H\".\n iRight. iSplit; first done. iRight. iExists _, _. iSplit; done.\n Qed.\n\n (* ------------------------------------------------------------------------- *)\n (** Resources related to the socket and socket addresses. *)\n (* ------------------------------------------------------------------------- *)\n\n Definition is_skt_val (skt : val) (sh : socket_handle) (s: side) : iProp Σ :=\n ⌜skt = ((#(LitSocket sh),\n (side_elim s (s_ser (s_serializer (msg_serialization RCParams_clt_ser)))\n (s_ser (s_serializer (msg_serialization RCParams_srv_ser))),\n side_elim s (s_deser (s_serializer (msg_serialization RCParams_srv_ser)))\n (s_deser (s_serializer (msg_serialization RCParams_clt_ser))))),\n side_elim s (s_ser (s_serializer RCParams_clt_ser))\n (s_ser (s_serializer RCParams_srv_ser)))%V⌝.\n\n (** In the definition below, for the server side we are tracking message histories\n in the following way:\n 1) the resource `(∃ R0, ⌜R ⊆ R0⌝ ∗ own γ_srv_known_messages_R_name (◯ R0))`\n states that the received messages are tracked precisely _outside_ the\n socket resource invariant, by the server listen loop.\n Therefore, every time we receive a new fresh message m,\n the resource `own γ_srv_known_messages_R_name R0` must be updated accordingly.\n This is needed to know that the domain of the session map\n (associating session names to client addresses) is precisely the set of\n \"INIT\" messages from distinct clients;\n 2) the resource `(∃ T0, ⌜T0 ⊆ T⌝ ∗ own γ_srv_known_messages_T_name (● T0))`\n states that on the contrary the sent messages are tracked precisely by\n the socket resources, but there is actually a distinguished subset of\n messages T0 in T, which can be updated whenever a new message is sent.\n Howevef, doing this update is possible, but not necessary.\n Every time the update is performed, a duplicable snapshot\n `own γ_srv_known_messages_T_name (◯ {[m]} ∪ T0))` can be generated\n as a certificate that the message m has been sent indeed.\n Thus, knowing that a message is in the set T0 allows to resend it\n without providing resources specified by the destination protocol.\n This is useful to encode that if the connection state for a given client\n is half-opened, then \"INIT-ACK\" has been already sent.\n Similarly, if the connection state for a given client is in the established mode,\n then \"COOKIE-ACK\" has benn already sent. *)\n Definition socket_inv_def sh sa sock s : iProp Σ :=\n (∃ (R T : message_soup),\n sh ↪[ip_of_address sa] sock ∗ sa ⤳ (R, T) ∗\n (side_elim s True (∃ R0, ⌜R ⊆ R0⌝ ∗ own γ_srv_known_messages_R_name (◯ R0))) ∗\n (side_elim s True (∃ T0, ⌜T0 ⊆ T⌝ ∗ own γ_srv_known_messages_T_name (● T0))) ∗\n [∗ set] m ∈ R, client_server_interp_pers s m).\n\n (** This definition is common for client and server, as the channel ghost name\n for the fraglists is existentially quantified in the idmsg_interp but is tied\n via the session_token clt_addr γ *)\n Definition socket_resource\n (skt : val) (sa : socket_address) (N : namespace) (s : side) : iProp Σ :=\n ∃ (sh : socket_handle) (sock : socket),\n is_skt_val skt sh s ∗\n ⌜saddress sock = Some sa⌝ ∗\n ⌜sblock sock = true⌝ ∗\n sa ⤇ side_elim s client_interp server_interp ∗\n inv N (socket_inv_def sh sa sock s).\n\n Definition isSocket skt h s sa ϕ bflag (sd : side) : iProp Σ :=\n is_skt_val skt h sd ∗\n ⌜saddress s = Some sa⌝ ∗\n ⌜sblock s = bflag⌝ ∗\n h ↪[ip_of_address sa] s ∗\n sa ⤇ ϕ.\n\n Global Instance serInit (str: string) (n : nat) (s: side) :\n Serializable (msg_serialization\n (side_elim s RCParams_clt_ser RCParams_srv_ser))\n (InjLV (#str, #n%nat)).\n Proof. exists (#str, #n)%V. left. split; first eauto; simpl.\n do 2 eexists; split; first done. split; by eexists.\n Qed.\n\n Lemma msg_ser_is_ser_injective s :\n ser_is_injective (msg_serialization\n (side_elim s RCParams_clt_ser RCParams_srv_ser)).\n Proof.\n apply sum_ser_is_ser_injective.\n - apply prod_ser_is_ser_injective.\n + apply string_ser_is_ser_injective.\n + apply int_ser_is_ser_injective.\n - apply sum_ser_is_ser_injective.\n + apply int_ser_is_ser_injective.\n + apply prod_ser_is_ser_injective.\n * apply int_ser_is_ser_injective.\n * intros str mval1 mval2 Hs1 Hs2.\n destruct s; [by eapply RCParams_clt_ser_inj|\n by eapply RCParams_srv_ser_inj].\n Qed.\n\n Lemma msg_ser_is_ser_injective_alt s :\n ser_is_injective_alt (msg_serialization\n (side_elim s RCParams_clt_ser RCParams_srv_ser)).\n Proof.\n apply sum_ser_is_ser_injective_alt.\n - apply prod_ser_is_ser_injective_alt.\n + apply string_ser_is_ser_injective_alt.\n + apply int_ser_is_ser_injective_alt.\n - apply sum_ser_is_ser_injective_alt.\n + apply int_ser_is_ser_injective_alt.\n + apply prod_ser_is_ser_injective_alt.\n * apply int_ser_is_ser_injective_alt.\n * intros str mval1 mval2 Hs1 Hs2.\n destruct s; [by eapply RCParams_clt_ser_inj_alt|\n by eapply RCParams_srv_ser_inj_alt].\n Qed.\n\nEnd SocketInterp.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/reliable_communication/resources/socket_interp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2720245628973633, "lm_q1q2_score": 0.13707485577945736}} {"text": "Require Import Setoid PArith.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import TView View Time Event Cell Thread Memory Configuration Local.\n\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import Execution_eco.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_bob imm_s_ppo.\nFrom imm Require Import CombRelations.\nFrom imm Require Import AuxDef.\nFrom imm Require Import AuxRel2.\n\nFrom imm Require Import TraversalConfig.\nRequire Import SimulationRel.\nRequire Import SimState.\nRequire Import MemoryAux.\nRequire Import MaxValue.\nRequire Import ViewRel.\nFrom imm Require Import ViewRelHelpers.\nRequire Import Event_imm_promise.\nRequire Import ExtTraversalConfig.\nRequire Import ExtTraversal.\nRequire Import ExtTraversalProperties.\nFrom imm Require Import TraversalProperties.\nRequire Import FtoCoherent.\nRequire Import SimulationRelProperties.\nRequire Import IntervalHelper.\nRequire Import AuxTime.\n\nSet Implicit Arguments.\n\nSection Aux.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'co'\" := G.(co).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'lab'\" := G.(lab).\nNotation \"'msg_rel'\" := (msg_rel G sc).\nNotation \"'urr'\" := (urr G sc).\nNotation \"'release'\" := G.(release).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_'\" := (fun l => W ∩₁ Loc_ l).\nNotation \"'FR'\" := (fun x => F x \\/ R x).\nNotation \"'FW'\" := (fun x => F x \\/ W x).\n\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nHypothesis IMMCON : imm_consistent G sc.\n\nVariable T : trav_config.\nVariable S : actid -> Prop.\nHypothesis ETCCOH : etc_coherent G sc (mkETC T S).\n\nHypothesis RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T.\n\nVariable f_to f_from : actid -> Time.t.\nHypothesis FCOH : f_to_coherent G S f_to f_from.\n\nVariable thread : thread_id.\nVariable PC : Configuration.t.\nVariable local : Local.t.\n\nHypothesis SIM_TVIEW : sim_tview G sc (covered T) f_to local.(Local.tview) thread.\nHypothesis SIM_MEM : sim_mem G sc T f_to f_from thread local PC.(Configuration.memory).\nHypothesis INHAB : Memory.inhabited PC.(Configuration.memory).\nHypothesis PLN_RLX_EQ : pln_rlx_eq local.(Local.tview).\nHypothesis MEM_CLOSE : memory_close local.(Local.tview) PC.(Configuration.memory).\n\nHypothesis SIM_RES_MEM :\n sim_res_mem G T S f_to f_from thread local (Configuration.memory PC).\n\nHypothesis PROM_IN_MEM :\n forall thread' langst local\n (TID : IdentMap.find thread' PC.(Configuration.threads) =\n Some (langst, local)),\n Memory.le local.(Local.promises) PC.(Configuration.memory).\n\n(* In the correspoding case, we don't reserve new events\n so the simulation would be able to proceed with the same timestamp mapping functions,\n i.e. f_to' = f_to /\\ f_from' = f_from, but we need to guarantee that\n the new message is not immediately before others\n (specifically, reservations introduced by the capped memory).\n *)\nLemma exists_time_interval_for_issue_reserved_no_next\n w locw valw langst smode\n (WNISS : ~ issued T w)\n (ISSUABLE : issuable G sc T w)\n (SW : S w)\n (NONEXT : dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ⊆₁ ∅)\n (LOC : loc lab w = Some locw)\n (VAL : val lab w = Some valw)\n (WTID : thread = tid w)\n (RESERVED_TIME: reserved_time G T S f_to f_from smode PC.(Configuration.memory))\n (TID : IdentMap.find (tid w) PC.(Configuration.threads) = Some (langst, local)) :\n let promises := local.(Local.promises) in\n let memory := PC.(Configuration.memory) in\n let T' := mkTC (covered T) (issued T ∪₁ eq w) in\n let S' := S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) in\n exists p_rel, rfrmw_prev_rel G sc T f_to f_from PC.(Configuration.memory) w locw p_rel /\\\n let f_to' := upd f_to w (Time.middle (f_from w) (f_to w)) in\n let rel'' :=\n if is_rel lab w\n then (TView.cur (Local.tview local))\n else (TView.rel (Local.tview local) locw)\n in\n let rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n (View.singleton_ur locw (f_to' w))) in\n ⟪ RELWFEQ : View.pln rel' = View.rlx rel' ⟫ /\\\n ⟪ REL_VIEW_LT : Time.lt (View.rlx rel'' locw) (f_to' w) ⟫ /\\\n ⟪ REL_VIEW_LE : Time.le (View.rlx rel' locw) (f_to' w) ⟫ /\\\n\n ⟪ REQ_TO : forall e (NEQ : e <> w), f_to' e = f_to e ⟫ /\\\n ⟪ ISSEQ_TO : forall e (ISS : issued T e), f_to' e = f_to e ⟫ /\\\n\n exists promises_cancel memory_cancel,\n ⟪ PCANCEL :\n Memory.remove promises locw (f_from w) (f_to w)\n Message.reserve promises_cancel ⟫ /\\\n ⟪ MCANCEL :\n Memory.remove memory locw (f_from w) (f_to w)\n Message.reserve memory_cancel ⟫ /\\\n\n exists promises_add memory_add,\n ⟪ PADD :\n Memory.add promises_cancel locw (f_from w) (f_to' w)\n (Message.full valw (Some rel')) promises_add ⟫ /\\\n ⟪ MADD :\n Memory.add memory_cancel locw (f_from w) (f_to' w)\n (Message.full valw (Some rel')) memory_add ⟫ /\\\n\n ⟪ INHAB : Memory.inhabited memory_add ⟫ /\\\n ⟪ RELMCLOS : Memory.closed_timemap (View.rlx rel') memory_add ⟫ /\\\n ⟪ RELVCLOS : Memory.closed_view rel' memory_add ⟫ /\\\n\n ⟪ FCOH : f_to_coherent G S' f_to' f_from ⟫ /\\\n\n ⟪ HELPER :\n sim_mem_helper\n G sc f_to' w (f_from w) valw\n (View.join (View.join (if is_rel lab w\n then (TView.cur (Local.tview local))\n else (TView.rel (Local.tview local) locw))\n p_rel.(View.unwrap))\n (View.singleton_ur locw (f_to' w))) ⟫ /\\\n\n ⟪ RESERVED_TIME :\n reserved_time G T' S' f_to' f_from smode memory_add ⟫.\nProof using WF IMMCON ETCCOH RELCOV FCOH SIM_TVIEW SIM_RES_MEM SIM_MEM INHAB PLN_RLX_EQ MEM_CLOSE PROM_IN_MEM.\n assert (sc_per_loc G) as SPL.\n { apply coherence_sc_per_loc. apply IMMCON. }\n assert (complete G) as COMPL by apply IMMCON.\n assert (tc_coherent G sc T) as TCCOH by apply ETCCOH.\n\n (* set (AA:=TSTEP). *)\n (* destruct AA as [_ ETCCOH']. *)\n\n assert (E w) as EW.\n { by apply ETCCOH.(etc_S_in_E). }\n assert (W w) as WW.\n { by apply (reservedW WF ETCCOH). }\n \n assert (~ covered T w) as WNCOV.\n { intros HH. apply WNISS.\n eapply w_covered_issued; [by apply ETCCOH|by split]. }\n assert (~ is_init w) as WNINIT.\n { intros HH. apply WNCOV. eapply init_covered; [by apply ETCCOH| by split]. }\n\n assert (W_ex w) as WEXW.\n { apply ETCCOH. by split. }\n\n assert ((E ∩₁ W ∩₁ Loc_ locw) w) as WEW.\n { split; [split|]; auto. }\n\n assert (codom_rel (rf ⨾ rmw) w) as [wprev PRMWE].\n { eapply W_ex_in_codom_rfrmw; eauto. }\n \n assert (E wprev) as EPREV.\n { apply WF.(wf_rfrmwE) in PRMWE. by destruct_seq PRMWE as [AA BB]. }\n assert (W wprev) as WPREV.\n { apply WF.(wf_rfrmwD) in PRMWE. by destruct_seq PRMWE as [AA BB]. }\n \n assert (wprev <> w) as NEQPREV.\n { intros HH; subst. eapply wf_rfrmw_irr; eauto. }\n\n assert (loc lab wprev = Some locw) as PREVLOC.\n { rewrite <- LOC. by apply WF.(wf_rfrmwl). }\n\n assert (issued T wprev) as ISSPREV.\n { assert ((issued T ∪₁ eq w) wprev) as AA.\n 2: by destruct AA; desf.\n left. eapply (dom_rf_rmw_S_in_I WF ETCCOH).\n exists w. apply seqA. apply seq_eqv_r. split; auto. }\n assert (S wprev) as SPREV.\n { by apply ETCCOH.(etc_I_in_S). }\n\n assert (dom_rel (rf ⨾ rmw ⨾ ⦗eq w⦘) ⊆₁ issued T) as RFRMWISS.\n { rewrite <- seqA. intros a [b HH]. apply seq_eqv_r in HH. desc; subst.\n assert (a = wprev); subst; auto.\n eapply wf_rfrmwf; eauto. }\n \n assert (dom_rel (rf ⨾ rmw ⨾ ⦗eq w⦘) ⊆₁ S) as DRFRMWS.\n { rewrite RFRMWISS. apply ETCCOH. }\n assert (immediate (⦗S⦘ ⨾ co) wprev w) as IMMSPREV.\n { eapply (rfrmwP_in_immPco WF IMMCON) with (P':=eq w); auto.\n apply seqA. basic_solver. }\n\n assert (exists vprev, val lab wprev = Some vprev) as [vprev PREVVAL] by (by apply is_w_val).\n\n edestruct exists_wprev_rel with (w:=w) as [p_rel PRELSPEC]; eauto.\n \n exists p_rel. split.\n { apply PRELSPEC. }\n\n red in PRELSPEC.\n set (rel'' :=\n if Rel w\n then TView.cur (Local.tview local)\n else TView.rel (Local.tview local) locw).\n\n assert (Time.lt (f_from w) (f_to w)) as FFT by (by apply FCOH).\n assert (co wprev w) as COWPREV.\n { eapply rf_rmw_in_co; eauto. }\n \n set (f_to' := upd f_to w (Time.middle (f_from w) (f_to w))).\n assert (REQ_TO : forall e (NEQ : e <> w), f_to' e = f_to e).\n { ins. unfold f_to'. rewrite updo; auto. }\n assert (ISSEQ_TO : forall e (ISS : issued T e), f_to' e = f_to e).\n { ins. unfold f_to'. rewrite updo; auto. by intros HH; subst. }\n\n assert (Time.lt (f_to' wprev) (f_to w)) as PREVNLT.\n { rewrite REQ_TO; auto. eapply f_to_co_mon; eauto. }\n assert (Time.le (f_to' wprev) (f_from w)) as PREVNEF.\n { rewrite REQ_TO; auto. apply FCOH; eauto. }\n assert (Time.lt (f_to' wprev) (f_to' w)) as PREVNLT'.\n { unfold f_to' at 2. rewrite upds.\n eapply TimeFacts.le_lt_lt with (b:=f_from w); auto.\n by apply Time.middle_spec. }\n\n assert (Time.le (View.rlx rel'' locw)\n (View.rlx (TView.cur (Local.tview local)) locw)) as GG.\n { unfold rel''. destruct (Rel w).\n { reflexivity. }\n subst. eapply rel_le_cur; eauto. }\n\n assert (Time.lt (View.rlx rel'' locw) (f_to' w)) as REL_VIEW_LT.\n { eapply TimeFacts.le_lt_lt; [by apply GG|].\n eapply TimeFacts.le_lt_lt; [|by apply PREVNLT'].\n rewrite REQ_TO; auto. eapply le_cur_f_to_wprev; eauto. }\n\n set (rel' := View.join (View.join rel'' (View.unwrap p_rel))\n (View.singleton_ur locw (f_to' w))).\n assert (Time.le (View.rlx (View.unwrap p_rel) locw) (f_to' wprev)) as PREL_LE'.\n { rewrite REQ_TO; auto.\n eapply le_p_rel_f_to_wprev; eauto. }\n assert (Time.le (View.rlx (View.unwrap p_rel) locw) (f_to' w)) as PREL_LE.\n { desc.\n destruct PRELSPEC0; desc.\n { rewrite PREL. apply Time.bot_spec. }\n assert (p = wprev); subst.\n { eapply wf_rfrmwf; eauto. }\n apply Time.le_lteq. left.\n eapply TimeFacts.le_lt_lt.\n 2: by apply PREVNLT'.\n done. }\n\n assert (Time.le (View.rlx rel' locw) (f_to' w)) as REL_VIEW_LE.\n { unfold rel'.\n unfold View.join, TimeMap.join. simpls.\n unfold TimeMap.singleton, LocFun.add.\n rewrite Loc.eq_dec_eq.\n apply Time.join_spec; [|reflexivity].\n apply Time.join_spec; auto.\n apply Time.le_lteq; auto. }\n \n assert (Memory.get locw (f_to w) (Local.promises local) =\n Some (f_from w, Message.reserve)) as PMSG.\n { eapply SIM_RES_MEM; eauto. }\n assert (exists promises_cancel,\n Memory.remove (Local.promises local) locw\n (f_from w) (f_to w) Message.reserve promises_cancel)\n as [promises_cancel PCANCEL].\n { by apply Memory.remove_exists. }\n\n assert (Memory.get locw (f_to w) (Configuration.memory PC) =\n Some (f_from w, Message.reserve)) as MMSG.\n { eapply SIM_RES_MEM; eauto. }\n assert (exists memory_cancel,\n Memory.remove\n PC.(Configuration.memory) locw (f_from w) (f_to w)\n Message.reserve memory_cancel)\n as [memory_cancel MCANCEL].\n { by apply Memory.remove_exists. }\n\n assert (Time.lt (f_from w) (f_to' w)) as WFLT.\n { unfold f_to'. rewrite upds. by apply Time.middle_spec. }\n\n assert (View.pln rel' = View.rlx rel') as RELWFEQ.\n { unfold rel'. simpls. desc. rewrite REL_PLN_RLX.\n arewrite (View.pln rel'' = View.rlx rel'').\n 2: reflexivity.\n unfold rel''. destruct (Rel w); apply PLN_RLX_EQ. }\n assert (View.opt_wf (Some rel')) as RELWF.\n { apply opt_wf_unwrap. simpls.\n constructor. \n arewrite (View.pln rel' = View.rlx rel').\n apply TimeMap.le_PreOrder. }\n \n simpls. splits; eauto.\n do 2 eexists. splits; eauto.\n\n assert (Message.wf (Message.full valw (Some rel'))) as MWF by (by constructor).\n\n assert (Interval.le (f_from w, f_to' w) (f_from w, f_to w)) as LENIOI.\n { unfold f_to'. rewrite upds. constructor; simpls.\n { reflexivity. }\n apply Time.le_lteq. left. by apply Time.middle_spec. }\n\n assert (exists promises_add,\n Memory.add promises_cancel locw\n (f_from w) (f_to' w) (Message.full valw (Some rel'))\n promises_add)\n as [promises_add PADD].\n { apply Memory.add_exists; auto.\n (* TODO: generalize to a lemma. *)\n ins.\n erewrite Memory.remove_o in GET2; eauto.\n destruct (loc_ts_eq_dec (locw, to2) (locw, f_to w)) as [LTEQ|LTNEQ].\n { simpls. desc; subst.\n rewrite (loc_ts_eq_dec_eq locw (f_to w)) in GET2. inv GET2. }\n rewrite loc_ts_eq_dec_neq in GET2; eauto.\n apply Interval.le_disjoint with (b:=(f_from w, f_to w)); auto.\n edestruct Memory.get_disjoint with (t1:=f_to w) (t2:=to2)\n (m:=Local.promises local); eauto.\n desf. }\n assert (exists memory_add,\n Memory.add memory_cancel locw\n (f_from w) (f_to' w) (Message.full valw (Some rel'))\n memory_add)\n as [memory_add MADD].\n { apply Memory.add_exists; auto.\n (* TODO: generalize to a lemma. *)\n ins.\n erewrite Memory.remove_o in GET2; eauto.\n destruct (loc_ts_eq_dec (locw, to2) (locw, f_to w)) as [LTEQ|LTNEQ].\n { simpls. desc; subst.\n rewrite (loc_ts_eq_dec_eq locw (f_to w)) in GET2. inv GET2. }\n rewrite loc_ts_eq_dec_neq in GET2; eauto.\n apply Interval.le_disjoint with (b:=(f_from w, f_to w)); auto.\n edestruct Memory.get_disjoint with (t1:=f_to w) (t2:=to2)\n (m:=PC.(Configuration.memory)); eauto.\n desf. }\n\n assert (Memory.inhabited memory_add) as INHABADD.\n { red. ins.\n erewrite Memory.add_o; eauto.\n erewrite Memory.remove_o; eauto.\n destruct (loc_ts_eq_dec (loc, Time.bot) (locw, f_to' w)) as [AA|LL']; simpls; desc; subst.\n { exfalso. eapply time_lt_bot with (a:=f_from w). rewrite AA0; auto. }\n rewrite !(loc_ts_eq_dec_neq LL').\n destruct (loc_ts_eq_dec (loc, Time.bot) (locw, f_to w)) as [AA|LL]; simpls; desc; subst.\n { exfalso. eapply time_lt_bot with (a:=f_from w). rewrite AA0; auto. }\n rewrite !(loc_ts_eq_dec_neq LL).\n apply INHAB. }\n\n assert (S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ≡₁ S) as NEWS.\n { arewrite (dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ≡₁ ∅).\n generalize SW. basic_solver. }\n\n assert (reserved_time G (mkTC (covered T) (issued T ∪₁ eq w))\n S f_to' f_from smode memory_add) as REST.\n { destruct smode; [|by apply RESERVED_TIME].\n unfold f_to'.\n red. splits.\n 3: { intros x y SX SY CO FF.\n destruct (classic (x = w)); subst.\n 2: { rewrite REQ_TO in FF; auto. by apply RESERVED_TIME. }\n exfalso. rewrite upds in FF.\n eapply Time.lt_strorder with (x:=Time.middle (f_from w) (f_to w)).\n rewrite FF at 2.\n apply TimeFacts.lt_le_lt with (b:=f_to w).\n 2: by apply FCOH.\n by apply Time.middle_spec. }\n all: red; ins; erewrite Memory.add_o in MSG; eauto.\n all: destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [LTEQ|LTNEQ'].\n { simpls. desc; subst. right. exists w. splits; eauto.\n { clear. basic_solver. }\n rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in MSG. inv MSG. }\n { rewrite loc_ts_eq_dec_neq in MSG; eauto.\n erewrite Memory.remove_o in MSG; eauto.\n destruct (loc_ts_eq_dec (l, to) (locw, f_to w)) as [LTEQ|LTNEQ].\n { simpls. desc. subst. rewrite (loc_ts_eq_dec_eq locw (f_to w)) in MSG. inv MSG. }\n rewrite loc_ts_eq_dec_neq in MSG; eauto.\n eapply RESERVED_TIME in MSG. destruct MSG as [|MSG]; desc; subst; auto.\n right. exists b. splits; eauto.\n by left. }\n { simpls. desc; subst. \n rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in MSG. inv MSG. }\n rewrite loc_ts_eq_dec_neq in MSG; eauto.\n erewrite Memory.remove_o in MSG; eauto.\n destruct (loc_ts_eq_dec (l, to) (locw, f_to w)) as [LTEQ|LTNEQ].\n { simpls. desc. subst. rewrite (loc_ts_eq_dec_eq locw (f_to w)) in MSG. inv MSG. }\n rewrite loc_ts_eq_dec_neq in MSG; eauto.\n eapply RESERVED_TIME in MSG.\n desc. subst.\n assert (b <> w) as NEQBW.\n { intros HH. subst. simpls.\n rewrite LOC0 in LOC. inv LOC.\n clear -LTNEQ. desf. }\n exists b. splits; eauto.\n intros [|AA]; desf. }\n\n assert (f_to_coherent G S f_to' f_from) as FCOH_NEW.\n { unfold f_to' in *.\n red. splits.\n { intros x []. rewrite REQ_TO; [|by intros HH; subst]. by apply FCOH. }\n { by apply FCOH. }\n all: ins; destruct (classic (x = w)); subst; [rewrite upds|rewrite updo; auto; by apply FCOH].\n { by apply Time.middle_spec. }\n { apply Time.le_lteq. left. apply TimeFacts.lt_le_lt with (b:=f_to w).\n { by apply Time.middle_spec. }\n by apply FCOH. }\n exfalso. apply WNISS. eapply dom_rf_rmw_S_in_I with (T:=mkETC T S); eauto.\n exists y. apply seqA. apply seq_eqv_r. by split. }\n\n assert (forall tmap (MCLOS : Memory.closed_timemap tmap PC.(Configuration.memory)),\n Memory.closed_timemap tmap memory_add) as MADDCLOS.\n { ins. eapply Memory.add_closed_timemap; eauto.\n eapply Memory.cancel_closed_timemap; eauto. }\n\n assert (Memory.closed_timemap (View.rlx rel') memory_add) as RELMCLOS.\n { unfold rel'. simpls.\n apply Memory.join_closed_timemap.\n 2: { unfold TimeMap.singleton, LocFun.add, LocFun.find.\n red. ins. destruct (Loc.eq_dec loc locw) as [|LNEQ]; subst.\n { erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq. eauto. }\n unfold LocFun.init.\n exists Time.bot, 0, None. apply INHABADD. }\n apply MADDCLOS.\n desc. apply Memory.join_closed_timemap; auto.\n unfold rel''.\n destruct (Rel w); simpls.\n all: apply MEM_CLOSE. }\n do 2 eexists. splits; eauto.\n { constructor; auto. simpls. by rewrite RELWFEQ. }\n { by rewrite NEWS. }\n { eapply sim_helper_issue with (S':=S); eauto. by apply ETCCOH. }\n eapply reserved_time_more.\n 3: by apply NEWS.\n all: eauto.\n apply same_trav_config_refl.\nQed.\n\nLemma exists_time_interval_for_issue_reserved_with_next\n w locw valw langst wnext smode\n (SW : S w)\n (WNISS : ~ issued T w)\n (ISSUABLE : issuable G sc T w)\n (WNEXT : dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) wnext)\n (LOC : loc lab w = Some locw)\n (VAL : val lab w = Some valw)\n (WTID : thread = tid w)\n (RESERVED_TIME: reserved_time G T S f_to f_from smode PC.(Configuration.memory))\n (TID : IdentMap.find (tid w) PC.(Configuration.threads) = Some (langst, local)) :\n let promises := local.(Local.promises) in\n let memory := PC.(Configuration.memory) in\n let T' := mkTC (covered T) (issued T ∪₁ eq w) in\n let S' := S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) in\n let n_to := Time.middle (f_from w) (f_to w) in\n let f_to' := upd (upd f_to w n_to) wnext (f_to w) in\n let f_from' := upd f_from wnext n_to in\n\n exists p_rel, rfrmw_prev_rel G sc T f_to f_from PC.(Configuration.memory) w locw p_rel /\\\n let rel'' :=\n if is_rel lab w\n then (TView.cur (Local.tview local))\n else (TView.rel (Local.tview local) locw)\n in\n let rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n (View.singleton_ur locw (f_to' w))) in\n ⟪ RELWFEQ : View.pln rel' = View.rlx rel' ⟫ /\\\n ⟪ REL_VIEW_LT : Time.lt (View.rlx rel'' locw) (f_to' w) ⟫ /\\\n ⟪ REL_VIEW_LE : Time.le (View.rlx rel' locw) (f_to' w) ⟫ /\\\n\n exists promises_split memory_split,\n ⟪ PSPLIT :\n Memory.split local.(Local.promises) locw (f_from' w) (f_to' w) (f_to' wnext)\n (Message.full valw (Some rel')) Message.reserve promises_split ⟫ /\\\n ⟪ MSPLIT :\n Memory.split memory locw (f_from' w) (f_to' w) (f_to' wnext)\n (Message.full valw (Some rel')) Message.reserve memory_split ⟫ /\\\n\n ⟪ INHAB : Memory.inhabited memory_split ⟫ /\\\n ⟪ RELMCLOS : Memory.closed_timemap (View.rlx rel') memory_split ⟫ /\\\n ⟪ RELVCLOS : Memory.closed_view rel' memory_split ⟫ /\\\n\n ⟪ FCOH : f_to_coherent G S' f_to' f_from' ⟫ /\\\n\n ⟪ HELPER :\n sim_mem_helper\n G sc f_to' w (f_from' w) valw\n (View.join (View.join (if is_rel lab w\n then (TView.cur (Local.tview local))\n else (TView.rel (Local.tview local) locw))\n p_rel.(View.unwrap))\n (View.singleton_ur locw (f_to' w))) ⟫ /\\\n\n ⟪ RESERVED_TIME :\n reserved_time G T' S' f_to' f_from' smode memory_split ⟫.\nProof using WF IMMCON ETCCOH RELCOV FCOH SIM_TVIEW SIM_RES_MEM SIM_MEM INHAB PLN_RLX_EQ MEM_CLOSE PROM_IN_MEM.\n assert (sc_per_loc G) as SPL.\n { apply coherence_sc_per_loc. apply IMMCON. }\n assert (complete G) as COMPL by apply IMMCON.\n assert (tc_coherent G sc T) as TCCOH by apply ETCCOH.\n\n assert (E w) as EW.\n { by apply ETCCOH.(etc_S_in_E). }\n assert (W w) as WW.\n { by apply (reservedW WF ETCCOH). }\n \n assert (~ covered T w) as WNCOV.\n { intros HH. apply WNISS.\n eapply w_covered_issued; [by apply ETCCOH|by split]. }\n assert (~ is_init w) as WNINIT.\n { intros HH. apply WNCOV. eapply init_covered; [by apply ETCCOH| by split]. }\n\n assert (W_ex w) as WEXW.\n { apply ETCCOH. by split. }\n\n assert ((E ∩₁ W ∩₁ Loc_ locw) w) as WEW.\n { split; [split|]; auto. }\n\n assert (codom_rel (rf ⨾ rmw) w) as [wprev PRMWE].\n { eapply W_ex_in_codom_rfrmw; eauto. }\n \n assert (E wprev) as EPREV.\n { apply WF.(wf_rfrmwE) in PRMWE. by destruct_seq PRMWE as [AA BB]. }\n assert (W wprev) as WPREV.\n { apply WF.(wf_rfrmwD) in PRMWE. by destruct_seq PRMWE as [AA BB]. }\n \n assert (wprev <> w) as NEQPREV.\n { intros HH; subst. eapply wf_rfrmw_irr; eauto. }\n\n assert (loc lab wprev = Some locw) as PREVLOC.\n { rewrite <- LOC. by apply WF.(wf_rfrmwl). }\n\n assert (issued T wprev) as ISSPREV.\n { assert ((issued T ∪₁ eq w) wprev) as AA.\n 2: by destruct AA; desf.\n left. eapply (dom_rf_rmw_S_in_I WF ETCCOH).\n exists w. apply seqA. apply seq_eqv_r. split; auto. }\n assert (S wprev) as SPREV.\n { by apply ETCCOH.(etc_I_in_S). }\n\n assert (dom_rel (rf ⨾ rmw ⨾ ⦗eq w⦘) ⊆₁ issued T) as RFRMWISS.\n { rewrite <- seqA. intros a [b HH]. apply seq_eqv_r in HH. desc; subst.\n assert (a = wprev); subst; auto.\n eapply wf_rfrmwf; eauto. }\n \n assert (dom_rel (rf ⨾ rmw ⨾ ⦗eq w⦘) ⊆₁ S) as DRFRMWS.\n { rewrite RFRMWISS. apply ETCCOH. }\n assert (immediate (⦗S⦘ ⨾ co) wprev w) as IMMSPREV.\n { eapply (rfrmwP_in_immPco WF IMMCON) with (P':=eq w); auto.\n apply seqA. basic_solver. }\n\n assert (exists vprev, val lab wprev = Some vprev) as [vprev PREVVAL] by (by apply is_w_val).\n\n edestruct exists_wprev_rel with (w:=w) as [p_rel PRELSPEC]; eauto.\n \n exists p_rel. split.\n { apply PRELSPEC. }\n\n red in PRELSPEC.\n set (rel'' :=\n if Rel w\n then TView.cur (Local.tview local)\n else TView.rel (Local.tview local) locw).\n \n assert (co wprev w) as COWPREV.\n { eapply rf_rmw_in_co; eauto. }\n assert (Time.lt (f_to wprev) (f_to w)) as PREVNLT_OLD.\n { eapply f_to_co_mon; eauto. }\n\n assert ((rf ⨾ rmw) w wnext) as RFRMWNEXT.\n { destruct WNEXT as [_ BB]. generalize BB. unfold Execution.rfi.\n clear. basic_solver. }\n assert (w <> wnext) as NEQ.\n { intros HH; subst. eapply wf_rfrmw_irr; eauto. }\n assert (co w wnext) as COWNEXT.\n { by apply rf_rmw_in_co. }\n assert (~ is_init wnext) as NINITNEXT.\n { apply no_co_to_init in COWNEXT; auto. by destruct_seq_r COWNEXT as AA. }\n assert (E wnext) as EWNEXT.\n { apply WF.(wf_coE) in COWNEXT. by destruct_seq COWNEXT as [AA BB]. }\n assert (~ S wnext) as NSNEXT.\n { intros HH. apply WNISS. eapply dom_rf_rmw_S_in_I with (T:=mkETC T S); eauto.\n exists wnext. apply seqA. apply seq_eqv_r. by split. }\n assert (~ issued T wnext) as NINEXT.\n { intros HH. apply NSNEXT. by apply ETCCOH.(etc_I_in_S). }\n assert (loc lab wnext = Some locw) as NLOC.\n { rewrite <- LOC. symmetry. by apply wf_rfrmwl. }\n\n set (n_to := Time.middle (f_from w) (f_to w)).\n set (f_to' := upd (upd f_to w n_to) wnext (f_to w)).\n set (f_from' := upd f_from wnext n_to).\n\n assert (Time.lt (f_from w) (f_to w)) as WFLT by (by apply FCOH).\n assert (Time.lt (f_from w) (Time.middle (f_from w) (f_to w))) as FROMNTOLT.\n { by apply Time.middle_spec. }\n assert (Time.lt (Time.middle (f_from w) (f_to w)) (f_to w)) as NTOTOLT.\n { by apply Time.middle_spec. }\n\n assert (f_to wprev = f_from w) as PREVFEQ by (by apply FCOH).\n assert (Time.lt (f_to wprev) (f_to' w)) as PREVNLT.\n { unfold f_to'. rewrite updo; auto. rewrite upds.\n unfold n_to. eapply TimeFacts.le_lt_lt with (b:=f_from w); auto.\n rewrite PREVFEQ. apply DenseOrder_le_PreOrder. }\n\n assert (Time.le (View.rlx rel'' locw)\n (View.rlx (TView.cur (Local.tview local)) locw)) as GG.\n { unfold rel''. destruct (Rel w).\n { reflexivity. }\n subst. eapply rel_le_cur; eauto. }\n\n assert (Time.lt (View.rlx rel'' locw) (f_to' w)) as REL_VIEW_LT.\n { eapply TimeFacts.le_lt_lt; [by apply GG|].\n eapply TimeFacts.le_lt_lt; [|by apply PREVNLT].\n eapply le_cur_f_to_wprev with (w:=w) (wprev:=wprev); eauto. }\n\n set (rel' := View.join (View.join rel'' (View.unwrap p_rel))\n (View.singleton_ur locw (f_to' w))).\n assert (Time.le (View.rlx (View.unwrap p_rel) locw) (f_to wprev)) as PREL_LE'.\n { eapply le_p_rel_f_to_wprev with (w:=w) (wprev:=wprev); eauto. }\n assert (Time.le (View.rlx (View.unwrap p_rel) locw) (f_to' w)) as PREL_LE.\n { desc.\n destruct PRELSPEC0; desc.\n { rewrite PREL. apply Time.bot_spec. }\n assert (p = wprev); subst.\n { eapply wf_rfrmwf; eauto. }\n apply Time.le_lteq. left.\n eapply TimeFacts.le_lt_lt.\n 2: by apply PREVNLT.\n done. }\n\n assert (Time.le (View.rlx rel' locw) (f_to' w)) as REL_VIEW_LE.\n { unfold rel'.\n unfold View.join, TimeMap.join. simpls.\n unfold TimeMap.singleton, LocFun.add.\n rewrite Loc.eq_dec_eq.\n apply Time.join_spec; [|reflexivity].\n apply Time.join_spec; auto.\n apply Time.le_lteq; auto. }\n\n assert (View.pln rel' = View.rlx rel') as RELWFEQ.\n { unfold rel'. simpls. desc. rewrite REL_PLN_RLX.\n arewrite (View.pln rel'' = View.rlx rel'').\n 2: reflexivity.\n unfold rel''. destruct (Rel w); apply PLN_RLX_EQ. }\n assert (View.opt_wf (Some rel')) as RELWF.\n { apply opt_wf_unwrap. simpls.\n constructor. \n arewrite (View.pln rel' = View.rlx rel').\n apply TimeMap.le_PreOrder. }\n\n assert (Message.wf (Message.full valw (Some rel'))) as MWF by (by constructor).\n\n assert (Memory.get locw (f_to w) (Local.promises local) =\n Some (f_from w, Message.reserve)) as PMSG.\n { eapply SIM_RES_MEM; eauto. }\n assert (exists promises_split,\n Memory.split (Local.promises local) locw\n (f_from' w) (f_to' w) (f_to' wnext)\n (Message.full valw (Some rel'))\n Message.reserve promises_split)\n as [promises_split PSPLIT].\n { unfold f_from'. rewrite updo; auto.\n unfold f_to'. rewrite upds. rewrite updo; auto. rewrite upds.\n by apply Memory.split_exists. }\n \n assert (Memory.get locw (f_to w) (Configuration.memory PC) =\n Some (f_from w, Message.reserve)) as MMSG.\n { eapply SIM_RES_MEM; eauto. }\n assert (exists memory_split,\n Memory.split PC.(Configuration.memory) locw\n (f_from' w) (f_to' w) (f_to' wnext)\n (Message.full valw (Some rel'))\n Message.reserve memory_split)\n as [memory_split MSPLIT].\n { unfold f_from'. rewrite updo; auto.\n unfold f_to'. rewrite upds. rewrite updo; auto. rewrite upds.\n by apply Memory.split_exists. }\n\n assert (forall tmap (MCLOS : Memory.closed_timemap tmap PC.(Configuration.memory)),\n Memory.closed_timemap tmap memory_split) as MSPLITCLOS.\n { ins. eapply Memory.split_closed_timemap; eauto. }\n\n assert (Memory.inhabited memory_split) as INHABSPLIT.\n { red. ins.\n erewrite Memory.split_o; eauto.\n destruct (loc_ts_eq_dec (loc, Time.bot) (locw, Time.middle (f_from w) (f_to w)))\n as [AA|LL]; simpls; desc; subst.\n { exfalso. eapply time_lt_bot. rewrite AA0.\n by do 2 (apply Time.middle_spec with (lhs:=f_from w)). }\n unfold f_to'. rewrite upds. rewrite updo; auto. rewrite upds.\n rewrite !(loc_ts_eq_dec_neq LL).\n destruct (loc_ts_eq_dec (loc, Time.bot) (locw, f_to w))\n as [AA|LL']; simpls; desc; subst.\n { exfalso. eapply time_lt_bot. rewrite AA0. by apply FCOH. }\n rewrite !(loc_ts_eq_dec_neq LL').\n apply INHAB. }\n\n assert (dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ≡₁ eq wnext) as NEWS'.\n { eapply dom_sb_S_rfrmw_single; eauto. }\n\n assert (S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ≡₁ S ∪₁ eq wnext) as NEWS.\n { rewrite NEWS'. generalize SW. clear. basic_solver. }\n\n splits; eauto. eexists promises_split, memory_split.\n \n (* TODO: generalize to a lemma. *)\n assert (f_to_coherent\n G (S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G {| etc_TC := T; reserved := S |} rfi (eq w))\n f_to' f_from') as FCOH'.\n { eapply f_to_coherent_more.\n 2: by apply NEWS.\n all: eauto.\n red. splits; unfold f_to', f_from', n_to.\n 1,2: intros x [IE EX].\n 1,2: repeat (rewrite updo; [|by intros HH; desf]).\n 1,2: by apply FCOH; split.\n { intros x [SX|] IE; subst.\n 2: by rewrite !upds.\n do 2 (rewrite updo; [|by intros HH; desf]).\n destruct (classic (x = w)); subst.\n { by rewrite upds. }\n rewrite updo; auto. by apply FCOH. }\n { intros x y SX SY CO; subst.\n assert (x <> y) as NEQXY.\n { intros HH; subst. eapply co_irr; eauto. }\n destruct SX as [SX|]; destruct SY as [SY|]; subst.\n 4: by exfalso; eapply co_irr; eauto.\n 3: { rewrite upds. rewrite updo; auto.\n apply FCOH; eauto. eapply co_trans; eauto. }\n { rewrite updo; [|by intros HH; desf].\n rewrite updo with (a:=wnext); [|by intros HH; desf].\n destruct (classic (x = w)); subst.\n { rewrite upds.\n etransitivity.\n { apply Time.le_lteq.\n left. by apply Time.middle_spec with (lhs:=f_from w) (rhs:=f_to w). }\n by apply FCOH. }\n rewrite updo; auto. by apply FCOH. }\n rewrite upds. rewrite updo; auto.\n destruct (classic (x = w)); subst.\n { rewrite upds. apply DenseOrder_le_PreOrder. }\n rewrite updo; auto.\n etransitivity.\n 2: { apply Time.le_lteq.\n left. by apply Time.middle_spec with (lhs:=f_from w) (rhs:=f_to w). }\n apply FCOH; auto.\n edestruct WF.(wf_co_total) with (a:=x) (b:=w); eauto.\n 2: by exfalso; eapply rfrmw_in_im_co; eauto.\n split; [split|].\n { by apply ETCCOH.(etc_S_in_E). }\n { by apply (reservedW WF ETCCOH). }\n apply WF.(wf_col) in CO. rewrite CO.\n rewrite <- LOC. symmetry. by apply wf_rfrmwl. }\n intros x y SX SY CO; subst.\n assert (x <> y) as NEQXY.\n { intros HH; subst. eapply wf_rfrmw_irr; eauto. }\n cdes FCOH.\n destruct SX as [SX|]; destruct SY as [SY|]; subst; try done.\n 3: { rewrite upds. rewrite updo; auto.\n exfalso. apply NSNEXT. eapply dom_rf_rmw_S with (T:=mkETC T S); eauto.\n exists y. apply seqA. apply seq_eqv_r. by split. }\n { rewrite updo; [|by intros HH; desf].\n rewrite updo with (a:=wnext); [|by intros HH; desf].\n destruct (classic (x = w)); subst.\n 2: by rewrite updo; auto.\n exfalso.\n assert (y = wnext); [|by desf].\n eapply wf_rfrmwsf; eauto. }\n rewrite upds. rewrite updo; auto.\n assert (x = w); [|by subst; rewrite upds].\n eapply wf_rfrmwf; eauto. }\n\n assert (S ⊆₁ E ∩₁ W) as SEW.\n { apply set_subset_inter_r. split; [by apply ETCCOH|].\n apply (reservedW WF ETCCOH). }\n \n (* TODO: generalize to a lemma. *)\n assert (reserved_time G (mkTC (covered T) (issued T ∪₁ eq w))\n (S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w))\n f_to' f_from' smode memory_split) as REST.\n { eapply reserved_time_more.\n 3: by apply NEWS.\n all: eauto.\n { apply same_tc. }\n destruct smode; simpls; desc.\n 2: { splits.\n 2: rewrite RMW_BEF_S; basic_solver 10.\n rewrite <- FOR_SPLIT.\n hahn_frame.\n clear. apply eqv_rel_mori.\n apply AuxRel.set_compl_mori. red.\n basic_solver 10. }\n splits.\n 3: { intros x y SX SY CO; subst.\n assert (x <> y) as NEQXY.\n { intros HH; subst. eapply co_irr; eauto. }\n unfold f_to', f_from'.\n destruct SX as [SX|]; destruct SY as [SY|]; subst; try done.\n { repeat (rewrite updo with (a:=wnext); [|by intros HH; desf]).\n destruct (classic (x = w)) as [|NEQXW]; subst;\n [rewrite upds|by rewrite updo; auto].\n unfold n_to. intros HH.\n exfalso.\n apply no_co_to_init in CO; auto. destruct_seq_r CO as BB.\n edestruct to_from_disjoint_from with (w:=w) (w':=y) (I:=S) as [AA|AA]; eauto.\n { by apply wf_col. }\n { rewrite <- HH in AA. by eapply time_middle_lt_lhs; [|apply AA]. }\n rewrite <- HH in AA. by eapply time_middle_le_rhs; [|apply AA]. }\n { rewrite upds. rewrite updo; auto.\n destruct (classic (x = w)) as [|NEQXW]; subst; auto.\n rewrite updo; auto.\n unfold n_to. intros HH.\n exfalso.\n edestruct to_from_disjoint_to with (w:=w) (w':=x) (I:=S) as [AA|AA]; eauto.\n { red. rewrite LOC. symmetry. rewrite <- NLOC. by apply WF.(wf_col). }\n { rewrite HH in AA. by eapply time_middle_le_lhs; [|apply AA]. }\n rewrite HH in AA. by eapply time_middle_lt_rhs; [|apply AA]. }\n rewrite upds. rewrite updo; auto.\n intros HH.\n exfalso.\n apply TFRMW in HH; auto.\n 2: { eapply co_trans; eauto. }\n apply NEQXY. eapply wf_rfrmwsf; eauto. }\n all: red; ins; erewrite Memory.split_o in MSG; eauto; unfold f_to', f_from' in *.\n all: rewrite updo in MSG; auto; rewrite upds in MSG.\n all: destruct (loc_ts_eq_dec (l, to) (locw, n_to)) as [LTEQ|LTNEQ].\n { simpls. desc; subst. right.\n rewrite (loc_ts_eq_dec_eq locw n_to) in MSG. inv MSG.\n exists w. splits; eauto.\n { by right. }\n rewrite updo; auto. by rewrite upds. }\n { rewrite loc_ts_eq_dec_neq in MSG; eauto.\n rewrite upds in MSG.\n destruct (loc_ts_eq_dec (l, to) (locw, f_to w)) as [LTEQ|LTNEQ'].\n { simpls. desc; subst.\n rewrite (loc_ts_eq_dec_eq locw (f_to w)) in MSG. inv MSG. }\n rewrite loc_ts_eq_dec_neq in MSG; auto.\n apply MEM in MSG. destruct MSG as [|MSG]; [left|right]; auto.\n desc. exists b.\n assert (S b) as SB by (by apply ETCCOH.(etc_I_in_S)).\n splits; eauto.\n { by left. }\n { by rewrite updo; [|by intros HH; desf]. }\n by repeat (rewrite updo; [|by intros HH; desf]). }\n { simpls. desc; subst. \n rewrite (loc_ts_eq_dec_eq locw n_to) in MSG. inv MSG. }\n rewrite loc_ts_eq_dec_neq in MSG; eauto.\n rewrite upds in MSG.\n destruct (loc_ts_eq_dec (l, to) (locw, f_to w)) as [LTEQ|LTNEQ'].\n { simpls. desc; subst.\n rewrite (loc_ts_eq_dec_eq locw (f_to w)) in MSG. inv MSG.\n exists wnext. rewrite !upds. splits; auto.\n { by right. }\n intros [A|A]; desf. }\n rewrite loc_ts_eq_dec_neq in MSG; auto. simpls.\n apply HMEM in MSG.\n desc.\n assert (b <> wnext) as BNEQ by (intros HH; desf).\n exists b. rewrite !updo with (a:=wnext); auto. splits; auto.\n { by left. }\n { intros [A|A]; desf. }\n destruct (classic (w = b)); subst.\n 2: by rewrite updo; auto.\n exfalso. rewrite LOC in LOC0. inv LOC0. inv LTNEQ'. }\n\n assert (Memory.closed_timemap (View.rlx rel') memory_split) as RELMCLOS.\n { unfold rel'. simpls.\n apply Memory.join_closed_timemap.\n 2: { unfold TimeMap.singleton, LocFun.add, LocFun.find.\n red. ins. destruct (Loc.eq_dec loc locw) as [|LNEQ]; subst.\n { erewrite Memory.split_o; eauto. rewrite loc_ts_eq_dec_eq. eauto. }\n unfold LocFun.init.\n exists Time.bot, 0, None. apply INHABSPLIT. }\n apply MSPLITCLOS.\n desc. apply Memory.join_closed_timemap; auto.\n unfold rel''.\n destruct (Rel w); simpls.\n all: apply MEM_CLOSE. }\n \n splits; eauto.\n { constructor; auto. simpls. unfold rel''0. by rewrite RELWFEQ. }\n eapply sim_helper_issue with\n (S':=S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G {| etc_TC := T; reserved := S |} rfi (eq w)); eauto.\n 3: { etransitivity; [by apply ETCCOH.(etc_I_in_S)|]. basic_solver. }\n 2: basic_solver.\n unfold f_to'. ins. by repeat (rewrite updo; [|by intros HH; desf]).\nQed.\n\nEnd Aux.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/interval_allocation/ExistsIssueReservedInterval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.136571647543316}} {"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Tactics.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Promote.\nRequire Import Hygiene.\nRequire Import Rules.\nRequire Defs.\nRequire Import Obligations.\nRequire Import Morphism.\nRequire Import DefsEquiv.\nRequire Import Equivalence.\nRequire Import Equivalences.\nRequire Import Dots.\n\nRequire Import DerivedRules.\nRequire Import ValidationUtil.\nRequire Import Defined.\n\nRequire Import SumLemmas.\nRequire Import ValidationSigma.\n\n\nHint Rewrite def_inl def_inr def_sum def_sumcase : prepare.\n\n\nLemma sum_body_formation :\n forall G a b c d,\n tr G (deqtype a c)\n -> tr G (deqtype b d)\n -> tr (hyp_tm booltp :: G) (deqtype (bite (var 0) (subst sh1 a) (subst sh1 b)) (bite (var 0) (subst sh1 c) (subst sh1 d))).\nProof.\nintros G a b c d Hac Hbd.\napply tr_booltp_elim_eqtype.\n {\n eapply hypothesis; eauto using index_0.\n }\n\n {\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n auto.\n }\n\n {\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n auto.\n }\nQed.\n\n\nLemma sumForm_valid : sumForm_obligation.\nProof.\nprepare.\nintros G a b ext1 ext0 Ha Hb.\napply tr_sigma_formation.\n {\n apply tr_booltp_istype.\n }\napply sum_body_formation; auto.\nQed.\n\n\nLemma sumEq_valid : sumEq_obligation.\nProof.\nprepare.\nintros G a b c d ext1 ext0 Ha Hb.\napply tr_sigma_formation.\n {\n apply tr_booltp_istype.\n }\napply sum_body_formation; auto.\nQed.\n\n\nLemma sumFormUniv_valid : sumFormUniv_obligation.\nProof.\nprepare.\nintros G a b i ext1 ext0 Ha Hb.\napply tr_sigma_formation_univ.\n {\n apply (tr_univ_cumulative _ Defined.nzero); auto.\n {\n apply tr_booltp_formation_univ.\n }\n\n {\n apply tr_univ_formation_invert.\n eapply tr_inhabitation_formation; eauto.\n }\n\n {\n rewrite -> leqpagetp_nzero_equiv.\n apply tr_unittp_intro.\n }\n }\nreplace (univ (subst sh1 i)) with (subst1 (var 0) (univ (subst (sh 2) i))) by (simpsub; auto).\napply tr_booltp_elim.\n {\n eapply hypothesis; eauto using index_0.\n }\n\n {\n simpsub.\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n cbn [List.app].\n exact Ha.\n }\n\n {\n simpsub.\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n cbn [List.app].\n exact Hb.\n }\nQed.\n\n\nLemma sumEqUniv_valid : sumEqUniv_obligation.\nProof.\nprepare.\nintros G a b c d i ext1 ext0 Ha Hb.\napply tr_sigma_formation_univ.\n {\n apply (tr_univ_cumulative _ Defined.nzero); auto.\n {\n apply tr_booltp_formation_univ.\n }\n\n {\n apply tr_univ_formation_invert.\n eapply tr_inhabitation_formation; eauto.\n }\n\n {\n rewrite -> leqpagetp_nzero_equiv.\n apply tr_unittp_intro.\n }\n }\nreplace (univ (subst sh1 i)) with (subst1 (var 0) (univ (subst (sh 2) i))) by (simpsub; auto).\napply tr_booltp_elim.\n {\n eapply hypothesis; eauto using index_0.\n }\n\n {\n simpsub.\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n cbn [List.app].\n exact Ha.\n }\n\n {\n simpsub.\n eapply (weakening _ [_] []).\n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n \n {\n cbn [length unlift].\n simpsub.\n auto.\n }\n cbn [length unlift].\n simpsub.\n cbn [List.app].\n exact Hb.\n }\nQed.\n\n\nLemma sumSub_valid : sumSub_obligation.\nProof.\nprepare.\nintros G a b c d ext1 ext0 Hab Hcd.\napply tr_sigma_sub.\n {\n apply tr_subtype_intro; auto using tr_booltp_istype.\n eapply hypothesis; eauto using index_0.\n }\n\n {\n apply (tr_subtype_eta2 _ _ _ (bite (var 0) (subst (under 0 sh1) triv) (subst (under 0 sh1) triv)) (bite (var 0) (subst (under 0 sh1) triv) (subst (under 0 sh1) triv))).\n apply (tr_booltp_eta_hyp _ []).\n {\n simpsub.\n cbn [List.app].\n rewrite -> !equiv_bite_l.\n auto.\n }\n\n {\n simpsub.\n cbn [List.app].\n rewrite -> !equiv_bite_r.\n auto.\n }\n }\n\n {\n apply sum_body_formation.\n {\n eapply tr_subtype_formation_invert2.\n eapply tr_inhabitation_formation; eauto.\n }\n\n {\n eapply tr_subtype_formation_invert2.\n eapply tr_inhabitation_formation; eauto.\n }\n }\nQed.\n\n\nLemma sumIntro1Of_valid : sumIntro1Of_obligation.\nProof.\nprepare.\nintros G a b m ext1 ext0 Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_btrue.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_l.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumIntro1Eq_valid : sumIntro1Eq_obligation.\nProof.\nprepare.\nintros G a b m n ext1 ext0 Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_btrue.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_l.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumIntro1_valid : sumIntro1_obligation.\nProof.\nprepare.\nintros G a b ext0 m Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_btrue.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_l.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumIntro2Of_valid : sumIntro2Of_obligation.\nProof.\nprepare.\nintros G a b m ext1 ext0 Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_bfalse.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_r.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumIntro2Eq_valid : sumIntro2Eq_obligation.\nProof.\nprepare.\nintros G a b m n ext1 ext0 Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_bfalse.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_r.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumIntro2_valid : sumIntro2_obligation.\nProof.\nprepare.\nintros G a b ext0 m Hb Hm.\napply tr_sigma_intro.\n {\n apply tr_booltp_intro_bfalse.\n }\n\n {\n simpsub.\n rewrite -> equiv_bite_r.\n auto.\n }\n\n {\n apply sum_body_formation; auto.\n eapply tr_inhabitation_formation; eauto.\n }\nQed.\n\n\nLemma sumElimOf_valid : sumElimOf_obligation.\nProof.\nprepare.\nintros G a b c m p r ext2 ext1 ext0 Hm Hp Hr.\neapply tr_sumtype_elim; eauto.\nQed.\n\n\nLemma sumElimOfNondep_valid : sumElimOfNondep_obligation.\nProof.\nprepare.\nintros G a b c m p r ext2 ext1 ext0 Hm Hp Hr.\nreplace c with (subst1 m (subst sh1 c)) by (simpsub; auto).\neapply tr_sumtype_elim; eauto; simpsub; auto.\nQed.\n\n\nLemma sumElimEq_valid : sumElimEq_obligation.\nProof.\nprepare.\nintros G a b c m n p q r s ext2 ext1 ext0 Hab Hpq Hrs.\neapply tr_sumtype_elim; eauto.\nQed.\n\n\nLemma sumElim_valid : sumElim_obligation.\nProof.\nprepare.\nintros G a b c m ext0 p r Hm Hp Hr.\neapply tr_sumtype_elim; eauto.\nQed.\n\n\nLemma sumElimNondep_valid : sumElimNondep_obligation.\nProof.\nprepare.\nintros G a b c m p r Hm Hp Hr.\nreplace c with (subst1 m (subst sh1 c)) by (simpsub; auto).\neapply tr_sumtype_elim; eauto; simpsub; auto.\nQed.\n\n\nLemma sumElimIstype_valid : sumElimIstype_obligation.\nProof.\nprepare.\nintros G a b c e m ext2 ext1 ext0 Hab Hc He.\neapply tr_sumtype_elim_eqtype; eauto.\nQed.\n\n\nLemma sumElimEqtype_valid : sumElimEqtype_obligation.\nProof.\nprepare.\nintros G a b c d e f m n ext2 ext1 ext0 Hmn Hcd Hef.\neapply tr_sumtype_elim_eqtype; eauto.\nQed.\n\n\nLemma sumFormInv1_valid : sumFormInv1_obligation.\nProof.\nprepare.\nintros G a b ext0 Hsig.\nunfold sumtype in Hsig.\nso (tr_sigma_formation_invert2 _#5 Hsig) as Hab.\nso (tr_generalize _#4 (tr_booltp_intro_btrue _) Hab) as Ha.\nsimpsubin Ha.\nrewrite -> (steps_equiv _#3 (star_one _#4 (step_bite2 _#3))) in Ha.\nauto.\nQed.\n\n\nLemma sumFormInv2_valid : sumFormInv2_obligation.\nProof.\nprepare.\nintros G a b ext0 Hsig.\nunfold sumtype in Hsig.\nso (tr_sigma_formation_invert2 _#5 Hsig) as Hab.\nso (tr_generalize _#4 (tr_booltp_intro_bfalse _) Hab) as Hb.\nsimpsubin Hb.\nrewrite -> (steps_equiv _#3 (star_one _#4 (step_bite3 _#3))) in Hb.\nauto.\nQed.\n\n\nHint Rewrite def_intersect def_pi def_arrow : prepare.\n\n\nRequire Import NatLemmas.\n\n\nLemma sumcaseType_valid : sumcaseType_obligation.\nProof.\nprepare.\nintros G.\nunfold Defs.sumcase.\napply tr_intersect_intro; auto using tr_nattp_formation.\nsimpsub.\napply tr_intersect_intro.\n {\n apply tr_univ_formation.\n unfold pagetp.\n eapply hypothesis; eauto using index_0.\n }\nsimpsub.\napply tr_intersect_intro.\n {\n apply tr_univ_formation.\n unfold pagetp.\n eapply hypothesis; eauto using index_0, index_S.\n }\nsimpsub.\napply tr_intersect_intro.\n {\n apply tr_univ_formation.\n unfold pagetp.\n eapply hypothesis; eauto using index_0, index_S.\n }\nsimpsub.\ncbn [Nat.add].\nsimpsub.\napply tr_pi_intro.\n {\n apply tr_sumtype_formation.\n {\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n\n {\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n }\neapply tr_pi_intro.\n {\n eapply tr_pi_formation.\n {\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\neapply tr_pi_intro.\n {\n eapply tr_pi_formation.\n {\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n eapply tr_formation_weaken.\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\nmatch goal with\n| |- tr ?X _ =>\n change (tr X (deq (sumcase (var 2) (app (var 2) (var 0)) (app (var 1) (var 0))) (sumcase (var 2) (app (var 2) (var 0)) (app (var 1) (var 0))) (subst1 (var 2) (var 4))))\nend.\neapply tr_sumtype_elim.\n {\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n\n {\n eapply tr_pi_elim'.\n {\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n\n {\n eapply hypothesis; eauto using index_0.\n }\n \n {\n simpsub.\n auto.\n }\n }\n\n {\n eapply tr_pi_elim'.\n {\n eapply hypothesis; eauto using index_0, index_S.\n simpsub.\n cbn [Nat.add].\n eauto.\n }\n\n {\n eapply hypothesis; eauto using index_0.\n }\n \n {\n simpsub.\n auto.\n }\n }\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ValidationSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.13657164456779627}} {"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend Require Csem.\nFrom trancert.lib Require All.\nFrom trancert.invariants Require Common EnvAppears EnvsFreeable EnvAppearsNot\n ForallExprInState EnvsFreeable.\nFrom trancert.properties Require Estate State Events.\nFrom trancert.analysis Require Genv.\nFrom trancert.transformations Require Specification LocalDeclarations.\nFrom trancert Require simulations.Def .\nFrom trancert.axioms Require NoFreeLocals Biject.\nFrom trancert.semantics Require CsemAugmented.\nFrom trancert.simulations.memory.bijection\n Require Def Env Continuation Context Symbols Semantics.\nFrom trancert.simulations.tags Require KcallLifted MatchExprImm MatchExprReds\n ContextCommute FunctionsMapped.\n\n\nImport Csem lib.All Coqlib Csyntax Ctypes Events Values Memory Mem Errors invariants.Common\n transformations.Specification common.Events properties.Events common.Values properties.State\n Globalenvs Globalenvs.Genv analysis.Genv Def\n EnvAppearsNot EnvAppears EnvsFreeable\n ForallExprInState\n analysis.Program\n analysis.Function\n bijection.Symbols\n bijection.Semantics\n bijection.Def bijection.Env bijection.Continuation bijection.Context PTree bijection.AST\n LocalDeclarations .\n\nImport KcallLifted MatchExprImm MatchExprReds ContextCommute FunctionsMapped.\n\nLocal Notation program := Csyntax.program.\nLocal Notation fundef := Csyntax.fundef.\nLocal Notation ident := AST.ident.\nLocal Notation function := Csyntax.function.\nLocal Notation type := Ctypes.type.\nLocal Notation globalenv := Csem.genv.\n\nSection Step.\n\n Context (p p': program) (refparams: LocalDeclarations.params).\n Let ge := Csem.globalenv p.\n Let ge' := Csem.globalenv p'.\n\n (*Hypothesis Huniques: Program.distinct_functions p.\n Hypothesis Huniques': Program.distinct_functions p'.*)\n Hypothesis Hp: LocalDeclarations.spec refparams p p'.\n\n Hypothesis Hfreeable: axioms.NoFreeLocals.locals_stay_free_axiom.\n Hypothesis Hextcall_biject: axioms.Biject.biject_extcall_axiom.\n\n\n Record bisim_params : Type :=\n {\n bp_mapping: mapping\n }.\n\n Inductive R__env (b:bisim_params): fundef -> ident -> env -> env -> Prop :=\n | env_refactored:\n forall e1 e2,\n biject_env (bp_mapping b) (remove (var refparams) e1) e2 ->\n forall func, R__env b func (fn refparams) e1 e2\n | env_other:\n forall fid e1 e2,\n fid <> fn refparams ->\n biject_env (bp_mapping b) e1 e2 ->\n forall func, R__env b func fid e1 e2.\n\n Local Notation _with_embedding R:= (fun M => R (m_fwd M)) .\n\n Record R__mem (b: bisim_params) (m1 m2: mem) : Prop :=\n {\n rm_biject: biject (bp_mapping b) m1 m2 ;\n rm_symbols: symbols_biject (bp_mapping b) ge ge' ;\n rm_globals: forall i def, find_def ge i = Some def -> m_fwd (bp_mapping b) i = Some i ;\n rm_globals': forall i def, find_def ge' i = Some def -> m_fwd (bp_mapping b) i = Some i\n }.\n\n Let P__state p := env_appears_removed p (var refparams) (ty refparams) (fn refparams)\n /*\\ state_env_freeable p\n /*\\ forall_expr_in_state\n (fun f i e => i = fn refparams ->\n ~ Appears.appears_expr (var refparams) e )\n (fun f i C => i = fn refparams ->\n ~ Appears.appears_ctx (var refparams) C ) p .\n\n Let P'__state p' := env_appears_not_removed p' (var refparams) (fn refparams)\n /*\\ state_env_freeable p'\n /*\\ forall_expr_in_state\n (fun f i e => i = fn refparams ->\n ~ Appears.appears_expr (var refparams) e )\n (fun f i C => i = fn refparams ->\n ~ Appears.appears_ctx (var refparams) C ) p'.\n\n\n Program Definition bparams : Def.sim_rel p p' bisim_params :=\n {|\n Def.P__program := precond refparams;\n Def.P'__program := postcond refparams;\n Def.R__program := spec refparams;\n Def.match_fundef := LocalDeclarations.R__fundef refparams;\n Def.match_var := LocalDeclarations.R__var;\n Def.match_env := R__env;\n Def.match_cont := fun b fd fid => biject_econt (m_fwd (bp_mapping b))\n (fun f1 fid f2 => R__fundef refparams fid f1 f2)\n (R__env b)\n ;\n Def.match_stmt := fun b _ _ => biject_statement (m_fwd (bp_mapping b));\n Def.match_expr := fun b _ _=> biject_expr (m_fwd (bp_mapping b));\n Def.match_ctx := fun b _ _ => biject_context (m_fwd (bp_mapping b));\n Def.match_value := fun b _ _ => biject_value (m_fwd (bp_mapping b));\n Def.match_mem := fun b _ _ => R__mem b;\n Def.match_event := Logic.eq ;\n Def.P__state := P__state p;\n Def.P'__state := P'__state p';\n Def.P__mem := fun _ => True ;\n Def.P'__mem := fun _ => True ;\n Def.P__expr := fun f i e => i = fn refparams -> ~ Appears.appears_expr (var refparams) e ;\n Def.P'__expr := fun f i e => i = fn refparams -> ~ Appears.appears_expr (var refparams) e;\n Def.P__env := fun f i e => i = fn refparams -> exists b, e ! (var refparams) = Some(b, ty refparams);\n Def.P'__env := fun f i e => i = fn refparams -> e ! (var refparams) = None\n |}.\n Next Obligation.\n econstructor; eauto;\n inv Hp; eauto.\n Qed.\n Next Obligation.\n subst P__state. simpl in *. decomp.\n inv H2.\n eapply sc_expr; eauto.\n Qed.\n Next Obligation.\n subst P'__state. simpl in *. decomp.\n inv H2.\n eapply sc_expr; eauto.\n Qed.\n Next Obligation.\n subst P__state. simpl in *. decomp.\n eapply i_env_appears; eauto.\n Qed.\n Next Obligation.\n subst P'__state. simpl in *. decomp.\n eapply i_env_appears_not; eauto.\n Qed.\n\n Program Definition is_kcalllifted := Build_KcallLifted bparams _.\n Next Obligation.\n econstructor; simpl in *; eauto.\n Qed.\n\n Program Definition is_match_expr_imm := Build_MatchExprImm bparams _ _.\n Next Obligation.\n inv H.\n by inv H2; eauto.\n Qed.\n Next Obligation.\n by inv H; eauto.\n Qed.\n\n\n\n\n Program Definition is_functions_mapped: FunctionsMapped bparams := Build_FunctionsMapped bparams _ _ _ .\n Next Obligation.\n inv Hp.\n inv rs_correct.\n eapply list_forall2_in_left in pm_idents; eauto.\n decomp.\n destruct x.\n inv H1.\n by inv H3; eauto.\n Qed.\n Next Obligation.\n inv Hp.\n inv rs_correct.\n eapply list_forall2_in_right in pm_idents; eauto.\n decomp.\n destruct x.\n inv H1.\n by inv H3; eauto.\n Qed.\n Next Obligation.\n inv Hp.\n exploit Programs.match_program_defs; eauto.\n by inversion 1; subst.\n Qed.\n\n\n Program Definition is_match_expr_red: MatchExprReds bparams := Build_MatchExprReds bparams _ _ _ _ _ _ . \n Next Obligation. (* lred fwd *)\n clean.\n inv H3; inv H4; simpl in *; try inv_biject_expr.\n - inv H2. inv mcse_env.\n + edestruct H1 as (b' & Hb); eauto.\n destruct (AST.ident_eq x (var refparams)).\n * subst. by contradiction H; repeat econstructor.\n * simpl in *.\n inv H2.\n unfold Env.inject_env in *.\n edestruct be_fwd as (b0' & Hb' & Hh); eauto.\n { rewrite gro; eauto. }\n eapply meminj_embedding_some in Hh.\n eexists. exists m1', b.\n split; auto.\n split; auto; repeat (econstructor; eauto).\n + inv H3.\n unfold Env.inject_env in *.\n edestruct be_fwd as (b0' & Hb' & Hh); eauto.\n eapply meminj_embedding_some in Hh.\n simpl in *.\n eexists. exists m1', b.\n split; auto.\n split; auto.\n * econstructor; eauto.\n ** econstructor; eauto.\n ** econstructor 2; eauto.\n econstructor; eauto.\n * econstructor 1; eauto.\n - exists (Eloc b0 Integers.Ptrofs.zero ty), m1', b.\n inv H2. simpl in *.\n split; auto.\n have Hmap: (m_fwd (bp_mapping b) b0 = Some b0).\n {\n eapply gwf_sd_correspond in H5; last by apply globalenv_wf; inv Hp.\n decomp. eapply mcse_mem; eauto.\n }\n have Hsymb': (find_symbol ge' x = Some b0).\n {\n inv mcse_mem.\n inv rm_symbols0.\n edestruct sb_symb_fwd as (b1 & Hfwd & Hsymb'); eauto.\n by rewrite Hmap in Hfwd; autoinj.\n }\n inv mcse_env.\n + (* refactored function *)\n edestruct H1 as (b' & Hb); eauto. \n destruct (peq x (var refparams)); first by subst; congruence.\n split; auto.\n * repeat (econstructor; eauto).\n * eapply biject_env_none in H2; eauto.\n rewrite gro in H2; eauto.\n econstructor 2; eauto. by eapply H2.\n + (* any other function *)\n econstructor; eauto.\n * econstructor; eauto.\n ** econstructor; eauto.\n ** econstructor 2; eauto.\n * econstructor 2; eauto.\n eapply biject_env_none in H3; eauto.\n eapply H3; eauto.\n - simpl in *. repeat inv_biject_expr.\n inv H6.\n exists (Eloc b2 ofs ty), m1', b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n - repeat inv_biject_expr.\n inv H7.\n eexists. exists m1', b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor 4 ; eauto.\n + simpl; inv Hp.\n erewrite Programs.pm_ce; eauto.\n eapply Programs.match_program_symm; eauto. \n + simpl; inv Hp.\n erewrite Programs.pm_ce; eauto.\n eapply Programs.match_program_symm; eauto. \n - repeat inv_biject_expr.\n inv H6.\n eexists. exists m1', b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor 5 ; eauto.\n + simpl; inv Hp.\n erewrite Programs.pm_ce; eauto.\n eapply Programs.match_program_symm; eauto. \n Qed.\n Next Obligation. (* lred bwd *)\n clean;\n inv H4; inv H3; inv H2; simpl in *; repeat inv_biject_expr.\n - inv mcse_env; simpl in *.\n + inv H2.\n destruct (AST.ident_eq x (var refparams)). \n * subst. contradiction H; repeat econstructor; eauto.\n * simpl in *.\n unfold Env.inject_env in *.\n edestruct be_bwd as (b0' & Hb' & Hh); eauto.\n eapply meminj_embedding_some in Hh.\n apply (bp_mapping b) in Hh.\n eexists. exists m1, b.\n rewrite gro in Hb'; auto.\n split; auto.\n split; auto; repeat (econstructor; eauto).\n + inv H3.\n unfold Env.inject_env in *.\n edestruct be_bwd as (b0' & Hb' & Hh); eauto.\n eapply meminj_embedding_some in Hh.\n apply (bp_mapping b) in Hh.\n simpl in *.\n eexists. exists m1, b.\n split; auto.\n split; auto.\n * econstructor; eauto.\n ** econstructor; eauto.\n ** econstructor 2; eauto.\n econstructor; eauto.\n * econstructor 1; eauto.\n - exists (Eloc b0 Integers.Ptrofs.zero ty), m1, b.\n split; auto.\n inv mcse_mem.\n eapply (sb_symb_bwd _ _ _ rm_symbols0) in H4; eauto.\n decomp.\n apply (bp_mapping b) in H2.\n\n have Hmap: (m_fwd (bp_mapping b) x0 = Some x0).\n {\n eapply gwf_sd_correspond in H3; last by apply globalenv_wf; inv Hp.\n decomp. inv rm_symbols0.\n eapply rm_globals0; eauto.\n }\n rewrite H2 in Hmap; autoinj.\n inv mcse_env.\n + (* refactored function *)\n destruct (peq x (var refparams)); first by subst; contradiction H; auto; repeat econstructor.\n have Hev: (ev ! x = None).\n {\n eapply biject_env_none in H4; eauto.\n rewrite -> gro in *; eauto. by apply H4.\n }\n split.\n * repeat (econstructor; eauto).\n * econstructor 2; eauto.\n + (* any other function *)\n have Hev: (ev ! x = None) by (by eapply biject_env_none in H5; eauto; apply H5).\n econstructor; eauto.\n * econstructor; eauto.\n ** econstructor; eauto.\n ** econstructor 2; eauto.\n ** econstructor; eauto.\n * econstructor 2; eauto.\n - inv H4. simpl in *.\n exists (Eloc b1 ofs ty), m1, b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor 3; eauto.\n - inv H6.\n eexists. exists m1, b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor 4 ; eauto.\n + simpl; inv Hp.\n erewrite <- Programs.pm_ce; eauto.\n by eapply Programs.match_program_symm; eauto.\n + simpl; inv Hp.\n erewrite <- Programs.pm_ce; eauto.\n by eapply Programs.match_program_symm; eauto.\n - inv H5.\n eexists. exists m1, b.\n split; auto.\n split; auto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor; eauto.\n econstructor 5 ; eauto.\n + simpl; inv Hp.\n erewrite <- Programs.pm_ce; eauto.\n by eapply Programs.match_program_symm; eauto.\n Qed.\n Next Obligation. (* rred fwd *)\n clean.\n rename f into f'', f' into f. rename f'' into f'.\n inv H3; inv H2; simpl in *; repeat inv_biject_expr; inv mcse_mem.\n - (* red_rvalof*)\n eapply biject_deref_loc1 in H0; eauto; decomp.\n eexists. exists m1', b, tra.\n constructor; auto.\n split; first by apply list_forall2_refl.\n split; constructor; simpl; auto.\n econstructor; eauto.\n econstructor; eauto.\n eassumption.\n - (* red_addrof *)\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n - (* red_unop *)\n eapply unop_biject in H0; eauto; decomp.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n - (* red_unop *)\n eapply binop_biject in H0; eauto; decomp.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n inv Hp.\n erewrite <- Programs.pm_ce; eauto.\n - (* red_cast *)\n eapply sem_cast_biject in H0; eauto; decomp.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n - (* red_seqand_true *)\n eapply bool_val_biject in H0; eauto.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + by eapply red_seqand_true.\n - (* red_seqand_false *)\n eapply bool_val_biject in H0; eauto.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + by eapply red_seqand_false.\n - (* red_seqor_true *)\n eapply bool_val_biject in H0; eauto.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + by eapply red_seqor_true.\n - (* red_seqor_false *)\n eapply bool_val_biject in H0; eauto.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + by eapply red_seqor_false.\n - (* red_condition *)\n eapply bool_val_biject in H0; eauto.\n eexists (Eparen (if b0 is true then e2' else e3') _ _). exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n destruct b0; eauto.\n econstructor; eauto.\n + by eapply red_condition.\n - (* red_sizeof *)\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + inv Hp.\n erewrite Programs.pm_ce; eauto.\n eapply red_sizeof.\n - (* red_alignof *)\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + inv Hp.\n erewrite Programs.pm_ce; eauto.\n eapply red_alignof.\n - (* red_assign *) \n eapply sem_cast_biject in H6; eauto.\n decomp.\n eapply biject_assign_loc in H3; try eapply H2; eauto; decomp; last by inv Hp; eapply Programs.pm_ce; eauto.\n eexists. exists x0, b, tra.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + econstructor; eauto.\n - (* red_assignop *) \n eapply biject_deref_loc1 in H0; eauto; decomp.\n eexists. exists m1', b, tra.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + econstructor; eauto.\n - (* red_postincr *)\n eapply biject_deref_loc1 in H0; eauto; decomp.\n eexists. exists m1', b, tra.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n - (* red_comma *)\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n econstructor; eauto.\n inv H6; reflexivity.\n - (* red_paren *)\n eapply sem_cast_biject in H0; eauto; decomp.\n eexists. exists m1', b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n econstructor; eauto.\n econstructor; eauto.\n - (* red_builtin *)\n eapply cast_arguments_biject in H0; eauto.\n decomp.\n edestruct (Hextcall_biject ef); eauto.\n decomp.\n eexists _, x2, (Build_bisim_params x0), tra.\n split; auto.\n + intros C C' k1 k2 _ _ H15 H16 H17.\n eapply biject_context_evolve; eauto.\n simpl in *.\n by inv H5; simpl in *.\n + split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n * econstructor; eauto.\n eapply biject_value_evolve; eauto.\n by inv H5.\n * inv mcse_env.\n ** econstructor; eauto.\n eapply biject_env_evolve; eauto.\n ** econstructor 2; eauto.\n eapply biject_env_evolve; eauto.\n * inv Hp.\n econstructor; simpl; auto.\n ** by eapply symbols_biject_evolve; eauto; eapply globalenv_wf.\n ** move => i def /rm_globals0.\n destruct b.\n simpl in *; subst.\n intros HH. inv H5. simpl in *.\n by eapply H13.\n ** move => i def /rm_globals'0.\n destruct b. inv H5.\n simpl in *. subst.\n by eapply H13.\n * inv H5. destruct b. simpl in *. subst. simpl in *.\n eapply biject_econt_evolve; eauto.\n simpl in *.\n eapply biject_econt_incr2; last by eauto.\n intros x0 y f0 i H5.\n inv H5.\n ** econstructor 1. simpl in *. eapply biject_env_evolve; eauto.\n econstructor; eauto.\n ** econstructor 2; simpl in *; auto. eapply biject_env_evolve;eauto.\n simpl in *.\n econstructor; simpl in *; eauto.\n Qed.\n\n Next Obligation. (* rred bwd *)\n clean.\n rename f into f'', f' into f. rename f'' into f'.\n inv H2; inv H3; simpl in *; repeat inv_biject_expr; inv mcse_mem;\n edestruct biject_symm_exists as (M' & Hmax1 & Hmax2 & Hinv); eauto; decomp;\n exploit symbols_biject_symm; eauto; intros Hsymb';\n match goal with |[H: mapping_inverse _ _|-_] => inversion H end;\n try match goal with |[Hfwd: m_fwd _ _ = Some _ |- _] => rewrite -> mi_fwd in Hfwd end.\n (*repeat match goal with |[Hval: biject_value (m_fwd ?M) ?x ?y , Hmap: mapping_inverse ?M _ |- _] =>\n eapply biject_value_inv_mapping in Hval; eauto end.*)\n - (* red_rvalof*)\n eapply biject_deref_loc1 in H0; eauto; decomp; last by apply M'; eauto.\n eexists. exists m1, b, tra'.\n constructor; eauto.\n split; first by apply list_forall2_refl.\n split; constructor; simpl; eauto.\n + econstructor; eauto with bijection.\n + econstructor; eauto.\n - (* red_addrof *)\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto.\n by rewrite mi_fwd.\n econstructor; eauto.\n - (* red_unop *)\n eapply unop_biject in H0; eauto with bijection; decomp.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto with bijection.\n econstructor; eauto with bijection.\n - (* red_binop *)\n eapply binop_biject in H0; eauto with bijection; decomp.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n + repeat econstructor; eauto.\n eapply mapping_inverse_symm in H2.\n eapply biject_value_inv_mapping; eauto.\n + econstructor; eauto.\n + inv Hp. erewrite Programs.pm_ce; eauto.\n - (* red_cast *)\n eapply sem_cast_biject in H0; eauto with bijection; decomp.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n repeat econstructor; eauto with bijection.\n + econstructor; eauto.\n - (* red_seqand_true *)\n eapply bool_val_biject in H0; eauto with bijection.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto.\n + by eapply red_seqand_true.\n - (* red_seqand_false *)\n eapply bool_val_biject in H0; eauto with bijection.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto.\n + by eapply red_seqand_false.\n - (* red_seqor_true *)\n eapply bool_val_biject in H0; eauto with bijection.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto.\n + by eapply red_seqor_true.\n - (* red_seqor_false *)\n eapply bool_val_biject in H0; eauto with bijection.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto.\n + by eapply red_seqor_false.\n - (* red_condition *)\n eapply bool_val_biject in H0; eauto with bijection.\n eexists (Eparen (if b0 is true then e2 else e3) _ _). exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto.\n destruct b0; eauto.\n econstructor; eauto.\n + by eapply red_condition.\n - (* red_sizeof *)\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + inv Hp.\n erewrite Programs.pm_ce; eauto; last by apply Programs.match_program_symm; eassumption.\n eapply red_sizeof.\n - (* red_alignof *)\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto.\n repeat econstructor; eauto.\n econstructor; eauto.\n + inv Hp.\n erewrite Programs.pm_ce; eauto; last by apply Programs.match_program_symm; eassumption.\n eapply red_alignof.\n - (* red_assign *)\n eapply sem_cast_biject in H0; eauto with bijection; decomp.\n eapply biject_assign_loc in H4; eauto with bijection; decomp;\n [|\n by eapply M'; eassumption|\n by inv Hp; eapply Programs.pm_ce; eauto with bijection; eapply Programs.match_program_symm; eassumption].\n\n eexists. exists x0, b, tra'.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n econstructor; eauto with bijection.\n + econstructor; eauto.\n - (* red_assignop *) \n eapply biject_deref_loc1 in H0; eauto with bijection; decomp.\n eexists. exists m1, b, tra'.\n split; auto.\n split; first by apply list_forall2_refl.\n split.\n + econstructor; simpl; eauto with bijection.\n repeat econstructor; eauto with bijection.\n by erewrite mi_fwd; eassumption.\n econstructor; eauto with bijection.\n + econstructor; eassumption.\n + by eapply M'.\n - (* red_postincr *)\n eapply biject_deref_loc1 in H0; eauto with bijection; decomp.\n eexists. exists m1, b, tra'.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto with bijection.\n + econstructor; eauto with bijection. \n econstructor; eauto with bijection;\n econstructor; eauto with bijection.\n by erewrite mi_fwd; eassumption.\n + econstructor; eauto with bijection.\n + by eapply M'.\n - (* red_comma *)\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n econstructor; eauto.\n inv H6; reflexivity.\n - (* red_paren *)\n eapply sem_cast_biject in H0; eauto with bijection; decomp.\n eexists. exists m1, b, E0.\n split; auto.\n split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto with bijection.\n + econstructor; eauto with bijection.\n - (* red_builtin *)\n rename M' into M1'.\n eapply cast_arguments_biject in H0; eauto with bijection;\n last by eapply biject_exprlist_symm; eauto; rewrite mi_fwd; eapply option_inverse_symm; eapply M1'.\n decomp.\n edestruct (Hextcall_biject ef); eauto. decomp. rename x0 into M2', x2 into m2.\n edestruct (biject_symm_exists M1' ) as (M1 & ? & ? & ? & ?); eauto with bijection.\n edestruct (mapping_inverse_exists M2') as (M2 & ?).\n have Hevolve: mapping_evolve M1 M2 by eauto with bijection.\n eexists _, m2, (Build_bisim_params M2 ), tra'.\n split; auto.\n + intros C C' k1 k2 _ _ ? ? ? .\n eapply biject_context_evolve; eauto.\n simpl in *.\n rewrite mi_fwd.\n inv H19.\n rewrite -mi_bwd0.\n by inv H8.\n + split; first by apply list_forall2_refl.\n split; econstructor; simpl; eauto.\n * econstructor.\n eapply biject_value_evolve with (f := m_fwd M1); last by inv Hevolve.\n by eauto with bijection.\n * inv mcse_env; [econstructor 1| econstructor 2]; eauto with bijection.\n * econstructor; simpl; eauto with bijection.\n ** eapply symbols_biject_evolve; eauto with bijection.\n by inv Hp; apply globalenv_wf; eauto.\n ** move => i def /rm_globals0.\n destruct b. simpl in *.\n rewrite mi_fwd.\n intros HH.\n inv H17.\n inv H19.\n inv Hevolve.\n simpl in *.\n apply H17.\n by rewrite -mi_bwd0.\n ** move => i def /rm_globals'0.\n destruct b. simpl in *.\n inv H19. inv H17.\n inv Hevolve.\n simpl in *.\n rewrite mi_fwd mi_bwd1.\n eapply H17.\n * eapply biject_econt_evolve with (f := m_fwd M1); eauto with bijection.\n by inv Hevolve.\n eapply biject_econt_incr2 with (T__env := R__env b); eauto with bijection.\n ** inversion 1; subst; [econstructor 1| econstructor 2]; eauto with bijection.\n ** inv H17.\n rewrite -mi_bwd0.\n rewrite -mi_fwd.\n eauto with bijection.\n Qed.\n Next Obligation. (* callred fwd *)\n clean.\n inv H1.\n inv H2.\n inversion mcse_mem.\n simpl in *.\n repeat inv_biject_expr.\n edestruct cast_arguments_biject as (vargs' & Hargs & Hcastargs); eauto with bijection.\n unfold find_funct, find_funct_ptr in *.\n repeat option_cases. autoinj.\n edestruct Programs.match_program_genv_def as (i & def' & Hsymb & Hsymb' & Hdef' & Hmatch); eauto; [destruct Hp; eauto| eapply Heq|].\n have Hs: (i = id__callee) by eapply (genv_vars_inj (genv_genv (Csem.globalenv p))); eauto. subst.\n inv Hmatch.\n inv H2.\n rename f' into f'__callee.\n have Hfindfunc: find_funct (Csem.globalenv p') v' = Some (Ctypes.Internal f'__callee).\n {\n inv H8. unfold find_funct, find_funct_ptr, find_def in *.\n goal_unmatch; last by congruence.\n have Hb: b0 = b2 by erewrite rm_globals0 in H10; eauto; autoinj.\n by subst b2; rewrite Hdef'; eauto.\n }\n inv H8.\n exists vargs', f'__callee, b.\n do 3 (split; auto).\n - econstructor; eauto.\n - split.\n econstructor; simpl; eauto.\n + econstructor; eauto.\n + econstructor; eauto.\n * have Hb: b0 = b2 by erewrite rm_globals0 in H10; eauto; autoinj.\n by subst.\n * inv H3; by [inv H1|].\n Qed.\n Next Obligation. (* callred bwd *)\n clean.\n inv H1.\n inv H2.\n inversion mcse_mem.\n simpl in *.\n repeat inv_biject_expr.\n edestruct biject_symm_exists as (M' & Hmax1 & Hmax2 & Hinv); eauto; decomp.\n exploit symbols_biject_symm; eauto; intros Hsymbols';\n match goal with |[H: mapping_inverse _ _|-_] => inversion H end.\n (*repeat match goal with |[Hval: biject_value (m_fwd ?M) ?x ?y , Hmap: mapping_inverse ?M _ |- _] =>\n eapply biject_value_inv_mapping in Hval; eauto end.*)\n edestruct cast_arguments_biject as (vargs' & Hargs & Hcastargs); eauto with bijection;\n try by eapply biject_exprlist_symm; eauto with bijection ext; rewrite -mi_bwd; apply (bp_mapping b).\n\n unfold find_funct, find_funct_ptr in *.\n repeat option_cases. autoinj.\n edestruct Programs.match_program_genv_def_inv as (i & def' & Hsymb & Hsymb' & Hdef' & Hmatch); eauto; [destruct Hp; eauto| eapply Heq|].\n inv Hmatch.\n\n have Hfindfunc: find_funct (Csem.globalenv p) v = Some f1.\n {\n inv H2. unfold find_funct, find_funct_ptr, find_def in *.\n goal_unmatch; last by congruence.\n have Hb0: m_fwd (bp_mapping b) b0 = Some b0 by eapply rm_globals'0; eauto.\n have Heq': b1 = b0 by eapply mapping_inj; eauto. subst b1.\n by rewrite Hdef'.\n }\n inv H11.\n\n have Hs: (i = id__callee) by eapply (genv_vars_inj (genv_genv (Csem.globalenv p'))); eauto.\n subst i.\n rename f into f__callee.\n exists vargs', f__callee, b.\n split; auto.\n inv H2.\n split; auto.\n - rewrite mi_fwd.\n eapply list_forall2_inv; eauto; first by destruct M'; simpl; intros; eauto with bijection.\n - split; auto.\n + econstructor; simpl; eauto.\n + split; econstructor; simpl; eauto.\n * econstructor; eauto.\n * rewrite mi_fwd.\n eapply list_forall2_inv; eauto; first by destruct M'; simpl; intros; eauto with bijection.\n * have Heq': b1 = b0 by eapply mapping_inj; eauto. by subst b1.\n * inv H12; by [inv H3|].\n Qed.\n\n\n Require Import Behaviors.\n\n Definition ts : transformation_spec p p' (precond refparams) (postcond refparams) (spec refparams).\n inv Hp.\n constructor; auto.\n constructor; auto.\n Defined.\n\n Definition is_simulation:\n Def.Simulation p p' (precond refparams) (postcond refparams) (P__state p) (P'__state p')\n (Lockstep.BisimR bparams)\n (spec refparams) (Logic.eq) ts.\n constructor; eauto.\n\n\n Theorem behavior_preservation:\n forall beh,\n Behaviors.program_behaves (semantics p) beh ->\n exists beh',\n program_behavior_match Logic.eq Logic.eq beh beh' /\\\n Behaviors.program_behaves (semantics p') beh'.\n Proof.\n intros beh H.\n eapply behavior_preserved__fwd with (T__event := fun x => x); eauto.\n - move => ? ? ? -> -> ; eauto.\n - econstructor.\n + econstructor.\n\n\nEnd Step.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/simulations/Locals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.13657164456779627}} {"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Equivalence.\nRequire Import MapTerm.\nRequire Import Hygiene.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import SemanticsSimple.\nRequire Import SemanticsWtype.\nRequire Import SemanticsProperty.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import System.\nRequire Import Defined.\nRequire Import PageCode.\nRequire Import Hygiene.\nRequire Import Equivalences.\nRequire Import ProperClosed.\nRequire Import ProperEquiv.\nRequire Import ProperFun.\nRequire Import ProperDownward.\nRequire Import Ordinal.\nRequire Import Judgement.\n\nRequire Import Extend.\nRequire Import MapTerm.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import SemanticsMu.\nRequire Import SemanticsSigma.\nRequire Import ExtendTruncate.\nRequire Import Equality.\nRequire Import SemanticsPositive.\n\n\n\nLocal Ltac prove_hygiene :=\n repeat (first [ apply hygiene_shift_permit\n | apply hygiene_sumbool\n | apply natlit_closed\n | apply map_hygiene\n | apply hygiene_auto; cbn; repeat2 split; auto\n ]);\n eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1;\n try (apply hygiene_var; cbn; auto; done).\n\n\nDefinition nat_action i : nat -> relation sterm\n :=\n fun j m n =>\n exists k,\n j <= i\n /\\ natinterp m k\n /\\ natinterp n k.\n\n\nLemma nat_uniform :\n forall i, uniform _ (nat_action i).\nProof.\nintros i.\ndo2 3 split.\n\n(* closed *)\n{\nintros j m n H.\ndestruct H as (k & _ & Hm & Hn).\nsplit; eauto using natinterp_closed.\n}\n\n(* equiv *)\n{\nintros j m m' n n' Hclm' Hcln' Hequivm Hequivn Hact.\ndestruct Hact as (k & Hj & Hm & Hn).\nexists k.\ndo2 2 split; eauto using natinterp_equiv.\n}\n\n(* zigzag *)\n{\nintros j m n p q Hmn Hpn Hpq.\ndestruct Hmn as (k & Hj & Hm & Hn).\ndestruct Hpn as (k' & _ & Hp & Hn').\nso (natinterp_fun _#3 Hn Hn'); subst k'.\ndestruct Hpq as (k' & _ & Hp' & Hq).\nso (natinterp_fun _#3 Hp Hp'); subst k'.\nexists k.\nauto.\n}\n\n(* downward *)\n{\nintros j m n H.\ndestruct H as (k & Hj & Hm & Hn).\nexists k.\ndo2 2 split; auto.\nomega.\n}\nQed.\n\n\nDefinition nat_urel i : surel := mk_urel (nat_action i) (nat_uniform i).\n\n\nLemma bool_eval_iff_true :\n forall w i j m p,\n rel (bool_urel w i) j m p\n -> star step m btrue <-> star step p btrue.\nProof.\nintros w i j m p Hmp.\ndestruct Hmp as (_ & _ & _ & [(Hm & Hp) | (Hm & Hp)]).\n {\n split; auto.\n }\n \n {\n split.\n {\n intro Hm'.\n so (determinism_eval _#4 (conj Hm value_bfalse) (conj Hm' value_btrue)) as H.\n discriminate H.\n }\n\n {\n intro Hp'.\n so (determinism_eval _#4 (conj Hp value_bfalse) (conj Hp' value_btrue)) as H.\n discriminate H.\n }\n }\nQed.\n\n\nLemma bool_eval_iff_false :\n forall w i j m p,\n rel (bool_urel w i) j m p\n -> star step m bfalse <-> star step p bfalse.\nProof.\nintros w i j m p Hmp.\ndestruct Hmp as (_ & _ & _ & [(Hm & Hp) | (Hm & Hp)]).\n {\n split.\n {\n intro Hm'.\n so (determinism_eval _#4 (conj Hm' value_bfalse) (conj Hm value_btrue)) as H.\n discriminate H.\n }\n\n {\n intro Hp'.\n so (determinism_eval _#4 (conj Hp' value_bfalse) (conj Hp value_btrue)) as H.\n discriminate H.\n }\n }\n\n {\n split; auto.\n }\nQed.\n\n\nLemma bool_action_contra :\n forall w i j m,\n bool_action w i j btrue m\n -> bool_action w i j bfalse m\n -> False.\nProof.\nintros w i j m Htrue Hfalse.\nso (bool_eval_iff_true _#5 Htrue andel (star_refl _)) as H.\nso (bool_eval_iff_false _#5 Hfalse andel (star_refl _)) as H'.\nso (determinism_eval _#4 (conj H value_btrue) (conj H' value_bfalse)) as HH.\ndiscriminate HH.\nQed.\n\n\nLemma bool_urelsp_contra :\n forall w i (C : urelsp_car (bool_urel w i)) j,\n pi1 C j btrue\n -> pi1 C j bfalse\n -> False.\nProof.\nintros w i C j Htrue Hfalse.\nso (urelsp_eta _#2 C) as (k & m & p & Hmp & ->).\ncbn in Htrue, Hfalse.\ndestruct Htrue as (_ & _ & _ & _ & [(_ & Hsteps) | (Hcontra & _)]).\n2:{\n so (determinism_eval _#4 (conj (star_refl _) value_btrue) (conj Hcontra value_bfalse)) as H.\n discriminate H.\n }\ndestruct Hfalse as (_ & _ & _ & _ & [(Hcontra & _) | (_ & Hsteps')]).\n {\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj Hcontra value_btrue)) as H.\n discriminate H.\n }\nso (determinism_eval _#4 (conj Hsteps value_btrue) (conj Hsteps' value_bfalse)) as H.\ndiscriminate H.\nQed.\n\n\nDefinition sumtp_rhs_action w i (A B : wurel w) (C : urelsp_car (bool_urel w i))\n : nat -> wterm w -> wterm w -> Prop\n :=\n fun j m p =>\n (pi1 C j btrue /\\ rel A j m p)\n \\/\n (pi1 C j bfalse /\\ rel B j m p).\n\n\nLemma sumtp_rhs_uniform :\n forall w i A B C,\n uniform _ (sumtp_rhs_action w i A B C).\nProof.\nintros w i A B C.\ndo2 3 split.\n\n(* closed *)\n{\nintros j m p Hmp.\ndestruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)]; eapply urel_closed; eauto.\n}\n\n(* equiv *)\n{\nintros j m m' p p' Hclm' Hclp' Hequivm Hequivp Hmp.\ndestruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n eauto using urel_equiv.\n }\n\n {\n right.\n eauto using urel_equiv.\n }\n}\n\n(* zigzag *)\n{\nintros j m p n q Hmp Hnp Hnq.\ndestruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n destruct Hnp as [(_ & Hnp) | (Hfalse & _)].\n 2:{\n destruct (bool_urelsp_contra _#4 Htrue Hfalse).\n }\n destruct Hnq as [(_ & Hnq) | (Hfalse & _)].\n 2:{\n destruct (bool_urelsp_contra _#4 Htrue Hfalse).\n }\n left.\n split; auto.\n eapply urel_zigzag; eauto.\n }\n\n {\n destruct Hnp as [(Htrue & _) | (_ & Hnp)].\n {\n destruct (bool_urelsp_contra _#4 Htrue Hfalse).\n }\n destruct Hnq as [(Htrue & _) | (_ & Hnq)].\n {\n destruct (bool_urelsp_contra _#4 Htrue Hfalse).\n }\n right.\n split; auto.\n eapply urel_zigzag; eauto.\n }\n}\n\n(* downward *)\n{\nintros j m p Hmp.\ndestruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left; split; auto using urel_downward.\n apply (urelsp_downward _#4 (S j)); auto.\n }\n\n {\n right; split; auto using urel_downward.\n apply (urelsp_downward _#4 (S j)); auto.\n }\n}\nQed.\n\n\nDefinition sumtp_rhs_urel w i (A B : wurel w) (C : car (urelsp (bool_urel w i)))\n : car (wurel_ofe w)\n :=\n mk_urel _ (sumtp_rhs_uniform w i A B C).\n\n\nLemma sumtp_rhs_meta_unique :\n forall w i (A B : wiurel w) (C : urelsp_car (bool_urel w i)),\n exists! (x : meta (obj w)), exists y,\n x = meta_truncate (S (urelsp_index _ C)) y\n /\\\n ((pi1 C (urelsp_index _ C) btrue /\\ y = snd A)\n \\/\n (pi1 C (urelsp_index _ C) bfalse /\\ y = snd B)).\nProof.\nintros w i A B C.\nso (urelsp_eta _ _ C) as (j & m & p & Hmp & ->).\nrewrite -> urelsp_index_inj.\ndestruct Hmp as (Hj & Hclm & Hclp & [(Hstepsm & Hstepsp) | (Hstepsm & Hstepsp)]).\n {\n exists (meta_truncate (S j) (snd A)).\n split.\n {\n exists (snd A).\n split; auto.\n left.\n split; auto.\n cbn.\n split; auto.\n do2 3 split; auto.\n {\n apply hygiene_auto; cbn; auto.\n }\n left.\n split; auto.\n apply star_refl.\n }\n\n {\n intros x Hx.\n destruct Hx as (y & -> & [(Htrue & ->) | (Hfalse & ->)]); auto.\n cbn in Hfalse.\n exfalso.\n destruct Hfalse as (_ & _ & _ & _ & [(Hcontra & _) | (_ & Hstepsp')]).\n {\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj Hcontra value_btrue)) as H.\n discriminate H.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsp' value_bfalse) (conj Hstepsp value_btrue)) as H.\n discriminate H.\n }\n }\n }\n\n {\n exists (meta_truncate (S j) (snd B)).\n split.\n {\n exists (snd B).\n split; auto.\n right.\n split; auto.\n cbn.\n split; auto.\n do2 3 split; auto.\n {\n apply hygiene_auto; cbn; auto.\n }\n right.\n split; auto.\n apply star_refl.\n }\n\n {\n intros x Hx.\n destruct Hx as (y & -> & [(Htrue & ->) | (Hfalse & ->)]); auto.\n cbn in Htrue.\n exfalso.\n destruct Htrue as (_ & _ & _ & _ & [(_ & Hstepsp') | (Hcontra & _)]).\n {\n so (determinism_eval _#4 (conj Hstepsp value_bfalse) (conj Hstepsp' value_btrue)) as H.\n discriminate H.\n }\n\n {\n so (determinism_eval _#4 (conj (star_refl _) value_btrue) (conj Hcontra value_bfalse)) as H.\n discriminate H.\n }\n }\n }\nQed.\n\n\nDefinition sumtp_rhs_meta w i (A B : wiurel w) (C : car (urelsp (bool_urel w i))) \n : meta (obj w)\n :=\n pi1 (description _ _ (sumtp_rhs_meta_unique w i A B C)).\n\n\nDefinition sumtp_rhs w i (A B : wiurel w) (C : car (urelsp (bool_urel w i)))\n : car (wiurel_ofe w)\n :=\n (sumtp_rhs_urel w i (den A) (den B) C, sumtp_rhs_meta w i A B C).\n\n\nLemma sumtp_rhs_nonexpansive :\n forall w i A B, nonexpansive (sumtp_rhs w i A B).\nProof.\nintros w i A B.\nintros j C D Hdist.\nsplit.\n {\n intros k Hj.\n fextensionality 2.\n intros m p.\n pextensionality.\n {\n intro Hmp.\n destruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n split; auto.\n rewrite <- Hdist; auto.\n }\n \n {\n right.\n split; auto.\n rewrite <- Hdist; auto.\n }\n }\n \n {\n intro Hmp.\n destruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n split; auto.\n rewrite -> Hdist; auto.\n }\n \n {\n right.\n split; auto.\n rewrite -> Hdist; auto.\n }\n }\n }\n\n {\n destruct j as [| j].\n {\n apply dist_zero.\n }\n unfold sumtp_rhs.\n cbn [snd].\n unfold sumtp_rhs_meta.\n match goal with\n | |- dist _ (pi1 (@description _ _ ?Z)) (pi1 (@description _ _ ?Z')) =>\n set (X := Z); set (Y := Z')\n end.\n destruct X as (xx & Hxx).\n destruct Y as (yy & Hyy).\n rewrite -> !description_beta.\n destruct Hxx as ((x & -> & Hx) & Huniq).\n destruct Hyy as ((y & -> & Hy) & _).\n so (urelsp_eta _ _ C) as (k & m & p & Hmp & ->).\n so (urelsp_eta _ _ D) as (k' & n & q & Hnq & ->).\n rewrite -> !urelsp_index_inj in Hx, Huniq, Hy |- *.\n rewrite -> urelsp_index_inj.\n cut (x = y).\n {\n intros <-.\n so (urelspinj_dist_index' _#11 Hdist) as [(<- & _) | (Hle & Hle')].\n {\n apply dist_refl.\n }\n\n {\n eapply dist_trans.\n {\n refine (dist_downward_leq _#5 Hle _).\n apply meta_truncate_near.\n }\n eapply dist_trans.\n 2:{\n apply dist_symm.\n refine (dist_downward_leq _#5 Hle' _).\n apply meta_truncate_near.\n }\n apply dist_refl.\n }\n }\n so (urelspinj_dist_invert _#11 Hdist) as Hmq.\n destruct Hx as [(Htrue & ->) | (Hfalse & ->)].\n {\n destruct Hy as [(_ & ->) | (Hfalse & ->)]; auto.\n exfalso.\n cbn -[rel] in Htrue, Hfalse.\n destruct Htrue as (_ & Htrue).\n destruct Hfalse as (_ & Hfalse).\n so (bool_eval_iff_true _#5 Htrue andel (star_refl _)) as H.\n rewrite <- (bool_eval_iff_true _#5 Hmp) in H.\n rewrite -> (bool_eval_iff_true _#5 Hmq) in H.\n rewrite <- (bool_eval_iff_true _#5 Hfalse) in H.\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj H value_btrue)) as H'.\n discriminate H'.\n }\n\n {\n destruct Hy as [(Htrue & ->) | (_ & ->)]; auto.\n exfalso.\n cbn -[rel] in Htrue, Hfalse.\n destruct Htrue as (_ & Htrue).\n destruct Hfalse as (_ & Hfalse).\n so (bool_eval_iff_true _#5 Htrue andel (star_refl _)) as H.\n rewrite <- (bool_eval_iff_true _#5 Hmq) in H.\n rewrite -> (bool_eval_iff_true _#5 Hmp) in H.\n rewrite <- (bool_eval_iff_true _#5 Hfalse) in H.\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj H value_btrue)) as H'.\n discriminate H'.\n }\n }\nQed.\n\n\nDefinition sumtp_rhs_ne w i (A B : wiurel w) : urelsp (bool_urel w i) -n> wiurel_ofe w\n :=\n expair (sumtp_rhs w i A B) (sumtp_rhs_nonexpansive w i A B).\n\n\nDefinition sumtp_def w i (A B : wiurel w) : wiurel w\n :=\n iusigma w\n (iubase (bool_urel w i))\n (sumtp_rhs_ne w i A B).\n\n\nLemma interp_sumtp :\n forall pg s i a b A B,\n interp pg s i a A\n -> interp pg s i b B\n -> interp pg s i (sumtype a b) (sumtp_def stop i A B).\nProof.\nintros pg s i a b A B Hinta Hintb.\nso (basic_closed _#6 Hinta) as Hcla.\nso (basic_closed _#6 Hintb) as Hclb.\napply interp_eval_refl.\napply interp_sigma.\n {\n apply interp_eval_refl.\n apply interp_bool.\n }\napply functional_i.\n {\n prove_hygiene.\n }\n\n {\n rewrite -> den_iubase.\n rewrite -> ceiling_bool.\n rewrite -> min_l; auto.\n }\nintros j m p Hj Hmp.\nsimpsub.\ncbn.\nso Hmp as H.\ncbn in H.\ndestruct H as (_ & Hclm & Hclp & Hsteps).\nassert (hygiene clo (if s then m else p)) as Hclmp.\n {\n destruct s; auto.\n }\ndestruct Hsteps as [(Hstepsm & Hstepsp) | (Hstepsm & Hstepsp)].\n {\n assert (star step (if s then m else p) btrue) as Hsteps.\n {\n destruct s; auto.\n }\n assert (interp pg s j (bite (if s then m else p) a b) (iutruncate (S j) A)) as H.\n {\n refine (basic_equiv _#7 _ _ (basic_downward _#7 Hj Hinta)).\n {\n prove_hygiene.\n }\n\n {\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun z => bite z _ _)); eauto using step_bite1.\n }\n apply star_one.\n apply step_bite2.\n }\n }\n force_exact H; clear H.\n unfold interp.\n f_equal.\n unfold iutruncate.\n unfold sumtp_rhs.\n f_equal.\n {\n apply urel_extensionality.\n fextensionality 3.\n intros k n q.\n cbn.\n pextensionality.\n {\n intros (Hk & Hnq).\n left.\n cbn.\n split; auto.\n split; [omega |].\n do2 3 split; [omega | prove_hygiene | auto |].\n left; split; auto.\n apply star_refl.\n }\n\n {\n intro Hnq.\n destruct Hnq as [(Htrue & Hnq) | (Hfalse & _)].\n {\n cbn in Htrue.\n destruct Htrue as (Hk & Htrue).\n split; auto.\n omega.\n }\n\n {\n exfalso.\n destruct Hfalse as (Hk & Hfalse).\n destruct Hfalse as (_ & _ & _ & [(Hcontra & _) | (_ & Hfalse)]).\n {\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj Hcontra value_btrue)) as H.\n discriminate H.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsp value_btrue) (conj Hfalse value_bfalse)) as H.\n discriminate H.\n }\n }\n }\n }\n\n {\n unfold sumtp_rhs_meta.\n match goal with\n | |- _ = pi1 (description _ _ ?Z) =>\n set (X := Z)\n end.\n destruct X as (x & Hx).\n rewrite -> description_beta.\n symmetry.\n apply (Hx ander).\n rewrite -> urelsp_index_inj.\n exists (snd A).\n split; auto.\n left.\n split; auto.\n cbn -[rel].\n split; auto.\n do2 3 split; auto; try prove_hygiene.\n left; auto using star_refl.\n }\n }\n\n {\n assert (star step (if s then m else p) bfalse) as Hsteps.\n {\n destruct s; auto.\n }\n assert (interp pg s j (bite (if s then m else p) a b) (iutruncate (S j) B)) as H.\n {\n refine (basic_equiv _#7 _ _ (basic_downward _#7 Hj Hintb)).\n {\n prove_hygiene.\n }\n\n {\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun z => bite z _ _)); eauto using step_bite1.\n }\n apply star_one.\n apply step_bite3.\n }\n }\n force_exact H; clear H.\n unfold interp.\n f_equal.\n unfold iutruncate.\n unfold sumtp_rhs.\n f_equal.\n {\n apply urel_extensionality.\n fextensionality 3.\n intros k n q.\n cbn.\n pextensionality.\n {\n intros (Hk & Hnq).\n right.\n cbn.\n split; auto.\n split; [omega |].\n do2 3 split; [omega | prove_hygiene | auto |].\n right; split; auto.\n apply star_refl.\n }\n\n {\n intro Hnq.\n destruct Hnq as [(Htrue & _) | (Hfalse & Hnq)].\n {\n exfalso.\n destruct Htrue as (Hk & Htrue).\n destruct Htrue as (_ & _ & _ & [(_ & Htrue) | (Hcontra & _)]).\n {\n so (determinism_eval _#4 (conj Hstepsp value_bfalse) (conj Htrue value_btrue)) as H.\n discriminate H.\n }\n\n {\n so (determinism_eval _#4 (conj (star_refl _) value_btrue) (conj Hcontra value_bfalse)) as H.\n discriminate H.\n }\n }\n\n {\n cbn in Hfalse.\n destruct Hfalse as (Hk & Hfalse).\n split; auto.\n omega.\n }\n }\n }\n\n {\n unfold sumtp_rhs_meta.\n match goal with\n | |- _ = pi1 (description _ _ ?Z) =>\n set (X := Z)\n end.\n destruct X as (x & Hx).\n rewrite -> description_beta.\n symmetry.\n apply (Hx ander).\n rewrite -> urelsp_index_inj.\n exists (snd B).\n split; auto.\n right.\n split; auto.\n cbn -[rel].\n split; auto.\n do2 3 split; auto; try prove_hygiene.\n right; auto using star_refl.\n }\n }\nQed.\n\n\n(* Proving extend_sumtp is much harder than it seems like it should be. *)\n\n\nLemma extend_iurel_sumtp_rhs :\n forall v w (h : v <<= w) i A B C,\n extend_iurel h (sumtp_rhs v i A B C)\n =\n sumtp_rhs w i (extend_iurel h A) (extend_iurel h B) \n (transport (extend_bool v w i h) urelsp_car (extend_urelsp h _ C)).\nProof.\nintros v w h i A B C.\nunfold sumtp_rhs, extend_iurel.\ncbn.\nf_equal.\n {\n apply urel_extensionality.\n cbn.\n unfold sumtp_rhs_action.\n fextensionality 3.\n intros j m p.\n cbn.\n rewrite -> (pi1_transport_lift _ _ urelsp_car_rhs _ _ (extend_bool v w i h)).\n pextensionality.\n {\n intros H.\n destruct H as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n split; auto.\n }\n\n {\n right.\n split; auto.\n }\n }\n\n {\n intros H.\n destruct H as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n split; auto.\n }\n\n {\n right.\n split; auto.\n }\n }\n }\n\n {\n unfold sumtp_rhs_meta.\n match goal with\n | |- extend_meta _ (pi1 (description _ _ ?Z1)) = pi1 (description _ _ ?Z2) =>\n set (x := Z1); set (y := Z2)\n end.\n destruct x as (x & Hx).\n destruct y as (y & Hy).\n rewrite -> !description_beta.\n symmetry.\n apply (Hy ander).\n destruct Hx as (Hx & _).\n destruct Hx as (x' & -> & Hx).\n rename x' into x.\n destruct Hy as (Hy & _).\n destruct Hy as (y' & -> & Hy).\n rename y' into y.\n so (urelsp_eta _ _ C) as (j & m & p & Hmp & ->).\n rewrite -> !urelsp_index_inj in Hx |- *.\n exists (extend_meta h x).\n split.\n {\n rewrite -> extend_meta_truncate.\n rewrite -> urelsp_index_transport.\n rewrite -> urelsp_index_extend.\n rewrite -> urelsp_index_inj.\n reflexivity.\n }\n destruct Hy as [(Htrue & ->) | (Hfalse & ->)].\n {\n left.\n split; auto.\n cbn.\n destruct Hx as [(_ & ->) | (Hcontra & _)]; auto.\n exfalso.\n rewrite -> (pi1_transport_lift _ _ urelsp_car_rhs _ _ (extend_bool v w i h)) in Htrue.\n destruct Htrue as (_ & Htrue).\n rewrite -> urelsp_index_transport in Htrue.\n rewrite -> urelsp_index_extend in Htrue.\n rewrite -> urelsp_index_inj in Htrue.\n simpmapin Htrue.\n cbn in Htrue.\n cbn in Hcontra.\n exact (bool_action_contra _#4 Htrue (Hcontra ander)).\n }\n\n {\n right.\n split; auto.\n cbn.\n destruct Hx as [(Hcontra & _) | (_ & ->)]; auto.\n exfalso.\n rewrite -> (pi1_transport_lift _ _ urelsp_car_rhs _ _ (extend_bool v w i h)) in Hfalse.\n destruct Hfalse as (_ & Hfalse).\n rewrite -> urelsp_index_transport in Hfalse.\n rewrite -> urelsp_index_extend in Hfalse.\n rewrite -> urelsp_index_inj in Hfalse.\n simpmapin Hfalse.\n cbn in Hfalse.\n cbn in Hcontra.\n exact (bool_action_contra _#4 (Hcontra ander) Hfalse).\n }\n }\nQed.\n\n\nLemma urelsp_of_extend :\n forall v w (A : wurel v) (C : urelsp_car (extend_urel v w A)),\n v <<= w\n -> pi1 C = (fun i m => pi1 C i (map_term (extend v w) (map_term (extend w v) m))).\nProof.\nintros v w A C Hvw.\nso (urelsp_eta _ _ C) as (i & m & p & Hmp & ->).\ncbn.\nfextensionality 2.\nintros j n.\npextensionality.\n {\n intros (Hj & Hnp).\n split; auto.\n rewrite -> (extend_term_cancel _ _ Hvw); auto.\n }\n\n {\n intros (Hj & Hnp).\n split; auto.\n rewrite -> (extend_term_cancel _ _ Hvw) in Hnp; auto.\n }\nQed.\n\n\nLemma extend_sumtp :\n forall v w i A B (h : v <<= w),\n extend_iurel h (sumtp_def v i A B)\n =\n sumtp_def w i (extend_iurel h A) (extend_iurel h B).\nProof.\nintros v w i A B h.\nunfold sumtp_def.\nrewrite -> extend_iusigma.\ncbn.\nmatch goal with\n| |- iusigma _ ?x1 ?x2 = iusigma _ ?y1 ?y2 =>\n set (x := @expair \n (wiurel w) (fun X => urelsp (den X) -n> wiurel_ofe w)\n x1 x2);\n set (y := @expair\n (wiurel w) (fun X => urelsp (den X) -n> wiurel_ofe w)\n y1 y2)\nend.\nchange (iusigma w (pi1 x) (pi2 x) = iusigma w (pi1 y) (pi2 y)).\ncut (x = y).\n {\n clearbody x y.\n intros <-.\n auto.\n }\nsubst x y.\napply expair_compat_dep.\napply exT_extensionality_prop_eq_dep.\ncbn.\napply (eq_dep_prod_fst (wurel w) (meta (obj w)) (fun X => urelsp_car X -> wiurel w)).\n {\n f_equal.\n rewrite -> extend_iubase.\n f_equal.\n apply extend_bool; auto.\n }\ncbn.\napply functional_extensionality_eq_dep_dom.\n {\n rewrite -> extend_bool; auto.\n }\nintros C D Heq.\nchange (urelsp_car (extend_urel v w (bool_urel v i))) in C.\nchange (urelsp_car (bool_urel w i)) in D.\nrewrite -> extend_iurel_sumtp_rhs.\nf_equal.\nso (eq_dep_impl_eq _#6 Heq) as (h' & <-).\nso (proof_irrelevance _ (extend_bool v w i h) h'); subst h'.\nf_equal.\napply exT_extensionality_prop.\ncbn.\nfextensionality 2.\nintros j m.\nso (f_equal (fun z => z j m) (urelsp_of_extend _#3 C h)) as H.\ncbn in H.\nrewrite -> H.\nreflexivity.\nQed.\n\n\nDefinition nattp_body w i (X : car (wurel_ofe w)) : wiurel w\n :=\n sumtp_def w i \n (iubase (unit_urel w i))\n (iubase (ceiling (S i) X)).\n\n\nDefinition nattp_def w i : siurel :=\n iubase\n (extend_urel w stop (mu_urel w (fun X => den (nattp_body w i X)))).\n\n\nLemma nattp_body_mono :\n forall w i,\n monotone (fun X => den (nattp_body w i X)).\nProof.\nintros w i.\nintros X Y Hincl.\nunfold nattp_body.\ncbn.\nintros j m p Hmp.\ncbn in Hmp.\ncbn.\ndecompose Hmp.\nintros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\nexists m1, p1, m2, p2, Hmp1.\ndo2 4 split; auto.\ndestruct Hmp2 as [(Htrue & Hmp2) | (Hfalse & Hmp2)].\n {\n left.\n split; auto.\n }\n\n {\n right.\n split; auto.\n destruct Hmp2 as (Hj & Hmp2).\n split; auto.\n }\nQed.\n\n\nLemma nattp_body_mono_blur :\n forall v w i,\n monotone (fun X => den (nattp_body w i (extend_urel v w (extend_urel w v X)))).\nProof.\nintros v w i.\nassert (monotone (fun X => extend_urel v w (extend_urel w v X))) as Hmono.\n {\n intros X Y Hincl.\n intros j m p Hmp.\n cbn.\n cbn in Hmp.\n apply Hincl; auto.\n }\nso (Lattice.impl_compose _#8 Hmono (nattp_body_mono w i)) as H.\nexact H.\nQed.\n\n\nLemma interp_nattp :\n forall pg s i,\n interp pg s i nattp (nattp_def (cin pg) i).\nProof.\nintros pg s i.\nassert (cin pg <<= stop) as Hstop.\n {\n eapply le_ord_trans; eauto using cin_top.\n apply succ_nodecrease.\n }\napply interp_eval_refl.\napply interp_mu; auto using le_ord_refl.\n {\n intros X h.\n simpsub.\n unfold nattp_body.\n rewrite -> extend_sumtp.\n rewrite -> extend_iubase.\n rewrite <- iutruncate_iubase.\n rewrite -> extend_unit; auto.\n apply interp_sumtp.\n {\n apply interp_eval_refl.\n apply interp_unit.\n }\n\n {\n apply interp_eval_refl.\n apply interp_extt.\n apply le_ord_refl.\n }\n }\n\n {\n intros j X Y Hdist.\n destruct j as [| j].\n {\n apply dist_zero.\n }\n eapply dist_trans.\n {\n apply dist_symm.\n apply ceiling_near.\n }\n eapply dist_trans.\n 2:{\n apply ceiling_near.\n }\n apply dist_refl'.\n unfold nattp_body.\n cbn.\n rewrite -> !ceiling_sigma.\n f_equal.\n apply nearrow_extensionality.\n intros Z.\n cbn.\n apply ceiling_collapse.\n intros k Hk.\n fextensionality 2.\n intros m p.\n revert X Y Hdist.\n match goal with\n | |- forall (X Y : car (wurel_ofe (cin pg))), _ -> ?Z = ?Z' =>\n cut (forall (X Y : car (wurel_ofe (cin pg))), dist (S j) X Y -> Z -> Z')\n end.\n {\n intro Hprop.\n intros X Y Hdist.\n pextensionality; intro H; eapply Hprop; eauto.\n apply dist_symm; auto.\n }\n intros X Y Hdist Hmp.\n destruct Hmp as [(Htrue & Hmp) | (Hfalse & Hmp)].\n {\n left.\n split; auto.\n }\n\n {\n right.\n split; auto.\n destruct Hmp as (Hk' & Hmp).\n split; auto.\n eapply rel_from_dist; eauto.\n apply (dist_downward_leq _ _ (S j)); auto.\n }\n }\n\n {\n apply nattp_body_mono.\n }\n\n {\n apply robust_sigma.\n {\n replace booltp with (@subst (obj stop) (under 0 sh1) booltp) by (simpsub; auto).\n apply robust_const.\n }\n replace (var 0) with (@subst (obj stop) (under 1 sh1) (var 0)) by (simpsub; auto).\n apply robust_bite.\n {\n simpsub.\n replace unittp with (@subst (obj stop) (under 1 sh1) unittp) by (simpsub; auto).\n apply robust_const.\n }\n\n {\n simpsub.\n apply robust_var.\n }\n }\nQed.\n\n\nLemma map_natinterp_conv :\n forall (f : obj stop -> obj stop) m i,\n natinterp (map_term f m) i\n -> natinterp m i.\nProof.\nintros f m i H.\nremember (map_term f m) as n eqn:Heq.\nrevert m Heq.\ninduct H.\n\n(* 0 *)\n{\nintros ? n p Hhyg Hstepsm Hstepsn Hstepsp m ->.\nso (map_steps_form _#5 Hstepsm) as (np & Heqnp & Hstepsm').\nso (map_eq_ppair_invert _#6 (eqsymm Heqnp)) as (n' & p' & -> & <- & <-).\nso (map_steps_form _#5 Hstepsn) as (r & Heqr & Hstepsn').\nso (map_eq_btrue_invert _#4 (eqsymm Heqr)); subst r.\nso (map_steps_form _#5 Hstepsp) as (t & Heqt & Hstepsp').\nso (map_eq_triv_invert _#4 (eqsymm Heqt)); subst t.\neapply natinterp_0; eauto using map_hygiene_conv.\n}\n\n(* S *)\n{\nintros ? n p i Hhyg Hstepsm Hstepsn _ IH m ->.\nso (map_steps_form _#5 Hstepsm) as (np & Heqnp & Hstepsm').\nso (map_eq_ppair_invert _#6 (eqsymm Heqnp)) as (n' & p' & -> & <- & <-).\nso (map_steps_form _#5 Hstepsn) as (r & Heqr & Hstepsn').\nso (map_eq_bfalse_invert _#4 (eqsymm Heqr)); subst r.\neapply natinterp_S; eauto using map_hygiene_conv.\n}\nQed.\n\n\nLemma nattp_nat_urel :\n forall w i,\n w <<= stop\n -> den (nattp_def w i) = nat_urel i.\nProof.\nintros w i Hw.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\npextensionality.\n {\n intros Hmp.\n cut (incl (den (nattp_def w i)) (nat_urel i)).\n {\n intro Hincl.\n unfold nattp_def in Hincl.\n rewrite -> den_iubase in Hincl.\n apply Hincl.\n exact Hmp.\n }\n clear j m p Hmp.\n unfold nattp_def in *.\n rewrite -> den_iubase.\n rewrite -> extend_mu; auto.\n 2:{\n apply nattp_body_mono.\n }\n apply mu_least.\n unfold nattp_body.\n rewrite <- (den_extend_iurel _ _ Hw).\n rewrite -> extend_sumtp.\n rewrite -> !extend_iubase.\n rewrite -> extend_unit; auto.\n intros j m p Hmp.\n destruct Hmp as (m1 & p1 & m2 & p2 & Hmp1 & Hclm & Hclp & Hstepsm & Hstepsp & Hmp2).\n cbn in Hmp2.\n destruct Hmp2 as [(Htrue & Hmp2) | (Hfalse & Hmp2)].\n {\n cbn in Htrue.\n destruct Htrue as (_ & _ & _ & _ & [(Htrue & Hstepsp1) | (Hcontra & _)]).\n 2:{\n so (determinism_eval _#4 (conj (star_refl _) value_btrue) (conj Hcontra value_bfalse)) as H.\n discriminate H.\n }\n destruct Hmp2 as (_ & Hj & _ & _ & Hstepsm2 & Hstepsp2).\n exists 0.\n do2 2 split; auto.\n {\n eapply natinterp_0; eauto.\n apply (bool_eval_iff_true _#5 Hmp1); auto.\n }\n\n {\n eapply natinterp_0; eauto.\n }\n }\n\n {\n cbn in Hfalse.\n destruct Hfalse as (_ & _ & _ & _ & [(Hcontra & _) | (Hfalse & Hstepsp1)]).\n {\n so (determinism_eval _#4 (conj (star_refl _) value_bfalse) (conj Hcontra value_btrue)) as H.\n discriminate H.\n }\n destruct Hmp2 as (_ & Hmp2).\n destruct Hmp2 as (n & Hj & Hm2 & Hp2).\n exists (S n).\n do2 2 split; auto.\n {\n eapply natinterp_S; eauto.\n apply (bool_eval_iff_false _#5 Hmp1); auto.\n rewrite -> map_term_compose in Hm2.\n eapply map_natinterp_conv; eauto.\n }\n\n {\n eapply natinterp_S; eauto.\n rewrite -> map_term_compose in Hp2.\n eapply map_natinterp_conv; eauto.\n }\n }\n }\n\n {\n intros Hmp.\n so (nattp_body_mono w i) as Hmono.\n unfold nattp_def.\n rewrite -> den_iubase.\n cbn [rel extend_urel].\n unfold nattp_body.\n destruct Hmp as (k & Hj & Hm & Hp).\n revert p Hp.\n induct Hm.\n (* 0 *)\n {\n intros m m1 m2 Hclm Hstepsm Hstepsm1 Hstepsm2 p Hp.\n invertc Hp.\n intros p1 p2 Hclp Hstepsp Hstepsp1 Hstepsp2.\n rewrite -> mu_fix; auto.\n so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsm Hclm)) as H; cbn in H.\n destruct H as (Hclm1 & Hclm2 & _).\n so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsp Hclp)) as H; cbn in H.\n destruct H as (Hclp1 & Hclp2 & _).\n so (map_steps _ _ (extend stop w) _ _ Hstepsm) as Hstepsm'.\n simpmapin Hstepsm'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsp) as Hstepsp'.\n simpmapin Hstepsp'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsm1) as Hstepsm1'.\n simpmapin Hstepsm1'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsp1) as Hstepsp1'.\n simpmapin Hstepsp1'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsm2) as Hstepsm2'.\n simpmapin Hstepsm2'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsp2) as Hstepsp2'.\n simpmapin Hstepsp2'.\n assert (rel (bool_urel w i) j (map_term (extend stop w) m1) (map_term (extend stop w) p1)) as Hmp1.\n {\n do2 3 split; auto; try prove_hygiene.\n }\n exists (map_term (extend stop w) m1), (map_term (extend stop w) p1), (map_term (extend stop w) m2), (map_term (extend stop w) p2), Hmp1.\n do2 4 split; auto; try prove_hygiene.\n left.\n split.\n {\n cbn.\n split; auto.\n do2 3 split; auto; try prove_hygiene.\n left; split; auto.\n apply star_refl.\n }\n\n {\n do2 4 split; auto; try prove_hygiene.\n }\n }\n\n (* S *)\n {\n intros m m1 m2 k Hclm Hstepsm Hstepsm1 _ IH p Hp.\n invertc Hp.\n intros p1 p2 Hclp Hstepsp Hstepsp1 Hstepsp2.\n so (IH _ Hstepsp2) as Hmp2.\n rewrite -> mu_fix; auto.\n so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsm Hclm)) as H; cbn in H.\n destruct H as (Hclm1 & Hclm2 & _).\n so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsp Hclp)) as H; cbn in H.\n destruct H as (Hclp1 & Hclp2 & _).\n\n so (map_steps _ _ (extend stop w) _ _ Hstepsm) as Hstepsm'.\n simpmapin Hstepsm'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsp) as Hstepsp'.\n simpmapin Hstepsp'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsm1) as Hstepsm1'.\n simpmapin Hstepsm1'.\n so (map_steps _ _ (extend stop w) _ _ Hstepsp1) as Hstepsp1'.\n simpmapin Hstepsp1'.\n assert (rel (bool_urel w i) j (map_term (extend stop w) m1) (map_term (extend stop w) p1)) as Hmp1.\n {\n do2 3 split; auto; try prove_hygiene.\n }\n exists (map_term (extend stop w) m1), (map_term (extend stop w) p1), (map_term (extend stop w) m2), (map_term (extend stop w) p2), Hmp1.\n do2 4 split; auto; try prove_hygiene.\n right.\n split.\n {\n cbn.\n split; auto.\n do2 3 split; auto; try prove_hygiene.\n right; split; auto.\n apply star_refl.\n }\n\n {\n split; [omega |].\n apply IH; auto.\n }\n }\n }\nQed.\n\n\nLemma interp_nattp_invert :\n forall pg s i A j m n,\n interp pg s i nattp A\n -> rel (den A) j m n\n -> exists k,\n natinterp m k\n /\\ natinterp n k.\nProof.\nintros pg s i A j m n Hint Hmn.\nso (basic_fun _#7 Hint (interp_nattp pg s i)); subst A.\nrewrite -> nattp_nat_urel in Hmn; auto using cin_stop.\ndestruct Hmn as (k & _ & Hm & Hn).\neauto.\nQed.\n\n\nLemma interp_pagetp_invert :\n forall pg s i A j m n,\n interp pg s i pagetp A\n -> rel (den A) j m n\n -> exists pg',\n pginterp m pg'\n /\\ pginterp n pg'.\nProof.\nintros pg s i A j m n Hint Hmn.\nso (interp_nattp_invert _#7 Hint Hmn) as (k & Hm & Hn).\nset (pg' := mk_page (fin k) (fin k) (fin k) (le_ord_trans _#3 (le_fin_omega _ _) omega_top) (le_ord_trans _#3 (le_fin_omega _ _) omega_top) (le_ord_refl _)).\nexists pg'.\nsplit.\n {\n exists (fin k).\n do2 3 split; auto.\n exists k; auto.\n }\n\n {\n exists (fin k).\n do2 3 split; auto.\n exists k; auto.\n }\nQed.\n\n\nLemma theta_fix :\n forall object (m : term object),\n star step (app theta m) (app m (app theta m)).\nProof.\nintros object m.\neapply star_step.\n {\n apply step_app1.\n unfold theta.\n apply step_app2.\n }\nsimpsub.\neapply star_step.\n {\n apply step_app2.\n }\nsimpsub.\napply star_refl.\nQed.\n\n\nLemma app_leqtp_equiv :\n forall object (m b p b' n c q c' : @term object),\n star step m (ppair b p)\n -> star step n (ppair c q)\n -> star step b b'\n -> star step c c'\n -> equiv\n (app (app leqtp m) n)\n (bite b' unittp\n (bite c' voidtp\n (app (app leqtp p) q))).\nProof.\nintros object m b p b' n c q c' Hm Hn Hb Hc.\neapply equiv_trans.\n {\n apply equiv_app; [| apply equiv_refl].\n eapply equiv_trans.\n {\n eapply equiv_trans.\n {\n apply equiv_app; [| apply equiv_refl].\n eapply equiv_trans.\n {\n apply steps_equiv.\n apply theta_fix.\n }\n fold (@leqtp object).\n apply steps_equiv.\n apply star_one.\n apply step_app2.\n }\n simpsub.\n cbn [Nat.add].\n apply steps_equiv.\n apply star_one.\n apply step_app2.\n }\n simpsub.\n cbn [Nat.add].\n apply equiv_refl.\n }\neapply equiv_trans.\n {\n apply steps_equiv.\n apply star_one.\n apply step_app2.\n }\nsimpsub.\ncbn [Nat.add].\nunfold sumcase.\napply equiv_bite.\n {\n eapply equiv_trans.\n {\n apply equiv_ppi1.\n apply steps_equiv; eauto.\n }\n apply steps_equiv.\n eapply star_step.\n {\n apply step_ppi12.\n }\n auto.\n }\n\n {\n simpsub.\n apply equiv_refl.\n }\nsimpsub.\napply equiv_bite.\n {\n eapply equiv_trans.\n {\n apply equiv_ppi1.\n apply steps_equiv; eauto.\n }\n apply steps_equiv.\n {\n eapply star_step.\n {\n apply step_ppi12.\n }\n auto.\n }\n }\n\n {\n apply equiv_refl.\n }\napply equiv_app.\n {\n apply equiv_app.\n {\n apply equiv_refl.\n }\n\n {\n eapply equiv_trans.\n {\n apply equiv_ppi2.\n apply steps_equiv; eauto.\n }\n apply steps_equiv.\n apply star_one.\n apply step_ppi22.\n }\n }\n\n {\n eapply equiv_trans.\n {\n apply equiv_ppi2.\n apply steps_equiv; eauto.\n }\n apply steps_equiv.\n apply star_one.\n apply step_ppi22.\n }\nQed.\n\n\nLemma leqtp_false_equiv :\n forall m n i j,\n natinterp m i\n -> natinterp n j\n -> j < i\n -> equiv (app (app leqtp m) n) voidtp.\nProof.\nintros m n i j Hm Hn Hlt.\nrevert n j Hn Hlt.\ninduct Hm.\n\n(* 0 *)\n{\nintros m _ _ _ _ _ _ n j _ Hlt.\nomega.\n}\n\n(* S *)\n{\nintros m b p i Hclm Hstepsm Hstepsb _ IH n jj Hn Hlt.\ninvertc Hn.\n (* n = 0 *)\n {\n intros c q _ Hstepsn Hstepsc _ <-.\n eapply equiv_trans.\n {\n eapply app_leqtp_equiv; eauto.\n }\n eapply equiv_trans.\n {\n apply steps_equiv.\n apply star_one.\n apply step_bite3.\n }\n eapply equiv_trans.\n {\n apply steps_equiv.\n apply star_one.\n apply step_bite2.\n }\n apply equiv_refl.\n }\n\n (* n > 0 *)\n {\n intros c q j Hcln Hstepsn Hstepsc Hc <-.\n eapply equiv_trans.\n {\n eapply app_leqtp_equiv; eauto.\n }\n eapply equiv_trans.\n {\n apply steps_equiv.\n apply star_one.\n apply step_bite3.\n }\n eapply equiv_trans.\n {\n apply steps_equiv.\n apply star_one.\n apply step_bite3.\n }\n eapply IH; eauto.\n omega.\n }\n}\nQed.\n\n\nLemma interp_leqtp_invert :\n forall pg s i m n A j p q k k',\n interp pg s i (app (app leqtp m) n) A\n -> rel (den A) j p q\n -> natinterp m k\n -> natinterp n k'\n -> k <= k'.\nProof.\nintros pg s i m n A j p q k k' Hint Hpq Hm Hn.\nso (le_lt_dec k k') as [| Hlt]; auto.\nexfalso.\nso (leqtp_false_equiv _#4 Hm Hn Hlt) as Hequiv.\neassert _ as Hint'; [refine (basic_equiv _#7 _ Hequiv Hint) |].\n {\n apply hygiene_auto; cbn; auto.\n }\nso (basic_fun _#7 Hint' (interp_eval_refl _#6 (interp_void _#4))); subst A.\ncbn in Hpq.\ndestruct Hpq.\nQed.\n\n\nLemma interp_lttp_invert :\n forall pg s i m n A j p q k k',\n interp pg s i (app (app lttp m) n) A\n -> rel (den A) j p q\n -> natinterp m k\n -> natinterp n k'\n -> k < k'.\nProof.\nintros pg s i m n A j p q k k' Hint Hpq Hm Hn.\nso (le_lt_dec (S k) k') as [| Hlt]; auto.\nexfalso.\nso (natinterp_nsucc _ _ Hm) as Hm'.\nso (leqtp_false_equiv _#4 Hm' Hn Hlt) as Hequiv.\neassert _ as Hint'; [refine (basic_equiv _#5 voidtp _ _ _ Hint) |].\n {\n apply hygiene_auto; cbn; auto.\n }\n\n {\n eapply equiv_trans; eauto.\n apply equiv_app; [| apply equiv_refl].\n unfold lttp.\n eapply steps_equiv.\n eapply star_step.\n {\n apply step_app2.\n }\n simpsub.\n apply star_refl.\n }\nso (basic_fun _#7 Hint' (interp_eval_refl _#6 (interp_void _#4))); subst A.\ncbn in Hpq.\ndestruct Hpq.\nQed.\n\n\nLemma interp_leqpagetp_invert :\n forall pg s i lv1 lv2 A j m n pg1 pg2,\n interp pg s i (leqpagetp lv1 lv2) A\n -> rel (den A) j m n\n -> pginterp lv1 pg1\n -> pginterp lv2 pg2\n -> le_page pg1 pg2.\nProof.\nintros pg s i lv1 lv2 A j m n pg1 pg2 Hint Hmn Hlv1 Hlv2.\ndestruct pg1 as [str1 cex1 cin1].\ndestruct pg2 as [str2 cex2 cin2].\nunfold le_page; cbn.\ndestruct Hlv1 as (w1 & Hlv1 & H).\ncbn in H.\ndestruct H as (-> & -> & ->).\ndestruct Hlv2 as (w2 & Hlv2 & H).\ncbn in H.\ndestruct H as (-> & -> & ->).\ndestruct Hlv1 as (k1 & Hk1 & ->).\ndestruct Hlv2 as (k2 & Hk2 & ->).\nunfold leqpagetp in Hint.\nso (interp_leqtp_invert _#11 Hint Hmn Hk1 Hk2) as Hle.\ndo2 2 split; apply le_fin; auto.\nQed.\n\n\nLemma interp_ltpagetp_invert :\n forall pg s i lv1 lv2 A j m n pg1 pg2,\n interp pg s i (ltpagetp lv1 lv2) A\n -> rel (den A) j m n\n -> pginterp lv1 pg1\n -> pginterp lv2 pg2\n -> lt_page pg1 pg2.\nProof.\nintros pg s i lv1 lv2 A j m n pg1 pg2 Hint Hmn Hlv1 Hlv2.\ndestruct pg1 as [str1 cex1 cin1].\ndestruct pg2 as [str2 cex2 cin2].\nunfold lt_page; cbn.\ndestruct Hlv1 as (w1 & Hlv1 & H).\ncbn in H.\ndestruct H as (-> & -> & ->).\ndestruct Hlv2 as (w2 & Hlv2 & H).\ncbn in H.\ndestruct H as (-> & -> & ->).\ndestruct Hlv1 as (k1 & Hk1 & ->).\ndestruct Hlv2 as (k2 & Hk2 & ->).\nunfold ltpagetp in Hint.\nso (interp_lttp_invert _#11 Hint Hmn Hk1 Hk2) as Hlt.\nsplit; apply le_fin; auto.\nQed.\n\n\nLemma seq_pagetp_invert :\n forall G lv,\n (forall i t t',\n pwctx i t t' G\n -> exists pg R,\n interp pg true i (subst t pagetp) R\n /\\ rel (den R) i (subst t lv) (subst t' lv))\n -> forall i s s',\n pwctx i s s' G\n -> exists pg,\n pginterp (subst s lv) pg\n /\\ pginterp (subst s' lv) pg.\nProof.\nintros G lv Hseq i s s' Hs.\nso (Hseq _#3 Hs) as (pg & R & HR & Hlv).\nexact (interp_pagetp_invert _#7 HR Hlv).\nQed.\n\n\nLemma seq_leqpagetp_invert :\n forall G lv lv' m,\n (forall i t t',\n pwctx i t t' G\n -> exists pg R,\n interp pg true i (subst t (leqpagetp lv lv')) R\n /\\ rel (den R) i (subst t m) (subst t' m))\n -> forall i s s' pg pg',\n pwctx i s s' G\n -> pginterp (subst s lv) pg\n -> pginterp (subst s lv') pg'\n -> le_page pg pg'.\nProof.\nintros G lv lv' m Hseq i s s' pg pg' Hs Hlv Hlv'.\nso (Hseq _#3 Hs) as (pg'' & R & HR & Hm).\nexact (interp_leqpagetp_invert _#11 HR Hm Hlv Hlv').\nQed.\n\n\nLemma seq_ltpagetp_invert :\n forall G lv lv' m,\n (forall i t t',\n pwctx i t t' G\n -> exists pg R,\n interp pg true i (subst t (ltpagetp lv lv')) R\n /\\ rel (den R) i (subst t m) (subst t' m))\n -> forall i s s' pg pg',\n pwctx i s s' G\n -> pginterp (subst s lv) pg\n -> pginterp (subst s lv') pg'\n -> lt_page pg pg'.\nProof.\nintros G lv lv' m Hseq i s s' pg pg' Hs Hlv Hlv'.\nso (Hseq _#3 Hs) as (pg'' & R & HR & Hm).\nexact (interp_ltpagetp_invert _#11 HR Hm Hlv Hlv').\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/PageType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.2509127980882971, "lm_q1q2_score": 0.13621134164879808}} {"text": "Require Import Program.Basics Lia.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic Language.\nFrom imm Require Import Events Execution Prog ProgToExecution ProgToExecutionProperties\n CombRelations.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import EventStructure.\nRequire Import Consistency.\nRequire Import BasicStep.\nRequire Import ImmProperties.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection EventToAction.\n\n Variable S : ES.t.\n Hypothesis WF : ES.Wf S.\n Variable G : execution.\n\n Notation \"'SE'\" := S.(ES.acts_set).\n Notation \"'SEinit'\" := S.(ES.acts_init_set).\n Notation \"'SEninit'\" := S.(ES.acts_ninit_set).\n Notation \"'Stid'\" := (S.(ES.tid)).\n Notation \"'Slab'\" := (S.(ES.lab)).\n Notation \"'Sloc'\" := (Events.loc (ES.lab S)).\n Notation \"'K'\" := S.(ES.cont_set).\n\n Notation \"'STid' t\" := (fun x => Stid x = t) (at level 1).\n Notation \"'SNTid' t\" := (fun x => Stid x <> t) (at level 1).\n\n Notation \"'Ssb'\" := (S.(ES.sb)).\n Notation \"'Scf'\" := (S.(ES.cf)).\n\n Notation \"'GE'\" := G.(acts_set).\n Notation \"'GEinit'\" := (is_init ∩₁ GE).\n Notation \"'GEninit'\" := ((set_compl is_init) ∩₁ GE).\n Notation \"'Glab'\" := (lab G).\n Notation \"'Gloc'\" := (Events.loc (lab G)).\n Notation \"'Gtid'\" := (Events.tid).\n\n Notation \"'GTid' t\" := (fun x => Gtid x = t) (at level 1).\n Notation \"'GNTid' t\" := (fun x => Gtid x <> t) (at level 1).\n\n Notation \"'Gsb'\" := (Execution.sb G).\n\n Definition e2a (e : eventid) : actid :=\n if excluded_middle_informative (Stid e = tid_init)\n then\n InitEvent (opt_ext BinNums.xH (Sloc e))\n else\n ThreadEvent (Stid e) (ES.seqn S e).\n\n (******************************************************************************)\n (** ** e2a general properties *)\n (******************************************************************************)\n\n Lemma e2a_init e (EINITe : SEinit e) :\n e2a e = InitEvent (opt_ext BinNums.xH (Sloc e)).\n Proof.\n unfold ES.acts_ninit_set, ES.acts_init_set in EINITe.\n destruct EINITe as [SEe STIDe].\n unfold e2a.\n destruct\n (excluded_middle_informative (Stid e = tid_init));\n [auto | congruence].\n Qed.\n\n Lemma e2a_init_loc e (EINITe : SEinit e) :\n exists l,\n ⟪ SLOC : Sloc e = Some l⟫ /\\\n ⟪ E2Ai : e2a e = InitEvent l⟫.\n Proof.\n edestruct ES.init_lab as [l SLAB]; eauto.\n exists l.\n assert (Sloc e = Some l) as SLOC.\n { unfold Events.loc. by rewrite SLAB. }\n splits; auto.\n rewrite e2a_init; auto.\n unfold opt_ext. by rewrite SLOC.\n Qed.\n\n Lemma e2a_ninit e (ENINITe : SEninit e) :\n e2a e = ThreadEvent (Stid e) (ES.seqn S e).\n Proof.\n unfold ES.acts_ninit_set, ES.acts_init_set in ENINITe.\n destruct ENINITe as [SEe HH].\n unfold e2a.\n destruct (excluded_middle_informative (Stid e = tid_init)); [|auto].\n exfalso. apply HH. by unfolder.\n Qed.\n\n (******************************************************************************)\n (** ** e2a tid properties *)\n (******************************************************************************)\n\n Lemma e2a_tid e :\n Stid e = Gtid (e2a e).\n Proof.\n unfold e2a.\n destruct (excluded_middle_informative (Stid e = tid_init)).\n 1 : destruct (Sloc e).\n all : by unfold Events.tid.\n Qed.\n\n Lemma e2a_Tid thread :\n e2a □₁ STid thread ⊆₁ GTid thread.\n Proof. unfolder. ins. desf. symmetry. apply e2a_tid. Qed.\n\n Lemma e2a_NTid thread :\n e2a □₁ SNTid thread ⊆₁ GNTid thread.\n Proof.\n unfolder.\n intros x [y [NTIDy EQx]].\n intros TIDx. apply NTIDy.\n subst. apply e2a_tid.\n Qed.\n\n Lemma e2a_Einit\n (EE : e2a □₁ SE ⊆₁ GE):\n e2a □₁ SEinit ⊆₁ GEinit.\n Proof.\n red. unfolder.\n intros e [e' [[Ee TIDe] E2A]].\n split; [|by apply EE; basic_solver].\n unfold e2a in E2A.\n desf.\n Qed.\n\n Lemma e2a_Eninit\n (EE : e2a □₁ SE ⊆₁ GE) :\n e2a □₁ SEninit ⊆₁ GEninit.\n Proof.\n unfold ES.acts_ninit_set, ES.acts_init_set, ES.acts_set.\n unfold e2a. unfolder.\n ins; split; desf; auto.\n { exfalso; auto. }\n apply EE. unfolder.\n eexists; split; eauto.\n unfold e2a.\n destruct\n (excluded_middle_informative (Stid y = tid_init));\n auto.\n by exfalso.\n Qed.\n\n Lemma e2a_map_Einit :\n SE ∩₁ e2a ⋄₁ GEinit ⊆₁ SEinit.\n Proof.\n intros x [SEx [INITx GEx]].\n split; auto.\n unfold is_init, EventToAction.e2a in INITx.\n destruct\n (excluded_middle_informative (Stid x = tid_init));\n done.\n Qed.\n\n (******************************************************************************)\n (** ** e2a sb properties *)\n (******************************************************************************)\n\n Lemma e2a_ext_sb_restr (X : eventid -> Prop)\n (XE : X ⊆₁ SE):\n e2a □ restr_rel X Ssb ⊆ ext_sb.\n Proof.\n rewrite WF.(ES.sb_Einit_Eninit).\n unfolder.\n intros a1 a2 [e1 [e2 HH]].\n destruct HH as [[SSB [Xe1 Xe2]] [EQ1 EQ2]].\n unfold e2a in EQ1, EQ2.\n destruct (excluded_middle_informative (ES.tid S e1 = tid_init));\n destruct (excluded_middle_informative (ES.tid S e2 = tid_init)).\n 1, 3:\n unfold ES.acts_ninit_set, ES.acts_init_set in *;\n unfolder in *; desf; basic_solver.\n { subst. basic_solver. }\n subst. simpls.\n desf.\n { exfalso. apply n, SSB. }\n assert (SAME_TID : ES.same_tid S e1 e2).\n { apply WF.(ES.sb_tid). basic_solver. }\n split; auto.\n by apply ES.seqn_sb_alt.\n Qed.\n\n Lemma e2a_ext_sb :\n e2a □ Ssb ⊆ ext_sb.\n Proof.\n rewrite <- e2a_ext_sb_restr; eauto.\n rewrite WF.(ES.sbE) at 1.\n by rewrite restr_relE.\n Qed.\n\n Lemma e2a_sb\n (EE : e2a □₁ SE ⊆₁ GE) :\n e2a □ Ssb ⊆ Gsb.\n Proof.\n rewrite WF.(ES.sbE).\n unfold Execution.sb.\n by rewrite !collect_rel_seqi, collect_rel_eqv, e2a_ext_sb, EE.\n Qed.\n\n (******************************************************************************)\n (** ** e2a cf properties *)\n (******************************************************************************)\n\n Lemma e2a_eq_in_cf x y (Ex : SE x) (Ey : SE y) :\n e2a x = e2a y -> x = y \\/ Scf x y.\n Proof.\n intros EQ.\n apply ES.acts_set_split in Ex.\n destruct Ex as [INITx | nINITx].\n { edestruct e2a_init_loc as [l HH];\n eauto; desc.\n assert (SEinit y) as INITy.\n { destruct (e2a y) as [l' | HH] eqn:Heqy;\n [|congruence].\n unfold e2a in Heqy.\n destruct\n (excluded_middle_informative (Stid y = tid_init));\n [|congruence].\n unfold ES.acts_init_set.\n basic_solver. }\n edestruct e2a_init_loc as [l' HH];\n eauto; desc.\n left. eapply WF.(ES.init_uniq); auto.\n congruence. }\n erewrite e2a_ninit in EQ; auto.\n assert (SEninit y) as nINITy.\n { destruct (e2a y) as [l' | HH] eqn:Heqy;\n [congruence|].\n unfold e2a in Heqy.\n destruct\n (excluded_middle_informative (Stid y = tid_init));\n [congruence|].\n unfold ES.acts_ninit_set, ES.acts_init_set.\n split; auto.\n intros [_ INIT]; auto. }\n erewrite e2a_ninit in EQ; auto.\n inversion EQ as [[TIDeq SEQNeq]].\n destruct (classic (x = y)) as [EQxy | nEQxy].\n { basic_solver. }\n right.\n edestruct ES.same_thread_alt\n with (x := x) (y := y) as [SB | CF]; eauto.\n { apply nINITx. }\n exfalso.\n destruct SB as [EQ' | [SB | tSB]]; auto.\n { apply ES.seqn_sb_alt in SB; auto. lia. }\n unfold transp in tSB.\n apply ES.seqn_sb_alt in tSB; auto; [lia|].\n red. congruence.\n Qed.\n\n Lemma e2a_inj X (XinSE : X ⊆₁ SE) (CFF : ES.cf_free S X) :\n inj_dom X e2a.\n Proof.\n unfolder. ins.\n\n destruct\n (excluded_middle_informative (Stid x = tid_init),\n excluded_middle_informative (Stid y = tid_init))\n as [[INITx | nINITx] [INITy | nINITy]].\n { assert (SEinit x) as EINITx.\n { unfold ES.acts_init_set, set_inter.\n split; auto. }\n assert (SEinit y) as EINITy.\n { unfold ES.acts_init_set, set_inter.\n split; auto. }\n edestruct e2a_init_loc as [lx [SLOCx GEx]]; auto.\n { apply EINITx. }\n edestruct e2a_init_loc as [ly [SLOCy GEy]]; auto.\n { apply EINITy. }\n eapply WF.(ES.init_uniq); auto; congruence. }\n all: unfold e2a in *; desf.\n eapply ES.seqn_inj.\n { eauto. }\n { eapply set_inter_Proper.\n { unfold ES.acts_ninit_set.\n eapply set_minus_mori; [eapply XinSE|].\n unfold flip. eauto. }\n eapply set_subset_refl. }\n { eapply ES.cf_free_mori; try apply CFF; auto.\n red. basic_solver. }\n assert (~ SEinit x) as nEINITx.\n { unfold ES.acts_init_set, set_inter.\n red. intros [_ HH]. auto. }\n assert (~ SEinit y) as nEINITy.\n { unfold ES.acts_init_set, set_inter.\n red. intros [_ HH]. auto. }\n 1,3: basic_solver.\n unfolder; splits; auto.\n red. intros [_ HH]. auto.\n Qed.\n\n Lemma e2a_inj_init :\n inj_dom SEinit e2a.\n Proof.\n eapply e2a_inj; auto.\n { unfold ES.acts_init_set. basic_solver. }\n apply ES.ncfEinit.\n Qed.\n\n Lemma e2a_cont_sb_dom_inj k a b lang (st : Language.state lang)\n (KE : K (k, existT _ lang st))\n (ACTS : e2a □₁ SE ⊆₁ acts_set G)\n (AIN : ES.cont_sb_dom S k a)\n (BIN : ES.cont_sb_dom S k b)\n (EQ : e2a a = e2a b) :\n a = b.\n Proof.\n assert (SE a) as EA.\n { eapply ES.cont_sb_domE; eauto. }\n assert (SE b) as EB.\n { eapply ES.cont_sb_domE; eauto. }\n red in AIN. red in BIN. desf.\n { eapply e2a_inj_init; eauto. }\n assert (a = b \\/ (Ssb a b \\/ Ssb b a)) as AA.\n 2: { destruct AA as [|AA]; auto.\n exfalso. desf.\n all: eapply sb_irr with (G:=G); eapply e2a_sb; eauto.\n 1,2: by red; eauto. }\n destruct (classic (SEinit a)) as [AINIT|ANINIT].\n { destruct (classic (SEinit b)) as [BINIT|BNINIT].\n { left. eapply e2a_inj_init; eauto. }\n right. left. apply WF.(ES.sb_Einit_Eninit). left.\n repeat (split; auto). }\n destruct (classic (SEinit b)) as [BINIT|BNINIT].\n { right. right. apply WF.(ES.sb_Einit_Eninit). left.\n repeat (split; auto). }\n destruct (classic (a = b)) as [|NEQ]; [by left|right].\n unfolder in AIN. unfolder in BIN. desf; auto.\n eapply WF.(ES.sb_tot); auto.\n { eapply ES.K_inEninit; eauto. }\n all: unfolder; splits; eauto.\n Qed.\n\nEnd EventToAction.\n\nSection EventToActionLemmas.\n\n Variable prog : Prog.t.\n Variable PROG_NINIT : ~ (IdentMap.In tid_init prog).\n\n Variable S : ES.t.\n Variable G : execution.\n Variable GPROG : program_execution prog G.\n\n Variable WF : ES.Wf S.\n\n Notation \"'SE' S\" := S.(ES.acts_set) (at level 10).\n Notation \"'SEinit' S\" := S.(ES.acts_init_set) (at level 10).\n Notation \"'SEninit' S\" := S.(ES.acts_ninit_set) (at level 10).\n\n Notation \"'Stid' S\" := (S.(ES.tid)) (at level 10).\n Notation \"'Slab' S\" := (S.(ES.lab)) (at level 10).\n Notation \"'Sloc' S\" := (Events.loc S.(ES.lab)) (at level 10).\n\n Notation \"'K' S\" := S.(ES.cont_set) (at level 10).\n\n Notation \"'STid' S\" := (fun t e => S.(ES.tid) e = t) (at level 10).\n\n Notation \"'Ssb' S\" := (S.(ES.sb)) (at level 10).\n Notation \"'Scf' S\" := (S.(ES.cf)) (at level 10).\n Notation \"'Srmw' S\" := (S.(ES.rmw)) (at level 10).\n\n Notation \"'GE'\" := G.(acts_set).\n Notation \"'GEinit'\" := (is_init ∩₁ GE).\n Notation \"'GEninit'\" := ((set_compl is_init) ∩₁ GE).\n\n Notation \"'Glab'\" := (lab G).\n Notation \"'Gloc'\" := (Events.loc (lab G)).\n Notation \"'Gtid'\" := (Events.tid).\n\n Notation \"'GTid' t\" := (fun x => Gtid x = t) (at level 1).\n Notation \"'GNTid' t\" := (fun x => Gtid x <> t) (at level 1).\n\n Notation \"'Gsb'\" := (Execution.sb G).\n Notation \"'Grmw'\" := (Execution.rmw G).\n\n Lemma basic_step_e2a_eq_dom e e' S'\n (BSTEP : basic_step e e' S S') :\n eq_dom (SE S) (e2a S') (e2a S).\n Proof.\n cdes BSTEP; cdes BSTEP_.\n red. intros x. ins.\n unfold e2a.\n assert (Stid S' x = tid_init <-> Stid S x = tid_init) as AA.\n { red; split; ins;\n [ erewrite <- basic_step_tid_eq_dom\n | erewrite basic_step_tid_eq_dom\n ]; eauto. }\n assert ((Sloc S') x = (Sloc S) x) as BB.\n { eapply basic_step_loc_eq_dom; eauto. }\n unfold opt_ext; desf; try by (exfalso; intuition).\n assert ((Stid S') x = (Stid S) x) as CC.\n { eapply basic_step_tid_eq_dom; eauto. }\n assert (ES.seqn S' x = ES.seqn S x) as DD.\n { eapply basic_step_seqn_eq_dom; eauto. }\n congruence.\n Qed.\n\n Lemma basic_step_e2a_set_collect_eq_dom e e' S' s\n (BSTEP : basic_step e e' S S')\n (inE : s ⊆₁ SE S) :\n e2a S' □₁ s ≡₁ e2a S □₁ s.\n Proof.\n eapply set_collect_eq_dom.\n rewrite inE.\n eapply basic_step_e2a_eq_dom; eauto.\n Qed.\n\n Lemma basic_step_e2a_collect_rel_eq_dom e e' S' r\n (BSTEP : basic_step e e' S S')\n (restrE : r ≡ ⦗ SE S ⦘ ⨾ r ⨾ ⦗ SE S ⦘) :\n e2a S' □ r ≡ e2a S □ r.\n Proof.\n rewrite restrE, <- restr_relE.\n eapply collect_rel_restr_eq_dom.\n eapply basic_step_e2a_eq_dom; eauto.\n Qed.\n\n Lemma basic_step_e2a_set_map_inter_old e e' S' s s'\n (BSTEP : basic_step e e' S S')\n (inE : s ⊆₁ SE S) :\n s ∩₁ (e2a S' ⋄₁ s') ≡₁ s ∩₁ (e2a S ⋄₁ s').\n Proof.\n unfolder. split.\n { intros x [Sx S'x].\n splits; auto.\n erewrite <- basic_step_e2a_eq_dom; eauto. }\n intros x [Sx S'x].\n splits; auto.\n erewrite basic_step_e2a_eq_dom; eauto.\n Qed.\n\n Lemma basic_step_e2a_map_rel_inter_restr e e' S' r r'\n (BSTEP : basic_step e e' S S') :\n restr_rel (SE S) r ∩ (e2a S' ⋄ r') ≡ restr_rel (SE S) r ∩ (e2a S ⋄ r').\n Proof.\n unfolder. split.\n { intros x y [[Rxy [Ex Ey]] R'xy].\n splits; auto.\n erewrite <- basic_step_e2a_eq_dom; eauto.\n erewrite <- basic_step_e2a_eq_dom; eauto. }\n intros x y [[Rxy [Ex Ey]] R'xy].\n splits; auto.\n erewrite basic_step_e2a_eq_dom; eauto.\n erewrite basic_step_e2a_eq_dom with (S' := S'); eauto.\n Qed.\n\n Lemma basic_step_e2a_map_rel_inter_old e e' S' r r'\n (BSTEP : basic_step e e' S S')\n (restrE : r ≡ ⦗ SE S ⦘ ⨾ r ⨾ ⦗ SE S ⦘) :\n r ∩ (e2a S' ⋄ r') ≡ r ∩ (e2a S ⋄ r').\n Proof.\n rewrite restrE.\n rewrite <- restr_relE.\n eapply basic_step_e2a_map_rel_inter_restr; eauto.\n Qed.\n\nEnd EventToActionLemmas.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/imm_aux/EventToAction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.24220563966531902, "lm_q1q2_score": 0.13616232255519017}} {"text": "(*\n Bonsai generator for the terminal\n\n Copyright (C) 2019 Guillaume Claret\n Copyright (C) 2019 John Allbritten\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*)\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import ListString.All.\nRequire Import SimpleIO.SimpleIO.\nRequire SimpleIO.IO_Random.\nRequire Coq.extraction.ExtrOcamlIntConv.\n\nImport ListNotations.\n\nLocal Open Scope bool.\nLocal Open Scope string.\nLocal Open Scope list.\n\nNotation \"x ^^ y\" := (String.append x y) (right associativity, at level 60).\n\nDefinition columns := 50.\nDefinition rows := 28.\nDefinition lifeStart := 28.\nDefinition multiplier := 5.\nDefinition branchesMax := multiplier * 110.\nDefinition shootsMax := multiplier.\n\nModule Random.\n Definition t : Set := N * N.\n\n Definition seed : t := (2, 2) % N.\n\n Definition M : N := 1000.\n\n Definition next (seed : t) : t :=\n let '(n, n') := seed in\n let n'' := N.modulo (n + n') M in\n (n', n'').\nEnd Random.\n\nModule M.\n Definition t (A : Set) : Set :=\n Random.t -> A * Random.t.\n\n Definition ret {A : Set} (x : A) : t A :=\n fun seed => (x, seed).\n\n Definition bind {A B : Set} (x : t A) (f : A -> t B) : t B :=\n fun seed =>\n let '(x', seed') := x seed in\n f x' seed'.\n\n Definition random (n : nat) : t nat :=\n fun seed =>\n let seed' := Random.next seed in\n let result := N.to_nat (N.modulo (fst seed) (N.of_nat n)) in\n (result, seed').\n\n Definition run {A : Set} (x : t A) (seed : Random.t) : A :=\n fst (x seed).\nEnd M.\n\nNotation \"'let*' x ':=' X 'in' Y\" :=\n (M.bind X (fun x => Y))\n (at level 200, x pattern, X at level 100, Y at level 200).\n\nDefinition new_line := \"\n\".\n\nModule Colors.\n Definition escape : string -> string := String (ascii_of_nat 27).\n Definition LightBrown := escape \"[38;5;172m\".\n Definition DarkBrown := escape \"[38;5;130m\".\n Definition BrownGreen := escape \"[38;5;142m\".\n Definition Green := escape \"[38;5;106m\".\n Definition Gray := escape \"[38;5;243m\".\n Definition R := escape \"[0m\".\nEnd Colors.\n\nModule Base.\n Definition width := 15.\n Definition art_lines : list string := [\n Colors.Gray ^^ \":\" ^^ Colors.Green ^^ \"___________\" ^^ Colors.DarkBrown ^^\n \"./~~\\.\" ^^ Colors.Green ^^ \"___________\" ^^ Colors.Gray ^^ \":\";\n \" \\ /\";\n \" \\________________________/\";\n \" (_) (_)\"\n ].\n Definition art_lines_with_shift : list LString.t :=\n List.map (fun art_line =>\n LString.repeat (LString.s \" \") (Nat.div2 columns - width) ++\n LString.s art_line\n ) art_lines.\nEnd Base.\n\nModule List.\n Fixpoint apply_ith {A : Type} (l : list A) (index : nat) (f : A -> A)\n : list A :=\n match l with\n | nil => nil\n | cons x l =>\n match index with\n | O => cons (f x) l\n | S index => cons x (apply_ith l index f)\n end\n end.\nEnd List.\n\nModule Grid.\n Inductive Typ : Set :=\n | Dead\n | Dying\n | ShootLeft\n | ShootRight\n | Trunk.\n\n Definition isShoot (typ : Typ) : bool :=\n match typ with\n | ShootLeft | ShootRight => true\n | _ => false\n end.\n\n Definition isTrunk (typ : Typ) : bool :=\n match typ with\n | Trunk => true\n | _ => false\n end.\n\n Record t : Set := {\n pixels : list (list (string * option string));\n trace : list (nat * nat * Typ * option string)\n }.\n\n Definition init : t := {|\n pixels := List.repeat (List.repeat (Colors.R, None) columns) rows;\n trace := []\n |}.\n\n Definition set (grid : t) (x y : nat) (typ : Typ) (color : string)\n (chars : option string) : t :=\n {|\n pixels :=\n List.apply_ith grid.(pixels) y (fun line =>\n List.apply_ith line x (fun _ => (color, chars))\n );\n trace := cons (x, y, typ, chars) grid.(trace)\n |}.\n\n (* Get dy based on type. *)\n Definition get_dy (y : nat) (typ : Typ) (life : nat) : M.t Z :=\n let* rand10 := M.random 10 in\n let dy :=\n match typ with\n | Dying =>\n match rand10 with\n | 0 | 1 => (-1) % Z\n | 9 => 1 % Z\n | _ => 0 % Z\n end\n | ShootLeft | ShootRight =>\n match rand10 with\n | 0 | 1 => (-1) % Z\n | 8 | 9 => 1 % Z\n | _ => 0 % Z\n end\n | _ =>\n if negb (Nat.eqb life lifeStart) && Nat.ltb 2 rand10 then\n (-1) % Z\n else\n 0 % Z\n end in\n (* If we're about to hit the ground, cut it off. *)\n if\n (Z.gtb dy 0 && Nat.ltb y (rows - 1)) || (isTrunk typ && Nat.ltb life 4)\n then\n M.ret (0 % Z)\n else\n M.ret dy.\n\n (* Get dx based on type. *)\n Definition get_dx (typ : Typ) : M.t Z :=\n match typ with\n | ShootLeft => (* tend left: dx=[-2,1] *)\n let* rand10 := M.random 10 in\n M.ret match rand10 with\n | 0 | 1 => (-2) % Z\n | 2 | 3 | 4 | 5 => (-1) % Z\n | 6 | 7 | 8 => 0 % Z\n | _ => 1 % Z\n end\n | ShootRight => (* tend right: dx=[-1,2] *)\n let* rand10 := M.random 10 in\n M.ret match rand10 with\n | 0 | 1 => 2 % Z\n | 2 | 3 | 4 | 5 => 1 % Z\n | 6 | 7 | 8 => 0 % Z\n | _ => (-1) % Z\n end\n | Dying => (* tend left/right: dx=[-3,3] *)\n let* rand7 := M.random 7 in\n M.ret (Z.of_nat rand7 - 2) % Z\n | _ => (* tend equal: dx=[-1,1] *)\n let* rand3 := M.random 3 in\n M.ret (Z.of_nat rand3 - 1) % Z\n end.\n\n Fixpoint branch (grid : t) (branches : nat) (shoots : nat)\n (isShootRight : bool) (x y : nat) (typ : Typ) (life : nat) (fuel : nat)\n {struct fuel} : M.t t :=\n match life, fuel with\n | O, _ | _, O => M.ret grid\n | S life, S fuel =>\n let* dy := get_dy y typ life in\n let* dx := get_dx typ in\n let branches := branches + 1 in\n (* Re-branch upon conditions. *)\n let* (grid, shoots, isShootRight) :=\n let current := (grid, shoots, isShootRight) in\n if Nat.ltb branches branchesMax then\n let* rand16_multiplier := M.random (16 - multiplier) in\n (* Branch is dead. *)\n if Nat.ltb life 3 then\n let* grid := branch grid branches shoots isShootRight x y Dead life fuel in\n M.ret (grid, shoots, isShootRight)\n (* Branch is dying and needs to branch into leaves. *)\n else if (isShoot typ || isTrunk typ) && Nat.ltb life (multiplier + 2) then\n let* grid := branch grid branches shoots isShootRight x y Dying life fuel in\n M.ret (grid, shoots, isShootRight)\n (* Re-branch if: not close to the base AND (pass a chance test OR be a trunk,\n not have too many shoots already, and not be about to die) *)\n else if\n isTrunk typ && Nat.ltb life (lifeStart - 8) &&\n (\n Nat.eqb rand16_multiplier 0 ||\n (Nat.eqb (Nat.modulo life 5) 0 && Nat.ltb 5 life)\n )\n then\n (* If a trunk is splitting and not about to die, chance to create another trunk *)\n let* rand3 := M.random 3 in\n if Nat.eqb rand3 0 && Nat.ltb 7 life then\n let* grid := branch grid branches shoots isShootRight x y Trunk life fuel in\n M.ret (grid, shoots, isShootRight)\n else if Nat.ltb shoots shootsMax then\n (* Give the shoot some life. *)\n let life := life + multiplier - 2 in\n\n (* Shoots alternate from the first. *)\n let isShootRight := negb isShootRight in\n let typ := if isShootRight then ShootRight else ShootLeft in\n let* grid := branch grid branches shoots isShootRight x y typ life fuel in\n M.ret (grid, shoots + 1, isShootRight)\n else\n M.ret current\n else\n M.ret current\n else\n M.ret current in\n (* Implement dx, dy. *)\n let x := Z.to_nat (Z.of_nat x + dx) in\n let y := Z.to_nat (Z.of_nat y + dy) in\n (* Choose color. *)\n let* rand4 := M.random 4 in\n let color :=\n match typ with\n | ShootLeft | ShootRight | Trunk =>\n if Nat.eqb rand4 0 then\n Colors.LightBrown\n else\n Colors.DarkBrown\n | Dying => Colors.BrownGreen\n | Dead => Colors.Green\n end in\n (* Choose branch character. *)\n let chars : option string :=\n match typ with\n | Trunk =>\n let chars :=\n if Z.ltb dx 0 then\n \"λ\"\n else if Z.eqb dx 0 then\n \"/|\"\n else\n \"/\" in\n if Z.eqb dy 0 then\n Some \"/~\"\n else\n Some chars\n (* Shoots tend to look horizontal. *)\n | ShootLeft =>\n let chars :=\n if Z.ltb dx 0 then\n \"\\|\"\n else if Z.eqb dx 0 then\n \"/|\"\n else\n \"/\" in\n (* growing down *)\n if Z.gtb dy 0 then\n Some \"/\"\n (* not growing *)\n else if Z.eqb dy 0 then\n Some \"\\_\"\n else\n Some chars\n | ShootRight =>\n let chars :=\n if Z.ltb dx 0 then\n \"\\|\"\n else if Z.eqb dx 0 then\n \"/|\"\n else\n \"/\" in\n (* growing down *)\n if Z.gtb dy 0 then\n Some \"\\\"\n (* not growing *)\n else if Z.eqb dy 0 then\n Some \"_/\"\n else\n Some chars\n | _ => None\n end in\n (* Choose leaf character. *)\n let chars :=\n if Nat.ltb life 4 then\n Some \"&\"\n else\n chars in\n (* Add character(s) to our grid. *)\n let grid := set grid x y typ color chars in\n branch grid branches shoots isShootRight x y typ life fuel\n end.\n\n Definition grow : M.t t :=\n let* rand2 := M.random 2 in\n let isShootRight := Nat.eqb rand2 0 in\n let fuel := columns * rows in\n branch init 0 0 isShootRight (Nat.div2 columns) rows Trunk lifeStart fuel.\n\n Definition to_string (grid : t) : LString.t :=\n List.concat\n (List.map (fun line =>\n List.concat (List.map (fun '(color, chars) =>\n let chars :=\n match chars with\n | None => \" \"\n | Some chars => chars\n end in\n LString.s (color ^^ chars)) line\n ) ++ LString.s new_line\n )\n grid.(pixels)\n ).\nEnd Grid.\n\nImport IO.Notations.\n\nDefinition main : IO unit :=\n let random_max := ExtrOcamlIntConv.int_of_z 32768 in\n IO_Random.ORandom.self_init tt;;\n n <- IO_Random.ORandom.int random_max;;\n m <- IO_Random.ORandom.int random_max;;\n let seed := (ExtrOcamlIntConv.n_of_int n, ExtrOcamlIntConv.n_of_int m) in\n let grid := M.run Grid.grow seed in\n let message :=\n Grid.to_string grid ++\n LString.join (LString.s new_line) Base.art_lines_with_shift ++\n LString.s Colors.R in\n print_endline (LString.to_string message).\n\nDefinition run_main := IO.unsafe_run main.\n\n(** Extract the Bonsai program to `extraction/main.ml`. Run the `Makefile`\n in `extraction/` to compile it. *)\nExtraction \"extraction/main\" run_main.\n", "meta": {"author": "formal-land", "repo": "coq-bonsai", "sha": "57d7301552e098334efd5ab0ad443142a24240b7", "save_path": "github-repos/coq/formal-land-coq-bonsai", "path": "github-repos/coq/formal-land-coq-bonsai/coq-bonsai-57d7301552e098334efd5ab0ad443142a24240b7/src/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.25091277568224823, "lm_q1q2_score": 0.13523777223274072}} {"text": "From Perennial.base_logic.lib Require Import mono_nat.\nFrom Perennial.Helpers Require Import Transitions NamedProps Map gset range_set.\nFrom Perennial.algebra Require Import auth_map log_heap.\nFrom Perennial.base_logic Require Import lib.ghost_map.\n\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Goose.github_com.mit_pdos.go_journal Require Import obj.\nFrom Goose.github_com.mit_pdos.go_journal Require Import wal.\nFrom Perennial.program_proof Require Import wal.specs wal.lib wal.heapspec addr.addr_proof buf.buf_proof disk_lib.\nFrom Perennial.program_proof Require Import obj.invariant.\nFrom Perennial.goose_lang.lib Require Import slice.typed_slice.\nFrom Perennial.goose_lang Require Import crash_modality.\n\nFrom RecordUpdate Require Import RecordUpdate.\nImport RecordSetNotations.\nSection goose_lang.\nContext `{!txnG Σ}.\nContext `{!heapGS Σ}.\n\nImplicit Types (γ: txn_names).\n\nDefinition txn_init_ghost_state γ : iProp Σ :=\n let logm0 := Build_async (∅: gmap addr object) [] in\n \"logheap\" ∷ ghost_map_auth γ.(txn_logheap) 1 (latest logm0) ∗\n \"crashstates\" ∷ ghost_var γ.(txn_crashstates) 1 logm0 ∗\n \"metaheap\" ∷ map_ctx γ.(txn_metaheap) 1 (∅ : gmap addr gname).\n\nLemma alloc_txn_init_ghost_state (γtxn_walnames: wal_heap_gnames) kinds :\n ⊢ |==> ∃ γ, ⌜γ.(txn_walnames) = γtxn_walnames⌝ ∗\n ⌜γ.(txn_kinds) = kinds⌝ ∗\n txn_init_ghost_state γ.\nProof.\n set (logm:=Build_async (∅: gmap addr object) []).\n iMod (ghost_map_alloc (latest logm)) as (txn_logheap) \"[? _]\".\n iMod (ghost_var_alloc logm) as (txn_crashstates) \"?\".\n iMod (map_init (∅ : gmap addr gname)) as (txn_metaheap) \"?\".\n iModIntro.\n iExists (Build_txn_names _ _ _ _ _).\n rewrite /txn_init_ghost_state /=.\n by iFrame.\nQed.\n\nDefinition is_txn_durable γ dinit : iProp Σ :=\n ∃ ls' logm crash_heaps,\n \"%Hpostcrash\" ∷ ⌜ wal_post_crash ls' ⌝ ∗\n \"His_wal_inner_durable\" ∷ is_wal_inner_durable γ.(txn_walnames).(wal_heap_walnames) ls' dinit ∗\n \"Hwal_res\" ∷ wal_resources γ.(txn_walnames).(wal_heap_walnames) ∗\n \"Hwal_heap_inv\" ∷ wal_heap_inv γ.(txn_walnames) ls' ∗\n \"Hlocked_walheap\" ∷ is_locked_walheap γ.(txn_walnames) {| locked_wh_σd := ls'.(log_state.d);\n locked_wh_σtxns := ls'.(log_state.txns);\n |} ∗\n \"His_txn_always\" ∷ is_txn_state γ logm crash_heaps.\n\n\nDefinition inode0_map : gmap u64 object :=\n gset_to_gmap (existT _ (bufInode inode_buf0))\n (list_to_set $ (λ i, U64 (i*8*128)%Z) <$> (seqZ 0 32)).\n\nDefinition bit0_map : gmap u64 object :=\n gset_to_gmap (existT _ (bufBit false))\n (list_to_set $ U64 <$> seqZ 0 (8*block_bytes)).\n\nDefinition block0_map : gmap u64 object :=\n {[U64 0 := existT _ (bufBlock block0)]}.\n\nDefinition kind_heap0 (kinds: gmap u64 bufDataKind) : gmap addr object :=\n gmap_uncurry ((λ K, match K with\n | KindBit => bit0_map\n | KindInode => inode0_map\n | KindBlock => block0_map\n end) <$> kinds).\n\nLemma repeat_to_replicate {A} (x:A) n :\n repeat x n = replicate n x.\nProof.\n induction n; simpl; congruence.\nQed.\n\nLemma crash_heap0_repeat_block0 (sz: nat) :\n 513 + sz < 2^64 →\n crash_heap0 (repeat block0 sz) = gset_to_gmap block0 (rangeSet 513 (Z.of_nat sz)).\nProof.\n rewrite repeat_to_replicate.\n intros Hbound.\n rewrite /crash_heap0.\n apply map_eq; intros i.\n apply option_eq; intros b.\n rewrite lookup_gset_to_gmap.\n rewrite lookup_list_to_map.\n - rewrite elem_of_lookup_imap.\n setoid_rewrite lookup_replicate.\n destruct (decide (i ∈ rangeSet 513 sz));\n try (rewrite -> option_guard_True by done);\n try (rewrite -> option_guard_False by done).\n + apply rangeSet_lookup in e; [ | word .. ].\n split; [ naive_solver | ].\n inversion 1; subst.\n eexists (Z.to_nat (int.Z i - 513)), _.\n split_and!; eauto; try lia.\n f_equal; word.\n + rewrite -> rangeSet_lookup in n by word.\n split; [ | inversion 1 ]; intros.\n destruct H as (i' & b' & [=] & ? & ?); subst.\n move: n; word.\n - rewrite fst_imap.\n rewrite replicate_length.\n eapply NoDup_fmap_2_strong; last by eapply NoDup_seq.\n intros x y Hx Hy Heq.\n eapply elem_of_seq in Hx.\n eapply elem_of_seq in Hy.\n assert (int.Z (U64 (513 + Z.of_nat x)) = int.Z (U64 (513 + Z.of_nat y))).\n { rewrite Heq. eauto. }\n revert H. word.\nQed.\n\nLemma alloc_metamap names (m: gmap addr object):\n map_ctx names 1 ∅ ==∗\n ∃ metam,\n map_ctx names 1 metam ∗\n ([∗ map] addr↦bufData;γm ∈ m;metam, ghost_var γm (1/2) true) ∗\n ([∗ map] addr↦bufData;γm ∈ m;metam, ptsto_mut names addr 1 γm ∗ ghost_var γm (1/2) true).\nProof.\n iIntros \"Hctx\".\n iInduction m as [|i x m] \"IH\" using map_ind.\n - iExists ∅. rewrite ?big_sepM2_empty //. by iFrame.\n - iMod (\"IH\" with \"Hctx\") as (metam) \"(H1&H2&H3)\".\n iDestruct (big_sepM2_dom with \"H2\") as %Hdom.\n iMod (ghost_var_alloc true) as (γm) \"[Hm1 Hm2]\".\n assert (metam !! i = None).\n { apply not_elem_of_dom. rewrite -Hdom.\n apply not_elem_of_dom. eauto. }\n iMod (map_alloc i γm with \"[$]\") as \"(Hctx&Hpts)\"; auto.\n iExists (<[i := γm]>metam).\n iFrame. iSplitL \"H2 Hm1\".\n { rewrite big_sepM2_insert //. by iFrame. }\n { rewrite big_sepM2_insert //. by iFrame. }\nQed.\n\nTheorem mapsto_txn_alloc {T} (γ : gname) (logm : gmap addr T) :\n map_ctx γ 1 ∅\n ==∗\n ∃ m,\n ⌜dom m = dom logm⌝ ∗\n map_ctx γ 1 m ∗\n ([∗ map] a↦_ ∈ logm, ∃ (γm : gname), a [[γ]]↦ γm ∗ ghost_var γm (1/2) true) ∗\n ([∗ map] _↦γm ∈ m, ghost_var γm (1/2) true).\nProof.\n iIntros \"H\".\n iInduction logm as [|a v m] \"IH\" using map_ind.\n { iModIntro. iExists _. iFrame. rewrite !big_sepM_empty. rewrite !dom_empty_L. done. }\n iMod (\"IH\" with \"H\") as (m0) \"(%Hdom & H & H0 & H1)\".\n assert (m0 !! a = None).\n { apply not_elem_of_dom in H. apply not_elem_of_dom. rewrite Hdom. eauto. }\n iMod (ghost_var_alloc true) as (γm) \"[Hγ0 Hγ1]\".\n iMod (map_alloc a γm with \"H\") as \"[H Ha]\"; eauto.\n iModIntro. iExists _. iFrame \"H\". iSplit.\n { iPureIntro. rewrite !dom_insert_L Hdom. done. }\n iSplitL \"H0 Hγ0 Ha\".\n { iApply big_sepM_insert; eauto. iFrame. iExists _. iFrame. }\n iApply big_sepM_insert; eauto. iFrame.\nQed.\n\nHint Rewrite repeat_length : len.\n\nLemma block_bytes_pos : 0 < Z.of_nat block_bytes.\nProof. rewrite /block_bytes. lia. Qed.\n\nLemma lookup_bit0_map (off: u64) o :\n bit0_map !! off = Some o ↔\n int.Z off < block_bytes * 8 ∧\n o = existT KindBit (bufBit false).\nProof.\n rewrite /bit0_map.\n rewrite lookup_gset_to_gmap_Some.\n rewrite elem_of_list_to_set.\n rewrite elem_of_list_fmap.\n setoid_rewrite elem_of_seqZ.\n change block_bytes with (Z.to_nat 4096).\n split; intros.\n - intuition (subst; auto).\n destruct H0 as [off' [? ?]]; subst.\n word.\n - intuition (subst; auto).\n exists (int.Z off); split; word.\nQed.\n\nLemma lookup_inode0_map (off: u64) o :\n inode0_map !! off = Some o ↔\n ∃ (i:Z), i < 32 ∧\n int.Z off = i * 8 * 128 ∧\n o = existT KindInode (bufInode inode_buf0).\nProof.\n rewrite /inode0_map.\n rewrite lookup_gset_to_gmap_Some.\n rewrite elem_of_list_to_set.\n rewrite elem_of_list_fmap.\n setoid_rewrite elem_of_seqZ.\n split.\n - intuition (subst; auto).\n destruct H0 as [y [? ?]]; subst.\n exists y; repeat split; try word.\n - intros.\n destruct H as [i (?&?&?)]; subst.\n split; auto.\n exists i; split; word.\nQed.\n\nLemma lookup_block0_map (off: u64) o :\n block0_map !! off = Some o ↔\n off = (U64 0) ∧\n o = existT KindBlock (bufBlock block0).\nProof.\n rewrite /block0_map.\n rewrite lookup_singleton_Some.\n intuition auto.\nQed.\n\nOpaque block_bytes.\n\nLemma bit0_map_not_empty : ∅ ≠ bit0_map.\nProof.\n intro H.\n assert (bit0_map !! (U64 0) = None).\n { rewrite -H. apply lookup_empty. }\n assert (bit0_map !! (U64 0) = Some (existT KindBit (bufBit false))).\n { apply lookup_bit0_map.\n split; auto.\n pose proof block_bytes_pos.\n word. }\n rewrite H0 in H1.\n congruence.\nQed.\n\nLemma inode0_map_not_empty : ∅ ≠ inode0_map.\nProof.\n intro H. assert (inode0_map !! (U64 0) = None).\n { rewrite -H. apply lookup_empty. }\n apply lookup_gset_to_gmap_None in H0.\n apply H0.\n apply elem_of_list_to_set.\n apply elem_of_list_lookup.\n exists 0%nat; auto.\nQed.\n\nLemma block0_map_not_empty : ∅ ≠ block0_map.\nProof.\n intro H. assert (block0_map !! (U64 0) = None).\n { rewrite -H. apply lookup_empty. }\n rewrite lookup_singleton in H0. congruence.\nQed.\n\nHint Resolve bit0_map_not_empty : notempty.\nHint Resolve inode0_map_not_empty : notempty.\nHint Resolve block0_map_not_empty : notempty.\n\nLemma repeat_lookup_inv {T} (a b : T) : ∀ n i, repeat a n !! i = Some b -> a = b.\nProof.\n induction n; simpl; intros.\n { rewrite lookup_nil in H. congruence. }\n destruct i; eauto.\n inversion H; eauto.\nQed.\n\nLemma block0_to_vals : Block_to_vals block0 = replicate block_bytes (#(U8 0)).\nProof. reflexivity. Qed.\n\nLtac Zify.zify_post_hook ::= Z.div_mod_to_equations.\n\nLemma extract_inode0 (off: u64) :\n (* off is actually less than 8*8*128 *)\n int.Z off `mod` 1024 = 0 →\n int.Z off < 8*4096 → (* TODO: not sure what bound is *)\n extract_nth block0 inode_bytes (int.nat off `div` (inode_bytes * 8)) =\n inode_to_vals inode_buf0.\nProof.\n intros.\n rewrite /extract_nth.\n rewrite block0_to_vals.\n rewrite take_replicate drop_replicate.\n rewrite /inode_buf0.\n rewrite /inode_to_vals.\n rewrite vec_to_list_replicate.\n rewrite fmap_replicate.\n f_equal.\n rewrite /inode_bytes block_bytes_eq.\n rewrite Nat.min_l; try word.\n change (Z.to_nat 128 * 8)%nat with 1024%nat.\n change (Z.to_nat 4096) with 4096%nat.\n change (Z.to_nat 128) with 128%nat.\n assert (int.nat off < 8 * 4096)%nat by lia.\n cut (int.nat off `div` 1024 < 32)%nat; try lia.\n change (8*4096)%nat with (Z.to_nat 32768) in H1.\n apply Nat2Z.inj_lt.\n rewrite Nat2Z.inj_div.\n lia.\nQed.\n\nLemma bufDataT_in_block0_bit off o (n: u64) :\n bit0_map !! off = Some o ->\n int.Z n * block_bytes * 8 < 2 ^ 64 ->\n bufDataT_in_block block0 KindBit n off o.\nProof.\n intros H H0.\n eapply lookup_gset_to_gmap_Some in H. intuition subst.\n assert (valid_off KindBit off).\n { apply valid_off_bit_trivial; eauto. }\n rewrite /bufDataT_in_block /=.\n apply elem_of_list_to_set in H1.\n apply elem_of_list_lookup in H1 as [i ?].\n fmap_Some in H1.\n apply lookup_seqZ in H1 as [-> ?].\n intuition eauto.\n + rewrite /is_bufData_at_off. intuition eauto.\n exists (U8 0).\n rewrite !Z.add_0_l.\n split.\n * rewrite /extract_nth block0_to_vals.\n rewrite take_replicate drop_replicate.\n match goal with\n | |- context[replicate ?n _] => replace n with 1%nat; [ reflexivity | ]\n end.\n rewrite block_bytes_eq in H1 |- *.\n rewrite !Nat.mul_1_r.\n rewrite Nat.min_l; [ lia | ].\n replace (int.nat i) with i by word.\n apply Z.div_lt_upper_bound in H1; [ | lia ].\n rewrite -> Z2Nat.id in H1 by lia.\n replace (Nat.div i 8) with (Z.to_nat $ Z.div (Z.of_nat i) 8); try lia.\n rewrite Z2Nat.inj_div; try lia.\n change (Z.to_nat 8) with 8%nat.\n rewrite Nat2Z.id.\n lia.\n * rewrite /get_bit.\n rewrite decide_False //.\n intros Heq%(f_equal int.Z); move: Heq.\n rewrite word.unsigned_and_nowrap.\n rewrite word.unsigned_sru_nowrap.\n { change (int.Z (U8 0)) with 0; simpl.\n rewrite Z.shiftr_0_l //. }\n rewrite /u8_from_u64.\n rewrite word.unsigned_of_Z word.unsigned_modu_nowrap //.\n change (int.Z 8) with 8.\n rewrite block_bytes_eq in H1.\n replace (int.Z i) with (Z.of_nat i) by word.\n rewrite /word.wrap.\n assert (0 ≤ i `mod` 8 < 8) by (apply Z.mod_bound_pos; lia).\n rewrite Z.mod_small; lia.\n + rewrite /valid_addr /addr2flat_z /=.\n rewrite -> block_bytes_eq in *.\n split_and!; try word.\nQed.\n\nLemma bufDataT_in_block0_inode off o (n: u64) :\n inode0_map !! off = Some o ->\n int.Z n * block_bytes * 8 < 2 ^ 64 ->\n bufDataT_in_block block0 KindInode n off o.\nProof.\n intros.\n eapply lookup_gset_to_gmap_Some in H. intuition subst.\n apply elem_of_list_to_set in H1.\n apply elem_of_list_lookup in H1 as [i Hlookup].\n fmap_Some in Hlookup.\n apply lookup_seqZ in Hlookup as [-> ?].\n rewrite Z.add_0_l.\n set (off:=i * 8* 128).\n rewrite /bufDataT_in_block; simpl.\n rewrite /is_bufData_at_off.\n feed pose proof (extract_inode0 off) as Hextract; [ word .. | ].\n rewrite /valid_addr /valid_off /addr2flat_z /=.\n assert (valid_off KindInode off).\n { rewrite /valid_off /=.\n word. }\n split_and!; auto.\n { rewrite block_bytes_eq. word. }\n - lia.\n - rewrite /valid_off /= in H.\n rewrite block_bytes_eq in H0 |- *.\n word.\nQed.\n\nLtac Zify.zify_post_hook ::= idtac.\n\nLemma bufDataT_in_block0_block off o (n: u64) :\n block0_map !! off = Some o ->\n int.Z n * block_bytes * 8 < 2 ^ 64 ->\n bufDataT_in_block block0 KindBlock n off o.\nProof.\n rewrite /block0_map => H H0.\n eapply lookup_singleton_Some in H. intuition subst.\n assert (valid_off KindBlock (U64 0)).\n { rewrite /valid_off.\n replace (int.Z (U64 0)) with 0 by reflexivity.\n rewrite Zmod_0_l. done. }\n rewrite /bufDataT_in_block /=. intuition eauto.\n + rewrite /is_bufData_at_off. intuition eauto.\n + rewrite /valid_addr /addr2flat_z /=.\n intuition try word.\n pose proof (block_bytes_pos). word.\nQed.\n\nLemma bufDataT_in_block0 kind off o n :\n match kind with\n | KindBit => bit0_map\n | KindInode => inode0_map\n | KindBlock => block0_map\n end !! off = Some o ->\n int.Z n * block_bytes * 8 < 2 ^ 64 ->\n bufDataT_in_block block0 kind n off o.\nProof.\n intros. destruct kind;\n auto using bufDataT_in_block0_bit,\n bufDataT_in_block0_block,\n bufDataT_in_block0_inode.\nQed.\n\n(* sz is the number of blocks besides the log (so the size of the disk - 513) *)\nLemma is_txn_durable_init dinit (kinds: gmap u64 bufDataKind) (sz: nat) :\n dom dinit = list_to_set (seqZ 513 sz) →\n dom kinds = list_to_set (U64 <$> (seqZ 513 sz)) →\n (513 + Z.of_nat sz) * block_bytes * 8 < 2^64 →\n 0 d↦∗ repeat block0 513 ∗ 513 d↦∗ repeat block0 sz -∗\n |==> ∃ γ,\n \"%Hγkinds\" ∷ ⌜ γ.(invariant.txn_kinds) = kinds ⌝ ∗\n \"Htxn_durable\" ∷ is_txn_durable γ dinit ∗\n \"#Hdurable_lb\" ∷ mono_nat_lb_own γ.(txn_walnames).(wal_heap_durable_lb) 0 ∗\n \"Hcrashstates\" ∷ ghost_var γ.(txn_crashstates) (3/4) (Build_async (kind_heap0 kinds) []) ∗\n \"Hmapsto_txns\" ∷ ([∗ map] a ↦ o ∈ kind_heap0 kinds, mapsto_txn γ a o).\nProof.\n iIntros (Hdinit_dom Hkinds_dom Hbound) \"H\".\n iMod (is_wal_inner_durable_init dinit with \"H\") as (γwalnames) \"[Hwal Hwal_res]\".\n { len; auto. }\n\n set (bs:=repeat block0 sz).\n\n assert (513 + Z.of_nat sz < 2^64) as Hbound2.\n { pose proof (block_bytes_pos). lia. }\n\n iMod (wal_heap_inv_init γwalnames bs) as (γheapnames Heq1) \"Hheap\".\n { rewrite /bs; len. }\n iNamed \"Hheap\".\n\n iMod (alloc_txn_init_ghost_state γheapnames kinds) as (γ Heq2 Heq3) \"Hinit\".\n iNamed \"Hinit\".\n iMod (ghost_map_insert_big (kind_heap0 kinds) with \"logheap\") as \"[logheap logheap_mapsto_curs]\".\n { simpl. apply map_disjoint_empty_r. }\n iMod (ghost_var_update (Build_async (kind_heap0 kinds) [])\n with \"crashstates\") as \"H\".\n iEval (rewrite -Qp.quarter_three_quarter) in \"H\".\n iDestruct (fractional.fractional_split with \"H\") as \"[crashstates1 crashstates2]\".\n\n iMod (alloc_metamap _ (kind_heap0 kinds) with \"metaheap\") as (metamap) \"(metaheap & Hmetas1 & Hmetas2)\".\n\n iModIntro. iExists γ.\n rewrite Heq2.\n iFrame \"Hheap_lb crashstates2\".\n rewrite /is_txn_durable.\n iSplit.\n { eauto. }\n iSplitR \"Hmetas2 logheap_mapsto_curs\".\n 2: {\n iDestruct (big_sepM2_sepM_1 with \"Hmetas2\") as \"Hmetas2\".\n iDestruct (big_sepM_sep with \"[$Hmetas2 $logheap_mapsto_curs]\") as \"H\".\n iApply (big_sepM_mono with \"H\").\n iIntros (k x Hkx) \"[H0 H1]\".\n iDestruct \"H0\" as (γm) \"(% & Ha & Hb)\".\n iExists _. iFrame.\n }\n iExists (log_state0 bs), (Build_async (kind_heap0 kinds) []).\n iExists (Build_async (crash_heap0 bs) []).\n\n iSplit.\n { iPureIntro.\n auto using log_state0_post_crash. }\n rewrite Heq2 Heq1.\n iFrame \"Hwal Hwal_res Hheap_inv wal_heap_locked\".\n rewrite /is_txn_state.\n iExists metamap.\n rewrite Heq2.\n simpl. rewrite right_id.\n iFrame \"wal_heap_crash_heaps logheap crashstates1 metaheap\".\n\n iSplitL \"Hmetas1 wal_heap_h_mapsto\".\n - iDestruct (gmap_addr_by_block_big_sepM2 with \"Hmetas1\") as \"Hmetas\".\n iDestruct (big_sepM2_dom with \"Hmetas\") as \"%Hmetadom\".\n iApply big_sepM_sepM2_merge_ex; eauto.\n iDestruct (big_sepM2_sepM_1 with \"Hmetas\") as \"Hmetas\".\n\n rewrite /kind_heap0 /gmap_addr_by_block.\n rewrite gmap_curry_uncurry_non_empty; last first.\n {\n intros i x Hix. rewrite lookup_fmap in Hix.\n apply fmap_Some_1 in Hix. destruct Hix. intuition idtac.\n destruct x0; subst.\n { eapply bit0_map_not_empty. eassumption. }\n { eapply inode0_map_not_empty. eassumption. }\n { eapply block0_map_not_empty. eassumption. }\n }\n\n iDestruct (big_sepM_sepM2_merge with \"[$wal_heap_h_mapsto $Hmetas]\") as \"H\".\n { rewrite /gh_heapblock0.\n rewrite dom_fmap_L Hkinds_dom.\n rewrite dom_list_to_map_L. f_equal.\n rewrite fst_imap. subst bs. rewrite repeat_length. rewrite /seqZ.\n replace (Z.to_nat (Z.of_nat sz)) with sz by lia.\n rewrite list_fmap_compose. f_equal.\n eapply list_fmap_ext; eauto. lia.\n }\n\n iDestruct (big_sepM.big_sepM2_sepM_2 with \"H\") as \"H\".\n iApply (big_sepM_mono with \"H\").\n intros.\n iIntros \"Hm\".\n iDestruct \"Hm\" as (hb) \"(%Hhb & Hmapsto & H)\". destruct hb.\n iDestruct \"H\" as (mm) \"(%Hmm & Hmm)\".\n iExists _. iSplit; first by eauto.\n rewrite lookup_fmap in H.\n destruct (kinds !! k) eqn:Hk; simpl in H; inversion H; clear H. subst.\n iExists _, _, _. iSplit; first by (subst; eauto).\n iFrame. iApply (big_sepM2_mono with \"Hmm\").\n intros. iIntros \"H\".\n iExists _. iFrame. iPureIntro.\n apply lookup_list_to_map_1 in Hhb.\n apply elem_of_lookup_imap_1 in Hhb. destruct Hhb as [hb_i [hb_b [Hhb0 Hhb1]]].\n inversion Hhb0; clear Hhb0; subst. simpl.\n apply repeat_lookup_inv in Hhb1; subst.\n\n eapply bufDataT_in_block0; eauto.\n assert (is_Some (γ.(txn_kinds) !! U64 (513 + Z.of_nat hb_i))) as Hs; eauto.\n eapply elem_of_dom in Hs. rewrite Hkinds_dom in Hs.\n eapply elem_of_list_to_set in Hs.\n eapply elem_of_list_fmap_2 in Hs. destruct Hs as [y [Hs0 Hs1]]. rewrite Hs0.\n eapply elem_of_seqZ in Hs1. intuition subst.\n replace (int.Z (U64 y)) with y by word.\n rewrite -Z.mul_assoc. rewrite -Z.mul_assoc in Hbound.\n eapply Z.le_lt_trans; last by apply Hbound.\n pose proof (block_bytes_pos).\n eapply Zmult_gt_0_le_compat_r; try lia.\n\n - rewrite right_id /named.\n rewrite /bufDataTs_in_crashblock.\n\n rewrite /kind_heap0 /gmap_addr_by_block.\n rewrite gmap_curry_uncurry_non_empty; last first.\n {\n intros i x Hix. rewrite lookup_fmap in Hix.\n apply fmap_Some_1 in Hix. destruct Hix. intuition idtac.\n destruct x0; subst.\n { eapply bit0_map_not_empty. eassumption. }\n { eapply inode0_map_not_empty. eassumption. }\n { eapply block0_map_not_empty. eassumption. }\n }\n\n iApply big_sepM_sepM2_merge_ex.\n {\n rewrite /crash_heap0.\n rewrite dom_fmap_L Hkinds_dom.\n rewrite dom_list_to_map_L. f_equal.\n rewrite fst_imap. subst bs. rewrite repeat_length. rewrite /seqZ.\n replace (Z.to_nat (Z.of_nat sz)) with sz by lia.\n rewrite -list_fmap_compose.\n eapply list_fmap_ext; eauto.\n intros. rewrite /compose. f_equal. lia.\n }\n\n rewrite big_sepM_forall. iPureIntro. intros x m Hxm.\n rewrite lookup_fmap in Hxm.\n destruct (kinds !! x) eqn:He; inversion Hxm; clear Hxm; subst.\n exists block0. split.\n {\n rewrite crash_heap0_repeat_block0; last by lia.\n eapply lookup_gset_to_gmap_Some; intuition eauto.\n eapply rangeSet_lookup; try lia.\n assert (is_Some (γ.(txn_kinds) !! x)) as Hs; eauto.\n eapply elem_of_dom in Hs. rewrite Hkinds_dom in Hs.\n eapply elem_of_list_to_set in Hs.\n eapply elem_of_list_fmap_2 in Hs. destruct Hs as [y [Hs0 Hs1]].\n eapply elem_of_seqZ in Hs1. intuition subst; word.\n }\n\n eexists _. intuition eauto.\n eapply map_Forall_lookup_2. intros.\n\n eapply bufDataT_in_block0; eauto.\n assert (is_Some (γ.(txn_kinds) !! x)) as Hs; eauto.\n eapply elem_of_dom in Hs. rewrite Hkinds_dom in Hs.\n eapply elem_of_list_to_set in Hs.\n eapply elem_of_list_fmap_2 in Hs. destruct Hs as [y [Hs0 Hs1]].\n eapply elem_of_seqZ in Hs1. intuition subst.\n replace (int.Z (U64 y)) with y by word.\n rewrite -Z.mul_assoc. rewrite -Z.mul_assoc in Hbound.\n etransitivity; last by apply Hbound.\n pose proof (block_bytes_pos).\n eapply Zmult_gt_0_lt_compat_r; lia.\nQed.\n\nDefinition crash_heap_match γ logmap walheap : iProp Σ :=\n ([∗ map] blkno ↦ offmap;walblock ∈ gmap_addr_by_block logmap;walheap,\n ∃ blockK,\n \"%Htxn_cb_kind\" ∷ ⌜ γ.(txn_kinds) !! blkno = Some blockK ⌝ ∗\n \"Htxn_in_cb\" ∷ bufDataTs_in_crashblock walblock blkno blockK offmap)%I.\n\nDefinition crash_heaps_match γ logm crash_heaps : iProp Σ :=\n ([∗ list] logmap;walheap ∈ possible logm;possible crash_heaps, crash_heap_match γ logmap walheap).\n\nLemma crash_heaps_match_async_take γ logm crash_heaps n :\n (0 < n)%nat →\n (n ≤ length (possible logm))%nat →\n crash_heaps_match γ logm crash_heaps -∗\n crash_heaps_match γ (async_take n logm) (async_take n crash_heaps).\nProof.\n rewrite /crash_heaps_match.\n iIntros (Hlt Hle) \"Hl\".\n iDestruct (big_sepL2_length with \"Hl\") as %Hlen.\n iApply (big_sepL2_prefix with \"Hl\"); auto.\n - apply async_take_possible_prefix; auto.\n - apply async_take_possible_prefix; auto. lia.\n - rewrite ?possible_list_to_async ?take_length; lia.\nQed.\n\nLemma crash_heaps_match_transfer_gname γ1 γ2 logm crash_heaps :\n txn_kinds γ2 = txn_kinds γ1 →\n crash_heaps_match γ1 logm crash_heaps -∗\n crash_heaps_match γ2 logm crash_heaps.\nProof. iIntros (Heq) \"H\". rewrite /crash_heaps_match/crash_heap_match Heq. eauto. Qed.\n\nLemma crash_heaps_match_heapmatch_latest γ logm crash_heaps :\n \"Hmetactx\" ∷ map_ctx γ.(txn_metaheap) 1 ∅ ∗\n \"Hcrash_heaps0\" ∷ ([∗ map] a↦b ∈ latest crash_heaps, ∃ hb,\n ⌜hb_latest_update hb = b⌝ ∗\n a ↪[γ.(txn_walnames).(wal_heap_h)] hb) ∗\n \"Hcrashheapsmatch\" ∷ crash_heaps_match γ logm crash_heaps ==∗\n ∃ metam,\n map_ctx γ.(txn_metaheap) 1 metam ∗\n \"Hheapmatch\" ∷ ( [∗ map] blkno ↦ offmap;metamap ∈ gmap_addr_by_block (latest logm);gmap_addr_by_block metam,\n ∃ installed bs blockK,\n \"%Htxn_hb_kind\" ∷ ⌜ γ.(txn_kinds) !! blkno = Some blockK ⌝ ∗\n \"Htxn_hb\" ∷ blkno ↪[γ.(txn_walnames).(wal_heap_h)] (HB installed bs) ∗\n \"Htxn_in_hb\" ∷ bufDataTs_in_block installed bs blkno blockK offmap metamap ) ∗\n \"Hmapsto_txns\" ∷ ([∗ map] addr↦bufData ∈ latest logm, ∃ γm, ptsto_mut γ.(txn_metaheap) addr 1 γm ∗ ghost_var γm (1/2) true).\nProof.\n iNamed 1.\n iMod (mapsto_txn_alloc _ logm.(latest) with \"Hmetactx\") as (metam) \"(%Hdom & Hmetactx' & H0 & H1)\".\n\n rewrite /crash_heaps_match /possible.\n rewrite big_sepL2_snoc.\n iDestruct \"Hcrashheapsmatch\" as \"[_ Hlatestmatch]\".\n rewrite /crash_heap_match.\n\n iModIntro. iExists _. iFrame \"Hmetactx'\".\n iFrame \"H0\".\n\n iDestruct (big_sepM2_flip with \"Hlatestmatch\") as \"Hlatestmatch\".\n iDestruct (big_sepM2_sepM_merge with \"[$Hlatestmatch $Hcrash_heaps0]\") as \"Hlatestmatch\".\n iDestruct (big_sepM2_flip with \"Hlatestmatch\") as \"Hlatestmatch\".\n\n iDestruct (big_sepM2_sepM_1 with \"Hlatestmatch\") as \"Hlatestmatch\".\n iDestruct (gmap_addr_by_block_big_sepM with \"H1\") as \"H1\".\n iDestruct (big_sepM_sepM2_merge with \"[$Hlatestmatch $H1]\") as \"H\".\n { eapply gmap_addr_by_block_dom_eq; eauto. }\n\n iApply (big_sepM2_mono with \"H\").\n iIntros (k y1 y2 Hky1 Hky2) \"[H0 H1]\".\n iDestruct \"H0\" as (y0) \"(%Hcl & H0 & H2)\".\n iDestruct \"H0\" as (block) \"[%Hk H0]\". iNamed \"H0\".\n iDestruct \"H2\" as (hb) \"[%Hb Hmapsto]\".\n destruct hb.\n iExists _, _, _. iFrame. iFrame \"%\".\n\n rewrite /bufDataTs_in_block /bufDataTs_in_crashblock.\n iDestruct (big_sepM_sepM2_merge with \"[$Htxn_in_cb $H1]\") as \"H1\".\n { eapply gmap_addr_by_block_dom_eq2; eauto. }\n\n iApply (big_sepM2_mono with \"H1\").\n iIntros (k0 y3 y4 Hky3 Hky4) \"[%Hblk H]\".\n iExists _. iFrame. iPureIntro.\n rewrite -Hb in Hblk. eauto.\nQed.\n\nGlobal Instance is_txn_always_discretizable γ :\n Discretizable (is_txn_always γ).\nProof. apply _. Qed.\n\nGlobal Instance is_txn_durable_discretizable γ dinit :\n Discretizable (is_txn_durable γ dinit).\nProof. apply _. Qed.\n\nLemma log_crash_txns_length ls1 ls2 :\n relation.denote log_crash ls1 ls2 () →\n (length ls2.(log_state.txns) ≤ length ls1.(log_state.txns))%nat.\nProof.\n rewrite log_crash_unfold. intros (?&?&?).\n subst. rewrite /=.\n rewrite -{2}(take_drop (S x) (ls1.(log_state.txns))).\n rewrite app_length. lia.\nQed.\n\nLemma wal_heap_inv_wf names ls:\n wal_heap_inv names ls -∗\n ⌜ wal_wf ls ⌝.\nProof. iNamed 1. eauto. Qed.\n\nLemma latest_wal_heap_h_mapsto_split (γ: gname) gh :\n ([∗ map] a ↦ b ∈ gh, ∃ hb, ⌜hb_latest_update hb = b⌝ ∗ a ↪[γ] hb) ⊣⊢\n ([∗ map] a ↦ b ∈ gh, ∃ hb, ⌜hb_latest_update hb = b⌝ ∗ a ↪[γ]{#1/2} hb) ∗\n ([∗ map] a ↦ b ∈ gh, ∃ hb, ⌜hb_latest_update hb = b⌝ ∗ a ↪[γ]{#1/2} hb).\nProof.\n rewrite -big_sepM_sep.\n repeat f_equiv.\n iSplit.\n - iDestruct 1 as (hb <-) \"[H1 H2]\".\n iSplitL \"H1\"; eauto with iFrame.\n - iDestruct 1 as \"[H1 H2]\".\n iDestruct \"H1\" as (hb <-) \"H1\".\n iDestruct \"H2\" as (hb' <-) \"H2\".\n iDestruct (ghost_map_elem_agree with \"H1 H2\") as %<-.\n iCombine \"H1 H2\" as \"H\".\n eauto.\nQed.\n\n(*\nDefinition txn_pre_exchange γ γ' : iProp Σ :=\n (∃ σs : async (gmap addr object), \"H◯async\" ∷ ghost_var γ'.(txn_crashstates) (3/4) σs ∗\n heapspec_durable_exchanger γ.(txn_walnames) (length (possible σs) - 1)).\n\nDefinition txn_post_exchange γ γ' : iProp Σ :=\n (∃ σs : async (gmap addr object), \"H◯async\" ∷ ghost_var γ.(txn_crashstates) (3/4) σs).\n\nDefinition txn_exchanger (γ γ' : @txn_names Σ) : iProp Σ :=\n ∃ ls ls', heapspec_exchanger ls ls' γ.(txn_walnames) γ'.(txn_walnames) ∗\n (txn_pre_exchange γ γ' ∨ txn_post_exchange γ γ').\n*)\n\nDefinition txn_resources γ γ' logm : iProp Σ :=\n (∃ logm0 (txn_id : nat),\n \"%Hasync_pre\" ∷ ⌜ async_prefix logm logm0 ⌝ ∗\n \"%Hlen_crash_txn\" ∷ ⌜ (length (possible logm) = txn_id + 1)%nat ⌝ ∗\n \"%Hlen_compare\" ∷ ⌜ (length (possible logm) ≤ length (possible logm0))%nat ⌝ ∗\n \"Hlogm\" ∷ ghost_var γ'.(txn_crashstates) (3/4) logm ∗\n \"Holdlogm\" ∷ ghost_var γ.(txn_crashstates) (1/4) logm0 ∗\n \"Hmapsto_txns\" ∷ ([∗ map] a ↦ v ∈ latest (logm), mapsto_txn γ' a v) ∗\n \"Hdurable\" ∷ mono_nat_lb_own γ'.(txn_walnames).(heapspec.wal_heap_durable_lb) txn_id ∗\n \"Hdurable_exchanger\" ∷ heapspec_durable_exchanger γ.(txn_walnames) txn_id)%I.\n\n\nLemma txn_crash_transform dinit (γ γ': txn_names) γ'_walnames logm1 crash_heaps\n (* (Hwalnames_eq : γ'.(txn_walnames) = γ'_txn_walnames) *)\n (Hkinds_eq : γ'.(txn_kinds) = γ.(txn_kinds)) :\n (\"His_txn_always\" ∷ is_txn_state γ logm1 crash_heaps ∗\n \"Htxn_init\" ∷ txn_init_ghost_state γ' ∗\n \"Hcrash\" ∷ ∃ (σ0 σ' : log_state.t),\n ⌜relation.denote log_crash σ0 σ' tt⌝ ∗\n is_wal_inner_durable γ'_walnames σ' dinit ∗ wal_resources γ'_walnames ∗\n ▷ (wal_heap_inv γ'.(txn_walnames) σ' ∗\n heapspec_resources γ.(txn_walnames) γ'.(txn_walnames) σ0 σ')) -∗\n (|={∅}=> ∃ (logm' : async (gmap addr object)),\n let γ' := (γ'<|txn_walnames;wal_heap_walnames := γ'_walnames|>) in\n ⌜γ'.(txn_kinds) = γ.(txn_kinds)⌝ ∗ is_txn_durable γ' dinit ∗ txn_resources γ γ' logm').\nProof.\n iNamed 1.\n iDestruct \"Hcrash\" as (ls1) \"HP\".\n iDestruct \"HP\" as (ls2 Hcrashls12) \"(Hdur' & Hres' & HP)\".\n iNamed \"His_txn_always\".\n rewrite /txn_resources.\n\n rewrite /Prec. iDestruct \"HP\" as \"(>Hheap_inv&Hheap_res)\".\n rewrite /is_txn_durable.\n\n rewrite /heapspec_resources.\n iDestruct \"Hheap_res\" as \"(>Hheap_exchanger&>Hlocked_walheap)\".\n iDestruct (heapspec_exchange_crash_heaps with \"[$] [$]\") as \"(Hheap_exchange&Hnew)\".\n iDestruct \"Hnew\" as \"(Hheap_lb_exchange&Hcrash_heaps0)\".\n iNamed \"Hcrash_heaps0\".\n\n iDestruct (wal_heap_inv_wf with \"Hheap_inv\") as %Hls2wf.\n iNamed \"Htxn_init\".\n iDestruct (big_sepL2_length with \"Hcrashheapsmatch\") as %Hlen_logm.\n assert (length ls2.(log_state.txns) ≤ length (possible logm1))%nat.\n { rewrite Hlen_logm -Hlenold //=.\n apply log_crash_txns_length. auto. }\n assert (0 < length ls2.(log_state.txns))%nat.\n { destruct Hls2wf. lia. }\n\n iMod (ghost_var_update (async_take (length ls2.(log_state.txns)) logm1) with \"crashstates\")\n as \"crashstates\".\n iDestruct (crash_heaps_match_async_take γ _ _ (length ls2.(log_state.txns)) with \"Hcrashheapsmatch\")\n as \"#Hcrashheapsmatch'\"; auto.\n iDestruct (crash_heaps_match_transfer_gname _ γ' with \"Hcrashheapsmatch'\") as \"#Hcrashheapsmatch_new\".\n { auto. }\n\n iMod (ghost_map_insert_big (async_take (length ls2.(log_state.txns)) logm1).(latest) with \"logheap\")\n as \"[logheap Hlatest]\".\n { apply map_disjoint_empty_r. }\n\n iMod (crash_heaps_match_heapmatch_latest γ' with \"[$Hcrashheapsmatch_new $metaheap $Hcrash_heaps0]\") as\n (metam_new) \"(metaheap&Heapmatch_new&Hpts)\".\n\n iExists (async_take (length ls2.(log_state.txns)) logm1).\n iSplitL \"\"; first eauto.\n\n\n iEval (rewrite -Qp.quarter_three_quarter) in \"crashstates\".\n iDestruct (fractional.fractional_split_1 with \"crashstates\") as\n \"[crashstates1 crashstates2]\".\n iDestruct (heapspec_durable_exchanger_dup with \"[$]\")\n as \"(Hheap_lb_exchange1&Hheap_lb_exchange2)\".\n iSplitR \"Hcrashstates crashstates2 Hheap_lb_exchange2 Hheap_exchange Hpts Hlatest\"; last first.\n { iModIntro. iExists _, ((length ls2.(log_state.txns)) - 1)%nat. iFrame.\n iSplitL \"\".\n {\n iPureIntro. apply async_take_async_prefix; lia.\n }\n iSplitL \"\".\n { iPureIntro. rewrite /async_take.\n rewrite possible_list_to_async; last first.\n { rewrite take_length. lia. }\n { rewrite take_length. lia. }\n }\n iSplitL \"\".\n { iPureIntro. rewrite /async_take.\n rewrite possible_list_to_async; last first.\n { rewrite take_length. lia. }\n { rewrite take_length. lia. }\n }\n iCombine \"Hpts Hlatest\" as \"Hpts\".\n rewrite -big_sepM_sep.\n iSplitL \"Hpts\".\n {\n iApply (big_sepM_mono with \"Hpts\").\n iIntros (???) \"(H1&H2)\".\n iDestruct \"H1\" as (γm) \"(H1a&H1b)\".\n iExists γm. iFrame.\n }\n iNamed \"Hheap_exchange\". simpl.\n rewrite (wal_post_crash_durable_lb_length_txns ls2); first iFrame \"#\".\n eapply log_crash_to_post_crash; eauto.\n }\n iExists ls2, _, _. simpl. iFrame \"Hheap_inv Hres' Hdur'\".\n\n iFrame \"Hcrash_heaps\".\n iSplitL \"\".\n { iModIntro. iPureIntro. eapply log_crash_to_post_crash; eauto. }\n iFrame.\n iExists metam_new.\n iFrame \"# ∗\".\n simpl. iEval (rewrite right_id) in \"logheap\". iFrame \"logheap\".\n eauto.\nQed.\n\n Definition txn_cfupd_cancel E dinit γ' : iProp Σ :=\n ( (|C={E}=> ▷ is_txn_durable γ' dinit)).\n\nDefinition txn_cfupd_res E γ γ' : iProp Σ :=\n ⌜γ'.(txn_kinds) = γ.(txn_kinds)⌝ ∗\n ( (|C={E}=> ▷ ∃ logm, txn_resources γ γ' logm)).\n\nTheorem wpc_MkLog E d dinit (γ:txn_names) :\n ↑walN ⊆ E →\n ↑invN ⊆ E →\n {{{ is_txn_durable γ dinit }}}\n obj.MkLog (disk_val d) @ ⊤\n {{{ γ' (l: loc), RET #l;\n is_txn l γ dinit ∗\n txn_cfupd_cancel E dinit γ' ∗\n txn_cfupd_res E γ γ' }}}\n {{{ ∃ γ' logm', ⌜ txn_kinds γ' = txn_kinds γ ⌝ ∗ is_txn_durable γ' dinit\n ∗ (⌜ γ' = γ ⌝ ∨ txn_resources γ γ' logm') }}}.\nProof.\n iIntros (?? Φ Φc) \"Hdur HΦ\".\n rewrite /obj.MkLog. wpc_pures.\n { crash_case. iExists _, _. iFrame. eauto. }\n\n iCache with \"Hdur HΦ\".\n { crash_case. iExists _, _. iFrame. eauto. }\n wpc_bind (lock.new _).\n wpc_frame; wp_apply (wp_new_free_lock).\n iIntros (lk) \"Hlock\". iNamed 1.\n wpc_bind (wal.MkLog _).\n iNamed \"Hdur\".\n iMod (alloc_heapspec_init_ghost_state (γ.(txn_walnames).(wal_heap_walnames)))\n as (γ'_txn_walnames ?) \"Hheapspec_init\".\n iMod (alloc_txn_init_ghost_state γ'_txn_walnames γ.(txn_kinds)) as\n (γ' Hwalnames_eq Hkinds_eq) \"Htxn_init\".\n set (P := λ ls, (wal_heap_inv γ.(txn_walnames) ls ∗ heapspec_init_ghost_state γ'_txn_walnames)%I).\n set (Prec (ls ls': log_state.t) :=\n (wal_heap_inv γ'.(txn_walnames) ls' ∗\n heapspec_resources γ.(txn_walnames) γ'.(txn_walnames) ls ls')%I).\n set (Pcrash (ls ls' : log_state.t) := (True)%I : iProp Σ).\n iApply wpc_cfupd.\n wpc_apply (wpc_MkLog_recover dinit P (↑walN) _ _ _ Prec Pcrash\n with \"[] [$His_wal_inner_durable Hwal_res Hwal_heap_inv Hheapspec_init]\").\n - auto.\n - auto.\n - iIntros \"!>\" (???) \">HP\".\n iDestruct \"HP\" as \"[Hinv Hinit]\".\n iMod (wal_heap_inv_crash_transform with \"Hinv Hinit\") as \"[Hinv Hres]\"; eauto.\n rewrite /Prec /Pcrash.\n rewrite Hwalnames_eq.\n iModIntro.\n by iFrame.\n - iFrame.\n - iSplit.\n { iLeft in \"HΦ\".\n iIntros \"Hcrash HC\".\n iDestruct \"Hcrash\" as (γ'wal_names) \"Hcrash\".\n iPoseProof (txn_crash_transform with \"[$]\") as \"Htransform\".\n { auto. }\n iMod (fupd_mask_mono with \"Htransform\") as \"Htransform\"; auto.\n iModIntro. iApply \"HΦ\".\n iDestruct \"Htransform\" as (?) \"(?&?&?)\".\n iExists _, _. iFrame.\n }\n iNext. iIntros (γ'' l) \"(#Hwal & Hwal_cfupd & #Hwal_cinv)\".\n iApply wpc_fupd.\n iApply wpc_cfupd.\n wpc_frame_compl \"Hlock Hlocked_walheap\".\n {\n iLeft in \"HΦ\".\n iIntros \"HC\".\n rewrite /wal_cfupd_cancel.\n rewrite own_discrete_elim.\n iSpecialize (\"Hwal_cfupd\" with \"[$]\").\n iMod (fupd_mask_mono with \"Hwal_cfupd\") as \"Hwal_cfupd\"; auto.\n iPoseProof (txn_crash_transform with \"[$His_txn_always $Htxn_init Hwal_cfupd]\") as \"Htransform\".\n { auto. }\n { iDestruct \"Hwal_cfupd\" as (??) \"H\".\n iExists _, _. iFrame.\n }\n iMod (fupd_mask_mono with \"Htransform\") as \"Htransform\"; auto.\n iModIntro. iApply \"HΦ\".\n iDestruct \"Htransform\" as (?) \"(?&?&?)\".\n iExists _, _. iFrame.\n }\n rewrite -wp_fupd.\n wp_apply wp_allocStruct; first by val_ty.\n iIntros (txn_l) \"Htxn\".\n iApply struct_fields_split in \"Htxn\". iNamed \"Htxn\".\n wp_pures.\n iMod (readonly_alloc_1 with \"mu\") as \"#mu\".\n iMod (readonly_alloc_1 with \"log\") as \"#log\".\n iMod (alloc_lock lockN _ _ (is_txn_locked txn_l γ.(txn_walnames))\n with \"Hlock [pos Hlocked_walheap]\") as \"#Htxn_lock\".\n { iNext. rewrite /is_txn_locked.\n iExists _, _, _; iFrame. }\n iModIntro.\n iNamed 1.\n rewrite /wal_cfupd_cancel.\n iDestruct (own_discrete_laterable with \"Hwal_cfupd\") as (Pwal_tok) \"(HPwal_tok&#HPwal_tok_wand)\".\n iMod (ncinv_cinv_alloc' invN _ E\n (is_txn_always γ ∗ Pwal_tok ∗ txn_init_ghost_state γ')\n (∃ logm',\n txn_resources γ ((γ' <| txn_walnames; wal_heap_walnames := γ'' |>)) logm')%I\n (is_txn_durable ((γ' <| txn_walnames; wal_heap_walnames := γ'' |>)) dinit)%I\n with \"[] [His_txn_always HPwal_tok Htxn_init]\") as \"(#Htxn_inv&Hcfupd)\".\n { set_solver. }\n { iIntros \"!> (>H&?&>Hinit) #HC\".\n iSpecialize (\"Hwal_cinv\" with \"[$]\").\n iMod (\"HPwal_tok_wand\" with \"[$]\") as \"Hwal_cfupd\".\n iSpecialize (\"Hwal_cfupd\" with \"HC\").\n iDestruct \"H\" as (??) \"H\".\n iMod (fupd_mask_mono with \"Hwal_cfupd\") as \"Hwal_cfupd\".\n { solve_ndisj. }\n iPoseProof (txn_crash_transform _ γ γ' with \"[H Hwal_cfupd Hinit]\") as \"Htransform\".\n { auto. }\n { iFrame \"H Hinit\".\n iDestruct \"Hwal_cfupd\" as (??) \"(?&?&?&?)\".\n iExists _, _. iFrame.\n }\n iMod (fupd_mask_mono with \"Htransform\") as \"Htransform\"; auto.\n { set_solver+. }\n iModIntro.\n iDestruct \"Htransform\" as (??) \"(Hdur&Hres)\".\n iSplitR \"Hdur\".\n { iNext. iExists _. iFrame. }\n { iNext. iFrame. }\n }\n { iNext. iFrame. iExists _, _; iFrame. }\n iDestruct \"Hcfupd\" as \"(Hcfupd_cancel&Hcfupd)\".\n iRight in \"HΦ\".\n iApply \"HΦ\".\n iSplitL \"\".\n {\n iExists _, _; iFrame \"#\".\n iSplitL.\n - iApply (is_wal_alter with \"Hwal\").\n do 2 iModIntro. iClear \"#\".\n rewrite /P.\n iIntros (?) \"[$ $]\".\n iIntros (?) \"$\".\n - iApply (ncinv_alter with \"Htxn_inv\").\n iIntros \"!> !> !> (H&?)\".\n iFrame. eauto.\n }\n iModIntro. iFrame \"Hcfupd_cancel\".\n rewrite /txn_cfupd_res.\n rewrite /txn_cfupd_cancel.\n iFrame.\n Unshelve.\n (* XXX: track this down. *)\n { simpl. eauto. }\n { exact (Build_async (∅: gmap addr object) []). }\n { exact (Build_async (∅: gmap addr object) []). }\n { exact (U64 0). }\nQed.\n\nEnd goose_lang.\n\nSection stable.\nContext `{!txnG Σ}.\nContext `{!heapGS Σ}.\n\nExisting Instance ghost_var_into_crash.\nExisting Instance mono_nat_auth_own_into_crash.\nExisting Instance is_wal_inner_durable_stable.\n\nGlobal Instance is_txn_durable_stable γ dinit:\n IntoCrash (is_txn_durable γ dinit) (λ _, is_txn_durable γ dinit).\nProof.\n rewrite /IntoCrash.\n iNamed 1.\n iDestruct (post_crash_nodep with \"His_txn_always\") as \"His_txn_always\".\n iDestruct (post_crash_nodep with \"Hwal_res\") as \"Hwal_res\".\n iDestruct (post_crash_nodep with \"Hwal_heap_inv\") as \"Hwal_heap_inv\".\n iDestruct (post_crash_nodep with \"Hlocked_walheap\") as \"Hlocked_walheap\".\n iCrash.\n iExists ls', logm, crash_heaps.\n iSplit; first eauto.\n iFrame \"Hwal_res\".\n iFrame \"Hwal_heap_inv\".\n iFrame \"Hlocked_walheap\".\n iFrame \"His_txn_always\".\n eauto.\nQed.\nEnd stable.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/obj/recovery_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.24508500761839525, "lm_q1q2_score": 0.1349456103769489}} {"text": "Require Import compcert.backend.Cminor.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Errors.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Maps.\nRequire Import Seccomp.\nRequire Import Seccompjit.\nRequire Import Seccompconf.\nImport ListNotations.\n\nFixpoint seccomp_func_filter (f: Seccomp.code) : bool :=\n match f with\n | [ Sret_k k ] => true\n | [ Sret_a ] => true\n\n | Salu_safe op :: rest => seccomp_func_filter rest\n | Salu_div op :: rest => seccomp_func_filter rest\n | Salu_shift op :: rest => seccomp_func_filter rest\n\n | Sjmp_ja off :: rest =>\n (Int.unsigned off \n (Byte.unsigned jt \n (Int.unsigned k seccomp_func_filter rest\n | Sldx_w_len :: rest => seccomp_func_filter rest\n\n | Sld_imm k :: rest => seccomp_func_filter rest\n | Sldx_imm k :: rest => seccomp_func_filter rest\n(*\n | Sld_mem k :: rest =>\n (Int.unsigned k seccomp_func_filter rest\n | Smisc_txa :: rest => seccomp_func_filter rest\n\n | Sret_k k :: rest => seccomp_func_filter rest\n | Sret_a :: rest => seccomp_func_filter rest\n\n | _ => false\n end.\n\nDefinition seccomp_filter (p: Seccomp.program) : bool :=\n let defs := p.(prog_defs) in\n let main := p.(prog_main) in\n match defs with\n (* Just one identifier *)\n | [ (id, Gfun (Internal f)) ] =>\n (id =? main)%positive &&\n seccomp_func_filter f\n | _ => false\n end.\n\nDefinition transl_program_filter (p: Seccomp.program) : res Cminor.program :=\n match seccomp_filter p with\n | true => transl_program p\n | false => Error (msg \"filter reject\")\n end.\n\n", "meta": {"author": "utokyo-lzh", "repo": "Jitk", "sha": "7f7f6eb541c7e8a2613974fff5b4fc6fc0783182", "save_path": "github-repos/coq/utokyo-lzh-Jitk", "path": "github-repos/coq/utokyo-lzh-Jitk/Jitk-7f7f6eb541c7e8a2613974fff5b4fc6fc0783182/Seccompfilter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.24508500761839525, "lm_q1q2_score": 0.13399732414441642}} {"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.lang Require Import lang trans_extra.\nFrom HypVeri.algebra Require Import base pagetable mem trans.\nFrom HypVeri.rules Require Import run.\nFrom HypVeri.logrel Require Import logrel logrel_extra.\nFrom HypVeri Require Import stdpp_extra proofmode.\nImport uPred.\n\nSection ftlr_run.\n Context `{hypconst:HypervisorConstants}.\n Context `{hypparams:!HypervisorParameters}.\n Context `{vmG: !gen_VMG Σ}.\n\nLemma ftlr_run Φ_t Φ_r {i mem_acc_tx ai regs rxs ps_acc p_tx p_rx instr trans r0}:\n base_extra.is_total_gmap regs ->\n base_extra.is_total_gmap rxs ->\n {[p_tx; p_rx]} ⊆ ps_acc ->\n i ≠ V0 ->\n currently_accessible_in_trans_memory_pages i trans ⊆ ps_acc ∖ {[p_tx; p_rx]} ->\n p_rx ∉ ps_acc ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i trans ->\n p_tx ∉ ps_acc ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i trans ->\n regs !! PC = Some ai ->\n tpa ai ∈ ps_acc ->\n tpa ai ≠ p_tx ->\n dom mem_acc_tx = set_of_addr (ps_acc ∖ {[p_tx]}) ->\n tpa ai ∈ ps_acc ∖ {[p_tx]} ->\n mem_acc_tx !! ai = Some instr ->\n decode_instruction instr = Some Hvc ->\n regs !! R0 = Some r0 ->\n decode_hvc_func r0 = Some Run ->\n p_tx ≠ p_rx ->\n ⊢ ▷ (∀ (a : gmap reg_name Addr) (a0 : gset PID) (a1 : gmap Addr transaction) (a2 : gmap VMID (option (Addr * VMID))),\n ⌜base_extra.is_total_gmap a2⌝ -∗\n ⌜base_extra.is_total_gmap a⌝ -∗\n ⌜{[p_tx; p_rx]} ⊆ a0⌝ -∗\n ⌜currently_accessible_in_trans_memory_pages i a1 ⊆ a0 ∖ {[p_tx; p_rx]}⌝ -∗\n ⌜p_rx ∉ a0 ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i a1⌝ -∗\n ⌜p_tx ∉ a0 ∖ {[p_rx; p_tx]} ∪ accessible_in_trans_memory_pages i a1⌝ -∗\n ([∗ map] r↦w ∈ a, r @@ i ->r w) -∗\n TX@i:=p_tx -∗\n p_tx -@O> - ∗ p_tx -@E> true -∗\n mailbox.rx_page i p_rx -∗\n i -@A> a0 -∗\n pagetable_entries_excl_owned i (a0 ∖ {[p_rx; p_tx]} ∖ currently_accessible_in_trans_memory_pages i a1) -∗\n transaction_hpool_global_transferred a1 -∗\n transaction_pagetable_entries_transferred i a1 -∗\n retrievable_transaction_transferred i a1 -∗\n rx_state_get i a2 -∗\n rx_states_global (delete i a2) -∗\n transaction_pagetable_entries_owned i a1 -∗\n retrieved_transaction_owned i a1 -∗\n (∃ mem : lang.mem, memory_pages (a0 ∪ (accessible_in_trans_memory_pages i a1)) mem) -∗\n ((∃ r0 : Addr, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗\n (∃ r1 : Addr, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝) ∗ (∃ r2 : Addr, R2 @@ V0 ->r r2) ∗\n ▷ VMProp V0 (vmprop_zero i Φ_t Φ_r a1 a2) (1 / 2) ∗ ∃ P, VMProp i P 1) -∗\n WP ExecI @ i {{ _, True }}) -∗\n ([∗ map] r↦w ∈ regs, r @@ i ->r w) -∗\n TX@i:=p_tx -∗\n p_tx -@O> - ∗ p_tx -@E> true -∗\n i -@A> ps_acc -∗\n pagetable_entries_excl_owned i (ps_acc ∖ {[p_rx; p_tx]} ∖ (currently_accessible_in_trans_memory_pages i trans)) -∗\n transaction_hpool_global_transferred trans -∗\n transaction_pagetable_entries_transferred i trans -∗\n retrievable_transaction_transferred i trans -∗\n rx_state_get i rxs -∗\n mailbox.rx_page i p_rx -∗\n rx_states_global (delete i rxs) -∗\n transaction_pagetable_entries_owned i trans -∗\n retrieved_transaction_owned i trans -∗\n (∃ mem1 : mem, memory_pages ((ps_acc ∪ (accessible_in_trans_memory_pages i trans)) ∖ ps_acc) mem1) -∗\n ([∗ map] k↦v ∈ mem_acc_tx, k ->a v) -∗\n (∃ mem2 : mem, memory_page p_tx mem2) -∗\n ((∃ r0 : Addr, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗\n (∃ r1 : Addr, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝) ∗ (∃ r2 : Addr, R2 @@ V0 ->r r2) ∗\n ▷ VMProp V0 (vmprop_zero i Φ_t Φ_r trans rxs) (1 / 2) ∗ ∃ P, VMProp i P 1) -∗\n SSWP ExecI @ i {{ bm, (if bm.1 then VMProp_holds i (1 / 2) else True) -∗ WP bm.2 @ i {{ _, True }} }}.\n Proof.\n iIntros (Htotal_regs Htotal_rxs Hsubset_mb Hneq_0 Hsubset_acc Hnin_rx Hnin_tx Hlookup_PC Hin_ps_acc Hneq_ptx Hdom_mem_acc_tx Hin_ps_acc_tx\n Hlookup_mem_ai Heqn Hlookup_reg_R0).\n iIntros ( Hdecode_hvc Hneq_mb) \"IH regs tx pgt_tx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state rx other_rx\n tran_pgt_owned retri_owned mem_rest mem_acc_tx mem_tx ([% [R0z %]]& [% [R1z %]] & [% R2z] & prop0 &propi)\".\n pose proof (Htotal_regs R0) as [a_arg1 Hlookup_arg1].\n pose proof (Htotal_regs R2) as [a_arg2 Hlookup_arg2].\n (* getting registers *)\n iDestruct ((reg_big_sepM_split_upd3 i Hlookup_PC Hlookup_arg1 Hlookup_arg2)\n with \"[$regs]\") as \"(PC & r_arg1 & r_arg2 & Hacc_regs)\"; [done | done | done | done |].\n (* getting mem *)\n iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with \"[$mem_acc_tx]\")\n as \"[mem_instr Hacc_mem_acc]\".\n rewrite Hlookup_arg1 in Hlookup_reg_R0.\n inversion Hlookup_reg_R0.\n subst a_arg1.\n iApply (run_not_primary (r0 := r0) ai i with \"[PC tx pgt_acc mem_instr r_arg1 r_arg2]\"); iFrameAutoSolve.\n iNext.\n iIntros \"(PC & mem_instr & pgt_acc & tx & r_arg1 & r_arg2) _\".\n iDestruct (\"Hacc_regs\" with \"[$PC $r_arg1 $r_arg2]\") as (regs') \"[%Htotal_regs' regs]\";iFrame.\n iDestruct (\"Hacc_mem_acc\" with \"[mem_instr]\") as \"mem\"; iFrame.\n iAssert (memory_pages (ps_acc ∖ {[p_tx]}) _)%I with \"[mem]\" as \"mem_acc\".\n by iFrame.\n iApply (\"IH\" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with \"regs tx pgt_tx rx pgt_acc pgt_owned\n trans_hpool_global tran_pgt_transferred retri rx_state other_rx tran_pgt_owned\n retri_owned [mem_rest mem_acc mem_tx] [R0z R1z R2z $prop0 $propi]\").\n {\n iDestruct (memory_pages_split_singleton' p_tx ps_acc with \"[mem_acc mem_tx]\") as \"mem_acc\". set_solver + Hsubset_mb.\n iSplitL \"mem_acc\".\n iExists mem_acc_tx; by iFrame \"mem_acc\".\n iFrame \"mem_tx\".\n iApply (memory_pages_split_diff' _ ps_acc with \"[$mem_rest $mem_acc]\").\n set_solver +.\n }\n {\n iSplitL \"R0z\". iExists _; iFrame. done.\n iSplitL \"R1z\". iExists _; iFrame. done.\n iExists _. iFrame.\n }\n Qed.\n\nEnd ftlr_run.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/logrel/ftlr_run.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2628418373713167, "lm_q1q2_score": 0.13244762372460755}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Locations.\nRequire Import DataType.\nRequire Import LAsm.\nRequire Import CDataTypes.\nRequire Import AsmExtra.\nRequire Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import MALOp.\nRequire Import MALInit.\nRequire Import ZArith.Zwf.\nRequire Import MALInitCode.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import Maps.\nRequire Import Heap.\nRequire Import RefinementTactic.\nRequire Import AuxLemma.\nRequire Import LayerTemplate2.\nRequire Export ALOpGen.\nRequire Import Implementation.\nRequire Import SeparateCompiler.\nRequire Import ClightImplemExtra.\nRequire Import LayerDefinition.\nRequire Import RealParams.\n\nOpen Local Scope string_scope.\nOpen Local Scope error_monad_scope.\n\nModule ALOPGENIMPL.\n Export ALOpGen.ALOPGEN.\n\n Lemma hprim_finite_type:\n forall\n (Q: MALOP.primOp -> Prop)\n (Q_dec: forall p, {Q p} + {~ Q p}),\n {forall p, Q p} + {~ forall p, Q p}.\n Proof with (try (right; eauto; fail)).\n intros.\n destruct (Q_dec MALOP.PSetPE)...\n destruct (Q_dec MALOP.PSetPT)...\n destruct (Q_dec MALOP.PGetNps)...\n destruct (Q_dec MALOP.PIsNorm)...\n destruct (Q_dec MALOP.PATGetU)...\n destruct (Q_dec MALOP.PATSetU)...\n destruct (Q_dec MALOP.PTrapIn)...\n destruct (Q_dec MALOP.PTrapOut)...\n destruct (Q_dec MALOP.PHostIn)...\n destruct (Q_dec MALOP.PHostOut)...\n destruct (Q_dec MALOP.PTrapGet)...\n destruct (Q_dec MALOP.PTrapRet)...\n destruct (Q_dec MALOP.PMemInit)...\n left; destruct p; assumption.\n Defined. \n\n Local Open Scope Z_scope.\n\n Section WithPrimitives.\n\n Context `{real_params: RealParams}.\n\n Notation HDATA := (MALOP.AbData (kern_high := kern_high) (kern_low := kern_low) (maxpage:= maxpage)).\n Notation LDATA := (MALINIT.AbData (PgSize := PgSize) (kern_low := kern_low)).\n \n Notation Hfundef := (fundef (external_function:= MALOP.primOp)).\n Notation Lfundef := (fundef (external_function:= MALINIT.primOp)).\n\n Notation funkind := (funkind Asm.code (Clight.fundef (external_function := MALINIT.primOp))).\n\n Notation dummy := (AST.Internal nil).\n\n Definition source_implem_extfuns (p: MALOP.primOp): funkind :=\n match p with\n | MALOP.PSetPE => Code _ (AST.External MALINIT.PSetPE)\n | MALOP.PSetPT => Code _ (AST.External MALINIT.PSetPT)\n | MALOP.PTrapIn => Code _ (AST.External MALINIT.PTrapIn)\n | MALOP.PTrapOut => Code _ (AST.External MALINIT.PTrapOut)\n | MALOP.PHostIn => Code _ (AST.External MALINIT.PHostIn)\n | MALOP.PHostOut => Code _ (AST.External MALINIT.PHostOut)\n | MALOP.PTrapGet => Code _ (AST.External MALINIT.PTrapGet)\n | MALOP.PTrapRet => Code _ (AST.External MALINIT.PTrapRet)\n | MALOP.PGetNps => Code _ (AST.External MALINIT.PGetNps)\n | MALOP.PIsNorm => Code _ (AST.External MALINIT.PIsNorm)\n | MALOP.PATGetU => Code _ (AST.External MALINIT.PATGetU)\n | MALOP.PATSetU => Code _ (AST.External MALINIT.PATSetU)\n | MALOP.PMemInit => SourceFun (Clight.Internal (MALINITCODE.f_mem_init set_nps set_norm get_size get_mms get_mml is_usable boot_loader)) dummy\n end.\n\n Notation varkind := (varkind unit Ctypes.type).\n\n Definition source_implem_impl_globs : list (ident * option (globdef funkind varkind)) :=\n (set_nps, Some (Gfun (SourceFun (Clight.External (MALINIT.PSetNps) (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid) dummy)))\n :: (set_norm, Some (Gfun (SourceFun (Clight.External (MALINIT.PATSetNorm) (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil)) Ctypes.Tvoid) dummy)))\n :: (get_size, Some (Gfun (SourceFun (Clight.External (MALINIT.PGetSize) Ctypes.Tnil tint) dummy)))\n :: (get_mms, Some (Gfun (SourceFun (Clight.External (MALINIT.PMMGetS) (Ctypes.Tcons tint Ctypes.Tnil) tint) dummy)))\n :: (get_mml, Some (Gfun (SourceFun (Clight.External (MALINIT.PMMGetL) (Ctypes.Tcons tint Ctypes.Tnil) tint) dummy)))\n :: (is_usable, Some (Gfun (SourceFun (Clight.External (MALINIT.PIsUsable) (Ctypes.Tcons tint Ctypes.Tnil) tint) dummy)))\n :: (boot_loader, Some (Gfun (SourceFun (Clight.External (MALINIT.PBootLoader) (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid) dummy)))\n :: nil.\n\n Let NOREPET_IMPL: list_norepet (map fst source_implem_impl_globs).\n Proof.\n case_eq (list_norepet_dec peq (map fst source_implem_impl_globs)); try discriminate; tauto.\n Qed.\n\n Definition source_implem : source_implem Asm.code unit MALOP.primOp (low := MALINIT.primOp) (Clight.fundef (external_function := MALINIT.primOp)) Ctypes.type.\n Proof.\n split.\n exact source_implem_extfuns.\n exact source_implem_impl_globs.\n Defined.\n\n Let im : implem Asm.code unit MALOP.primOp (low := MALINIT.primOp) := implem_of_source_implem transf_clight_fundef Cshmgen.transl_globvar source_implem.\n\n Notation Hprogram := (Asm.program (external_function:= MALOP.primOp)). \n Notation Lprogram := (Asm.program (external_function:= MALINIT.primOp)).\n\n Let Im_meminit: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns MALOP.PMemInit).\n\n Definition impl_glbl : list (ident * option (globdef Lfundef unit)) :=\n map\n (transf_source_def' transf_clight_fundef\n Cshmgen.transl_globvar)\n source_implem_impl_globs.\n\n Let well_new_glb: Genv.well_idglob_list impl_glbl = true.\n Proof. reflexivity. Qed.\n \n (* This is basically an axiom that can be easily checked because MALOP.primOp is a finite type. However, in practice, generation of CertiKOS code will be very slow because compilation will have to occur twice, one for this check, and a second independently for the generation of the actual code. *)\n \n Lemma extfun_compilation_succeeds_dec:\n {forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm} +\n {~ forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm}.\n Proof.\n apply hprim_finite_type.\n intro.\n destruct (source_implem_extfuns p); try (left; discriminate).\n case_eq (transf_clight_fundef sf).\n left. intros. inv H0. eauto.\n intros. right. intro. exploit H0; eauto. destruct 1. congruence.\n Defined.\n\n Hypothesis extfun_compilation_succeeds:\n forall p clight asmfallback, \n source_implem_extfuns p = SourceFun clight asmfallback ->\n exists asm, transf_clight_fundef clight = OK asm.\n\n Section WithProg.\n\n Variable prog: Hprogram.\n\n Definition tprog: Lprogram := Implementation.transf_program im prog.\n\n Let TRANSF: ALOPGEN.transf_program Im_meminit impl_glbl prog = OK tprog.\n Proof.\n unfold tprog.\n unfold Asm.program, Asm.fundef.\n generalize (transf_program_eq im prog).\n intros.\n rewrite <- H.\n unfold transf_program.\n simpl.\n f_equal.\n apply FunctionalExtensionality.functional_extensionality.\n destruct x; simpl.\n reflexivity.\n destruct p; reflexivity.\n Qed.\n\n Notation ge := (Genv.globalenv prog).\n Notation tge := (Genv.globalenv tprog).\n\n Hypothesis prog_nonempty:\n prog_defs_names prog <> nil.\n\n Hypothesis prog_main_valid:\n ~ Plt' (prog_main prog) (prog_first_symbol prog).\n\n Hypothesis prog_first_valid:\n ~ Plt' (prog_first_symbol prog) (get_next_symbol (map fst impl_glbl)).\n \n Let NEW_INJ: (forall s', Genv.find_symbol ge s' <> None -> \n ~ In s' (map fst impl_glbl)).\n Proof.\n change impl_glbl with (implem_new_globs im).\n apply new_ids_fresh.\n assumption.\n Qed.\n\n Let sprog : Clight.program (external_function := MALINIT.primOp) := source_program_only source_implem prog.\n Let sge := Genv.globalenv sprog.\n\n Ltac elim_or H t :=\n match type of H with\n | False => contradiction\n | _ \\/ _ =>\n let K := fresh \"K\" in\n destruct H as [H | K]; [ elim_or H t | elim_or K t ]\n | _ => t H\n end.\n\n Let tsprog_strong : {tsprog | transf_clight_program sprog = OK tsprog}.\n Proof.\n case_eq (transf_clight_program sprog); eauto.\n intros. exfalso.\n refine (_ (Implementation.compilation_succeeds\n transf_clight_fundef\n Cshmgen.transl_globvar\n source_implem _ _ _\n prog)).\n destruct 1.\n exploit transf_clight_fundef_to_program; eauto.\n unfold sprog in H.\n congruence.\n assumption.\n simpl. \n intros until fallback.\n intro K.\n let t J := (inv J; rewrite transf_clight_fundef_external; eauto) in elim_or K t.\n unfold Cshmgen.transl_globvar. eauto.\n Qed.\n\n Let tsprog := let (p, _) := tsprog_strong in p.\n\n Let tsprog_prop : transf_clight_program sprog = OK tsprog.\n Proof.\n unfold tsprog.\n destruct tsprog_strong.\n assumption.\n Qed.\n\n Let tsge := Genv.globalenv tsprog.\n \n Lemma tprog_first_next:\n prog_first_symbol tprog = get_first_symbol (map fst impl_glbl) /\\\n prog_next_symbol tprog = prog_next_symbol prog.\n Proof.\n replace (get_first_symbol (map fst impl_glbl)) with (implem_first_symbol im) by reflexivity.\n unfold tprog.\n apply transf_program_first_next_symbol.\n assumption.\n assumption.\n discriminate.\n Qed.\n\n Lemma tprog_main_valid:\n ~ Plt' (prog_main tprog) (prog_first_symbol tprog).\n Proof.\n Opaque Plt'.\n simpl.\n destruct tprog_first_next.\n rewrite H.\n apply Ple'_not_Plt'.\n eapply Ple'_trans.\n apply first_le_next.\n discriminate.\n eapply Ple'_trans.\n apply not_Plt'_Ple'.\n eassumption.\n apply not_Plt'_Ple'.\n assumption.\n Qed.\n\n Lemma tprog_nonempty:\n prog_defs_names tprog <> nil.\n Proof.\n apply transf_program_nonempty.\n assumption.\n Qed.\n\n (** boot_loader *)\n\n Let bbootloader : block := Genv.genv_next ge + Z.of_nat 6.\n\n Let hboot_loader1 : Genv.find_symbol sge boot_loader = Some bbootloader. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ boot_loader).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n\n Let hboot_loader2 : Genv.find_funct sge (Vptr bbootloader Int.zero) = Some (Clight.External (MALINIT.PBootLoader) (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ boot_loader _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed.\n\n Let hboot_loader3: Clight.type_of_global sge bbootloader = Some (Ctypes.Tfunction (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bbootloader).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bbootloader. unfold Asm.fundef. omega.\n intros.\n simpl in hboot_loader2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hboot_loader2. reflexivity.\n Qed.\n\n (** get_size *)\n\n Let bgetsize : block := Genv.genv_next ge + Z.of_nat 2.\n\n Let hget_size1 : Genv.find_symbol sge get_size = Some bgetsize.\n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ get_size).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n\n Let hget_size2 : Genv.find_funct sge (Vptr bgetsize Int.zero) = Some (Clight.External (MALINIT.PGetSize) Ctypes.Tnil tint).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ get_size _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed.\n\n Let hget_size3 : Clight.type_of_global sge bgetsize = Some (Ctypes.Tfunction Ctypes.Tnil tint).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bgetsize).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bgetsize. unfold Asm.fundef. omega.\n intros.\n simpl in hget_size2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hget_size2. reflexivity.\n Qed.\n \n (** get_mms *)\n\n Let bgetmms: block := Genv.genv_next ge + Z.of_nat 3.\n \n Let hget_mms1 : Genv.find_symbol sge get_mms = Some bgetmms. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ get_mms).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let hget_mms2 : Genv.find_funct sge (Vptr bgetmms Int.zero) = Some (Clight.External (MALINIT.PMMGetS) (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ get_mms _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed.\n\n Let hget_mms3 : Clight.type_of_global sge bgetmms = Some (Ctypes.Tfunction (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bgetmms).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bgetmms. unfold Asm.fundef. omega.\n intros.\n simpl in hget_mms2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hget_mms2. reflexivity.\n Qed.\n\n (** get_mml *)\n\n Let bgetmml: block := Genv.genv_next ge + Z.of_nat 4.\n\n Let hget_mml1 : Genv.find_symbol sge get_mml = Some bgetmml. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ get_mml).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let hget_mml2 : Genv.find_funct sge (Vptr bgetmml Int.zero) = Some (Clight.External (MALINIT.PMMGetL) (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ get_mml _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hget_mml3 : Clight.type_of_global sge bgetmml = Some (Ctypes.Tfunction (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bgetmml).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bgetmml. unfold Asm.fundef. omega.\n intros.\n simpl in hget_mml2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hget_mml2. reflexivity.\n Qed.\n \n (** is_usable *)\n\n Let bisusable: block := Genv.genv_next ge + Z.of_nat 5.\n\n Let his_usable1 : Genv.find_symbol sge is_usable = Some bisusable. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ is_usable).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let his_usable2 : Genv.find_funct sge (Vptr bisusable Int.zero) = Some (Clight.External (MALINIT.PIsUsable) (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ is_usable _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let his_usable3 : Clight.type_of_global sge bisusable = Some (Ctypes.Tfunction (Ctypes.Tcons tint Ctypes.Tnil) tint).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bisusable).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bisusable. unfold Asm.fundef. omega.\n intros.\n simpl in his_usable2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite his_usable2. reflexivity.\n Qed.\n\n (** set_norm *)\n\n Let batsetnorm: block := Genv.genv_next ge + Z.of_nat 1.\n\n Let hset_norm1 : Genv.find_symbol sge set_norm = Some batsetnorm. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ set_norm).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed.\n \n Let hset_norm2 : Genv.find_funct sge (Vptr batsetnorm Int.zero) = Some (Clight.External (MALINIT.PATSetNorm) (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil)) Ctypes.Tvoid).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ set_norm _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hset_norm3 : Clight.type_of_global sge batsetnorm = Some (Ctypes.Tfunction (Ctypes.Tcons tint (Ctypes.Tcons tint Ctypes.Tnil)) Ctypes.Tvoid).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge batsetnorm).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold batsetnorm. unfold Asm.fundef. omega.\n intros.\n simpl in hset_norm2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hset_norm2. reflexivity.\n Qed.\n\n (** set_nps *)\n\n Let bsetnps: block := Genv.genv_next ge + Z.of_nat 0.\n\n Let hset_nps1 : Genv.find_symbol sge set_nps = Some bsetnps. \n Proof.\n eapply add_globals_transf_augment_option.\n 2: eapply source_program_only_prop.\n assumption.\n intro. exploit Genv.find_symbol_exists_ex. eassumption. destruct 1.\n eapply (NEW_INJ set_nps).\n congruence.\n simpl; tauto.\n reflexivity.\n Qed. \n \n Let hset_nps2 : Genv.find_funct sge (Vptr bsetnps Int.zero) = Some (Clight.External (MALINIT.PSetNps) (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid).\n Proof.\n simpl. destruct (Int.eq_dec Int.zero Int.zero); try congruence.\n refine (_ (Genv.find_new_funct_ptr_exists_option _ _ _ _ _ _ _ set_nps _ _)).\n 2: exact (source_program_only_prop source_implem prog).\n 3: simpl; eauto 8.\n 2: assumption.\n fold sprog sge.\n destruct 1 as [? [? ?]].\n congruence.\n Qed. \n\n Let hset_nps3 : Clight.type_of_global sge bsetnps = Some (Ctypes.Tfunction (Ctypes.Tcons tint Ctypes.Tnil) Ctypes.Tvoid).\n Proof.\n unfold Clight.type_of_global.\n case_eq (Genv.find_var_info sge bsetnps).\n intros. exfalso.\n exploit Genv.find_var_info_rev_transf_augment_option.\n exact (source_program_only_prop source_implem prog).\n eassumption.\n rewrite zlt_false.\n simpl.\n intro K.\n let t _ := discriminate in elim_or K t.\n unfold bsetnps. unfold Asm.fundef. omega.\n intros.\n simpl in hset_nps2. destruct (Int.eq_dec Int.zero Int.zero); try congruence. rewrite hset_nps2. reflexivity.\n Qed. \n\n Context `{PageFaultHandler_LOC: ident}.\n\n Section WITHMEM.\n \n Context {mem__MALOP mem__MALINIT}\n `{HHmem: !LayerMemoryModel HDATA mem__MALOP}\n `{HLmem: !LayerMemoryModel LDATA mem__MALINIT}\n `{HLayerInject: !LayerMemoryInjections HDATA LDATA _ _}.\n\n Instance HLayer: LayerDefinition HDATA MALOP.primOp mem__MALOP :=\n MALOP.layer_def (maxpage := maxpage) (real_nps := real_nps) (real_AT := real_AT).\n\n Instance LLayer: LayerDefinition LDATA MALINIT.primOp mem__MALINIT :=\n MALINIT.layer_def (PgSize := PgSize) (real_size := real_size) (real_mm := real_mm) (kern_low := kern_low) (maxpage := maxpage).\n\n Notation HLoad:= (MALOP.exec_loadex (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) \n (PageFaultHandler_LOC := PageFaultHandler_LOC)).\n\n Notation HStore:= (MALOP.exec_storeex (NPT_LOC:= NPT_LOC) (PgSize:= PgSize)\n (PageFaultHandler_LOC := PageFaultHandler_LOC)).\n\n Notation LLoad := (MALINIT.exec_loadex (NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC := PageFaultHandler_LOC)).\n \n Notation LStore:= ( MALINIT.exec_storeex (NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC := PageFaultHandler_LOC)).\n\n Notation lstep:= (MALINIT.step (NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC := PageFaultHandler_LOC)\n (maxpage:= maxpage) (real_size:= real_size) (real_mm:= real_mm)).\n\n Notation LADT := MALINIT.ADT.\n\n Let meminit_spec:\n forall r' b m0 labd' mbi_adr sg,\n let labd := Mem.get_abstract_data m0 in\n r' PC = Vptr b Int.zero\n -> Genv.find_funct_ptr tge b = Some (Im_meminit)\n -> MALINIT.mem_init (kern_high:=kern_high) (maxpage:=maxpage) labd real_size real_nps real_mm \n (real_AT (MALINIT.AT (LADT labd))) (Int.unsigned mbi_adr) = Some labd'\n -> (forall b o, r' ESP = Vptr b o -> Mem.tget m0 b = Some Tag_stack)\n -> r' ESP <> Vundef\n -> r' RA <> Vundef\n -> Genv.find_funct_ptr ge b = Some (External MALOP.PMemInit)\n -> asm_invariant tge (State r' m0)\n -> sg = mksignature (Tint::nil) None\n -> extcall_arguments r' m0 sg (Vint mbi_adr::nil)\n -> exists f' m0' r_, \n inject_incr (Mem.flat_inj (Mem.nextblock m0)) f' \n /\\ Memtype.Mem.inject f' m0 m0'\n /\\ Mem.nextblock m0 <= Mem.nextblock m0'\n /\\ plus lstep tge (State r' m0) E0\n (State r_ (Mem.put_abstract_data m0' labd'))\n /\\ True\n /\\ r_ PC = r' RA\n /\\ r_ # ESP = r' # ESP\n /\\ (forall l,\n ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n Proof.\n intros. \n exploit (ClightImplemExtra.bigstep_clight_to_lsem\n MALOP.primOp\n (exec_load := LLoad)\n (exec_store := LStore)\n (primitive_call := MALINIT.primitive_call)\n (is_primitive_call := MALINIT.is_primitive_call)\n (kernel_mode := MALINIT.kernel_mode)\n ).\n apply MALINIT.exec_load_exec_loadex.\n apply MALINIT.exec_store_exec_storeex.\n apply MALINIT.extcall_not_primitive.\n apply MALINIT.primitive_kernel_mode.\n 3: eassumption.\n assumption.\n assumption.\n 2: eassumption.\n 5: eassumption.\n 9: eassumption.\n 7: reflexivity.\n intros; eapply MALINITCODE.mem_init_correct.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n 2: eassumption. eassumption. assumption.\n assumption.\n (* BEGIN hypotheses coming from refinement proof *)\n eassumption.\n reflexivity.\n (* END hypotheses coming from refinement proof *)\n assumption.\n assumption.\n assumption.\n assumption.\n assumption.\n unfold MALINIT.kernel_mode.\n destruct (MALINIT.INV (Mem.get_abstract_data m0)).\n apply MALINIT.mem_init_eq in H1.\n functional inversion H1.\n functional inversion H10; unfold adt0 in *; auto.\n destruct 1 as [? [? [m_asm [? [INJ [NB [PLUS [? [? [? ?]]]]]]]]]].\n generalize (Mem.put_abstract_data_inject_inside _ _ _ INJ (Mem.get_abstract_data m0)).\n rewrite Mem.put_put_abstract_data.\n rewrite Mem.put_get_abstract_data.\n intro.\n replace (Mem.nextblock m_asm) with (Mem.nextblock (Mem.put_abstract_data m_asm (Mem.get_abstract_data m0))) in NB by (rewrite Mem.nextblock_put_abstract_data; reflexivity).\n replace m_asm with (Mem.put_abstract_data (Mem.put_abstract_data m_asm (Mem.get_abstract_data m0)) labd') in PLUS.\n eauto 11.\n rewrite Mem.put_put_abstract_data.\n replace labd' with (Mem.get_abstract_data m_asm).\n rewrite Mem.put_get_abstract_data.\n reflexivity.\n erewrite <- Mem.get_abstract_data_inject_inside; eauto.\n rewrite Mem.get_put_abstract_data.\n reflexivity.\n Qed.\n\n Theorem transf_program_correct:\n Smallstep.backward_simulation\n (MALOP.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (kern_low:=kern_low) (kern_high:=kern_high) (maxpage:=maxpage) \n (PageFaultHandler_LOC:= PageFaultHandler_LOC) (real_nps:= real_nps) (real_AT:= real_AT) prog) \n (MALINIT.semantics (NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC) (maxpage:= maxpage) \n (real_size:= real_size) (real_mm:= real_mm) tprog).\n Proof.\n eapply ALOPGEN.transf_program_correct; simpl; eauto.\n Grab Existential Variables.\n omega.\n inversion real_params; auto.\n inversion real_params; auto.\n inversion real_params; auto. \n inversion real_params; auto.\n Qed.\n\n End WITHMEM.\n\n End WithProg.\n\n End WithPrimitives.\n\nEnd ALOPGENIMPL.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/ALOpGenImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.13231046140559008}} {"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n Definition destroy_table (llt_gidx: Z) (idx: Z) (rtt_addr: Z) (rtt_gidx: Z) (level: Z) (map_addr: Z) (adt: RData) :=\n let gn_llt := (gs (share adt)) @ llt_gidx in\n let llt_pte := (g_data (gnorm gn_llt)) @ idx in\n rely (g_tag (ginfo gn_llt) =? GRANULE_STATE_TABLE);\n rely (gtype gn_llt =? GRANULE_STATE_TABLE);\n rely is_int64 llt_pte;\n if (__entry_is_table llt_pte) && (rtt_addr =? (Z.land llt_pte ADDRESS_MASK)) then\n rely GRANULE_ALIGNED rtt_addr;\n let adt := adt {share: (share adt) {gs: (gs (share adt)) # llt_gidx == (gn_llt {glock: Some CPU_ID})}} in\n let gn_rtt := (gs (share adt)) @ rtt_gidx in\n rely prop_dec (glock gn_rtt = None);\n rely (g_tag (ginfo gn_rtt) =? GRANULE_STATE_TABLE);\n rely (tbl_level (gaux gn_llt) =? level - 1);\n rely (tbl_level (gaux gn_rtt) =? level);\n let e := EVT CPU_ID (ACQ rtt_gidx) in\n let e' := EVT CPU_ID (REL rtt_gidx (gn_rtt {glock: Some CPU_ID})) in\n rely prop_dec (forall i : ZIndexed.t, is_int64 (g_data (gnorm gn_rtt)) @ i = true);\n let ipa_gidx := __addr_to_gidx map_addr in\n let tlbs' := (fun ipa_state cpu gidx =>\n if ipa_state =? IPA_STATE_PRESENT then\n if (gidx >=? ipa_gidx) && (gidx ? 0);\n let ipa_state :=\n (if prop_dec (exists i : Z, 0 <= i < PGTES_PER_TABLE /\\ PTE_TO_IPA_STATE (g_data (gnorm gn_rtt)) @ i = IPA_STATE_DESTROYED)\n then IPA_STATE_DESTROYED else IPA_STATE_VACANT)\n in\n let llt' := (g_data (gnorm gn_llt)) # idx == (IPA_STATE_TO_PTE ipa_state) in\n let gllt' := gn_llt {ginfo: (ginfo gn_llt) {g_refcount: (g_refcount (ginfo gn_llt)) - 1}}\n {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_tag: GRANULE_STATE_DELEGATED} {g_rd: 0} {g_refcount: 0}}\n {gnorm : zero_granule_data_normal} {grec: zero_granule_data_rec} in\n let e' := EVT CPU_ID (REL rtt_gidx (grtt' {glock: Some CPU_ID})) in\n Some (adt {log: EVT CPU_ID (REL llt_gidx gllt') :: e' :: e :: log adt}\n {share : (share adt) {gs : ((gs (share adt)) # rtt_gidx == (grtt' {gtype: GRANULE_STATE_DELEGATED}))\n # llt_gidx == (gllt' {glock: None})}\n {tlbs: tlbs' ipa_state}},\n VZ64 0)\n else\n if (g_refcount (ginfo gn_rtt)) =? PGTES_PER_TABLE + 1 then\n rely (level =? RTT_PAGE_LEVEL);\n let pgte := (g_data (gnorm gn_rtt)) @ 0 in\n let ipa_state := PTE_TO_IPA_STATE pgte in\n let base_pa' := __entry_to_phys pgte (level - 1) in\n let base_pa := __entry_to_phys pgte level in\n rely is_int64 base_pa;\n rely is_int64 (base_pa + PGTES_PER_TABLE * GRANULE_SIZE);\n rely (__addr_is_level_aligned base_pa (level - 1));\n rely prop_dec (forall i : Z, 0 <= i < PGTES_PER_TABLE ->\n let e := (g_data (gnorm gn_rtt)) @ i in\n let pa := __entry_to_phys e level in\n PTE_TO_IPA_STATE e = ipa_state /\\ pa = base_pa + i * GRANULE_SIZE);\n let new_pgte := (if ipa_state =? IPA_STATE_PRESENT then Z.lor (Z.lor (IPA_STATE_TO_PTE ipa_state) base_pa') PGTE_S2_BLOCK\n else Z.lor (IPA_STATE_TO_PTE ipa_state) base_pa') in\n let llt' := (g_data (gnorm gn_llt)) # idx == new_pgte in\n let gllt' := gn_llt {gnorm: (gnorm gn_llt) {g_data: llt'}} {glock: None} in\n let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_tag: GRANULE_STATE_DELEGATED} {g_rd: 0} {g_refcount: 0}}\n {gnorm : zero_granule_data_normal} {grec: zero_granule_data_rec} in\n let e' := EVT CPU_ID (REL rtt_gidx (grtt' {glock: Some CPU_ID})) in\n Some (adt {log: EVT CPU_ID (REL llt_gidx gllt') :: e' :: e :: log adt}\n {share : (share adt) {gs : ((gs (share adt)) # rtt_gidx == (grtt' {gtype: GRANULE_STATE_DELEGATED}))\n # llt_gidx == gllt'}\n {tlbs: tlbs' ipa_state}},\n VZ64 0)\n else None\n else Some (adt {log: EVT CPU_ID (REL llt_gidx gn_llt {glock: Some CPU_ID}) :: log adt}, VZ64 1).\n\n\n Definition table_destroy3_spec (g_rd: Pointer) (map_addr: Z64) (rtt_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n match map_addr, level, rtt_addr with\n | VZ64 map_addr, VZ64 level, VZ64 rtt_addr =>\n rely is_int64 map_addr; rely is_int64 rtt_addr; rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n let idx0 := __addr_to_idx map_addr 0 in\n let idx1 := __addr_to_idx map_addr 1 in\n let idx2 := __addr_to_idx map_addr 2 in\n let idx3 := __addr_to_idx map_addr 3 in\n let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n rely is_int64 idx0; rely is_int64 idx1; rely is_int64 idx2; rely is_int64 idx3;\n let rtt_gidx := __addr_to_gidx rtt_addr in\n rely is_gidx rtt_gidx;\n rely (peq (base g_rd) ginfo_loc);\n rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_RTT2 = None);\n let rd_gidx := (offset g_rd) in\n let grd := (gs (share adt)) @ rd_gidx in\n rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n rely prop_dec (glock grd = Some CPU_ID);\n let root_gidx := (g_rtt (gnorm grd)) in\n rely is_gidx rd_gidx;\n when adt == query_oracle adt;\n (* hold root lock *)\n rely is_gidx root_gidx;\n let groot := (gs (share adt)) @ root_gidx in\n rely (tbl_level (gaux groot) =? 0);\n rely prop_dec (glock groot = None);\n rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n rely (gtype groot =? GRANULE_STATE_TABLE);\n if level =? 1 then\n (* walk until root *)\n let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n let adt := adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n destroy_table root_gidx idx0 rtt_addr rtt_gidx 1 map_addr adt\n else\n (* walk deeper root *)\n rely (level >? 1);\n let entry0 := (g_data (gnorm groot)) @ idx0 in\n rely is_int64 entry0;\n let phys0 := __entry_to_phys entry0 3 in\n let lv1_gidx := __addr_to_gidx phys0 in\n rely is_int64 phys0;\n if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n (* level 1 valid, hold level 1 lock *)\n let glv1 := (gs (share adt)) @ lv1_gidx in\n rely prop_dec (glock glv1 = None);\n rely (tbl_level (gaux glv1) =? 1);\n if level =? 2 then\n (* walk until level 1 *)\n let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n let adt := adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n destroy_table lv1_gidx idx1 rtt_addr rtt_gidx 2 map_addr adt\n else\n (* walk deeper level 1 *)\n rely (level >? 2);\n rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n rely (gtype glv1 =? GRANULE_STATE_TABLE);\n let entry1 := (g_data (gnorm glv1)) @ idx1 in\n rely is_int64 entry1;\n let phys1 := __entry_to_phys entry1 3 in\n let lv2_gidx := __addr_to_gidx phys1 in\n rely is_int64 phys1;\n if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n (* level 2 valid, hold level 2 lock *)\n let glv2 := (gs (share adt)) @ lv2_gidx in\n rely (tbl_level (gaux glv2) =? 2);\n rely prop_dec (glock glv2 = None);\n if level =? 3 then\n (* walk until level 2 *)\n let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n let adt := adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n destroy_table lv2_gidx idx2 rtt_addr rtt_gidx 3 map_addr adt\n else None\n else\n (* level 2 invalid *)\n rely is_int lv2_gidx;\n Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n else\n (* level 1 invalid *)\n rely is_int lv1_gidx;\n Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n end.\n\nEnd Spec.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/Specs/table_destroy3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2598256322295121, "lm_q1q2_score": 0.13194253868999148}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of VMM *)\n(* *)\n(* Refinement Proof for PQueueInit *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between PQueueIntro layer and PQueueInit layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\nRequire Import LAsmModuleSemAux.\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import PThreadSched.\nRequire Import PThread.\nRequire Import ThreadGenSpec.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n Local Open Scope string_scope.\n Local Open Scope error_monad_scope.\n Local Open Scope Z_scope.\n\n Context `{real_params: RealParams}.\n \n Notation HDATA := RData.\n Notation LDATA := RData.\n\n Notation HDATAOps := (cdata (cdata_ops := pthread_data_ops) HDATA).\n Notation LDATAOps := (cdata (cdata_ops := pthreadsched_data_ops) LDATA).\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** Relation between raw data at two layers*)\n Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n mkrelate_RData {\n flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n devout_re: devout hadt = devout ladt;\n CR3_re: CR3 hadt = CR3 ladt;\n ikern_re: ikern hadt = ikern ladt;\n pg_re: pg hadt = pg ladt;\n ihost_re: ihost hadt = ihost ladt;\n AC_re: AC hadt = AC ladt;\n ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n LAT_re: LAT hadt = LAT ladt;\n nps_re: nps hadt = nps ladt;\n init_re: init hadt = init ladt;\n\n pperm_re: pperm hadt = pperm ladt;\n PT_re: PT hadt = PT ladt;\n ptp_re: ptpool hadt = ptpool ladt;\n idpde_re: idpde hadt = idpde ladt;\n ipt_re: ipt hadt = ipt ladt;\n smspool_re: smspool hadt = smspool ladt;\n\n kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n abtcb_re: abtcb hadt = abtcb ladt;\n abq_re: abq hadt = abq ladt;\n cid_re: cid hadt = cid ladt\n }.\n\n Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n | MATCH_RDATA: forall habd m f s, match_RData s habd m f. \n\n Local Hint Resolve MATCH_RDATA.\n\n Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n {\n relate_AbData s f d1 d2 := relate_RData f d1 d2;\n match_AbData s d1 m f := match_RData s d1 m f;\n new_glbl := nil\n }. \n\n (** ** Properties of relations*)\n Section Rel_Property.\n\n (** Prove that after taking one step, the refinement relation still holds*) \n Lemma relate_incr: \n forall abd abd' f f',\n relate_RData f abd abd'\n -> inject_incr f f'\n -> relate_RData f' abd abd'.\n Proof.\n inversion 1; subst; intros; inv H; constructor; eauto.\n - eapply kctxt_inj_incr; eauto.\n Qed.\n\n Lemma relate_kernel_mode:\n forall abd abd' f,\n relate_RData f abd abd' \n -> (kernel_mode abd <-> kernel_mode abd').\n Proof.\n inversion 1; simpl; split; congruence.\n Qed.\n\n Lemma relate_observe:\n forall p abd abd' f,\n relate_RData f abd abd' ->\n observe p abd = observe p abd'.\n Proof.\n inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n Qed.\n\n Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n Proof.\n constructor; intros; simpl; trivial.\n eapply relate_incr; eauto.\n eapply relate_kernel_mode; eauto.\n eapply relate_observe; eauto.\n Qed.\n\n End Rel_Property.\n\n (** * Proofs the one-step forward simulations for the low level specifications*)\n Section OneStep_Forward_Relation.\n\n (** ** The low level specifications exist*)\n Section Exists.\n\n Lemma thread_yield_exist:\n forall habd habd' labd rs r' rs0 f,\n ObjThread.thread_yield_spec \n habd (Pregmap.init Vundef)#ESP <- (rs#ESP)#EDI <- (rs#EDI)#ESI <- (rs#ESI)\n #EBX <- (rs#EBX)#EBP <- (rs#EBP)#RA <- (rs#RA) = Some (habd', rs0)\n -> relate_RData f habd labd\n -> high_level_invariant habd\n -> (forall reg : PregEq.t,\n val_inject f (Pregmap.get reg rs) (Pregmap.get reg r'))\n -> exists labd' r'0, thread_yield_spec\n labd (Pregmap.init Vundef)#ESP <- (r'#ESP)#EDI <- (r'#EDI)#ESI <- (r'#ESI)\n #EBX <- (r'#EBX)#EBP <- (r'#EBP)#RA <- (r'#RA) = Some (labd', r'0)\n /\\ relate_RData f habd' labd'\n /\\ (forall i r,\n ZtoPreg i = Some r -> val_inject f (rs0#r) (r'0#r)).\n Proof.\n Opaque remove.\n unfold ObjThread.thread_yield_spec, thread_yield_spec; intros until f.\n intros HP HR HINV HVL; pose proof HR as HR'; inv HR; revert HP.\n specialize (valid_TDQ _ HINV). \n specialize (correct_curid _ HINV). \n simpl; subrewrite'; intros Hcid' Hlast HQ. \n destruct (pg labd); contra_inv.\n destruct (Hcid' refl_equal) as [_ Hcid].\n rewrite Hcid.\n assert (HOS: 0<= num_chan <= num_chan) by omega.\n specialize (Hlast refl_equal _ HOS). \n subdestruct; contra_inv; simpl.\n inv HQ. refine_split'; eauto 1.\n - inv HR'. econstructor; eauto 1.\n simpl; kctxt_inj_simpl.\n - unfold kctxt_inj, Pregmap.get in *. \n intros. eapply kctxt_re0; eauto. \n destruct Hlast as [l0[HT Hlast]]. inv HT.\n apply Hlast. apply last_correct; auto.\n Qed.\n\n Lemma thread_sleep_exist:\n forall habd habd' labd rs r' rs0 n f,\n ObjThread.thread_sleep_spec \n habd (Pregmap.init Vundef)#ESP <- (rs#ESP)#EDI <- (rs#EDI)#ESI <- (rs#ESI)\n #EBX <- (rs#EBX)#EBP <- (rs#EBP)#RA <- (rs#RA) n = Some (habd', rs0)\n -> relate_RData f habd labd\n -> high_level_invariant habd\n -> (forall reg : PregEq.t,\n val_inject f (Pregmap.get reg rs) (Pregmap.get reg r'))\n -> exists labd' r'0, thread_sleep_spec \n labd (Pregmap.init Vundef)#ESP <- (r'#ESP)#EDI <- (r'#EDI)#ESI <- (r'#ESI)\n #EBX <- (r'#EBX)#EBP <- (r'#EBP)#RA <- (r'#RA) n = Some (labd', r'0)\n /\\ relate_RData f habd' labd'\n /\\ (forall i r,\n ZtoPreg i = Some r -> val_inject f (rs0#r) (r'0#r)).\n Proof.\n Opaque remove.\n unfold ObjThread.thread_sleep_spec, thread_sleep_spec; intros until f.\n intros HP HR HINV HVL; pose proof HR as HR'; inv HR; revert HP.\n specialize (valid_TDQ _ HINV); unfold AbQCorrect. \n specialize (correct_curid _ HINV). \n simpl; subrewrite'; intros Hcid' Hlast HQ.\n destruct (pg labd); contra_inv.\n destruct (Hcid' refl_equal) as [_ Hcid].\n rewrite Hcid.\n assert (HOS: 0<= num_chan <= num_chan) by omega.\n specialize (Hlast refl_equal _ HOS).\n subdestruct; simpl.\n inv HQ. refine_split'; eauto 1.\n - inv HR'. econstructor; simpl; eauto 2.\n kctxt_inj_simpl.\n - unfold kctxt_inj, Pregmap.get in *. \n intros. eapply kctxt_re0; eauto. \n destruct Hlast as [l0'[HT Hlast]]. inv HT.\n apply Hlast. apply last_correct; auto.\n Qed.\n\n End Exists.\n\n Section FRESH_PRIM.\n\n Lemma thread_yield_spec_ref:\n compatsim (crel HDATA LDATA) \n (primcall_thread_schedule_compatsem ObjThread.thread_yield_spec (prim_ident:= thread_yield)) \n thread_yield_spec_low.\n Proof. \n compatsim_simpl (@match_AbData).\n inv match_extcall_states.\n exploit thread_yield_exist; eauto 1.\n intros [labd' [r'0[HP [HM HReg]]]].\n refine_split; try econstructor; eauto. \n eapply reg_symbol_inject; eassumption.\n econstructor; eauto. constructor.\n subst rs3.\n val_inject_simpl; eapply HReg;\n apply PregToZ_correct; reflexivity.\n Qed.\n \n Lemma thread_sleep_spec_ref:\n compatsim (crel HDATA LDATA) \n (primcall_thread_transfer_compatsem ObjThread.thread_sleep_spec) \n thread_sleep_spec_low.\n Proof. \n compatsim_simpl (@match_AbData).\n inv match_extcall_states.\n exploit thread_sleep_exist; eauto 1.\n intros [labd' [r'0[HP [HM HReg]]]].\n refine_split; try econstructor; eauto. \n - eapply reg_symbol_inject; eassumption.\n - exploit (extcall_args_inject (D1:= HDATAOps) (D2:= LDATAOps)); eauto.\n instantiate (3:= d1').\n apply extcall_args_with_data; eauto.\n instantiate (1:= d2).\n intros [?[? Hinv]]. inv_val_inject.\n apply extcall_args_without_data in H; eauto.\n - econstructor; eauto. constructor.\n - subst rs3.\n val_inject_simpl; \n eapply HReg; apply PregToZ_correct; reflexivity.\n Qed.\n\n End FRESH_PRIM.\n\n Section PASSTHROUGH_PRIM.\n\n Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n Proof.\n accessor_prop_tac.\n - eapply flatmem_store_exists; eauto.\n Qed. \n\n Lemma passthrough_correct:\n sim (crel HDATA LDATA) pthread_passthrough pthreadsched.\n Proof.\n sim_oplus.\n - apply fload_sim.\n - apply fstore_sim.\n - apply flatmem_copy_sim.\n - apply vmxinfo_get_sim.\n - apply device_output_sim.\n - apply pfree_sim.\n - apply setPT_sim.\n - apply ptRead_sim. \n - apply ptResv_sim.\n - apply shared_mem_status_sim.\n - apply offer_shared_mem_sim.\n - apply get_state0_sim.\n - apply get_curid_sim.\n - apply thread_spawn_sim.\n - apply thread_wakeup_sim.\n - apply sched_init_sim.\n - apply ptin_sim.\n - apply ptout_sim.\n - apply container_get_nchildren_sim.\n - apply container_get_quota_sim.\n - apply container_get_usage_sim.\n - apply container_can_consume_sim.\n - apply alloc_sim. \n - apply trapin_sim.\n - apply trapout_sim.\n - apply hostin_sim.\n - apply hostout_sim.\n - apply trap_info_get_sim.\n - apply trap_info_ret_sim.\n - layer_sim_simpl.\n + eapply load_correct2.\n + eapply store_correct2.\n Qed.\n\n End PASSTHROUGH_PRIM.\n\n End OneStep_Forward_Relation.\n\n End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/ThreadGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.2538610126142736, "lm_q1q2_score": 0.13188621264252193}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Proof of functional correctness *)\n(* for the C functions implemented in the MBoot layer *)\n(* *)\n(* Xiongnan (Newman) Wu *)\n(* *)\n(* Yale University *)\n(* *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import MemWithData.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import LAsm.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import MBoot.\nRequire Import ZArith.Zwf.\nRequire Import VCGen.\nRequire Import RealParams.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import ALInitGenSpec.\nRequire Import MBootCSource.\nRequire Import TacticsForTesting.\n\nRequire Import AbstractDataType.\n\nGlobal Opaque compatdata_layerdata ldata_type.\n\nModule MBOOTCODE.\n\n Section WithPrimitives.\n\n Context `{real_params_ops : RealParamsOps}.\n Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n Context `{Hmwd: UseMemWithData memb}.\n\n Let mem := mwd (cdata RData).\n\n Context `{Hstencil: Stencil}.\n Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n Opaque PTree.get PTree.set.\n\n Local Open Scope Z_scope.\n\n Section GetNps.\n\n Let L: compatlayer (cdata RData) := NPS_LOC ↦ nps_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section GetNpsBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (s: stencil).\n\n Variables (ge: genv) (bnps_loc: block).\n\n Hypothesis hnps_loc1 : Genv.find_symbol ge NPS_LOC = Some bnps_loc.\n\n Lemma get_nps_body_correct: forall m d env le nps,\n env = PTree.empty _ ->\n Mem.loadv Mint32 (m, d) (Vptr bnps_loc Int.zero) = Some (Vint nps) ->\n exec_stmt ge env le (m, d) get_nps_body E0 le (m, d) (Out_return (Some (Vint nps, tint))).\n Proof.\n intros; subst.\n repeat vcgen.\n Qed.\n\n End GetNpsBody.\n\n Theorem get_nps_code_correct: \n spec_le (get_nps ↦ get_nps_spec_low) (〚get_nps ↦ f_get_nps〛 L).\n Proof.\n fbigstep_pre L.\n fbigstep (get_nps_body_correct (Genv.globalenv p) b0 H (fst m') (snd m')) m'.\n Qed. \n\n End GetNps.\n\n Section SetNps.\n\n Let L: compatlayer (cdata RData) := NPS_LOC ↦ nps_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section SetNpsBody.\n\n Context `{Hwb: WritableBlockAllowGlobals}.\n\n Variables (ge: genv) (bnps_loc: block).\n\n Hypothesis hnps_loc1 : Genv.find_symbol ge NPS_LOC = Some bnps_loc.\n\n Lemma set_nps_body_correct: forall m m' d env le nps,\n env = PTree.empty _ ->\n PTree.get tnewnps le = Some (Vint nps) ->\n Mem.store Mint32 (m, d) bnps_loc 0 (Vint nps) = Some (m', d) ->\n exec_stmt ge env le (m, d) set_nps_body E0 le (m', d) Out_normal\n .\n Proof.\n intros; subst.\n repeat vcgen.\n Qed.\n\n End SetNpsBody.\n\n Theorem set_nps_correct: \n spec_le (set_nps ↦ set_nps_spec_low) (〚set_nps ↦ f_set_nps 〛L).\n Proof.\n fbigstep_pre L. destruct H0 as [H0 Heq].\n fbigstep (set_nps_body_correct (Genv.globalenv p) b0 H (fst m) (fst m') (snd m) (PTree.empty _) \n (bind_parameter_temps' (fn_params f_set_nps)\n (Vint n::nil)\n (create_undef_temps (fn_temps f_set_nps)))) m.\n destruct m'; simpl in *. congruence.\n Qed.\n\n End SetNps.\n\n\n Section IsNorm.\n\n Lemma structsize: sizeof t_struct_A = 12.\n Proof.\n generalize max_unsigned_val; intro muval.\n simpl.\n unfold align; simpl.\n trivial.\n Qed.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section IsNormBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma is_norm_body_correct: forall m d env le index isnorm isnorm',\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n Mem.load Mint32 m bat_loc (Int.unsigned index * 12) = Some (Vint isnorm) ->\n Int.unsigned isnorm' = ZToATTypeZ (Int.unsigned isnorm) ->\n PTree.get tisnorm le = Some Vundef ->\n PTree.get tis_norm_index le = Some (Vint index) ->\n exists le',\n exec_stmt ge env le (m, d) is_norm_body E0 le' (m, d) (Out_return (Some (Vint isnorm', tint)))\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros.\n unfold is_norm_body.\n subst.\n unfold ZToATTypeZ in H2.\n\n assert(isnormcase: Int.unsigned isnorm = 0 \\/ Int.unsigned isnorm <> 0) by omega.\n Caseeq isnormcase.\n\n (* isnorm = 0 *)\n intro veq0.\n destruct (zeq (Int.unsigned isnorm) 0); try omega.\n change 0 with (Int.unsigned Int.zero) in e.\n change 0 with (Int.unsigned Int.zero) in H2.\n apply unsigned_inj in H2.\n apply unsigned_inj in e.\n subst.\n esplit.\n clear H3.\n repeat vcgen.\n unfold Mem.loadv.\n rewrite Z.add_0_r.\n rewrite Z.mul_comm.\n rewrite stsize.\n rewrite Z.add_0_l.\n rewrite Int.unsigned_repr; try omega.\n eassumption.\n discharge_cmp.\n discharge_cmp.\n repeat vcgen.\n rewrite PTree.gss; reflexivity.\n\n (* isnorm <> 0 *)\n intro vneq0.\n destruct (zeq (Int.unsigned isnorm) 0); try omega.\n assert(isnormcase2: Int.unsigned isnorm = 1 \\/ Int.unsigned isnorm <> 1) by omega.\n Caseeq isnormcase2.\n\n (* isnorm = 1 *)\n intro veq1.\n destruct (zeq (Int.unsigned isnorm) 1); try omega.\n change 0 with (Int.unsigned Int.zero) in H2.\n apply unsigned_inj in H2.\n subst.\n esplit.\n repeat vcgen.\n rewrite Z.add_0_r.\n rewrite Z.mul_comm.\n rewrite stsize.\n rewrite Z.add_0_l.\n unfold Mem.loadv.\n rewrite Int.unsigned_repr; try omega.\n eassumption.\n discharge_cmp.\n discharge_cmp.\n repeat vcgen.\n rewrite PTree.gss; reflexivity.\n (* isnorm <> 1 *)\n intro vneq1.\n destruct (zeq (Int.unsigned isnorm) 1); try omega.\n change 1 with (Int.unsigned Int.one) in H2.\n apply unsigned_inj in H2.\n subst.\n esplit.\n repeat vcgen.\n rewrite Z.add_0_r.\n rewrite Z.mul_comm.\n rewrite stsize.\n rewrite Z.add_0_l.\n unfold Mem.loadv.\n rewrite Int.unsigned_repr; try omega.\n eassumption.\n discharge_cmp.\n discharge_cmp.\n repeat vcgen.\n rewrite PTree.gss; reflexivity.\n Qed.\n\n End IsNormBody.\n\n Theorem is_norm_code_correct:\n spec_le (is_norm ↦ is_norm_spec_low) (〚is_norm ↦ f_is_norm 〛L).\n Proof.\n fbigstep_pre L.\n fbigstep (is_norm_body_correct (Genv.globalenv p) b0 H (fst m') (snd m') (PTree.empty _) (bind_parameter_temps' (fn_params f_is_norm)\n (Vint n::nil)\n (create_undef_temps (fn_temps f_is_norm)))) m'.\n Qed.\n\n End IsNorm.\n\n Section SetNorm.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section SetNormBody.\n\n Context `{Hwb: WritableBlockAllowGlobals}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma set_norm_body_correct: forall m m' m'' m''' d env le index normval,\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n PTree.get tset_norm_index le = Some (Vint index) ->\n PTree.get tnorm_val le = Some (Vint normval) ->\n Mem.store Mint32 (m, d) bat_loc (Int.unsigned (Int.repr (Int.unsigned index * 12))) (Vint normval) = Some (m', d) ->\n Mem.store Mint32 (m', d) bat_loc (Int.unsigned (Int.repr (Int.unsigned index * 12 + 4))) (Vint (Int.zero)) = Some (m'', d) ->\n Mem.store Mint32 (m'', d) bat_loc (Int.unsigned (Int.repr (Int.unsigned index * 12 + 8))) (Vint (Int.zero)) = Some (m''', d) ->\n exec_stmt ge env le (m, d) set_norm_body E0 le (m''', d) Out_normal\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros.\n subst.\n unfold set_norm_body.\n repeat vcgen.\n rewrite Z.add_0_r.\n rewrite Z.mul_comm.\n eassumption.\n rewrite Z.mul_comm.\n eassumption.\n rewrite Z.mul_comm.\n eassumption.\n Qed.\n\n End SetNormBody.\n\n Theorem set_norm_correct: \n spec_le (set_norm ↦ set_norm_spec_low) (〚set_norm ↦ f_set_norm 〛L).\n Proof.\n fbigstep_pre L. destruct H0 as [H0 Heq0]. destruct H1 as [H1 Heq1].\n destruct H2.\n fbigstep (set_norm_body_correct (Genv.globalenv p) b0 H (fst m) (fst m0) (fst m1) (fst m')\n (snd m) (PTree.empty _) (bind_parameter_temps' (fn_params f_set_norm)\n (Vint n::Vint v::nil)\n (create_undef_temps (fn_temps f_set_norm)))) m; eauto.\n destruct m'; simpl in *. congruence. \n Qed.\n\n End SetNorm.\n\n\n Section AtGet.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section ATGetBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma at_get_body_correct: forall m d env le index allocated v,\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n Mem.loadv Mint32 (m, d) (Vptr bat_loc (Int.repr ((Int.unsigned index) * 12 + 4))) = Some (Vint v) ->\n Int.unsigned allocated = IntToBoolZ v ->\n PTree.get tallocated le = Some Vundef ->\n PTree.get tat_get_index le = Some (Vint index) ->\n exists le',\n exec_stmt ge env le (m, d) at_get_body E0 le' (m, d) (Out_return (Some (Vint allocated, tint)))\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros.\n unfold at_get_body.\n subst.\n unfold IntToBoolZ in H2.\n unfold Int.eq in H2.\n change (Int.unsigned Int.zero) with 0 in H2.\n\n assert(isnormcase: Int.unsigned v = 0 \\/ Int.unsigned v <> 0) by omega.\n Caseeq isnormcase.\n\n (* isnorm = 0 *)\n intro veq0.\n destruct (zeq (Int.unsigned v) 0); try omega.\n change 0 with (Int.unsigned Int.zero) in H2, e.\n apply unsigned_inj in H2.\n apply unsigned_inj in e.\n subst.\n esplit.\n repeat vcgen.\n rewrite Z.mul_comm.\n eassumption.\n discharge_cmp.\n discharge_cmp.\n repeat vcgen.\n rewrite PTree.gss; reflexivity.\n\n (* isnorm <> 0 *)\n intro vneq0.\n destruct (zeq (Int.unsigned v) 0); try omega.\n change 1 with (Int.unsigned Int.one) in H2.\n apply unsigned_inj in H2.\n subst.\n esplit.\n repeat vcgen.\n rewrite Z.mul_comm.\n eassumption.\n discharge_cmp.\n discharge_cmp.\n repeat vcgen.\n rewrite PTree.gss; reflexivity.\n Qed.\n\n End ATGetBody.\n\n Theorem at_get_code_correct:\n spec_le (at_get ↦ at_get_spec_low) (〚at_get ↦ f_at_get 〛L).\n Proof.\n fbigstep_pre L.\n fbigstep (at_get_body_correct (Genv.globalenv p) b0 H (fst m') (snd m') (PTree.empty _) (bind_parameter_temps' (fn_params f_at_get)\n (Vint n::nil)\n (create_undef_temps (fn_temps f_at_get)))) m'.\n Qed.\n\n End AtGet.\n\n Section AtSet.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section ATSetBody.\n\n Context `{Hwb: WritableBlockAllowGlobals}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma at_set_body_correct: forall m m' d env le index allocatedval,\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n PTree.get tat_set_index le = Some (Vint index) ->\n PTree.get tallocated_val le = Some (Vint allocatedval) ->\n Mem.store Mint32 (m, d) bat_loc (Int.unsigned (Int.repr (Int.unsigned index * 12 + 4))) (Vint allocatedval) = Some (m', d) ->\n exec_stmt ge env le (m, d) at_set_body E0 le (m', d) Out_normal\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros; subst.\n repeat vcgen.\n rewrite Z.mul_comm.\n eassumption.\n Qed.\n\n End ATSetBody.\n\n Theorem at_set_code_correct:\n spec_le (at_set ↦ at_set_spec_low) (〚at_set ↦ f_at_set 〛L).\n Proof.\n fbigstep_pre L. destruct H0 as [H0 Heq].\n fbigstep (at_set_body_correct (Genv.globalenv p) b0 H (fst m) (fst m') (snd m) (PTree.empty _) (bind_parameter_temps' (fn_params f_at_set)\n (Vint n::Vint v::nil)\n (create_undef_temps (fn_temps f_at_set)))) m.\n destruct m'; simpl in *. congruence.\n Qed.\n\n End AtSet.\n\n\n Section AtGetC.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section ATGetCBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma at_get_c_body_correct: forall m d env le index c,\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n Mem.loadv Mint32 (m, d) (Vptr bat_loc (Int.repr ((Int.unsigned index) * 12 + 8))) = Some (Vint c) ->\n PTree.get tat_get_c_index le = Some (Vint index) ->\n exists le',\n exec_stmt ge env le (m, d) at_get_c_body E0 le' (m, d) (Out_return (Some (Vint c, tint)))\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros.\n unfold at_get_c_body.\n subst.\n unfold IntToBoolZ in H2.\n unfold Int.eq in H2.\n change (Int.unsigned Int.zero) with 0 in H2.\n esplit.\n repeat vcgen.\n rewrite stsize.\n rewrite Z.mul_comm.\n assumption.\n Qed.\n\n End ATGetCBody.\n\n Theorem at_get_c_code_correct:\n spec_le (at_get_c ↦ at_get_c_spec_low) (〚at_get_c ↦ f_at_get_c 〛L).\n Proof.\n fbigstep_pre L.\n fbigstep (at_get_c_body_correct (Genv.globalenv p) b0 H (fst m') (snd m') (PTree.empty _) (bind_parameter_temps' (fn_params f_at_get_c)\n (Vint n::nil)\n (create_undef_temps (fn_temps f_at_get_c)))) m'.\n Qed.\n\n End AtGetC.\n\n Section AtSetC.\n\n Let L: compatlayer (cdata RData) := AT_LOC ↦ at_loc_type.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section ATSetCBody.\n\n Context `{Hwb: WritableBlockAllowGlobals}.\n\n Variable (s: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches s ge).\n\n Variable (bat_loc: block).\n\n Hypothesis hat_loc : Genv.find_symbol ge AT_LOC = Some bat_loc.\n\n Lemma at_set_c_body_correct: forall m m' d env le index cval,\n env = PTree.empty _ ->\n 0 <= (Int.unsigned index) < maxpage ->\n PTree.get tat_set_c_index le = Some (Vint index) ->\n PTree.get tc_val le = Some (Vint cval) ->\n Mem.store Mint32 (m, d) bat_loc (Int.unsigned (Int.repr (Int.unsigned index * 12 + 8))) (Vint cval) = Some (m', d) ->\n exec_stmt ge env le (m, d) at_set_c_body E0 le (m', d) Out_normal\n .\n Proof.\n generalize max_unsigned_val; intro muval.\n generalize structsize; intro stsize.\n intros; subst.\n repeat vcgen.\n rewrite Z.mul_comm.\n eassumption.\n Qed.\n\n End ATSetCBody.\n\n Theorem at_set_c_code_correct:\n spec_le (at_set_c ↦ at_set_c_spec_low) (〚at_set_c ↦ f_at_set_c 〛L).\n Proof.\n fbigstep_pre L. destruct H0 as [H0 Heq].\n fbigstep (at_set_c_body_correct (Genv.globalenv p) b0 H (fst m) (fst m') (snd m) (PTree.empty _) (bind_parameter_temps' (fn_params f_at_set_c)\n (Vint n::Vint v::nil)\n (create_undef_temps (fn_temps f_at_set_c)))) m.\n destruct m'; simpl in *. congruence.\n Qed.\n\n End AtSetC.\n\n\n End WithPrimitives.\n\nEnd MBOOTCODE.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MBootCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.13188620593275366}} {"text": "Require Import PeanoNat Lia List ListSupport.\nRequire Import Common FMap.\nRequire Import Syntax Semantics SemFacts StepM Invariant Serial.\nRequire Import Reduction Commutativity QuasiSeq Topology.\nRequire Import RqRsTopo RqRsFacts.\n\nSet Implicit Arguments.\n\nOpen Scope list.\nOpen Scope fmap.\n\nSection FootprintInv.\n Context `{dv: DecValue} `{oifc: OStateIfc}.\n Variables (dtr: DTree)\n (sys: System).\n\n Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n (Hitr: GoodRqRsSys dtr sys).\n\n Definition FootprintUpOkEx (oidx: IdxT) (rqi: RqInfo Msg) :=\n exists rrFrom rqTo rsFrom,\n rqi.(rqi_rss) = [(rsFrom, None)] /\\\n rqi.(rqi_midx_rsb) = (rrFrom >>= (fun rrFrom => Some (snd rrFrom))) /\\\n FootprintUpOk dtr oidx rrFrom rqTo rsFrom.\n\n Definition FootprintDownOkEx (oidx: IdxT) (rqi: RqInfo Msg) :=\n exists rrFrom rqTos rssFrom,\n rqi.(rqi_rss) = rssFrom /\\\n rqi.(rqi_midx_rsb) = (rrFrom >>= (fun rrFrom => Some (snd rrFrom))) /\\\n (FootprintUpDownOk dtr sys oidx rrFrom rqTos rssFrom \\/\n (rrFrom >>=[False] (fun rrFrom => FootprintDownDownOk\n dtr oidx (fst rrFrom) rqTos rssFrom (snd rrFrom)))).\n\n Definition FootprintsOkORqs (orqs: ORqs Msg) :=\n forall oidx,\n orqs@[oidx] >>=[True]\n (fun orq =>\n (orq@[upRq] >>=[True] (fun rqiu => FootprintUpOkEx oidx rqiu)) /\\\n (orq@[downRq] >>=[True] (fun rqid => FootprintDownOkEx oidx rqid))).\n\n Lemma footprints_ok_orqs_add:\n forall orqs,\n FootprintsOkORqs orqs ->\n forall oidx norq,\n norq@[upRq] >>=[True] (fun rqiu => FootprintUpOkEx oidx rqiu) ->\n norq@[downRq] >>=[True] (fun rqid => FootprintDownOkEx oidx rqid) ->\n FootprintsOkORqs (orqs +[oidx <- norq]).\n Proof.\n unfold FootprintsOkORqs; intros.\n mred; simpl; intros; auto.\n Qed.\n\n Definition FootprintsOk (st: State) :=\n FootprintsOkORqs st.(st_orqs).\n\n Ltac disc_rule_custom ::=\n repeat\n match goal with\n | [H1: FootprintsOkORqs ?orqs, H2: ?orqs @[?oidx] = _ |- _] =>\n let Hf := fresh \"H\" in\n pose proof (H1 oidx) as Hf;\n rewrite H2 in Hf; simpl in Hf; dest;\n clear H2\n end.\n\n Lemma footprints_ok_init:\n InvInit sys FootprintsOk.\n Proof.\n intros; do 3 red.\n intros; simpl; mred.\n specialize (Hiorqs oidx); simpl in Hiorqs.\n destruct ((sys_orqs_inits sys)@[oidx]) as [orq|]; simpl in *; auto.\n subst; mred; simpl; auto.\n Qed.\n\n Lemma footprints_ok_step:\n InvStep sys step_m FootprintsOk.\n Proof.\n red; intros.\n red in H0; red.\n inv H1; try assumption.\n\n simpl in *.\n good_rqrs_rule_get rule.\n good_rqrs_rule_cases rule.\n\n - disc_rule_conds.\n + apply footprints_ok_orqs_add; auto; try (mred; fail).\n + apply footprints_ok_orqs_add; auto; try (mred; fail).\n - disc_rule_conds.\n apply footprints_ok_orqs_add; auto; try (mred; fail).\n - disc_rule_conds.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n red in H33; simpl in H33; dest.\n eexists None, _, _; repeat split; eassumption.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n red in H33; simpl in H33; dest.\n eexists (Some (rqFrom, rsbTo)), _, _; repeat split; try eassumption.\n simpl; eauto.\n + apply footprints_ok_orqs_add; disc_rule_conds.\n eexists None, _, _; repeat split; try eassumption.\n left; eassumption.\n + apply footprints_ok_orqs_add; disc_rule_conds.\n eexists (Some (rqFrom, rsbTo)), _, _; repeat split; try eassumption.\n left; eassumption.\n + apply footprints_ok_orqs_add; disc_rule_conds.\n eexists (Some (rqFrom, rsbTo)), _, _; repeat split; try eassumption.\n right; eassumption.\n - disc_rule_conds.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n + apply footprints_ok_orqs_add; disc_rule_conds; auto.\n - disc_rule_conds.\n apply footprints_ok_orqs_add; disc_rule_conds; auto.\n eexists (Some (rqOrig, rsbTo)), _, _; repeat split; try eassumption.\n left; eassumption.\n Qed.\n\n Lemma footprints_ok:\n InvReachable sys step_m FootprintsOk.\n Proof.\n eapply inv_reachable.\n - typeclasses eauto.\n - apply footprints_ok_init.\n - apply footprints_ok_step.\n Qed.\n\nEnd FootprintInv.\n\nLtac good_footprint_get oidx :=\n match goal with\n | [Hfpok: FootprintsOk _ _ _, Ho: _@[oidx] = Some _ |- _] =>\n let H := fresh \"H\" in\n pose proof Hfpok as H;\n specialize (H oidx); simpl in H; mred; dest\n end.\n\nLtac disc_footprints_ok :=\n match goal with\n | [H: FootprintUpOkEx _ _ _ |- _] =>\n let rrFrom := fresh \"rrFrom\" in\n let rqTo := fresh \"rqTo\" in\n let rsFrom := fresh \"rsFrom\" in\n destruct H as [rrFrom [rqTo [rsFrom ?]]]; dest\n | [H: FootprintDownOkEx _ _ _ _ |- _] =>\n let rrFrom := fresh \"rrFrom\" in\n let rqTos := fresh \"rqTos\" in\n let rssFrom := fresh \"rssFrom\" in\n destruct H as [rrFrom [rqTos [rssFrom ?]]]; dest\n | [H: Some _ = (?rrFrom) >>= _ |- _] =>\n let rqFrom := fresh \"rqFrom\" in\n let rsbTo := fresh \"rsbTo\" in\n destruct rrFrom as [[rqFrom rsbTo]|]; [|discriminate]; simpl in *; dest\n | [H: None = (?rrFrom) >>= _ |- _] =>\n destruct rrFrom; [discriminate|]; simpl in *\n | [H: (?rrFrom) >>=[False] _ |- _] =>\n match type of rrFrom with\n | option (IdxT * IdxT) =>\n let rqFrom := fresh \"rqFrom\" in\n let rsbTo := fresh \"rsbTo\" in\n destruct rrFrom as [[rqFrom rsbTo]|]; [|exfalso; auto]; simpl in *; dest\n end\n\n | [H: FootprintUpOk _ _ (Some _) _ _ |- _] =>\n red in H; simpl in H;\n let cidx := fresh \"cidx\" in\n destruct H as [[cidx ?] ?]; dest\n | [H: FootprintUpOk _ _ None _ _ |- _] => red in H; simpl in H; dest\n | [H: FootprintUpDownOk _ _ _ _ _ _ \\/ FootprintDownDownOk _ _ _ _ _ _ |- _] => destruct H\n | [H: FootprintUpDownOk _ _ _ _ _ _ \\/ False |- _] => destruct H; [|exfalso; auto]\n | [H: FootprintUpDownOk _ _ _ None _ _ |- _] => red in H; simpl in H; dest\n | [H: FootprintUpDownOk _ _ _ (Some (_, _)) _ _ |- _] =>\n red in H; simpl in H;\n let upCIdx := fresh \"upCIdx\" in\n let upCObj := fresh \"upCObj\" in\n destruct H as [upCIdx [upCObj ?]]; dest\n | [H: FootprintUpDownOk _ _ _ ?rrFrom _ _ |- _] =>\n let rqFrom := fresh \"rqFrom\" in\n let rsbTo := fresh \"rsbTo\" in\n destruct rrFrom as [[rqFrom rsbTo]|]; simpl in H;\n [let upCIdx := fresh \"upCIdx\" in\n let upCObj := fresh \"upCObj\" in\n destruct H as [upCIdx [upCObj ?]]; dest|]\n | [H: FootprintDownDownOk _ _ _ _ _ _ |- _] => red in H; dest\n end.\n\nLtac derive_footprint_info_basis oidx :=\n progress (good_footprint_get oidx);\n repeat (repeat disc_rule_conds_unit_simpl; try disc_footprints_ok).\n\nSection IncomingMessageInv.\n Context `{dv: DecValue} `{oifc: OStateIfc}.\n Variables (dtr: DTree)\n (sys: System).\n\n Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n (Hitr: GoodRqRsSys dtr sys).\n\n Definition RqUpMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n msgs = nil \\/\n exists cidx rqUp,\n msgs = [rqUp] /\\\n msg_type (valOf rqUp) = MRq /\\\n parentIdxOf dtr cidx = Some oidx /\\\n rqEdgeUpFrom dtr cidx = Some (idOf rqUp).\n\n Definition RqDownMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n exists obj rqDown,\n msgs = [rqDown] /\\\n msg_type (valOf rqDown) = MRq /\\\n edgeDownTo dtr oidx = Some (idOf rqDown) /\\\n In obj sys.(sys_objs) /\\ obj.(obj_idx) = oidx.\n\n Definition RsUpMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n Forall (fun msg => msg_type (valOf msg) = MRs) msgs /\\\n Forall (fun rs =>\n exists cidx,\n parentIdxOf dtr cidx = Some oidx /\\\n rsEdgeUpFrom dtr cidx = Some rs)\n (idsOf msgs).\n\n Definition RsDownMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n exists obj rsDown,\n msgs = [rsDown] /\\\n msg_type (valOf rsDown) = MRs /\\\n edgeDownTo dtr oidx = Some (idOf rsDown) /\\\n In obj sys.(sys_objs) /\\ obj.(obj_idx) = oidx.\n\n Ltac disc_rule_custom ::=\n disc_footprints_ok.\n\n Lemma messages_in_cases:\n forall st1 oidx ridx rins routs st2,\n Reachable (steps step_m) sys st1 ->\n step_m sys st1 (RlblInt oidx ridx rins routs) st2 ->\n RqUpMsgs oidx rins \\/\n RqDownMsgs oidx rins \\/\n RsUpMsgs oidx rins \\/\n RsDownMsgs oidx rins.\n Proof.\n intros.\n\n (* Register some necessary invariants to prove this invariant. *)\n pose proof (footprints_ok Hiorqs Hitr H).\n\n inv H0.\n good_rqrs_rule_get rule.\n good_rqrs_rule_cases rule.\n\n - left.\n disc_rule_conds.\n + left; reflexivity.\n + right; constr_rule_conds.\n\n - right; left.\n disc_rule_conds.\n constr_rule_conds.\n\n - disc_rule_conds.\n + left; left; constr_rule_conds.\n + left; right; constr_rule_conds.\n + left; left; constr_rule_conds.\n + left; right; constr_rule_conds.\n + right; left; constr_rule_conds.\n\n - good_footprint_get (obj_idx obj).\n disc_rule_conds.\n + right; right; right.\n constr_rule_conds.\n + right; right; right.\n constr_rule_conds.\n + right; right; left.\n split; auto.\n clear -H20 H26; apply Forall_forall; intros.\n rewrite H26 in H.\n eapply RqRsDownMatch_rs_rq in H20; [|eassumption].\n dest; eauto.\n + right; right; left.\n split; auto.\n clear -H5 H26; apply Forall_forall; intros.\n rewrite H26 in H.\n eapply RqRsDownMatch_rs_rq in H5; [|eassumption].\n dest; eauto.\n + right; right; left.\n split; auto.\n clear -H3 H26; apply Forall_forall; intros.\n rewrite H26 in H.\n eapply RqRsDownMatch_rs_rq in H3; [|eassumption].\n dest; eauto.\n\n - good_footprint_get (obj_idx obj).\n disc_rule_conds.\n right; right; right.\n constr_rule_conds.\n Qed.\n\nEnd IncomingMessageInv.\n\nSection OutgoingMessageInv.\n Context `{dv: DecValue} `{oifc: OStateIfc}.\n Variables (dtr: DTree)\n (sys: System).\n\n Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n (Hitr: GoodRqRsSys dtr sys).\n\n Definition RqUpOutMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n exists rqUp,\n msgs = [rqUp] /\\\n msg_type (valOf rqUp) = MRq /\\\n rqEdgeUpFrom dtr oidx = Some (idOf rqUp).\n\n Definition RqDownOutMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n Forall (fun msg => msg_type (valOf msg) = MRq) msgs /\\\n Forall (fun rq =>\n exists cidx,\n parentIdxOf dtr cidx = Some oidx /\\\n edgeDownTo dtr cidx = Some rq)\n (idsOf msgs).\n\n Definition RsUpOutMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n exists rsUp,\n msgs = [rsUp] /\\\n msg_type (valOf rsUp) = MRs /\\\n rsEdgeUpFrom dtr oidx = Some (idOf rsUp).\n\n Definition RsDownOutMsgs (oidx: IdxT) (msgs: list (Id Msg)): Prop :=\n msgs = nil \\/\n exists cidx rsDown,\n msgs = [rsDown] /\\\n msg_type (valOf rsDown) = MRs /\\\n parentIdxOf dtr cidx = Some oidx /\\\n edgeDownTo dtr cidx = Some (idOf rsDown).\n\n Ltac disc_rule_custom ::=\n disc_footprints_ok.\n\n Lemma messages_out_cases:\n forall st1 oidx ridx rins routs st2,\n Reachable (steps step_m) sys st1 ->\n step_m sys st1 (RlblInt oidx ridx rins routs) st2 ->\n RqUpOutMsgs oidx routs \\/\n RqDownOutMsgs oidx routs \\/\n RsUpOutMsgs oidx routs \\/\n RsDownOutMsgs oidx routs.\n Proof.\n intros.\n\n (* Register some necessary invariants to prove this invariant. *)\n pose proof (footprints_ok Hiorqs Hitr H).\n\n inv H0.\n good_rqrs_rule_get rule.\n good_rqrs_rule_cases rule.\n\n - right; right; right.\n disc_rule_conds.\n + left; reflexivity.\n + right; constr_rule_conds.\n\n - right; right; left.\n disc_rule_conds.\n constr_rule_conds.\n\n - disc_rule_conds.\n + left; constr_rule_conds.\n + left; constr_rule_conds.\n + right; left.\n constr_rule_conds.\n clear -H33; apply Forall_forall; intros.\n eapply RqRsDownMatch_rq_rs in H33; [|eassumption].\n dest; eauto.\n + right; left.\n constr_rule_conds.\n clear -H17; apply Forall_forall; intros.\n eapply RqRsDownMatch_rq_rs in H17; [|eassumption].\n dest; eauto.\n + right; left.\n constr_rule_conds.\n clear -H3; apply Forall_forall; intros.\n eapply RqRsDownMatch_rq_rs in H3; [|eassumption].\n dest; eauto.\n\n - good_footprint_get (obj_idx obj).\n disc_rule_conds.\n + right; right; right.\n right; constr_rule_conds.\n + right; right; right.\n left; reflexivity.\n + right; right; right.\n right; constr_rule_conds.\n + right; right; left.\n constr_rule_conds.\n + right; right; right.\n left; reflexivity.\n\n - right; left.\n disc_rule_conds.\n constr_rule_conds.\n clear -H17; apply Forall_forall; intros.\n eapply RqRsDownMatch_rq_rs in H17; [|eassumption].\n dest; eauto.\n Qed.\n\nEnd OutgoingMessageInv.\n\nLtac disc_messages_in :=\n match goal with\n | [H: RqUpMsgs _ _ _ |- _] =>\n let Hr := fresh \"H\" in\n destruct H as [|Hr];\n [subst|\n let cidx := fresh \"cidx\" in\n let rqUp := fresh \"rqUp\" in\n destruct Hr as [cidx [rqUp ?]]; dest; subst]\n | [H: RqDownMsgs _ _ _ _ |- _] =>\n let obj := fresh \"obj\" in\n let rqDown := fresh \"rqDown\" in\n destruct H as [obj [rqDown ?]]; dest; subst\n | [H: RsUpMsgs _ _ _ |- _] => red in H; dest\n | [H: RsDownMsgs _ _ _ _ |- _] =>\n let obj := fresh \"obj\" in\n let rsDown := fresh \"rsDown\" in\n destruct H as [obj [rsDown ?]]; dest; subst\n end.\n\nLtac disc_messages_out :=\n match goal with\n | [H: RqUpOutMsgs _ _ _ |- _] =>\n let rqUp := fresh \"rqUp\" in\n destruct H as [rqUp ?]; dest; subst\n | [H: RqDownOutMsgs _ _ _ |- _] => red in H; dest\n | [H: RsUpOutMsgs _ _ _ |- _] =>\n let rsUp := fresh \"rsUp\" in\n destruct H as [rsUp ?]; dest; subst\n | [H: RsDownOutMsgs _ _ _ |- _] =>\n let Hr := fresh \"H\" in\n destruct H as [|Hr];\n [subst|\n let cidx := fresh \"cidx\" in\n let rsDown := fresh \"rsDown\" in\n destruct Hr as [cidx [rsDown ?]]; dest; subst]\n end.\n\nSection ExtRss.\n Context `{dv: DecValue} `{oifc: OStateIfc}.\n Variables (dtr: DTree)\n (sys: System).\n Hypothesis (Hers: GoodExtRssSys sys).\n\n Definition ExtRssInvMP (msgs: MessagePool Msg) :=\n ForallQ (fun ers ersq =>\n In ers sys.(sys_merss) ->\n Forall (fun msg => msg_type msg = MRs) ersq) msgs.\n\n Definition ExtRssInv (st: State) :=\n ExtRssInvMP st.(st_msgs).\n\n Lemma extRssInv_init: InvInit sys ExtRssInv.\n Proof.\n repeat red; intros.\n constructor.\n Qed.\n\n Lemma extRssInv_case_outs:\n forall oss orqs msgs (eouts: list (Id Msg)),\n ExtRssInv {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n Forall (FirstMPI msgs) eouts ->\n NoDup (idsOf eouts) ->\n ExtRssInv {| st_oss := oss;\n st_orqs := orqs;\n st_msgs := deqMsgs (idsOf eouts) msgs |}.\n Proof.\n intros.\n do 2 red in H; do 2 red; simpl in *.\n red; intros.\n specialize (H _ H2).\n destruct (in_dec idx_dec midx (idsOf eouts)).\n + eapply findQ_In_NoDup_deqMsgs with (mp:= msgs) in H1; eauto.\n * destruct H1 as [hmsg ?].\n rewrite <-H1 in H.\n inv H; assumption.\n * intro Hx.\n apply in_map_iff in i.\n destruct i as [[midx' msg] [? ?]]; subst; simpl in *.\n rewrite Forall_forall in H0; specialize (H0 _ H4).\n eapply FirstMP_findQ_False in Hx; eauto.\n + rewrite findQ_not_In_deqMsgs by assumption.\n assumption.\n Qed.\n\n Lemma extRssInv_step: InvStep sys step_m ExtRssInv.\n Proof.\n red; induction 3; simpl; intros; subst; auto.\n - do 2 red in H0; do 2 red; simpl in *.\n red; intros.\n specialize (H0 _ H3).\n destruct H2.\n rewrite findQ_not_In_enqMsgs; [assumption|].\n eapply DisjList_In_1; [|eassumption].\n eapply DisjList_SubList; [eassumption|].\n apply sys_merqs_sys_merss_DisjList.\n\n - apply extRssInv_case_outs; auto.\n apply H3.\n\n - eapply extRssInv_case_outs in H0; [|eassumption|apply H7].\n do 2 red in H0; do 2 red; simpl in *.\n red; intros.\n specialize (H0 _ H3).\n destruct (in_dec idx_dec midx (idsOf outs)).\n + apply in_map_iff in i.\n destruct i as [[midx' msg] [? ?]]; simpl in *; subst.\n rewrite findQ_In_NoDup_enqMsgs with (msg:= msg); [|apply H10|assumption].\n apply Forall_app; [assumption|].\n repeat constructor.\n pose proof Hers.\n red in H12; rewrite Forall_forall in H12; specialize (H12 _ H1).\n red in H12; rewrite Forall_forall in H12; specialize (H12 _ H2).\n red in H12; specialize (H12 _ _ _ _ _ _ H8 H9).\n specialize (H12 _ H13 H3); assumption.\n + rewrite findQ_not_In_enqMsgs by assumption.\n assumption.\n Qed.\n\n Lemma extRssInv_ok: InvReachable sys step_m ExtRssInv.\n Proof.\n eapply inv_reachable.\n - typeclasses eauto.\n - apply extRssInv_init.\n - apply extRssInv_step.\n Qed.\n\nEnd ExtRss.\n\nLemma msgs_ext_out_rss:\n forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System) msgs eouts,\n SubList (idsOf eouts) sys.(sys_merss) ->\n Forall (FirstMPI msgs) eouts ->\n ExtRssInvMP sys msgs ->\n Forall (fun emsg => msg_type (valOf emsg) = MRs) eouts.\nProof.\n intros.\n rewrite Forall_forall in H0.\n apply Forall_forall; intros [emidx emsg] ?.\n specialize (H0 _ H2).\n apply FirstMP_InMP in H0; simpl in H0.\n apply in_map with (f:= idOf) in H2; simpl in H2.\n apply H in H2.\n specialize (H1 _ H2).\n rewrite Forall_forall in H1; specialize (H1 _ H0).\n assumption.\nQed.\n\nClose Scope list.\nClose Scope fmap.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Dsl/RqRsInvMsg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.23934934732271168, "lm_q1q2_score": 0.1317875135719375}} {"text": "Require Import CoqlibC.\nRequire Import SmallstepC.\nRequire Import Simulation.\nRequire Import ModSem AsmregsC GlobalenvsC MemoryC ASTC.\nRequire Import Skeleton SimModSemSR SimMem SimSymb.\nRequire Import Sound Preservation.\nRequire Import ModSemProps.\n\nSet Implicit Arguments.\n\n\n\n\n\nSection MATCHSIMFORWARD.\n\n Context {SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n\n Variable msp: ModSemPair.t.\n Variable index: Type.\n Variable order: index -> index -> Prop.\n Hypothesis WFORD: well_founded order.\n Let ms_src: ModSem.t := msp.(ModSemPair.src).\n Let ms_tgt: ModSem.t := msp.(ModSemPair.tgt).\n Variable sound_state: Sound.t -> mem -> ms_src.(state) -> Prop.\n Hypothesis PRSV: local_preservation ms_src sound_state.\n\n Variable match_states: forall\n (idx: index) (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm0: SimMem.t),\n Prop.\n\n Variable match_states_at: forall\n (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm_at sm_arg: SimMem.t),\n Prop.\n\n Inductive match_states_at_helper\n (idx_at: index) (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm_at sm_arg: SimMem.t): Prop :=\n | match_states_at_intro\n (MATCH: match_states idx_at st_src0 st_tgt0 sm_at)\n args_src args_tgt\n (CALLSRC: ms_src.(ModSem.at_external) st_src0 args_src)\n (CALLTGT: ms_tgt.(ModSem.at_external) st_tgt0 args_tgt)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (MLE: SimMem.le sm_at sm_arg)\n (MWF: SimMem.wf sm_arg)\n (MATCHARG: match_states_at st_src0 st_tgt0 sm_at sm_arg).\n\n Hypothesis INITBSIM: forall sm_arg args_src args_tgt st_init_tgt\n (SIMSKENV: ModSemPair.sim_skenv msp sm_arg)\n (MWF: SimMem.wf sm_arg)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (INITTGT: ms_tgt.(ModSem.initial_frame) args_tgt st_init_tgt)\n (SAFESRC: exists _st_init_src, ms_src.(ModSem.initial_frame) args_src _st_init_src),\n exists st_init_src sm_init idx_init,\n (<>) /\\\n (<>) /\\\n (<>).\n\n Hypothesis INITPROGRESS: forall sm_arg args_src args_tgt\n (SIMSKENV: ModSemPair.sim_skenv msp sm_arg)\n (MWF: SimMem.wf sm_arg)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (SAFESRC: exists st_init_src, ms_src.(ModSem.initial_frame) args_src st_init_src),\n exists st_init_tgt, (<>).\n\n Hypothesis ATMWF: forall idx0 st_src0 st_tgt0 sm0\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (CALLSRC: ms_src.(ModSem.is_call) st_src0),\n <>.\n\n Hypothesis ATFSIM: forall idx0 st_src0 st_tgt0 sm0 args_src\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (CALLSRC: ms_src.(ModSem.at_external) st_src0 args_src)\n (SOUND: exists su0 m_init, sound_state su0 m_init st_src0),\n exists args_tgt sm_arg,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Hypothesis AFTERFSIM: forall idx0 st_src0 st_tgt0 sm0 sm_arg sm_ret retv_src retv_tgt st_src1\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (MLE: SimMem.le sm0 sm_arg)\n (* (MWF: SimMem.wf sm_arg) *)\n (MLE: SimMem.lepriv sm_arg sm_ret)\n (MWF: SimMem.wf sm_ret)\n (SIMRET: SimMem.sim_retv retv_src retv_tgt sm_ret)\n (AFTERSRC: ms_src.(ModSem.after_external) st_src0 retv_src st_src1)\n (SOUND: exists su0 m_init, sound_state su0 m_init st_src0)\n\n (* history *)\n (HISTORY: match_states_at_helper idx0 st_src0 st_tgt0 sm0 sm_arg),\n\n (* just helpers *)\n (* (MWFAFTR: SimMem.wf (SimMem.unlift sm_arg sm_ret)) *)\n (* (MLEAFTR: SimMem.le sm_arg (SimMem.unlift sm_arg sm_ret)) *)\n exists sm_after idx1 st_tgt1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Hypothesis FINALFSIM: forall idx0 st_src0 st_tgt0 sm0 retv_src\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (FINALSRC: ms_src.(ModSem.final_frame) st_src0 retv_src),\n exists sm_ret retv_tgt,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Let STEPFSIM := forall idx0 st_src0 st_tgt0 sm0\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (NOTCALL: ~ ModSem.is_call ms_src st_src0)\n (NOTRET: ~ ModSem.is_return ms_src st_src0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (SOUND: exists su0 m_init, sound_state su0 m_init st_src0),\n (<>) /\\\n (<> \\/\n <>)\n /\\ (<>)\n (* Note: We require le for mle_preserves_sim_ge, but we cannot require SimMem.wf, beacuse of DCEproof *)\n /\\ (<>)>>).\n\n Let STEPBSIM := forall idx0 st_src0 st_tgt0 sm0\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (NOTCALL: ~ ModSem.is_call ms_src st_src0)\n (NOTRET: ~ ModSem.is_return ms_src st_src0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (SOUND: exists su0 m_init, sound_state su0 m_init st_src0),\n (* (< ModSem.is_step ms_tgt st_tgt0>>) *)\n (< ModSem.is_step ms_tgt st_tgt0>>) /\\\n (<> \\/\n <>)\n /\\ (<>)\n (* Note: We require le for mle_preserves_sim_ge, but we cannot require SimMem.wf, beacuse of DCEproof *)\n /\\ (<>)>>).\n\n Remark safe_modsem_is_smaller\n st_src0\n (NOTCALL: ~ ModSem.is_call ms_src st_src0)\n (NOTRET: ~ ModSem.is_return ms_src st_src0)\n (SAFE: safe_modsem ms_src st_src0):\n ModSem.is_step ms_src st_src0.\n Proof. rr. specialize (SAFE _ (star_refl _ _ _ _)). des; ss. eauto. Qed.\n\n Hypothesis STEPSIM: STEPFSIM \\/ STEPBSIM.\n\n Hypothesis BAR: bar_True.\n\n Lemma match_states_lxsimSR\n i0 st_src0 st_tgt0 sm0\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (* (MWF: SimMem.wf sm0) *)\n (* (MCOMPAT: mem_compat st_src0 st_tgt0 sm0) *)\n (MATCH: match_states i0 st_src0 st_tgt0 sm0):\n (* su0 *)\n (* <> *)\n < unit -> exists su0 m_init, sound_state su0 m_init st)\n (Ord.lift_idx WFORD i0) st_src0 st_tgt0 sm0>>.\n Proof.\n (* move su0 at top. *)\n revert_until BAR. pcofix CIH. i. pfold. ii.\n generalize (classic (ModSem.is_call ms_src st_src0)). intro CALLSRC; des.\n { (* CALL *)\n - (* u in CALLSRC. des. *)\n exploit ATMWF; eauto. i; des. eapply lxsimSR_at_external; eauto. ii. clear CALLSRC.\n exploit ATFSIM; eauto. { ii. eapply SUSTAR; eauto. eapply star_refl. apply tt. } i; des.\n (* determ_tac ModSem.at_external_dtm. clear_tac. *)\n esplits; eauto. i. exploit AFTERFSIM; try apply SAFESRC; try apply SIMRET; eauto.\n { ii. eapply SUSTAR; eauto. eapply star_refl. apply tt. }\n { econs; eauto. }\n i; des.\n assert(MLE4: SimMem.le sm0 sm_after).\n { etrans; cycle 1. { et. } refl. }\n esplits; eauto. right. eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once. left. et. }\n }\n generalize (classic (ModSem.is_return ms_src st_src0)). intro RETSRC; des.\n { (* RETURN *)\n u in RETSRC. des. exploit FINALFSIM; eauto. i; des.\n eapply lxsimSR_final; try apply SIMRET; eauto.\n }\n destruct STEPSIM as [STEPFSIM0|STEPBSIM0].\n { eapply lxsimSR_step_forward; eauto. i.\n (* hexploit1 SU0; ss. *)\n exploit STEPFSIM0; eauto. { ii. eapply SUSTAR; eauto. eapply star_refl. apply tt. } i; des.\n esplits; eauto. econs 1; eauto.\n ii. exploit STEPFSIM1; eauto. i; des_safe. esplits; eauto.\n - des.\n + left. eauto.\n + right. esplits; eauto. eapply Ord.lift_idx_spec; eauto.\n - right. eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n }\n { rr in STEPBSIM0. eapply lxsimSR_step_backward; eauto. i.\n (* hexploit1 SU0; ss. *)\n exploit STEPBSIM0; eauto. { ii. eapply SUSTAR; eauto. eapply star_refl. apply tt. } i; des. rr in PROGRESS. des.\n esplits; eauto; cycle 1. econs 1; eauto. ii. exploit STEPBSIM1; eauto. i; des_safe. esplits; eauto.\n - des.\n + left. eauto.\n + right. esplits; eauto. eapply Ord.lift_idx_spec; eauto.\n - right. eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n }\n Qed.\n\n Theorem match_states_sim: <>.\n Proof.\n econs.\n { eauto. }\n { instantiate (2 := unit). ii. eapply local_preservation_noguarantee_weak; eauto. eapply PRSV. }\n ii; ss. folder.\n exploit SimSymb.sim_skenv_func_bisim; eauto. { apply SIMSKENV. } intro FSIM; des.\n inv FSIM. exploit FUNCFSIM; eauto. { apply SimMem.sim_args_sim_fptr; et. } i; des.\n split; ii.\n - exploit INITBSIM; eauto. i; des.\n esplits; eauto.\n eapply match_states_lxsimSR; eauto.\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n - exploit INITPROGRESS; eauto.\n Unshelve.\n all: ss.\n Qed.\n\nEnd MATCHSIMFORWARD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/proof/MatchSimModSemSR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.21733752611649484, "lm_q1q2_score": 0.1312570506849981}} {"text": "(** * Extraction of various contracts to CameLIGO *)\n\nFrom Coq Require Import ZArith.\nFrom Coq Require Import List.\nFrom Coq Require Import String.\nFrom MetaCoq.Template Require Import All.\nFrom ConCert.Embedding Require Import Notations.\nFrom ConCert.Embedding.Extraction Require Import PreludeExt.\nFrom ConCert.Embedding.Extraction Require SimpleBlockchainExt.\nFrom ConCert.Examples.Crowdfunding Require Import CrowdfundingExt.\nFrom ConCert.Examples.Crowdfunding Require CrowdfundingDataExt.\nFrom ConCert.Extraction Require Import Common.\nFrom ConCert.Extraction Require Import CameLIGOPretty.\nFrom ConCert.Extraction Require Import CameLIGOExtract.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import ResultMonad.\n\nImport MCMonadNotation.\n\nLocal Open Scope string_scope.\nOpen Scope Z.\n\n#[local]\nExisting Instance PrintConfShortNames.PrintWithShortNames.\n\nModule Crowdfunding.\n\n Notation storage := ((time_coq × Z × address_coq) × Maps.addr_map_coq × bool).\n\n Definition crowdfunding_init (ctx : ContractCallContext)\n (setup : (time_coq × Z × address_coq))\n : result storage nat :=\n if ctx.(ctx_amount) =? 0 then Ok (setup, (Maps.mnil, false)) else Err 0%nat.\n\n Definition init (setup : (time_coq × Z × address_coq))\n : result storage nat :=\n Ok (setup, (Maps.mnil, false)).\n\n Lemma crowdfunding_init_eq_init ctx setup :\n ctx.(ctx_amount) =? 0 -> (* no money should be sent on deployment *)\n crowdfunding_init ctx setup = init setup.\n Proof.\n intros Hamount.\n unfold crowdfunding_init.\n now rewrite Hamount.\n Qed.\n\n Open Scope Z.\n Import SimpleBlockchainExt.AcornBlockchain.\n Import CrowdfundingDataExt.\n Import CrowdfundingContract.Receive.\n\n (* We assume that there is a function converting addresses to [nat] *)\n Parameter addr_to_nat : forall `{ChainBase}, Blockchain.Address -> nat.\n\n Definition to_simple_ctx_addr `{ChainBase} (addr : Blockchain.Address) : address_coq :=\n if address_is_contract addr then ContractAddr_coq (addr_to_nat addr) else\n UserAddr_coq (addr_to_nat addr).\n\n Definition crowdfunding_receive_inner\n (c : Chain)\n (ctx : ContractCallContext)\n (params : msg_coq)\n (st : storage)\n : result (list SimpleActionBody_coq × storage) nat :=\n let res := receive params st\n (Time_coq c.(current_slot),\n (to_simple_ctx_addr ctx.(ctx_from),\n (ctx.(ctx_amount),\n ctx.(ctx_contract_balance)))) in\n result_of_option res 0%nat.\n\n Definition crowdfunding_receive (c : Chain) (ctx : ContractCallContext) st msg :=\n match msg with\n | Some msg => crowdfunding_receive_inner c ctx msg st\n | None => Err 0%nat\n end.\n\n Definition CF_MODULE :\n CameLIGOMod _ _ _ storage SimpleActionBody_coq nat :=\n {| (* a name for the definition with the extracted code *)\n lmd_module_name := \"cameLIGO_crowdfunding\" ;\n\n (* definitions of operations on pairs and ints *)\n lmd_prelude :=\n CameLIGOPrelude\n ++ nl\n ++ nl\n ++ \"let test_account : address = (\"\"tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx\"\" : address)\"\n ++ nl\n ++ \"let init_storage : (timestamp * (tez * address)) =\n (Tezos.get_now (), (42tez,(\"\"tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx\"\": address)))\";\n\n (* initial storage *)\n lmd_init := init ;\n\n (* init requires some extra operations *)\n lmd_init_prelude := \"\";\n\n lmd_receive_prelude := \"\";\n\n (* the main functionality *)\n lmd_receive := crowdfunding_receive;\n\n (* code for the entry point *)\n lmd_entry_point :=\n \"type storage = ((time_coq * (tez * address)) * ((address,tez) map * bool))\" ++ nl\n ++ CameLIGOPretty.printMain \"crowdfunding_receive\"\n \"msg_coq\"\n \"storage\"\n |}.\n\n (** We run the extraction procedure inside the [TemplateMonad].\n It uses the certified erasure from [MetaCoq] and the certified deboxing procedure\n that removes application of boxes to constants and constructors. *)\n\nEnd Crowdfunding.\n\nSection CrowdfundingExtraction.\n Import Crowdfunding.\n Import SimpleBlockchainExt.AcornBlockchain.\n Import CrowdfundingDataExt.\n Import CrowdfundingContract.Receive.\n\n Definition TT_remap_crowdfunding : list (kername * String.string) :=\n\n [ (* types *)\n remap <%% address_coq %%> \"address\"\n ; remap <%% SimpleActionBody_coq %%> \"operation\"\n ; remap <%% Maps.addr_map_coq %%> \"(address,tez) map\"\n\n (* simple addresses and the execution layer addresses are treated as the same *)\n ; remap <%% @to_simple_ctx_addr %%> \"(fun (x : address) -> x)\"\n\n (* operations *)\n ; remap <%% eqb_addr %%> \"eq_addr\"\n ; remap <%% Maps.add_map %%> \"Map.add\"\n ; remap <%% lookup_map' %%> \"Map.find_opt\"\n ].\n\n (** A translation table of constructors and some constants. The corresponding definitions will be extracted and renamed. *)\n Definition TT_rename :=\n [ (\"nil\", \"[]\");\n (\"mnil\", \"Map.empty\") ].\n\n Time MetaCoq Run\n (CameLIGO_prepare_extraction [] TT_remap_crowdfunding (TT_rename ++ TT_rename_ctors_default) [] \"cctx_instance\" CF_MODULE).\n\n Time Definition cameLIGO_crowdfunding := Eval vm_compute in cameLIGO_crowdfunding_prepared.\n\n (** We redirect the extraction result for later processing and compiling with the CameLIGO compiler *)\n Redirect \"../extraction/tests/extracted-code/cameligo-extract/CrowdfundingCertifiedExtraction.mligo\"\n MetaCoq Run (tmMsg (String.of_string cameLIGO_crowdfunding)).\n\nEnd CrowdfundingExtraction.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/crowdfunding/CrowdfundingCameLIGO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.25386100696924885, "lm_q1q2_score": 0.13089579101884397}} {"text": "Require Import Classical List Relations Peano_dec.\nRequire Import Hahn.\n\nRequire Import Basic Dom RC11_Events RC11_Model RC11_PSC.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection GlobalSC.\n\nVariable G : execution.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'rf'\" := G.(rf).\nNotation \"'mo'\" := G.(mo).\nNotation \"'eco'\" := G.(eco).\nNotation \"'rb'\" := G.(rb).\nNotation \"'hb'\" := G.(hb).\nNotation \"'psc_f'\" := G.(psc_f).\nNotation \"'psc'\" := G.(psc).\nNotation \"'scb'\" := G.(scb).\nNotation \"'sb_neq_loc'\" := G.(sb_neq_loc).\nNotation \"'sb''\" := (sb \\ rmw).\n\nNotation \"'E'\" := G.(E).\nNotation \"'R'\" := (R lab).\nNotation \"'W'\" := (W lab).\nNotation \"'F'\" := (F lab).\nNotation \"'RMW'\" := (RMW lab).\n\nNotation \"'RW'\" := (RW lab).\nNotation \"'FR'\" := (FR lab).\nNotation \"'FW'\" := (FW lab).\n\nNotation \"'Na'\" := (Only_Na lab).\nNotation \"'Rlx'\" := (Rlx lab).\nNotation \"'Rel'\" := (Rel lab).\nNotation \"'Acq'\" := (Acq lab).\nNotation \"'Acqrel'\" := (Acqrel lab).\nNotation \"'Sc'\" := (Sc lab).\n\nNotation \"type ~ mode\" := (type ∩₁ mode) (at level 1).\n\nNotation \"'same_loc'\" := G.(same_loc).\nNotation \"rel |loc\" := (rel ∩ same_loc) (at level 1).\n\nImplicit Type WF : Wf G.\nImplicit Type NRMW : NO_RMW_EVENTS G.\n\nLemma global_sc_helper\n WF NRMW\n (HSC: ⦗RW~Sc⦘ ⨾ (sb' ∪ sb' ⨾ hb ⨾ sb') ⨾ ⦗RW~Sc⦘ ⊆ hb ⨾ ⦗F~Sc⦘ ⨾ hb) :\n ⦗F~Sc⦘ ⨾ hb ⨾ eco^? ⨾\n (⦗RW~Sc⦘ ⨾ (sb' ∪ sb' ⨾ hb ⨾ sb' ∪ eco) ⨾ ⦗RW~Sc⦘)^* ⨾\n eco^? ⨾ hb ⨾ ⦗F~Sc⦘ ⊆ psc_f⁺.\nProof.\nassert (transitive eco).\n by apply eco_trans; assumption.\nassert (transitive hb).\n by apply hb_trans; assumption.\neapply rt_ind_left with (P:= fun __ => ⦗F~Sc⦘ ⨾\n hb ⨾ eco ^? ⨾ __ ⨾ eco ^? ⨾ hb ⨾ ⦗F~Sc⦘).\n- eauto with rel.\n- relsf.\n arewrite (hb ⨾ eco ^? ⨾ hb ⊆ hb ∪ hb ⨾ eco ⨾ hb).\n by rewrite crE; relsf.\n apply inclusion_step_t, inclusion_refl2.\n- intros k IH.\n arewrite (⦗RW~Sc⦘ ⨾ (sb' ∪ sb' ⨾ hb ⨾ sb' ∪ eco) ⨾ ⦗RW~Sc⦘ ⊆\n ⦗RW~Sc⦘ ⨾ (sb' ∪ sb' ⨾ hb ⨾ sb') ⨾ ⦗RW~Sc⦘ ∪ eco) by basic_solver 42.\n rewrite HSC.\n arewrite (⦗F~Sc⦘ ⨾ hb ⨾ eco ^? ⨾ (hb ⨾ ⦗F~Sc⦘ ⨾ hb ∪ eco) ⊆ \n ⦗F~Sc⦘ ⨾ hb ⨾ eco ^? ⨾ hb ⨾ ⦗F~Sc⦘ ⨾ hb ⨾ eco^? ∪ ⦗F~Sc⦘ ⨾ hb ⨾ eco^?)\n by basic_solver 42.\n relsf.\n rewrite !seqA, IH.\n apply inclusion_union_l; try done.\n arewrite (psc_f⁺ ⊆ ⦗F~Sc⦘ ⨾ psc_f⁺).\n by apply doma_helper, ct_doma, doma_helper2.\n rewrite <- !seqA with (r3 := psc_f⁺).\n arewrite (⦗F~Sc⦘ ⨾ hb ⨾ eco ^? ⨾ hb ⨾ ⦗F~Sc⦘ ⊆ psc_f).\n unfold RC11_Model.psc_f; basic_solver 10.\n rewrite ct_begin at 2; basic_solver.\nQed.\n\nLemma RW_scb_RW :\n ⦗RW~Sc⦘ ⨾ scb ⨾ ⦗RW~Sc⦘ ⊆\n ⦗RW ~ Sc⦘ ⨾\n (sb ∪ sb_neq_loc ⨾ hb ⨾ sb_neq_loc ∪ ⦗RW⦘ ⨾ hb |loc ⨾ ⦗RW⦘ ∪ mo ∪ rb)\n ⨾ ⦗RW ~ Sc⦘.\nProof.\n unfold RC11_Model.scb; basic_solver 42.\nQed.\n\nLemma global_sc\n WF NRMW\n (COH: irreflexive (hb ⨾ eco^?))\n (HSC: ⦗RW~Sc⦘ ⨾ (sb' ∪ sb' ⨾ hb ⨾ sb') ⨾ ⦗RW~Sc⦘ ⊆ hb ⨾ ⦗F~Sc⦘ ⨾ hb)\n (ACYC: acyclic psc_f) : acyclic psc.\nProof.\nassert (transitive eco).\n by apply eco_trans; assumption.\nassert (transitive hb).\n by apply hb_trans; assumption.\neapply acyc_dom with (d:= RW~Sc) (e:= F~Sc); try edone.\n- unfold RC11_Model.psc, RC11_Model.psc_base, RC11_Model.psc_f; unionL.\n arewrite (⦗Sc⦘ ≡ ⦗RW~Sc⦘ ∪ ⦗F~Sc⦘) by solve_type_mismatch 42.\n basic_solver 42.\n basic_solver 42.\n- solve_type_mismatch 6.\n- unfold RC11_Model.psc, RC11_Model.psc_base, RC11_Model.psc_f; relsf; rewrite !seqA.\n arewrite_false !(⦗RW~Sc⦘ ⨾ ⦗F~Sc⦘).\n solve_type_mismatch 6.\n arewrite_false !( ⦗F~Sc⦘ ⨾ ⦗RW~Sc⦘).\n solve_type_mismatch 6.\n rels.\n arewrite (⦗RW~Sc⦘ ⨾ ⦗Sc⦘ ⊆ ⦗RW~Sc⦘).\n arewrite (⦗Sc⦘ ⨾ ⦗RW~Sc⦘ ⊆ ⦗RW~Sc⦘).\n rewrite RW_scb_RW.\n rewrite hb_loc_in_eco; auto.\n arewrite (sb_neq_loc ⊆ sb').\n by apply sb_neq_loc_in_sb_minus_rmw; auto.\n arewrite (sb ⊆ sb' ∪ rmw) at 1.\n by unfold inclusion, minus_rel, union; ins; tauto.\n rewrite rmw_in_rb at 2; auto.\n rewrite mo_in_eco; auto.\n rewrite rb_in_eco; auto.\n rewrite <- !unionA.\n relsf.\n arewrite (⦗RW~Sc⦘ ⨾ sb' ⨾ ⦗RW~Sc⦘ ⊆ hb ⨾ ⦗F~Sc⦘ ⨾ hb).\n by rewrite <- HSC; rels.\n arewrite (⦗RW~Sc⦘ ⨾ sb' ⨾ hb ⨾ sb' ⨾ ⦗RW~Sc⦘ ⊆ hb ⨾ ⦗F~Sc⦘ ⨾ hb).\n by rewrite <- HSC; rels; basic_solver 10.\n eapply acyclic_mon with (r := hb ⨾ ⦗F~Sc⦘ ⨾ hb ∪ ⦗RW~Sc⦘ ⨾ eco ⨾ ⦗RW~Sc⦘).\n 2: repeat apply inclusion_union_l; rels.\n apply acyclic_utt; splits.\n * apply transitiveI; arewrite_id ⦗F~Sc⦘ at 1; relsf.\n * apply transitiveI.\n arewrite_id ⦗RW~Sc⦘ at 2; relsf.\n arewrite_id ⦗RW~Sc⦘ at 2; relsf.\n * arewrite_id ⦗F~Sc⦘ at 1; relsf.\n by apply irr_hb.\n * arewrite_id ⦗RW~Sc⦘; relsf.\n by apply irr_eco.\n * arewrite (⦗F~Sc⦘ ⊆ ⦗F~Sc⦘ ⨾ ⦗F~Sc⦘).\n by basic_solver.\n do 2 (apply acyclic_seqC; try rewrite !seqA).\n eapply acyclic_mon with (r := psc_f); try done.\n unfold RC11_Model.psc_f.\n basic_solver 12.\n- by rewrite psc_f_f.\n- rewrite psc_rw_rw; try assumption.\n rewrite RW_scb_RW.\n arewrite (\n sb ∪ sb_neq_loc ⨾ hb ⨾ sb_neq_loc ∪ ⦗RW⦘ ⨾ hb|loc ⨾ ⦗RW⦘ ∪ mo ∪ rb \n ⊆ sb' ∪ sb' ⨾ hb ⨾ sb' ∪ eco\n ).\n { arewrite (sb ⊆ sb' ∪ rmw).\n by apply inclusion_union_minus. \n rewrite rmw_in_rb at 2; try assumption.\n rewrite rb_in_eco, mo_in_eco, sb_neq_loc_in_sb_minus_rmw, hb_loc_in_eco; try assumption.\n basic_solver 10.\n }\n sin_rewrite psc_rw_f; try assumption.\n sin_rewrite psc_f_rw; try assumption.\n rewrite psc_f_f; try assumption.\n arewrite_id ⦗RW~Sc⦘ at 1.\n arewrite_id ⦗RW~Sc⦘ at 3.\n rels.\n rewrite <- !seqA with (r3 := psc_f ^*), global_sc_helper; try assumption.\n red; rels.\nQed.\n\n(* Definition change_mode (l: label) (m: mode) : label := \n match l with\n | Aload l v _ => Aload l v m\n | Astore l v _ => Astore l v m\n | Afence _ => Afence m\n end. *)\n \n(* Definition change_modes (G: execution) (A: event -> Prop) (m: mode): execution :=\n Build_execution \n acts\n (fun a => if (A a) then change_mode (lab a) m else lab a)\n sb rmw rf mo. *)\n\n(* Lemma transf_g\n (NO_SC: ⦗Sc⦘ ≡ ∅₂)\n A (A_SUB: A ⊆₁ R_acq ∪₁ W_rel)\n (A1: ⦗A⦘ ⨾ (sb' ∪ sb'⨾hb⨾sb') ⨾ ⦗A⦘ ⊆ hb ⨾ ⦗F~Sc⦘ ⨾ hb)\n (A2: ⦗A⦘ ⨾ rmw ≡ rmw ⨾ ⦗A⦘)\n (G' : execution) (CHANGE: G' = G)\n : consistent G'.\nProof.\nAdmitted. *)\n\nEnd GlobalSC.", "meta": {"author": "personal-practice", "repo": "coq", "sha": "df9a5f44b57323b02ba108126569a22e98b433e2", "save_path": "github-repos/coq/personal-practice-coq", "path": "github-repos/coq/personal-practice-coq/coq-df9a5f44b57323b02ba108126569a22e98b433e2/scfix/RC11_GlobalSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.13086141686742497}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\nRequire Export AuxStateDataType.\nRequire Import Constant.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import XOmega.\nRequire Import CLemmas.\nRequire Import INVLemmaIntel.\nRequire Import Values.\nRequire Import liblayers.compat.CompatGenSem.\n\nSection REAL_EPT.\n\n Function Calculate_EPDTE_at_j (i: Z) (j: Z) (ept: EPT) : EPT :=\n match ZMap.get 0 ept with\n | EPML4EValid epdpt => \n match ZMap.get i epdpt with\n | EPDPTEValid epdt => \n ZMap.set 0 (EPML4EValid (ZMap.set i (EPDPTEValid (ZMap.set j (EPDTEValid (ZMap.init EPTEUndef)) epdt)) epdpt)) ept\n | _ => ept\n end\n | _ => ept\n end.\n\n Fixpoint Calculate_EPDTE (i: Z) (j: nat) (ept: EPT) : EPT := \n match j with\n | O => Calculate_EPDTE_at_j i 0 ept\n | S k => Calculate_EPDTE_at_j i (Z.of_nat (S k)) (Calculate_EPDTE i k ept)\n end.\n\n\n Function Calculate_EPDPTE_at_i (i: Z) (ept: EPT) : EPT :=\n match ZMap.get 0 ept with\n | EPML4EValid epdpt => \n Calculate_EPDTE i 511 (ZMap.set 0 (EPML4EValid (ZMap.set i (EPDPTEValid (ZMap.init EPDTEUndef)) epdpt)) ept)\n | _ => ept\n end.\n Fixpoint Calculate_EPDPTE (i: nat) (ept: EPT) : EPT := \n match i with\n | O => Calculate_EPDPTE_at_i 0 ept\n | S k => Calculate_EPDPTE_at_i (Z.of_nat (S k)) (Calculate_EPDPTE k ept)\n end.\n\n Definition real_ept (ept: EPT) := Calculate_EPDPTE 3 (ZMap.set 0 (EPML4EValid (ZMap.init EPDPTEUndef)) ept).\n\nEnd REAL_EPT.\n\nSection REAL_VMCS.\n\n Definition write64_aux (enc: Z) (value: Z64) (d: ZMap.t val) : ZMap.t val :=\n let d1 := ZMap.set enc (Vint (Int64.loword (Int64.repr (Z642Z value)))) d in\n ZMap.set (enc + 1) (Vint (Int64.hiword (Int64.repr (Z642Z value)))) d1.\n\n Definition write64_block_aux (enc: Z) (value: val) (d: ZMap.t val) : ZMap.t val :=\n let d1 := ZMap.set enc value d in\n ZMap.set (enc + 1) Vzero d1.\n\n Definition real_vmcs (vm: VMCS) (vmi: VMXInfo) (pml4ept_b tss_b gdt_b idt_b msr_bitmap_b io_bitmap_b host_rip_b: block):=\n match vm with\n | VMCSValid revid abrtid m =>\n\n let pinbased_ctls := ZMap.get (VMX_INFO_PINBASED_CTLS) vmi in\n let procbased_ctls := ZMap.get (VMX_INFO_PROCBASED_CTLS) vmi in\n let procbased_ctls2 := ZMap.get (VMX_INFO_PROCBASED_CTLS2) vmi in\n let exit_ctls := ZMap.get (VMX_INFO_EXIT_CTLS) vmi in\n let entry_ctls := ZMap.get (VMX_INFO_ENTRY_CTLS) vmi in\n let cr0_ones_mask := ZMap.get (VMX_INFO_CR0_ONES_MASK) vmi in\n let cr0_zeros_mask := ZMap.get (VMX_INFO_CR0_ZEROS_MASK) vmi in\n let cr4_ones_mask := ZMap.get (VMX_INFO_CR4_ONES_MASK) vmi in\n let cr4_zeros_mask := ZMap.get (VMX_INFO_CR4_ZEROS_MASK) vmi in\n\n let m1 := ZMap.set C_VMCS_PIN_BASED_CTLS (Vint (Int.repr pinbased_ctls)) m in\n let m2 := ZMap.set C_VMCS_PRI_PROC_BASED_CTLS (Vint (Int.repr procbased_ctls)) m1 in\n let m3 := ZMap.set C_VMCS_SEC_PROC_BASED_CTLS (Vint (Int.repr procbased_ctls2)) m2 in\n let m4 := ZMap.set C_VMCS_EXIT_CTLS (Vint (Int.repr exit_ctls)) m3 in\n let m5 := ZMap.set C_VMCS_ENTRY_CTLS (Vint (Int.repr entry_ctls)) m4 in\n\n let m6 := ZMap.set C_VMCS_HOST_RIP (Vptr host_rip_b Int.zero) m5 in\n\n (*rcr0_spec adt*)\n let m7 := ZMap.set C_VMCS_HOST_CR0 Vzero m6 in\n (*rcr3_spec adt*)\n let m8 := ZMap.set C_VMCS_HOST_CR3 Vzero m7 in\n (*rcr4_spec adt*)\n let m9 := ZMap.set C_VMCS_HOST_CR4 Vzero m8 in\n\n let m10 := ZMap.set C_VMCS_HOST_ES_SELECTOR (Vint (Int.repr CPU_GDT_KDATA)) m9 in\n let m11 := ZMap.set C_VMCS_HOST_CS_SELECTOR (Vint (Int.repr CPU_GDT_KCODE)) m10 in\n let m12 := ZMap.set C_VMCS_HOST_SS_SELECTOR (Vint (Int.repr CPU_GDT_KDATA)) m11 in\n let m13 := ZMap.set C_VMCS_HOST_DS_SELECTOR (Vint (Int.repr CPU_GDT_KDATA)) m12 in\n let m14 := ZMap.set C_VMCS_HOST_FS_SELECTOR (Vint (Int.repr CPU_GDT_KDATA)) m13 in\n let m15 := ZMap.set C_VMCS_HOST_GS_SELECTOR (Vint (Int.repr CPU_GDT_KDATA)) m14 in\n let m16 := ZMap.set C_VMCS_HOST_TR_SELECTOR (Vint (Int.repr CPU_GDT_TSS)) m15 in\n\n let m17 := ZMap.set C_VMCS_HOST_FS_BASE Vzero m16 in\n let m18 := ZMap.set C_VMCS_HOST_GS_BASE Vzero m17 in\n\n let m19 := ZMap.set C_VMCS_HOST_TR_BASE (Vptr tss_b Int.zero) m18 in\n let m20 := ZMap.set C_VMCS_HOST_GDTR_BASE (Vptr gdt_b Int.zero) m19 in\n let m21 := ZMap.set C_VMCS_HOST_IDTR_BASE (Vptr idt_b Int.zero) m20 in\n\n (* rdmsr_spec MSR_IA32_SYSENTER_CS adt *)\n let m22 := ZMap.set C_VMCS_HOST_IA32_SYSENTER_CS Vzero m21 in\n (*rdmsr_spec MSR_IA32_SYSENTER_ESP adt*)\n let m23 := ZMap.set C_VMCS_HOST_IA32_SYSENTER_ESP Vzero m22 in\n (*rdmsr_spec MSR_IA32_SYSENTER_EIP adt*)\n let m24 := ZMap.set C_VMCS_HOST_IA32_SYSENTER_EIP Vzero m23 in\n (*rdmsr_spec MSR_IA32_PERF_GLOBAL_CTRL adt*)\n let m25 := write64_aux C_VMCS_HOST_IA32_PERF_GLOBAL_CTRL (VZ64 0) m24 in\n (*rdmsr_spec MSR_PAT adt*)\n let m26 := write64_aux C_VMCS_HOST_IA32_PAT (VZ64 0) m25 in\n (*rdmsr_spec MSR_EFER adt*)\n let m27 := write64_aux C_VMCS_HOST_IA32_EFER (VZ64 0) m26 in\n\n let m28 := ZMap.set C_VMCS_GUEST_CR0 (Vint (Int.repr (Z.lor v0x60000010 CR0_NE))) m27 in\n let m29 := ZMap.set C_VMCS_GUEST_CR3 Vzero m28 in\n let m30 := ZMap.set C_VMCS_GUEST_CR4 (Vint (Int.repr CR4_VMXE)) m29 in\n let m31 := ZMap.set C_VMCS_GUEST_DR7 (Vint (Int.repr v0x00000400)) m30 in\n\n let m32 := write64_aux C_VMCS_GUEST_IA32_PAT (VZ64 v0x7040600070406) m31 in\n let m33 := ZMap.set C_VMCS_GUEST_IA32_SYSENTER_CS Vzero m32 in\n let m34 := ZMap.set C_VMCS_GUEST_IA32_SYSENTER_ESP Vzero m33 in\n let m35 := ZMap.set C_VMCS_GUEST_IA32_SYSENTER_EIP Vzero m34 in\n let m36 := write64_aux C_VMCS_GUEST_IA32_DEBUGCTL (VZ64 0) m35 in\n (*FIXME: it should be 64 bits*)\n let m37 := write64_block_aux C_VMCS_EPTP (Vptr pml4ept_b (Int.repr EPTP_pml4)) m36 in\n\n let m38 := ZMap.set C_VMCS_VPID Vone m37 in\n(* let m38' := ZMap.set C_VMCS_EXCEPTION_BITMAP (Vint (Int.repr T_MCHK_SHIFT)) m38 in *)\n let m39 := write64_block_aux C_VMCS_MSR_BITMAP (Vptr msr_bitmap_b Int.zero) m38 in\n let m40 := write64_aux C_VMCS_LINK_POINTER (VZ64 v0xffffffffffffffff) m39 in\n let m41 := ZMap.set C_VMCS_CR0_MASK (Vint (Int.repr (Z.lor cr0_ones_mask cr0_zeros_mask))) m40 in\n let m42 := ZMap.set C_VMCS_CR0_SHADOW (Vint (Int.repr cr0_ones_mask)) m41 in\n let m43 := ZMap.set C_VMCS_CR4_MASK (Vint (Int.repr (Z.lor cr4_ones_mask cr4_zeros_mask))) m42 in\n let m44 := ZMap.set C_VMCS_CR4_SHADOW (Vint (Int.repr cr4_ones_mask)) m43 in\n let m45 := write64_block_aux C_VMCS_IO_BITMAP_A (Vptr io_bitmap_b Int.zero) m44 in\n let m46 := write64_block_aux C_VMCS_IO_BITMAP_B (Vptr io_bitmap_b (Int.repr PgSize)) m45 in\n\n let m47 := ZMap.set C_VMCS_GUEST_ACTIVITY Vzero m46 in\n let m48 := ZMap.set C_VMCS_GUEST_INTERRUPTIBILITY Vzero m47 in\n let m49 := ZMap.set C_VMCS_GUEST_PENDING_DBG_EXCEPTIONS Vzero m48 in\n let m50 := ZMap.set C_VMCS_ENTRY_INTR_INFO Vzero m49 in\n\n let revid1 := Vzero in\n VMCSValid revid1 abrtid m50\n end.\n\n Lemma real_vmcs_inject_neutral:\n forall vm vmi n pml4ept_b tss_b gdt_b idt_b msr_bitmap_b io_bitmap_b\n host_rip_b,\n VMCS_inject_neutral vm n ->\n Mem.flat_inj n pml4ept_b = Some (pml4ept_b, 0) ->\n Mem.flat_inj n tss_b = Some (tss_b, 0) ->\n Mem.flat_inj n gdt_b = Some (gdt_b, 0) ->\n Mem.flat_inj n idt_b = Some (idt_b, 0) ->\n Mem.flat_inj n msr_bitmap_b = Some (msr_bitmap_b, 0) ->\n Mem.flat_inj n io_bitmap_b = Some (io_bitmap_b, 0) ->\n Mem.flat_inj n host_rip_b = Some (host_rip_b, 0) ->\n VMCS_inject_neutral\n (real_vmcs vm vmi pml4ept_b tss_b gdt_b idt_b msr_bitmap_b io_bitmap_b\n host_rip_b) n.\n Proof.\n intros. unfold real_vmcs. \n destruct vm.\n inversion H; subst.\n repeat (eapply VMCS_inject_neutral_gss_Vint_same \n || eapply VMCS_inject_neutral_gss_same); eauto 1;\n split; econstructor; eauto;\n generalize (H11 ofs); intro tmp; destruct tmp; eauto.\n Qed.\n\nEnd REAL_VMCS.\n\nSection REAL_VMX.\n\n Definition real_vmx (vm: VMX): VMX :=\n let vm1 := ZMap.set VMX_G_RIP' (Vint (Int.repr v0xfff0)) vm in\n let vm2 := ZMap.set VMX_VPID' Vone vm1 in\n let vm3 := ZMap.set VMX_G_CR2' Vzero vm2 in\n let vm4 := ZMap.set VMX_G_DR0' Vzero vm3 in\n let vm5 := ZMap.set VMX_G_DR1' Vzero vm4 in\n let vm6 := ZMap.set VMX_G_DR2' Vzero vm5 in\n let vm7 := ZMap.set VMX_G_DR3' Vzero vm6 in\n ZMap.set VMX_G_DR6' (Vint (Int.repr v0xffff0ff0)) vm7.\n\n Lemma real_vmx_inject_neutral:\n forall vm n,\n VMX_inject_neutral vm n ->\n VMX_inject_neutral\n (real_vmx vm) n.\n Proof.\n intros. unfold real_vmx. \n repeat eapply VMX_inject_neutral_gss_Vint.\n assumption.\n Qed.\n\nEnd REAL_VMX.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/clib/CalRealIntelModule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.24798742624020276, "lm_q1q2_score": 0.13076786744683055}} {"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import MmioCoreAux.Spec.\nRequire Import AbstractMachine.Spec.\nRequire Import MmioCoreAux.Layer.\nRequire Import RData.\nRequire Import MmioRaw.Spec.\nRequire Import Constants.\nRequire Import HypsecCommLib.\n\nLocal Open Scope Z_scope.\n\nSection MmioCoreSpec.\n\n Definition handle_smmu_write_spec (hsr: Z) (fault_ipa: Z64) (len: Z) (index: Z) (adt: RData) : option RData :=\n match fault_ipa with\n | VZ64 fault_ipa =>\n rely is_int hsr; rely is_addr fault_ipa; rely is_smmu index;\n if halt adt then Some adt else\n match SMMU_ID @ (lock adt) with\n | LockOwn true =>\n let vcpuid := cur_vcpuid adt in\n let rt := host_dabt_get_rd' hsr in\n rely is_vcpu vcpuid; rely is_int rt;\n let offset := Z.land fault_ipa SMMU_OFFSET_MASK in\n if offset =? 0) && (offset <=? ARM_SMMU_GR1_BASE) then\n if offset =? ARM_SMMU_GR0_sCR0 then\n let smmu_enable := Z.land (Z.shiftr data sCR0_SMCFCFG_SHIFT) 1 in\n if smmu_enable =? 0 then Some 0 else Some 1\n else if offset =? ARM_SMMU_GR0_sCR2 then\n if (Z.land data 255) =? 0 then Some 1 else Some 0\n else Some 1\n else if (offset >=? ARM_SMMU_GR1_BASE) && (offset None\n end\n end.\n\n Definition handle_smmu_read_spec (hsr: Z) (fault_ipa: Z64) (len: Z) (adt: RData) : option RData :=\n match fault_ipa with\n | VZ64 fault_ipa =>\n rely is_int hsr;\n if halt adt then Some adt else\n let vcpuid := cur_vcpuid adt in\n let rt := host_dabt_get_rd' hsr in\n let n := HOSTVISOR @ (data_log adt) in\n let data := (doracle adt) HOSTVISOR n in\n rely is_vcpu vcpuid; rely is_int rt; rely is_int64 data;\n let dlog' := (data_log adt) # HOSTVISOR == (n + 1) in\n if len =? 8 then\n set_shadow_ctxt_spec HOSTVISOR vcpuid rt (VZ64 data) (adt {data_log: dlog'})\n else if len =? 4 then\n set_shadow_ctxt_spec HOSTVISOR vcpuid rt (VZ64 (Z.land data INVALID)) (adt {data_log: dlog'})\n else\n Some adt {halt: true}\n end.\n\nEnd MmioCoreSpec.\n\nSection MmioCoreSpecLow.\n\n Context `{real_params: RealParams}.\n\n Notation LDATA := RData.\n\n Notation LDATAOps := (cdata (cdata_ops := MmioCoreAux_ops) LDATA).\n\n Definition handle_smmu_write_spec0 (hsr: Z) (fault_ipa: Z64) (len: Z) (index: Z) (adt: RData) : option RData :=\n match fault_ipa with\n | VZ64 fault_ipa =>\n let offset := Z.land fault_ipa SMMU_OFFSET_MASK in\n if offset \n let offset := Z.land fault_ipa SMMU_OFFSET_MASK in\n if offset Prop) m'0 labd labd' hsr fault_ipa len index\n (Hinv: high_level_invariant labd)\n (Hspec: handle_smmu_write_spec0 (Int.unsigned hsr) (VZ64 (Int64.unsigned fault_ipa)) (Int.unsigned len) (Int.unsigned index) labd = Some labd'):\n handle_smmu_write_spec_low_step s WB ((Vint hsr)::(Vlong fault_ipa)::(Vint len)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Inductive handle_smmu_read_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n | handle_smmu_read_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' hsr fault_ipa len\n (Hinv: high_level_invariant labd)\n (Hspec: handle_smmu_read_spec0 (Int.unsigned hsr) (VZ64 (Int64.unsigned fault_ipa)) (Int.unsigned len) labd = Some labd'):\n handle_smmu_read_spec_low_step s WB ((Vint hsr)::(Vlong fault_ipa)::(Vint len)::nil) (m'0, labd) Vundef (m'0, labd').\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModelX}.\n Context `{Hmwd: UseMemWithData mem}.\n\n Definition handle_smmu_write_spec_low: compatsem LDATAOps :=\n csem handle_smmu_write_spec_low_step (type_of_list_type (Tint32::Tint64::Tint32::Tint32::nil)) Tvoid.\n\n Definition handle_smmu_read_spec_low: compatsem LDATAOps :=\n csem handle_smmu_read_spec_low_step (type_of_list_type (Tint32::Tint64::Tint32::nil)) Tvoid.\n\n End WITHMEM.\n\nEnd MmioCoreSpecLow.\n\n", "meta": {"author": "VeriGu", "repo": "VRM-proof", "sha": "9e3c9751f31713a133a0a7e98f3d4c9600ca7bde", "save_path": "github-repos/coq/VeriGu-VRM-proof", "path": "github-repos/coq/VeriGu-VRM-proof/VRM-proof-9e3c9751f31713a133a0a7e98f3d4c9600ca7bde/sekvm/MmioCore/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.25683198569916993, "lm_q1q2_score": 0.13042232946442545}} {"text": "(******************************************************************************)\n(** Conversions between single steps and block execution steps *)\n(******************************************************************************)\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\nRequire Import Omega.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import OCaml.\nRequire Import OmmProgram.\nRequire Import ListHelpers.\nRequire Import OmmImmCompScheme. \nRequire Import ListHelpersTemp.\nRequire Import Utils.\nRequire Import ClosuresProperties. \nRequire Import Prog.\nRequire Import ProgToExecution.\nRequire Import ProgToExecutionProperties.\nRequire Import Logic.Decidable. \nFrom PromisingLib Require Import Basic Loc.\nRequire Import Basics. \nSet Implicit Arguments.\n\nSection Steps.\n\nLemma init_mm_same: forall PO BPI (COMP: is_thread_block_compiled PO BPI),\n mm_similar_states (init PO) (binit BPI).\nProof.\n ins. red. simpl. splits; auto.\n 3: { basic_solver. }\n 2: { ins. simpl. unfold DepsFile.init. simpl. basic_solver. }\n unfold init_execution. red. simpl. basic_solver. \nQed.\n\nLemma steps_same_instrs sti sti' (STEPS: exists tid, (step tid)* sti sti'):\n instrs sti = instrs sti'.\nProof.\n destruct STEPS as [tid STEPS]. apply crt_num_steps in STEPS.\n destruct STEPS as [n STEPS].\n generalize dependent sti'.\n induction n.\n - intros sti' STEPS. simpl in STEPS. generalize STEPS. basic_solver 10.\n - intros sti' STEPS.\n rewrite step_prev in STEPS. destruct STEPS as [sti'' STEPS'']. desc.\n replace (instrs sti) with (instrs sti'').\n { red in STEPS''0. desf. red in STEPS''0. desf. }\n symmetry. eapply IHn. eauto.\nQed.\n\nLemma omm_steps_same_instrs sto sto' (STEPS: exists tid, (Ostep tid)* sto sto'):\n instrs sto = instrs sto'.\nProof.\n (* TODO: join with previous*)\n destruct STEPS as [tid STEPS]. apply crt_num_steps in STEPS.\n destruct STEPS as [n STEPS].\n generalize dependent sto'.\n induction n.\n - intros sto' STEPS. simpl in STEPS. generalize STEPS. basic_solver 10.\n - intros sto' STEPS.\n rewrite step_prev in STEPS. destruct STEPS as [sto'' STEPS'']. desc.\n replace (instrs sto) with (instrs sto'').\n { red in STEPS''0. desf. red in STEPS''0. desf. }\n symmetry. eapply IHn. eauto.\nQed.\n\nDefinition on_block st block :=\n ⟪ PROG_BLOCK: block = sublist (instrs st) (pc st) (length block) ⟫ /\\\n ⟪ COMP_BLOCK: (exists oinstr, is_instruction_compiled oinstr block) ⟫.\n\nDefinition at_compilation_block st :=\n (exists block, on_block st block) \\/ is_terminal st.\n\nDefinition oseq_step (tid : thread_id) sti1 sti2 :=\n exists block, on_block sti1 block /\\\n (step tid) ^^ (length block) sti1 sti2. \n\nLemma igt_compiled_addr cond addr PO PI (IN_COMP: In (Instr.ifgoto cond addr) PI)\n (COMP: is_thread_compiled PO PI):\n addr <= length PI.\nProof.\n cdes COMP. cdes COMP0.\n red in COMP1. desc. clear COMP COMP0. subst PI. \n replace (length (flatten BPI)) with (length (flatten BPI0)). \n 2: { ins.\n rewrite <- firstn_all with (l := BPI0).\n rewrite <- firstn_all with (l := BPI).\n replace (length BPI) with (length BPI0).\n 2: { eapply Forall2_length; eauto. }\n apply SAME_STRUCT_PREF. eapply correction_same_struct; eauto. }\n assert (exists BPI_corr, Forall2 (block_corrected BPI_corr) BPI0 BPI /\\ same_struct BPI_corr BPI0) as CORR_ALT. \n { exists BPI0. splits; vauto. apply same_struct_refl. }\n desc.\n replace (length (flatten BPI0)) with (length (flatten BPI_corr)). \n 2: { ins.\n rewrite <- firstn_all with (l := BPI0).\n rewrite <- firstn_all with (l := BPI_corr).\n replace (length BPI_corr) with (length BPI0).\n 2: { symmetry. red in CORR_ALT0. eapply Forall2_length; eauto. }\n apply SAME_STRUCT_PREF. auto. }\n clear COMP3 CORR_ALT0. \n generalize dependent BPI. generalize dependent BPI0. induction PO.\n { ins. inversion COMP1. subst. inversion CORR_ALT. subst. vauto. }\n ins. inversion COMP1. subst. inversion CORR_ALT. subst.\n simpl in IN_COMP. apply in_app_or in IN_COMP. des.\n 2: { specialize (IHPO l' H3 l'0 IN_COMP H5). auto. }\n (* Ltac invert_nil := match goal with *)\n (* | H: *)\n inversion H1; subst. \n { inversion H2. subst. inversion H7. subst. inversion H4. subst.\n subst ld. simpl in IN_COMP. des; vauto. }\n { subst. inversion H2. subst. inversion H7. subst. inversion H9. subst.\n inversion H6. subst. inversion H4. subst. \n subst f st. simpl in IN_COMP. des; vauto. }\n { subst. inversion H2. subst. inversion H7. subst. inversion H9. subst.\n inversion H6. subst. inversion H4. subst. \n subst f ld. simpl in IN_COMP. des; vauto. }\n { subst. inversion H2. subst. inversion H7. subst. inversion H9. subst.\n inversion H6. subst. inversion H4. subst. \n subst f exc. simpl in IN_COMP. des; vauto. }\n { subst. inversion H2. subst. inversion H7. subst. inversion H4. subst.\n subst asn. simpl in IN_COMP. des; vauto. }\n subst. inversion H2. subst. inversion H7. subst.\n subst igt. inversion H4; vauto. \n simpl in IN_COMP. des; [| done].\n inversion IN_COMP. subst.\n subst addr1.\n rewrite <- firstn_skipn with (l := BPI_corr) (n := n) at 2.\n rewrite flatten_app, app_length. omega.\nQed. \n\nLemma is_terminal_pc_bounded st tid PO PI (REACH: (step tid)* (init PI) st)\n (COMP: is_thread_compiled PO PI):\n is_terminal st <-> pc st = length (instrs st).\nProof.\n unfold is_terminal. \n split; [|omega]. \n apply crt_num_steps in REACH. desc. generalize dependent st. induction n.\n { ins. red in REACH. desc. subst. simpl in *. omega. }\n ins. red in REACH. desc.\n do 2 (red in REACH0; desc).\n assert (forall instr, Some instr = nth_error (instrs z) (pc z) ->\n pc st = pc z + 1 -> pc st = length (instrs st)) as NEXT_HELPER. \n { ins. assert (pc z < length (instrs st)).\n { apply nth_error_Some, OPT_VAL. rewrite <- INSTRS. eauto. }\n omega. }\n inversion ISTEP0; try (by eapply NEXT_HELPER; eauto).\n destruct (Const.eq_dec (RegFile.eval_expr (regf z) expr) 0).\n { eapply NEXT_HELPER; eauto. }\n forward eapply (@igt_compiled_addr expr shift PO (instrs z)) as BOUND.\n { subst instr. eapply nth_error_In. eauto. }\n { replace (instrs z) with PI; auto.\n replace PI with (instrs (init PI)) by vauto.\n apply steps_same_instrs. exists tid. apply crt_num_steps. eauto. }\n rewrite INSTRS in BOUND. omega.\nQed. \n\nDefinition bst_from_st st BPI b :=\n {|\n binstrs := BPI;\n bpc := b;\n bG := G st; \n beindex := eindex st;\n bregf := regf st;\n bdepf := depf st;\n bectrl := ectrl st |}. \n\nDefinition min_prop {A: Type} (P: list A -> Prop)\n := forall l (Pl: P l), (forall l1 l2 (LT: l2 <> []) (SPLIT: l = l1 ++ l2), ~ P l1). \n\nLemma firstn_length_leq {A: Type} (l: list A) i:\n length (firstn i l) <= length l.\nProof.\n generalize dependent l. induction i.\n { ins. omega. }\n ins. destruct l; vauto.\n simpl. apply le_n_S. auto.\nQed. \n\n\nLemma start_block_deterministic\n (A : Type)\n (P : list A -> Prop)\n (block : list A)\n (block' : list A)\n (ll : list (list A))\n (MINPROP : min_prop P)\n (NEblock: block <> [])\n (Pblock: P block)\n (NE_B : block' <> [])\n (BLOCK'_P : P block')\n (BLOCK' : block' = firstn (length block') (flatten (block :: ll))):\n block' = block.\nProof.\n assert (block = firstn (length block) (block ++ flatten ll)) as L0. \n { rewrite <- Nat.add_0_r with (n := length block).\n rewrite firstn_app_2. simpl. symmetry. apply app_nil_r. }\n assert (length block' <= length (flatten (block :: ll))) as LEN_B.\n { apply (@f_equal _ _ (@length _)) in BLOCK'.\n pose proof (firstn_length_leq (flatten (block :: ll)) (length block')). omega. }\n assert (length block <= length (flatten (block :: ll))) as LEN_L0. \n { simpl. rewrite app_length. omega. }\n destruct (lt_eq_lt_dec (length block') (length block)) as [[LT | EQ] | GT].\n 2: { forward eapply (@firstn_ge_incl _ (flatten (block :: ll)) (length block') (length block)) as PREF; [omega| ].\n rewrite EQ in PREF at 2. rewrite skipn_firstn_nil in PREF.\n rewrite app_nil_r in PREF. simpl in BLOCK'. congruence. }\n { forward eapply (@firstn_ge_incl _ (flatten (block :: ll)) (length block') (length block)) as PREF; [omega| ].\n exfalso.\n simpl in *. rewrite <- BLOCK', <- L0 in PREF.\n red in MINPROP. specialize (MINPROP block Pblock block' (skipn (length block') block)).\n apply MINPROP; vauto.\n apply (@f_equal _ _ (@length _)) in PREF. rewrite app_length in PREF.\n red. ins. apply NE_B. apply length_zero_iff_nil.\n apply length_zero_iff_nil in H. omega. }\n forward eapply (@firstn_ge_incl _ (flatten (block :: ll)) (length block) (length block')) as PREF; [omega| ].\n exfalso. \n simpl in *. rewrite <- BLOCK', <- L0 in PREF.\n red in MINPROP. specialize (MINPROP block' BLOCK'_P block (skipn (length block) block')).\n apply MINPROP; vauto.\n apply (@f_equal _ _ (@length _)) in PREF. rewrite app_length in PREF.\n red. ins. apply NEblock.\n apply length_zero_iff_nil. apply length_zero_iff_nil in H. omega. \nQed. \n\nLemma ll_l_corr {A: Type} ll (l: list A) (FLT: l = flatten ll) block b\n (NE_LL: Forall (fun l => l <> []) ll)\n P (MINPROP: min_prop P)\n (P_LL: Forall P ll)\n (NE_B: block <> [])\n (BLOCK_P: P block):\n block = sublist l (length (flatten (firstn b ll))) (length block)\n <-> Some block = nth_error ll b.\nProof.\n generalize dependent block. generalize dependent ll. generalize dependent l. \n induction b.\n { intros. unfold sublist. rewrite FLT. simpl.\n split.\n { intros BLOCK. destruct ll.\n { simpl in BLOCK. rewrite firstn_nil in BLOCK. vauto. }\n f_equal.\n eapply start_block_deterministic; eauto; [inv NE_LL| inv P_LL]. }\n intros BLOCK. destruct ll; vauto. simpl.\n rewrite <- Nat.add_0_r with (n := length l0). rewrite firstn_app_2.\n simpl. symmetry. apply app_nil_r. } \n ins. destruct ll; vauto.\n { simpl. unfold sublist. simpl. rewrite firstn_nil. vauto. }\n simpl. rewrite app_length. unfold sublist.\n rewrite skipn_app.\n replace (skipn (length l0 + length (flatten (firstn b ll))) l0) with (@nil A).\n 2: { clear NE_LL. clear P_LL. induction l0.\n { simpl. destruct (length (flatten (firstn b ll))); vauto. }\n simpl. auto. }\n rewrite app_nil_l.\n replace (length l0 + length (flatten (firstn b ll)) - length l0) with (length (flatten (firstn b ll))) by omega. \n apply IHb; vauto.\n { inversion NE_LL. vauto. }\n inversion P_LL. vauto.\nQed. \n\nLemma instr_compiled_min_prop:\n min_prop (fun blk : list Instr.t =>\n exists oinstr : Instr.t, is_instruction_compiled oinstr blk).\nProof.\n red. intros block [oinstr COMP] block' block'' NE'' BLOCK_STRUCT.\n red. intros [oinstr' COMP'].\n inversion COMP; subst.\n all: (inversion COMP'; subst; inversion H0; subst; auto).\nQed. \n\nLemma ll_l_corr_helper BPI PI (FLT: PI = flatten BPI) block b\n (COMP: exists PO, is_thread_block_compiled PO BPI)\n (COMP_BLOCK: exists oinstr, is_instruction_compiled oinstr block)\n :\n block = sublist PI (length (flatten (firstn b BPI))) (length block)\n <-> Some block = nth_error BPI b.\nProof.\n eapply ll_l_corr with (P := fun blk => exists oinstr, is_instruction_compiled oinstr blk); vauto.\n { desc. eapply COMPILED_NONEMPTY; eauto. }\n { apply instr_compiled_min_prop. }\n { clear COMP_BLOCK. eapply Forall_index. ins.\n desc. eapply resulting_block_compiled; eauto.\n eapply COMPILED_NONEMPTY; eauto. } \n desc. inversion COMP_BLOCK; vauto.\nQed. \n\nLemma st_bst_prog_blocks bst block (COMP: exists PO, is_thread_block_compiled PO (binstrs bst)):\n on_block (bst2st bst) block <-> Some block = nth_error (binstrs bst) (bpc bst).\nProof.\n desc.\n assert (Forall (fun l : list Instr.t => l <> []) (binstrs bst)) as BPI_NE. \n { eapply COMPILED_NONEMPTY; eauto. }\n split.\n { intros ON_BLOCK. red in ON_BLOCK. desc.\n unfold bst2st in PROG_BLOCK. simpl in PROG_BLOCK.\n eapply ll_l_corr_helper in PROG_BLOCK; eauto. }\n intros BLOCK. red.\n forward eapply resulting_block_compiled as COMP'; eauto. \n splits; auto. \n eapply ll_l_corr_helper; vauto.\nQed. \n\nDefinition on_block_pc pc PI block := \n ⟪BLOCK: block = sublist PI pc (length block)⟫ /\\\n ⟪COMP_BLOCK: exists oinstr : Instr.t, is_instruction_compiled oinstr block⟫. \n\n(* TODO: remove it since exact instruction is known when block_start is called? *)\nLemma block_start pc PI block instr (BLOCK: on_block_pc pc PI block)\n (AT_PC: Some instr = nth_error PI pc):\n (exists mode, instr = Prog.Instr.fence mode) \\/\n (exists loc expr, instr = Prog.Instr.load Orlx loc expr) \\/\n (exists cond loc, instr = Prog.Instr.ifgoto cond loc) \\/\n (exists reg expr, instr = Prog.Instr.assign reg expr).\nProof.\n red in BLOCK. desc.\n inversion COMP_BLOCK.\n all: subst; simpl in *.\n (* TODO: refactor *)\n - assert (AT_PC1: Some ld = nth_error PI pc).\n { apply eq_trans with (y := nth_error [ld] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n right. left. subst ld. eauto.\n - assert (AT_PC1: Some f = nth_error PI pc).\n { apply eq_trans with (y := nth_error [f; st] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n left. subst f. eauto.\n - assert (AT_PC1: Some f = nth_error PI pc).\n { apply eq_trans with (y := nth_error [f; ld] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n left. subst f. eauto.\n - assert (AT_PC1: Some f = nth_error PI pc).\n { apply eq_trans with (y := nth_error [f; exc] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n left. subst f. eauto.\n - assert (AT_PC1: Some asn = nth_error PI pc).\n { apply eq_trans with (y := nth_error [asn] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n do 3 right. subst asn. eauto.\n - assert (AT_PC1: Some igt = nth_error PI pc).\n { apply eq_trans with (y := nth_error [igt] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r pc).\n eapply sublist_items; eauto. }\n rewrite <- AT_PC in AT_PC1. inversion AT_PC1.\n do 2 right. left. subst igt. eauto.\nQed.\n\n\nLemma block_mid pc PI block instr (BLOCK: on_block_pc pc PI block)\n (BLOCK_LEN: length block >= 2)\n (AT_PC1: Some instr = nth_error PI (pc + 1)):\n (exists loc expr, instr = Prog.Instr.store Orlx loc expr) \\/\n (exists loc expr, instr = Prog.Instr.load Osc loc expr) \\/\n (exists expr loc, instr = Prog.Instr.update (Prog.Instr.exchange expr) false Xpln Osc Osc exchange_reg loc).\nProof.\n red in BLOCK. desc.\n inversion COMP_BLOCK.\n all: (rename H into OINSTR; rename H0 into BLOCK_CONTENTS).\n all: subst block; simpl in *.\n (* trivial cases for single instruction blocks *)\n all: try omega.\n (* now only 2-blocks remain*)\n (* TODO: refactor *)\n { assert (AT_PC1': Some st = nth_error PI (pc + 1)).\n { apply eq_trans with (y := nth_error [f; st] 1); auto.\n eapply sublist_items; eauto. }\n replace instr with st; [| congruence].\n subst st. eauto. }\n { assert (AT_PC1': Some ld = nth_error PI (pc + 1)).\n { apply eq_trans with (y := nth_error [f; ld] 1); auto.\n eapply sublist_items; eauto. }\n replace instr with ld; [| congruence].\n subst ld. eauto. }\n { assert (AT_PC1': Some exc = nth_error PI (pc + 1)).\n { apply eq_trans with (y := nth_error [f; exc] 1); auto.\n eapply sublist_items; eauto. }\n replace instr with exc; [| congruence].\n subst exc. eauto. }\nQed.\n\nLemma no_acb_between_pc pc1 pc2 n (PC2: pc2 = pc1 + n)\n block (* (BLOCK: on_block st1 block) *)\n PI (BLOCK: on_block_pc pc1 PI block)\n (LT: n < length block) (NZ: n <> 0):\n not ((exists block', on_block_pc pc2 PI block') \\/ pc2 >= length PI).\nProof.\n pose proof BLOCK as BLOCK1.\n red in BLOCK. desc.\n inversion COMP_BLOCK.\n all: rename H into OINSTR.\n all: rename H0 into BLOCK_CONTENTS.\n all: subst block; simpl in *.\n (* trivial cases for single instruction blocks *)\n all: try (replace (n) with (0) in *; [vauto | omega]).\n (* now only 2-blocks remain*)\n all: replace n with 1 in *; [| omega].\n (* TODO: refactor *)\n { assert (AT_PC1: Some st = nth_error PI (pc1 + 1)).\n { apply eq_trans with (y := nth_error [f; st] 1); auto.\n eapply sublist_items; eauto. }\n assert (AT_PC: Some f = nth_error PI pc1).\n { apply eq_trans with (y := nth_error [f; st] 0); auto.\n replace pc1 with (pc1 + 0) by omega.\n eapply sublist_items; eauto. }\n \n red. intros ACB2. (* red in ACB2. *)\n destruct ACB2 as [[block2 BLOCK2]| TERM2].\n 2: { subst pc2. \n red in TERM2. (* rewrite NEXT_PC, SAME_INSTRS in TERM2. *)\n pose proof (nth_error_None PI (pc1 + 1)) as CONTRA.\n apply not_iff_compat in CONTRA. destruct CONTRA as [CONTRA _].\n forward eapply CONTRA; [apply OPT_VAL; eauto| ].\n ins. } \n forward eapply (block_start) as PC1_INSTR; eauto.\n { rewrite PC2. eauto. }\n forward eapply (block_mid BLOCK1) as PC1_INSTR'; eauto.\n des.\n all: (rewrite PC1_INSTR in PC1_INSTR'; discriminate). }\n { assert (AT_PC1: Some ld = nth_error PI (pc1 + 1)).\n { apply eq_trans with (y := nth_error [f; ld] 1); auto.\n eapply sublist_items; eauto. }\n assert (AT_PC: Some f = nth_error PI pc1).\n { apply eq_trans with (y := nth_error [f; ld] 0); auto.\n replace pc1 with (pc1 + 0) by omega.\n eapply sublist_items; eauto. }\n \n red. intros ACB2. \n destruct ACB2 as [[block2 BLOCK2]| TERM2].\n 2: { red in TERM2. (* rewrite NEXT_PC, SAME_INSTRS in TERM2. *)\n pose proof (nth_error_None PI (pc1 + 1)) as CONTRA.\n destruct CONTRA. forward eapply H0; try omega.\n intros. rewrite H1 in AT_PC1. discriminate. }\n forward eapply (block_start) as PC1_INSTR; eauto.\n { rewrite PC2. eauto. }\n forward eapply (block_mid BLOCK1) as PC1_INSTR'; eauto.\n des.\n all: (rewrite PC1_INSTR in PC1_INSTR'; discriminate). }\n { assert (AT_PC1: Some exc = nth_error PI (pc1 + 1)).\n { apply eq_trans with (y := nth_error [f; exc] 1); auto.\n eapply sublist_items; eauto. }\n assert (AT_PC: Some f = nth_error PI pc1).\n { apply eq_trans with (y := nth_error [f; exc] 0); auto.\n replace pc1 with (pc1 + 0) by omega.\n eapply sublist_items; eauto. } \n red. intros ACB2. \n destruct ACB2 as [[block2 BLOCK2]| TERM2].\n 2: { red in TERM2. rewrite PC2 in TERM2.\n pose proof (nth_error_None PI (pc1 + 1)) as CONTRA.\n destruct CONTRA. forward eapply H0; try omega.\n intros. rewrite H1 in AT_PC1. discriminate. }\n forward eapply (block_start) as PC1_INSTR; eauto.\n { rewrite PC2. eauto. }\n forward eapply (block_mid BLOCK1) as PC1_INSTR'; eauto.\n des.\n all: (rewrite PC1_INSTR in PC1_INSTR'; discriminate). }\nQed. \n\nLemma no_acb_between st1 st2 tid block n (STEPS: (step tid) ^^ n st1 st2)\n (BLOCK: on_block st1 block) (LT: n < length block) (NZ: n <> 0):\n not (at_compilation_block st2).\nProof.\n assert (SAME_INSTRS: instrs st2 = instrs st1).\n { symmetry. apply steps_same_instrs. eexists. eapply crt_num_steps. eauto. }\n pose proof BLOCK as BLOCK1.\n red in BLOCK. desc.\n\n cut (not ((exists block', on_block_pc (pc st2) (instrs st1) block') \\/ (pc st2 >= length (instrs st1)))).\n { ins. red. ins. apply H. red in H0. des.\n { left. exists block0. red in H0.\n rewrite SAME_INSTRS in H0. \n desc. red. splits; eauto. }\n right. red in H0. congruence. }\n\n eapply no_acb_between_pc; eauto.\n assert (length block = 2 -> exists md, Some (Instr.fence md) = nth_error (instrs st1) (pc st1)).\n { ins. inversion COMP_BLOCK; vauto.\n all: subst f.\n { exists Oacqrel.\n apply eq_trans with (y := nth_error [Instr.fence Oacqrel; st] 0); auto.\n replace (pc st1) with (pc st1 + 0) by omega.\n eapply sublist_items; vauto. }\n { exists Oacq.\n apply eq_trans with (y := nth_error [Instr.fence Oacq; ld] 0); auto.\n replace (pc st1) with (pc st1 + 0) by omega.\n eapply sublist_items; vauto. }\n exists Oacq.\n apply eq_trans with (y := nth_error [Instr.fence Oacq; exc] 0); auto.\n replace (pc st1) with (pc st1 + 0) by omega.\n eapply sublist_items; vauto. }\n inversion COMP_BLOCK; subst; simpl in *; try omega.\n all: replace n with 1 in * by omega.\n all: apply (same_relation_exp (pow_1 (step tid))) in STEPS.\n all: red in STEPS; desc; red in STEPS; desc.\n all: inversion ISTEP0; vauto.\n all: destruct H as [md FENCE]; auto.\n all: rewrite <- FENCE in ISTEP.\n all: inversion ISTEP.\nQed. \n\nLemma skipn_0 {A: Type} (l: list A): skipn 0 l = l.\nProof. destruct l; vauto. Qed. \n\nLemma on_block_iff_bindex BPI\n block pc (SL: block = sublist (flatten BPI) pc (length block))\n (COMP: exists PO, is_thread_block_compiled PO BPI):\n (exists oinstr, is_instruction_compiled oinstr block) <->\n exists b, Some block = nth_error BPI b /\\ pc = length (flatten (firstn b BPI)). \nProof.\n split.\n 2: { ins. desc. eapply resulting_block_compiled; eauto.\n eapply COMPILED_NONEMPTY; eauto. }\n intros COMP_BLOCK.\n assert (COMP': exists PO, itbc_weak PO BPI).\n { desc. exists PO. red. red in COMP. desc. eauto. }\n clear COMP. \n generalize dependent BPI.\n set (P := fun pc => forall BPI : list (list Instr.t),\n block = sublist (flatten BPI) pc (length block) ->\n (exists PO : list Instr.t, itbc_weak PO BPI) ->\n exists b : nat, Some block = nth_error BPI b /\\ pc = length (flatten (firstn b BPI))).\n generalize dependent pc. apply (strong_induction P).\n intros pc IH. red. intros BPI BLOCK COMP.\n destruct BPI as [| blk0 BPI']. \n { exfalso. unfold sublist in BLOCK.\n desc. \n destruct pc; simpl in BLOCK; rewrite firstn_nil in BLOCK; inversion COMP_BLOCK; vauto. }\n destruct (ge_dec pc (length blk0)) as [GE | LT].\n { assert (block = sublist (flatten BPI') (pc - length blk0) (length block)).\n { rewrite BLOCK at 1.\n simpl. unfold sublist at 1.\n rewrite skipn_app. unfold sublist.\n rewrite firstn_app.\n rewrite skipn_all2; [| omega]. rewrite firstn_nil. simpl.\n rewrite Nat.sub_0_r. auto. }\n forward eapply (IH (pc - length blk0)) as IHprev. \n { desc. forward eapply COMPILED_NONEMPTY_weak as NE; eauto.\n inversion NE. subst. destruct blk0; vauto. simpl in *. omega. }\n red in IHprev. forward eapply (IHprev BPI' H) as [b' BLOCK']. \n { desc. destruct PO as [| oinstr_ PO']. \n { red in COMP. desc. inversion COMP. subst. inversion COMP0. }\n exists PO'. red. red in COMP. destruct COMP as [BPI0 [BPI0' [COMP CORR]]].\n inversion CORR. subst. inversion COMP. subst. eauto. }\n exists (S b'). desc. split; auto. \n simpl. rewrite app_length. omega. }\n apply not_ge in LT.\n assert (blk0 = firstn (length blk0) (blk0 ++ flatten BPI')) as BLK0.\n { rewrite <- Nat.add_0_r with (n := length blk0). rewrite firstn_app_2.\n rewrite firstn_O. symmetry. apply app_nil_r. }\n destruct (gt_0_eq pc).\n 2: { subst. exists 0. simpl in *. split; auto. f_equal.\n unfold sublist in BLOCK. rewrite skipn_0 in BLOCK.\n eapply (start_block_deterministic (P := fun blk => exists oinstr, is_instruction_compiled oinstr blk)); eauto.\n { apply instr_compiled_min_prop. }\n { desc. pose proof (COMPILED_NONEMPTY_weak COMP).\n inv H. }\n { desc.\n eapply resulting_block_compiled_weak; eauto.\n { eapply COMPILED_NONEMPTY_weak; eauto. }\n Unshelve. 2: exact 0. vauto. }\n desc. inversion COMP_BLOCK; vauto. }\n exfalso.\n forward eapply (@no_acb_between_pc 0 pc pc) as NOACB; eauto. \n { Unshelve. 2: exact (blk0 ++ flatten BPI'). \n red. splits; vauto.\n desc. eapply resulting_block_compiled_weak; eauto.\n { eapply COMPILED_NONEMPTY_weak; eauto. }\n Unshelve. 2: exact 0. auto. }\n { omega. }\n apply not_or in NOACB. desc.\n apply NOACB. exists block. red. splits; eauto.\nQed. \n\nLemma acb_iff_bst st BPI\n (COMP: exists PO, is_thread_compiled_with PO (instrs st) BPI)\n (REACH: exists tid, (step tid)* (init (instrs st)) st):\n at_compilation_block st <-> exists bst, ⟪ST: st = bst2st bst⟫ /\\\n ⟪BINSTRS: binstrs bst = BPI⟫ /\\\n ⟪BPC: bpc bst <= length BPI⟫. \nProof.\n split.\n { intros ACB. desc. red in COMP. desc.\n red in ACB. des.\n 2: { exists (bst_from_st st BPI (length BPI)). splits; auto. \n unfold bst2st. simpl. rewrite firstn_all. rewrite <- COMP0.\n forward eapply (@is_terminal_pc_bounded st tid PO (flatten BPI)) as TERM; vauto.\n { congruence. }\n apply TERM in ACB. rewrite <- ACB.\n by destruct st. }\n red in ACB. desc. \n forward eapply (@on_block_iff_bindex BPI block (pc st)) as [BLOCK_INDEX _]; vauto. \n { congruence. }\n forward eapply BLOCK_INDEX as [b [BLOCK PC]]; eauto.\n exists (bst_from_st st BPI b). splits; auto.\n 2: { apply Nat.lt_le_incl. apply nth_error_Some, OPT_VAL. eauto. } \n unfold bst2st, bst_from_st. simpl.\n rewrite <- PC, <- COMP0. by destruct st. }\n intros. desc. red. red in COMP. desc.\n subst. \n destruct (ge_dec (bpc bst) (length (binstrs bst))) as [TERM | NONTERM].\n { right.\n forward eapply (@is_terminal_pc_bounded (bst2st bst) tid PO (instrs (bst2st bst))) as TERM_EQ; vauto.\n apply TERM_EQ. \n pose proof is_terminal_pc_bounded. \n simpl.\n rewrite <- firstn_skipn with (n := bpc bst) (l := binstrs bst) at 2.\n rewrite skipn_all2; [| auto]. \n rewrite app_nil_r. auto. }\n apply not_ge in NONTERM. left.\n apply nth_error_Some, OPT_VAL in NONTERM. destruct NONTERM as [block BLOCK].\n exists block. apply st_bst_prog_blocks; eauto. \nQed. \n\nDefinition non_igt instr :=\n ~ match instr with | Instr.ifgoto _ _ => True | _ => False end. \n\nLemma regular_pc_change st1 st2 tid (STEP: step tid st1 st2)\n instr (AT_PC: Some instr = nth_error (instrs st1) (pc st1))\n (NOT_IGT: non_igt instr):\n pc st2 = pc st1 + 1.\nProof.\n do 2 (red in STEP; desc). red in NOT_IGT. \n inversion ISTEP0; auto.\n assert (instr = instr0) by congruence. subst. vauto.\nQed. \n\nLemma steps_pc_change st1 st2 tid block (ON_BLOCK: on_block st1 block)\n (STEPS: (step tid) ^^ (length block) st1 st2):\n pc st2 = pc st1 + length block \\/\n (exists (cond : Instr.expr) (addr : nat),\n block = [Instr.ifgoto cond addr] /\\ pc st2 = addr).\nProof.\n red in ON_BLOCK. desc.\n destruct block as [| instr block'].\n { inversion COMP_BLOCK. }\n assert ([instr] = sublist (instrs st1) (pc st1) 1).\n { unfold sublist in *. simpl in PROG_BLOCK.\n simpl. destruct (skipn (pc st1) (instrs st1)); vauto. }\n assert (AT_PC: Some instr = nth_error (instrs st1) (pc st1)).\n { apply eq_trans with (y := nth_error [instr] 0); auto.\n rewrite <- (NPeano.Nat.add_0_r (pc st1)).\n eapply sublist_items; eauto. }\n destruct block' as [| instr' block''].\n { \n inversion COMP_BLOCK.\n 3: { subst. simpl in *.\n apply (same_relation_exp (seq_id_l (step tid))) in STEPS.\n do 2 (red in STEPS; desc).\n (* actually most cases here are nonsense, but they still fit into lemma statement *)\n inversion ISTEP0; auto.\n subst instr.\n destruct (Const.eq_dec (RegFile.eval_expr (regf st1) expr) 0); auto.\n right. exists e. exists n. split; eauto. \n assert (igt = Instr.ifgoto expr shift) by congruence.\n inversion H0. auto. } \n all: left; subst; simpl in *.\n all: try apply (same_relation_exp (seq_id_l (step tid))) in STEPS.\n all: eapply regular_pc_change; vauto. }\n left. \n assert ([instr; instr'] = sublist (instrs st1) (pc st1) 2).\n { unfold sublist in *. simpl in PROG_BLOCK.\n simpl. destruct (skipn (pc st1) (instrs st1)); vauto.\n destruct l; vauto. }\n assert (AT_PC': Some instr' = nth_error (instrs st1) (pc st1 + 1)).\n { apply eq_trans with (y := nth_error [instr; instr'] 1); auto.\n eapply sublist_items; eauto. }\n simpl. \n simpl in STEPS. red in STEPS. desc. red in STEPS. desc.\n assert (forall st' (STEP1: step tid st1 st') (STEP2: step tid st' st2)\n (NOT_IGT1: non_igt instr) (NOT_IGT2: non_igt instr'),\n pc st2 = pc st1 + 2) as STEPS2_HELPER. \n { ins.\n assert (pc st' = pc st1 + 1) by (eapply regular_pc_change; eauto). \n replace (pc st2) with (pc st' + 1); [omega| ]. \n symmetry. eapply regular_pc_change; eauto.\n replace (instrs st') with (instrs st1); [congruence |].\n do 2 (red in STEP1; desc). auto. }\n \n inversion COMP_BLOCK; subst; simpl in *; red in STEPS; subst; desc.\n all: forward eapply STEPS2_HELPER; vauto.\nQed.\n\nLemma oseq_continuos st1 st2 tid PO\n (OSEQ: (oseq_step tid) st1 st2)\n (REACH: (step tid)* (init (instrs st1)) st1)\n (GOTO_RESTR: goto_addresses_restricted PO)\n (COMP: is_thread_compiled PO (instrs st1)):\n at_compilation_block st2.\nProof.\n red in OSEQ. desc.\n red in COMP. desc. \n assert (exists bst1, st1 = bst2st bst1 /\\ binstrs bst1 = BPI /\\ bpc bst1 <= length BPI) as [bst1 [BST1 [BINSTRS1 BPC1]]].\n { apply acb_iff_bst; vauto. }\n assert (Some block = nth_error (binstrs bst1) (bpc bst1)) as BLOCK. \n { apply st_bst_prog_blocks; vauto.\n exists PO. red in COMP. desc. auto. }\n forward eapply steps_pc_change as PC2; eauto.\n assert (instrs st2 = instrs st1) as SAME_INSTRS. \n { symmetry. apply steps_same_instrs. exists tid. apply crt_num_steps. eauto. } \n assert ((step tid)* (init (instrs st2)) st2) as REACH'.\n { rewrite SAME_INSTRS. eapply rt_trans; eauto. apply crt_num_steps. eauto. }\n \n assert (forall blc (STEPS: (step tid) ^^ (length blc) st1 st2)\n (BLC: Some blc = nth_error (binstrs bst1) (bpc bst1))\n (PC_PLUS: pc st2 = pc st1 + length blc),\n at_compilation_block st2) as NEXT_BLOCK. \n { ins. forward eapply (@acb_iff_bst st2) as [_ ACB_IF_BST].\n 2: { eauto. }\n { rewrite SAME_INSTRS. eauto. }\n apply ACB_IF_BST. \n exists (bst_from_st st2 (binstrs bst1) (bpc bst1 + 1)).\n splits; auto.\n 2: { simpl. apply le_lt_or_eq in BPC1. destruct BPC1; [omega |]. \n subst.\n pose proof (proj2 (nth_error_None (binstrs bst1) (bpc bst1))).\n forward eapply H0; [omega| ]. ins. congruence. } \n unfold bst2st. simpl.\n replace (flatten (binstrs bst1)) with (instrs st2).\n 2: { rewrite <- (@steps_same_instrs st1 st2); [subst; eauto| ].\n exists tid. apply crt_num_steps. eauto. }\n red in OSEQ. desc.\n clear dependent oinstr. (* to avoid confusion with actual initial oinstr *)\n pose proof ll_index_shift. specialize H with (j := (bpc bst1 + 1)). specialize_full H; eauto. \n { eapply COMPILED_NONEMPTY. Unshelve. 2: exact PO.\n red in COMP. desc. vauto. }\n { cut (bpc bst1 < length (binstrs bst1)); [ins; omega|].\n apply nth_error_Some, OPT_VAL. vauto. }\n cdes H. rewrite H1; auto. \n subst st1. unfold bst2st in PC_PLUS. simpl in PC_PLUS. \n rewrite <- PC_PLUS. \n by destruct st2. }\n \n destruct PC2 as [PC2 | PC2]. \n - eapply NEXT_BLOCK; eauto. \n - desc. subst addr. (* subst block. *) simpl in *. \n red in COMP. desc.\n subst BPI. \n red in COMP. desc. \n assert (exists oinstr, Some oinstr = nth_error PO (bpc bst1)) as [oinstr OINSTR]. \n { apply OPT_VAL. apply nth_error_Some.\n replace (length PO) with (length (binstrs bst1)).\n { apply nth_error_Some, OPT_VAL. eauto. }\n symmetry. apply compilation_same_length. red; vauto. } \n assert (exists block0, Some block0 = nth_error BPI0 (bpc bst1)) as [block0 BLOCK0].\n { apply OPT_VAL. apply nth_error_Some.\n replace (length BPI0) with (length (binstrs bst1)).\n { apply nth_error_Some, OPT_VAL. eauto. }\n symmetry. eapply Forall2_length. eauto. }\n assert (is_instruction_compiled oinstr block0) as COMP_BLOCK.\n { eapply Forall2_index; eauto. } \n assert (block_corrected BPI0 block0 block) as CORR_BLOCK.\n { eapply Forall2_index; eauto. } \n subst block.\n inversion CORR_BLOCK. inversion H3. subst. \n inversion H2; vauto. subst addr.\n inversion COMP_BLOCK. subst. \n simpl in OSEQ0. apply (same_relation_exp (seq_id_l (step tid))) in OSEQ0.\n do 2 (red in OSEQ0; desc).\n assert (instr = Instr.ifgoto cond (pc st2)).\n { forward eapply (@near_pc (Instr.ifgoto cond (pc st2)) _ 0) as AT_PC; eauto.\n { vauto. }\n { apply nth_error_Some, OPT_VAL. eauto. }\n rewrite Nat.add_0_r in AT_PC. congruence. }\n subst instr. \n inversion ISTEP0. \n all: try discriminate.\n destruct (Const.eq_dec (RegFile.eval_expr (regf (bst2st bst1)) expr) 0). \n + eapply NEXT_BLOCK; eauto. simpl.\n apply (same_relation_exp (seq_id_l (step tid))).\n red. eexists. red. eauto.\n + subst.\n inversion CORR_BLOCK. subst. inversion H4; vauto.\n forward eapply acb_iff_bst as [_ ACB_IF_BST]. \n { rewrite <- INSTRS. exists PO. simpl. red. splits; eauto. \n vauto. }\n { eauto. }\n apply ACB_IF_BST. \n exists (bst_from_st st2 (binstrs bst1) addr0). splits; auto.\n 2: { simpl.\n replace (length (binstrs bst1)) with (length PO).\n 2: { apply compilation_same_length. vauto. }\n red in GOTO_RESTR. eapply GOTO_RESTR; eauto. }\n unfold bst2st. simpl.\n replace (flatten (binstrs bst1)) with (instrs st2).\n replace (length (flatten (firstn addr0 (binstrs bst1)))) with (length (flatten (firstn addr0 BPI0))).\n 2: { apply SAME_STRUCT_PREF. eapply correction_same_struct; eauto. } \n rewrite H5. by destruct st2. \nQed. \n\n\n(* had to define it separately since otherwise Coq doesn't understand what P is *)\nDefinition StepProp n := forall st1 st2 tid PO (STEPS: (step tid) ^^ n st1 st2)\n (REACH: (step tid)* (init (instrs st1)) st1)\n bst1 (BST1: st1 = bst2st bst1)\n bst2 (BST2: st2 = bst2st bst2)\n (BOUND1: bpc bst1 <= length (binstrs bst1))\n (BOUND2: bpc bst2 <= length (binstrs bst2))\n (COMP: is_thread_block_compiled PO (binstrs bst1))\n (GOTO_RESTR: goto_addresses_restricted PO)\n (SAME_BINSTRS: binstrs bst1 = binstrs bst2),\n (omm_block_step_PO PO tid)* bst1 bst2.\n\nLemma oseq_between_acb: forall n, StepProp n.\nProof.\n apply strong_induction. \n unfold StepProp. intros n IH. ins. desc.\n assert (at_compilation_block st1) as ACB1.\n { eapply acb_iff_bst; eauto.\n unfold is_thread_compiled_with. exists PO.\n split; [congruence| ]. rewrite BST1. simpl. congruence. }\n assert (at_compilation_block st2) as ACB2.\n { forward eapply (@acb_iff_bst st2) as [_ ACB_IF_BST]; eauto.\n { exists PO. red. split; eauto. rewrite SAME_BINSTRS. vauto. }\n { exists tid. replace (instrs st2) with (instrs st1).\n 2: { subst. simpl. congruence. }\n eapply transitive_rt; eauto.\n apply crt_num_steps. eauto. }\n apply ACB_IF_BST. exists bst2. splits; vauto. congruence. }\n assert (bst2st bst1 = bst2st bst2 -> (omm_block_step_PO PO tid)* bst1 bst2) as WHEN_SAME_BST. \n { intros SAME_BST2ST. \n replace bst2 with bst1; [apply rt_refl| ].\n destruct bst2. destruct bst1. \n f_equal; vauto. \n rewrite <- SAME_BINSTRS in BOUND2.\n simpl in *. \n eapply (@NONEMPTY_PREF _ binstrs); vauto. \n eapply COMPILED_NONEMPTY; eauto. }\n \n unfold at_compilation_block in ACB1. desf. \n 2: { destruct n.\n { apply WHEN_SAME_BST. apply steps0 in STEPS. auto. }\n forward eapply (@steps_sub _ (step tid) (S n) _ _ 1) as [st' STEP];\n [omega | eauto |].\n apply (same_relation_exp (pow_1 (step tid))) in STEP.\n do 2 (red in STEP; desc). \n cut (None = nth_error (instrs (bst2st bst1)) (pc (bst2st bst1))); [congruence| ].\n symmetry. apply nth_error_None. red in ACB1. omega. }\n pose proof (le_lt_dec (length block) n) as LEN. destruct LEN.\n { forward eapply (steps_split (step tid) (length block) (n - length block)) as SPLIT.\n { symmetry. apply le_plus_minus. auto. }\n apply SPLIT in STEPS. destruct STEPS as [st' [PREV_STEPS NEXT_STEPS]]. clear SPLIT.\n assert (oseq_step tid (bst2st bst1) st') as OSEQ. \n { red. eexists. eauto. }\n forward eapply (oseq_continuos OSEQ) as ACB'; vauto.\n assert (exists PO', is_thread_compiled PO' (instrs st')) as COMP'.\n { replace (instrs st') with (instrs (bst2st bst1)); vauto.\n apply steps_same_instrs. exists tid.\n (* remove duplicated proof *)\n red in OSEQ. desc. rewrite crt_num_steps. eexists. eauto. }\n assert (LEN': n - length block < n).\n { red in ACB1. desc. inversion COMP_BLOCK; subst; simpl in *; omega. }\n assert ((step tid)* (init (instrs st')) st') as REACH'.\n { replace (instrs st') with (instrs (bst2st bst1)).\n 2: { apply steps_same_instrs. exists tid. apply crt_num_steps. eauto. }\n eapply transitive_rt; eauto.\n apply crt_num_steps. eauto. }\n forward eapply (@acb_iff_bst st' (binstrs bst1)) as [BST_IF_ACB _]; eauto. \n { exists PO. red. split; auto.\n replace (instrs st') with (instrs (bst2st bst1)); auto.\n apply steps_same_instrs; eauto. exists tid. apply crt_num_steps. eauto. }\n specialize (BST_IF_ACB ACB'). destruct BST_IF_ACB as [bst' [BST' [SAME_BINSTRS' BPC']]]. \n forward eapply IH as IH_; eauto.\n { red in SAME_BINSTRS'. rewrite SAME_BINSTRS'. auto. }\n { congruence. }\n { congruence. }\n apply clos_trans_in_rt. apply t_step_rt. exists bst'. split; auto. \n red. splits; vauto. \n exists block. red. splits; auto.\n apply st_bst_prog_blocks; eauto. rewrite <- BST'. auto. }\n destruct (NPeano.Nat.eq_0_gt_0_cases n).\n { subst. apply steps0 in STEPS. apply WHEN_SAME_BST. auto. }\n forward eapply no_acb_between; eauto; [omega | vauto]. \nQed. \n\nDefinition is_block_terminal bst := bpc bst >= length (binstrs bst). \n\nLemma steps_imply_ommblocks bfin PO tid\n (BPC_LIM: bpc bfin <= length (binstrs bfin))\n (GOTO_RESTR: goto_addresses_restricted PO)\n (COMP: is_thread_block_compiled PO (binstrs bfin)):\n let fin := (bst2st bfin) in \n (step tid)* (init (instrs fin)) fin -> (omm_block_step_PO PO tid)* (binit (binstrs bfin)) bfin.\nProof.\n intros fin STEPS. apply crt_num_steps in STEPS as [n STEPS].\n eapply oseq_between_acb; eauto.\n 2: { simpl. omega. }\n simpl. apply rt_refl. \nQed. \n\nLemma ommblocks_imply_steps bfin tid PO:\n let fin := (bst2st bfin) in \n (omm_block_step_PO PO tid)* (binit (binstrs bfin)) bfin -> (step tid)* (init (instrs fin)) fin.\nProof.\n intros fin STEPS. apply crt_num_steps in STEPS as [n STEPS].\n generalize dependent bfin. induction n.\n { ins. red in STEPS. desc. subst. simpl.\n replace (init (flatten (binstrs bfin))) with (bst2st bfin); [apply rt_refl| ].\n rewrite <- STEPS. vauto. }\n ins. apply crt_num_steps.\n red in STEPS. desc.\n assert (binstrs bfin = binstrs z) as BINSTRS_SAME. \n { red in STEPS0. desc. vauto. }\n rewrite BINSTRS_SAME in STEPS. specialize (IHn z STEPS).\n red in STEPS0. desc. red in BLOCK_STEP. desc.\n apply crt_num_steps in IHn. desc. \n exists (n0 + length block). eapply steps_split; eauto.\n eexists. splits; eauto. rewrite BINSTRS_SAME. auto. \nQed. \n\nEnd Steps.\n", "meta": {"author": "fresheed", "repo": "omm-imm", "sha": "59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2", "save_path": "github-repos/coq/fresheed-omm-imm", "path": "github-repos/coq/fresheed-omm-imm/omm-imm-59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2/src/ocamlmm/BlockSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.24508501864634824, "lm_q1q2_score": 0.13019145554059938}} {"text": "Require Import CoqlibC Maps Integers Floats Lattice Kildall.\nRequire Import AST Linking.\nRequire Import ValuesC Events Memory Globalenvs Smallstep.\nRequire Compopts Machregs.\nRequire Import Op Registers RTLC.\nRequire Import Liveness ValueDomain ValueAOp ValueAnalysisC.\nRequire Import ConstpropOp ConstpropOpproof Constprop.\n(** newly added **)\nRequire Export Constpropproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem.\nRequire SimMemExt.\nRequire UnreachC.\n\nSet Implicit Arguments.\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariables prog tprog: program.\nLet md_src: Mod.t := (RTLC.module prog).\nLet md_tgt: Mod.t := (RTLC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\nHypothesis TRANSL: match_prog prog tprog.\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat) (st_src0: RTL.state) (st_tgt0: RTL.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: Constpropproof.match_states prog idx st_src0 st_tgt0)\n (MCOMPATSRC: (get_mem st_src0) = sm0.(SimMem.src))\n (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt)).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun cu f tf => tf = transf_fundef (romem_for cu) f) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nTheorem sim_modsem:ModSemPair.sim msp.\nProof.\n eapply match_states_sim with (match_states := match_states) (match_states_at := top4);\n eauto; ii; ss.\n - apply lt_wf.\n - eapply Preservation.local_preservation_strong_spec. eapply sound_state_preservation; auto.\n - (* init bsim *)\n destruct sm_arg; ss. clarify. inv INITTGT. inv SIMARGS; ss. clarify.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n eexists. eexists (SimMemExt.mk _ _). esplits; eauto.\n + econs; eauto; ss.\n * inv TYP. rpapply match_states_call; eauto.\n { econs; eauto. }\n { eapply lessdef_list_typify_list; try apply VALS; eauto. rewrite <- LEN.\n symmetry. eapply lessdef_list_length; eauto. }\n folder. inv SAFESRC. inv TYP.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. folder.\n inv FPTR; ss. clarify.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss. inv FPTR; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. des_ifs.\n inv TYP. esplits; eauto. econs; swap 1 2; eauto.\n + econs; eauto with congruence.\n erewrite <- lessdef_list_length; eauto.\n + erewrite <- lessdef_list_length; eauto.\n - (* call wf *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n u in CALLSRC. des. inv CALLSRC. inv MATCHST; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n inv CALLSRC. inv MATCHST; ss; cycle 1. folder. esplits; eauto.\n + econs; eauto.\n * folder. des. r in TRANSL. r in TRANSL.\n exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.\n { apply SIMSKENV. }\n intro GE. apply (fsim_external_funct_id GE); ss.\n folder. inv FPTR; ss.\n * des. esplits; eauto. eapply SimSymb.simskenv_func_fsim; eauto; ss.\n + econs; ss; eauto.\n * instantiate (1:= SimMemExt.mk _ _). ss.\n * ss.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; eauto.\n + econs; eauto.\n + econs; ss; eauto. clarify. econs; eauto. eapply lessdef_typify; ss.\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss.\n clarify. inv STACKS. destruct sm0; ss. clarify.\n eexists (SimMemExt.mk _ _). esplits; ss; eauto. econs; eauto.\n - left; i. esplits; eauto.\n { apply RTLC.modsem_receptive; et. }\n inv MATCH. ii. hexploit (@transf_step_correct prog skenv_link skenv_link); eauto.\n { inv SIMSKENV. ss. }\n { apply make_match_genvs; eauto. apply SIMSKENV. }\n { des. esplits; eauto. }\n i; des_safe. folder. des.\n + esplits; eauto.\n * left. apply plus_one. split. { apply modsem_determinate; et. } eauto.\n * instantiate (1:= (SimMemExt.mk _ _)). ss. econs; ss; eauto.\n + clarify. esplits; eauto.\n * right. esplits; eauto. { apply star_refl. }\n * instantiate (1:= (SimMemExt.mk _ _)). ss.\nUnshelve.\n all: ss. apply msp.\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariable prog tprog: RTL.program.\nHypothesis TRANSL: match_prog prog tprog.\n\nDefinition mp: ModPair.t := SimSymbId.mk_mp (RTLC.module prog) (RTLC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. eapply Sk.match_program_eq; eauto.\n ii. destruct f1; ss.\n + clarify. right. esplits; eauto.\n + clarify. left. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/ConstpropproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.12993396956731007}} {"text": "From aneris.aneris_lang Require Import lang resources.\nFrom stdpp Require Import gmap.\nFrom aneris.prelude Require Import misc.\nFrom aneris.examples.ccddb.spec Require Import base.\nFrom aneris.examples.ccddb.model Require Import events model_lst\n model_update_prelude.\n\nSection Lsec_udpate.\n Context `{!anerisG Mdl Σ, !DB_params}.\n\n Lemma update_condition_lsec_not_in e i t (s : gset apply_event) j :\n (i < length t) →\n (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n update_condition i e t →\n e ∉ DBM_lsec j s.\n Proof.\n intros Hjt Hst Hcnd Habs.\n apply (update_condition_time _ _ _ Hcnd).\n apply in_lsec_in_lhst in Habs.\n by pose proof update_condition_lhst_not_in e i t s Hjt Hst Hcnd.\n Qed.\n\n (* NB: The assumption\n \"t !! (ae_orig e) = Some (length (elements (DBM_lsec (ae_orig e) s))) →\"\n is important and can be derived either from\n Local state validity or from dynamic check)\n *)\n Lemma DBM_lsec_complete_update e i j t s :\n DBM_lhst_valid i s →\n (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n ae_seqid e = S (size s) →\n update_condition i e t →\n j < length DB_addresses →\n t !! (ae_orig e) = Some (length (elements (DBM_lsec (ae_orig e) s))) →\n DBM_lsec_complete j (s ∪ {[e]}).\n Proof.\n intros His Hs Hseq Hcnd Hj Hte.\n destruct (decide (j = e.(ae_orig))) as [ Heq | Hneq ]; last first.\n - intros k.\n rewrite !DBM_lsec_union !DBM_lsec_singleton_out; last lia.\n rewrite right_id_L.\n intros; eapply DBM_LSV_comp; first apply DBM_LHV_secs_valid; eauto.\n - intro k.\n rewrite !DBM_lsec_union !DBM_lsec_singleton_in; last done.\n pose proof Hcnd as\n (Hi & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n destruct (lookup_lt_is_Some_2 (ae_time e) i) as [ti Hti];\n eauto with lia.\n rewrite (comm_L _ _ {[_]}) elements_union_singleton /=; last first.\n { eapply update_condition_lsec_not_in; eauto; lia. }\n pose proof (DBM_LHV_secs_valid His j Hj) as Hij.\n destruct (decide (k ≤ (length (elements (DBM_lsec j s))))).\n + intros [? ?].\n destruct (DBM_LSV_comp Hij k) as [x [Hx1 Hx2]]; first eauto with lia.\n set_solver.\n + intros [Hk1 Hk2].\n assert (k = S (length (elements (DBM_lsec j s))))\n as -> by by simpl in *; lia.\n exists e. split; first set_solver.\n subst j. by rewrite Het Hte.\n Qed.\n\n Lemma DBM_lsec_locally_causal_refl_update e i t s :\n DBM_lhst_valid i s →\n (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n ae_seqid e = S (size s) →\n update_condition i e t →\n (ae_orig e = i →\n ∀ j, j < length DB_addresses →\n t !! j = Some (length (elements (DBM_lsec j s)))) →\n DBM_lsec_locally_causal_refl i (s ∪ {[e]}).\n Proof.\n intros His Hs Hseq Hcnd Htj.\n intros j' ei Hj' Hij'\n [He'1 [He'2| ->%elem_of_singleton]%elem_of_union]%elem_of_filter.\n pose proof DBM_LHV_bound_at His as Hb.\n pose proof DBM_LHV_secs_valid His i Hb as Hsv.\n - (* i ≠ ae_orig e *)\n assert (ae_time ei !! j' = Some (DBM_lsec_latest_in_frame j' s ei)) as ->.\n { apply (DBM_LSV_caus_refl Hsv j' ei); eauto with lia.\n rewrite -He'1. by apply in_lsec_orig. }\n rewrite /DBM_lsec_latest_in_frame. f_equal.\n apply nat_sup_equiv. intros k.\n rewrite !elem_of_list_omap.\n setoid_rewrite elem_of_list_filter.\n setoid_rewrite elem_of_elements.\n assert ( ae_seqid ei < ae_seqid e) as Hseqi.\n { pose proof DBM_LHV_seqids His ei He'2. lia. }\n split.\n + intros (x&[Hx1 Hxin]&Hx2).\n exists x; split_and!; [done| set_solver | done].\n + intros (x&[Hx1 Hxin]&Hx2).\n exists x; split_and!; [done| | done].\n assert ( ae_seqid x < ae_seqid e) by lia.\n rewrite (DBM_lsec_union j' s {[e]})in Hxin.\n apply elem_of_union in Hxin as [Hx | Hx]; first done.\n rewrite /DBM_lsec in Hx.\n apply elem_of_filter in Hx as [? <-%elem_of_singleton].\n eauto with lia.\n - (* i = ae_orig e *)\n pose proof Hcnd as\n (Hi & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n specialize (Het'' He'1).\n specialize (Htj He'1).\n assert (ae_time e !! j' = t !! j') as Hetj'.\n { rewrite Het''. eapply incr_time_proj_neq; lia. }\n rewrite (Htj j' Hj') in Hetj'.\n rewrite Hetj'. f_equal.\n rewrite (lsec_lsup_length i); eauto.\n rewrite /DBM_lsec_latest_in_frame /lsec_sup.\n apply nat_sup_equiv.\n intros k.\n rewrite !elem_of_list_omap.\n setoid_rewrite elem_of_list_filter.\n setoid_rewrite elem_of_elements.\n split.\n + intros (x&Hxin&Hx2).\n exists x; split_and!; [| set_solver | done].\n eapply in_lsec_in_lhst in Hxin.\n pose proof DBM_LHV_seqids His x Hxin. lia.\n + intros (x&[Hx1 Hxin]&Hx2).\n exists x; split_and!; [ | done].\n assert ( ae_seqid x < ae_seqid e) by lia.\n rewrite (DBM_lsec_union j' s {[e]})in Hxin.\n apply elem_of_union in Hxin as [Hx | Hx]; first done.\n rewrite /DBM_lsec in Hx.\n apply elem_of_filter in Hx as [? <-%elem_of_singleton].\n eauto with lia.\n Qed.\n\n Lemma DBM_lsec_locally_causal_update e i j t s :\n DBM_lhst_valid i s →\n (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n ae_seqid e = S (size s) →\n update_condition i e t →\n j < length DB_addresses →\n (ae_orig e = i →\n ∀ j, j < length DB_addresses →\n t !! j = Some (length (elements (DBM_lsec j s)))) →\n (∀ j, j < length DB_addresses →\n default O (t !! j) <= (length (elements (DBM_lsec j s)))) →\n DBM_lsec_locally_causal j (s ∪ {[e]}).\n Proof.\n intros His Hs Hseq Hcnd Hj Htj Htj2.\n pose proof Hcnd as\n (Hi & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n destruct (decide (j = i)) as [->|].\n - assert (DBM_lsec_locally_causal_refl i (s ∪ {[e]})) as Hvlrefl.\n { eapply DBM_lsec_locally_causal_refl_update; eauto. }\n rewrite /DBM_lsec_locally_causal_refl in Hvlrefl.\n rewrite /DBM_lsec_locally_causal.\n intros j' x Hj' Hneq Hxin.\n destruct (lookup_lt_is_Some_2 (ae_time x) j') as [k Hk].\n { rewrite DBM_lsec_union in Hxin.\n apply elem_of_union in Hxin as\n [[? Hx]%elem_of_filter |\n [? ->%elem_of_singleton ]%elem_of_filter].\n + pose proof DBM_LHV_times His x Hx. lia.\n + lia. }\n rewrite Hk.\n assert (ae_time x !! j' =\n Some (DBM_lsec_latest_in_frame j' (s ∪ {[e]}) x)) as Hx'.\n by eauto. rewrite -Hk Hx'. simpl. done.\n - pose proof DBM_LHV_bound_at His as Hb.\n intros j' ei Hj' Hij'\n [He'1 [He'2| ->%elem_of_singleton]%elem_of_union]%elem_of_filter.\n + pose proof DBM_LHV_secs_valid His j Hj as Hvs.\n assert (from_option\n (λ a : nat, a ≤ DBM_lsec_latest_in_frame j' s ei) False\n (ae_time ei !! j')) as Hle.\n { apply (DBM_LSV_caus Hvs j' ei); eauto with lia.\n subst j. by apply in_lsec_orig. }\n destruct (lookup_lt_is_Some_2 (ae_time ei) j') as [k Hk].\n pose proof DBM_LHV_times His ei He'2. lia.\n rewrite Hk. rewrite Hk in Hle. simpl in *.\n trans (DBM_lsec_latest_in_frame j' s ei); first done.\n rewrite /DBM_lsec_latest_in_frame.\n apply nat_sup_mono.\n intros r Hr.\n rewrite !elem_of_list_omap.\n setoid_rewrite elem_of_list_filter.\n setoid_rewrite elem_of_elements.\n erewrite elem_of_list_omap in Hr.\n destruct Hr as (ej & Hej1 & Hej2).\n setoid_rewrite elem_of_list_filter in Hej1.\n destruct Hej1 as [? ?].\n exists ej. split_and!; [ | | done]; eauto with lia.\n set_solver.\n + assert (j' ≠ ae_orig e) as Hj'e by lia.\n specialize (Het' j' Hj' Hj'e).\n destruct (lookup_lt_is_Some_2 (ae_time e) j') as [k Hk];\n first eauto with lia.\n rewrite Hk in Het'. rewrite Hk. simpl in *.\n specialize (Htj2 j' Hj').\n trans (length (elements (DBM_lsec j' s))).\n * trans (default 0 (t !! j')); eauto with lia.\n * erewrite (lsec_lsup_length i); eauto.\n rewrite /DBM_lsec_latest_in_frame /lsec_sup.\n apply nat_sup_mono.\n intros r Hr.\n rewrite !elem_of_list_omap.\n setoid_rewrite elem_of_list_filter.\n setoid_rewrite elem_of_elements.\n erewrite elem_of_list_omap in Hr.\n destruct Hr as (ej & Hej1 & Hej2).\n exists ej; split_and!; [| set_solver | done].\n rewrite /DBM_lsec in Hej1.\n erewrite elem_of_elements in Hej1.\n apply elem_of_filter in Hej1 as [? Hej1].\n pose proof DBM_LHV_seqids His ej Hej1.\n rewrite Hseq. by apply le_lt_n_Sm.\n Qed.\n\n Lemma DBM_lhst_lsec_update e i t s :\n DBM_lhst_valid i s →\n (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n e.(ae_seqid) = (S (size s)) →\n update_condition i e t →\n t !! ae_orig e = Some (length (elements (DBM_lsec (ae_orig e) s))) →\n (ae_orig e = i\n → ∀ j, j < strings.length DB_addresses\n → t !! j = Some (length (elements (DBM_lsec j s)))) →\n (∀ j, j < length DB_addresses →\n default O (t !! j) <= (length (elements (DBM_lsec j s)))) →\n DBM_lhst_lsec_valid i (s ∪ {[ e ]}).\n Proof.\n intros.\n split.\n - eapply DBM_LHV_bound_at; eauto.\n - done.\n - eapply DBM_lsec_complete_update; eauto.\n - eapply DBM_lsec_locally_causal_refl_update; eauto.\n - eapply DBM_lsec_locally_causal_update; eauto.\n Qed.\n\nEnd Lsec_udpate.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/ccddb/model/model_update_lsec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.23370635691404026, "lm_q1q2_score": 0.12958327582350088}} {"text": "Require Import compcert.lib.Axioms.\n\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.semantics_lemmas.\n\nRequire Import concurrency.pos.\nRequire Import concurrency.scheduler.\nRequire Import concurrency.TheSchedule.\nRequire Import concurrency.concurrent_machine.\nRequire Import concurrency.addressFiniteMap. (*The finite maps*)\nRequire Import concurrency.pos.\nRequire Import concurrency.lksize.\nRequire Import concurrency.permjoin_def.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n after Ssreflect eqtype.*)\nRequire Import compcert.common.AST. (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.lib.Integers.\nRequire Import concurrency.threads_lemmas.\nRequire Import concurrency.semantics.\nRequire Import concurrency.TheSchedule. Import TheSchedule.\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import concurrency.permissions.\nRequire Import concurrency.bounded_maps.\nRequire Import concurrency.threadPool.\n\nModule LocksAndResources.\n (** Dry resources are a permission map for non-lock locations and one for lock\n locations*)\n Definition res := (access_map * access_map)%type.\n Definition lock_info := (access_map * access_map)%type.\nEnd LocksAndResources.\n\n\nModule ThreadPool (SEM:Semantics) <: ThreadPoolSig\n with Module TID:= NatTID with Module SEM:=SEM\n with Module RES := LocksAndResources.\n\n Include (OrdinalPool SEM LocksAndResources).\n\nEnd ThreadPool.\n\nModule Concur.\n\n Module mySchedule := THESCH.\n\n (** The type of dry machines. This is basically the same as\n [ConcurrentMachineSig] but resources are instantiated with dry\n resources*)\n Module Type DryMachineSig (SEM: Semantics) <: ConcurrentMachineSig\n with Module ThreadPool.RES:= LocksAndResources\n with Module ThreadPool.TID:=mySchedule.TID.\n\n Declare Module Events : EventSig.\n Module ThreadPool := ThreadPool SEM.\n Import ThreadPool SEM.\n Import event_semantics Events.\n\n (** Memories*)\n Definition richMem: Type:= mem.\n Definition dryMem: richMem -> mem:= id.\n Definition diluteMem: mem -> mem := setMaxPerm.\n\n Notation thread_pool := (ThreadPool.t).\n\n (** The state respects the memory*)\n Record mem_compatible' tp m : Prop :=\n { compat_th :> forall {tid} (cnt: containsThread tp tid),\n permMapLt (getThreadR cnt).1 (getMaxPerm m) /\\\n permMapLt (getThreadR cnt).2 (getMaxPerm m);\n compat_lp : forall l pmaps, lockRes tp l = Some pmaps ->\n permMapLt pmaps.1 (getMaxPerm m) /\\\n permMapLt pmaps.2 (getMaxPerm m);\n lockRes_blocks: forall l rmap, lockRes tp l = Some rmap ->\n Mem.valid_block m l.1}.\n\n Definition mem_compatible tp m : Prop := mem_compatible' tp m.\n\n Record invariant' tp :=\n { no_race_thr :\n forall i j (cnti: containsThread tp i) (cntj: containsThread tp j)\n (Hneq: i <> j),\n permMapsDisjoint2 (getThreadR cnti)\n (getThreadR cntj); (*thread's resources are disjoint *)\n no_race_lr:\n forall laddr1 laddr2 rmap1 rmap2\n (Hneq: laddr1 <> laddr2)\n (Hres1: lockRes tp laddr1 = Some rmap1)\n (Hres2: lockRes tp laddr2 = Some rmap2),\n permMapsDisjoint2 rmap1 rmap2; (*lock's resources are disjoint *)\n no_race:\n forall i laddr (cnti: containsThread tp i) rmap\n (Hres: lockRes tp laddr = Some rmap),\n permMapsDisjoint2 (getThreadR cnti) rmap; (*resources are disjoint\n between threads and locks*)\n (* an address is in the lockres if there is at least one >= Readable\n lock permission - I am writing the weak version where this is required\n only for permissions of threads*)\n (* lock_res_perm: *)\n (* forall b ofs, *)\n (* (exists i (cnti: containsThread tp i), *)\n (* Mem.perm_order' ((getThreadR cnti).2 !! b ofs) Readable) -> *)\n (* lockRes tp (b, ofs); *)\n\n (* if an address is a lock then there can be no data\n permission above non-empty for this address*)\n thread_data_lock_coh:\n forall i (cnti: containsThread tp i),\n (forall j (cntj: containsThread tp j),\n permMapCoherence (getThreadR cntj).1 (getThreadR cnti).2) /\\\n (forall laddr rmap,\n lockRes tp laddr = Some rmap ->\n permMapCoherence rmap.1 (getThreadR cnti).2);\n locks_data_lock_coh:\n forall laddr rmap\n (Hres: lockRes tp laddr = Some rmap),\n (forall j (cntj: containsThread tp j),\n permMapCoherence (getThreadR cntj).1 rmap.2) /\\\n (forall laddr' rmap',\n lockRes tp laddr' = Some rmap' ->\n permMapCoherence rmap'.1 rmap.2);\n lockRes_valid: lr_valid (lockRes tp) (*well-formed locks*)\n }.\n\n Definition invariant := invariant'.\n Parameter threadStep :\n G ->\n forall tid0 (ms : t) (m : mem),\n containsThread ms tid0 ->\n mem_compatible ms m -> t -> mem -> seq mem_event -> Prop.\n\n Axiom threadStep_equal_run:\n forall g i tp m cnt cmpt tp' m' tr,\n @threadStep g i tp m cnt cmpt tp' m' tr ->\n forall j,\n (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n Parameter syncStep :\n bool -> (* if it's a Coarse machine. Temp solution to propagating changes. *)\n G ->\n forall tid0 (ms : t) (m : mem),\n containsThread ms tid0 ->\n mem_compatible ms m -> t -> mem -> sync_event -> Prop.\n\n Axiom syncstep_equal_run:\n forall b g i tp m cnt cmpt tp' m' tr,\n @syncStep b g i tp m cnt cmpt tp' m' tr ->\n forall j,\n (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n\n Axiom syncstep_not_running:\n forall b g i tp m cnt cmpt tp' m' tr,\n @syncStep b g i tp m cnt cmpt tp' m' tr ->\n forall cntj q, ~ @getThreadC i tp cntj = Krun q.\n\n\n Parameter threadHalted :\n forall tid0 (ms : t), containsThread ms tid0 -> Prop.\n Parameter init_mach : option RES.res -> G -> val -> seq val -> option t.\n\n\n\n Axiom threadHalt_update:\n forall i j, i <> j ->\n forall tp cnt cnti c' cnt',\n (@threadHalted j tp cnt) <->\n (@threadHalted j (@updThreadC i tp cnti c') cnt') .\n\n Axiom syncstep_equal_halted:\n forall b g i tp m cnti cmpt tp' m' tr,\n @syncStep b g i tp m cnti cmpt tp' m' tr ->\n forall j cnt cnt',\n (@threadHalted j tp cnt) <->\n (@threadHalted j tp' cnt').\n\n Axiom threadStep_not_unhalts:\n forall g i tp m cnt cmpt tp' m' tr,\n @threadStep g i tp m cnt cmpt tp' m' tr ->\n forall j cnt cnt',\n (@threadHalted j tp cnt) ->\n (@threadHalted j tp' cnt') .\n\n End DryMachineSig.\n\n Module DryMachineShell (SEM:Semantics) <: DryMachineSig SEM.\n\n Module Events := Events.\n Module ThreadPool := ThreadPool SEM.\n Import ThreadPool.\n Import ThreadPool.SEM ThreadPool.RES.\n Import event_semantics Events.\n\n Notation tid := NatTID.tid.\n\n (** Memories*)\n Definition richMem: Type:= mem.\n Definition dryMem: richMem -> mem:= id.\n Definition diluteMem: mem -> mem := setMaxPerm.\n\n Notation thread_pool := (ThreadPool.t).\n\n (** The state respects the memory*)\n\n Record mem_compatible' tp m : Prop :=\n { compat_th :> forall {tid} (cnt: containsThread tp tid),\n permMapLt (getThreadR cnt).1 (getMaxPerm m) /\\\n permMapLt (getThreadR cnt).2 (getMaxPerm m);\n compat_lp : forall l pmaps, lockRes tp l = Some pmaps ->\n permMapLt pmaps.1 (getMaxPerm m) /\\\n permMapLt pmaps.2 (getMaxPerm m);\n lockRes_blocks: forall l rmap, lockRes tp l = Some rmap ->\n Mem.valid_block m l.1}.\n\n Definition mem_compatible tp m : Prop := mem_compatible' tp m.\n\n\n (* should there be something that says that if something is a lock then\n someone has at least readable permission on it?*)\n Record invariant' tp :=\n { no_race_thr :\n forall i j (cnti: containsThread tp i) (cntj: containsThread tp j)\n (Hneq: i <> j),\n permMapsDisjoint2 (getThreadR cnti)\n (getThreadR cntj); (*thread's resources are disjoint *)\n no_race_lr:\n forall laddr1 laddr2 rmap1 rmap2\n (Hneq: laddr1 <> laddr2)\n (Hres1: lockRes tp laddr1 = Some rmap1)\n (Hres2: lockRes tp laddr2 = Some rmap2),\n permMapsDisjoint2 rmap1 rmap2; (*lock's resources are disjoint *)\n no_race:\n forall i laddr (cnti: containsThread tp i) rmap\n (Hres: lockRes tp laddr = Some rmap),\n permMapsDisjoint2 (getThreadR cnti) rmap; (*resources are disjoint\n between threads and locks*)\n (* an address is in the lockres if there is at least one >= Readable\n lock permission - I am writing the weak version where this is required\n only for permissions of threads*)\n (* lock_res_perm: *)\n (* forall b ofs, *)\n (* (exists i (cnti: containsThread tp i), *)\n (* Mem.perm_order' ((getThreadR cnti).2 !! b ofs) Readable) -> *)\n (* lockRes tp (b, ofs); *)\n\n (* if an address is a lock then there can be no data\n permission above non-empty for this address*)\n thread_data_lock_coh:\n forall i (cnti: containsThread tp i),\n (forall j (cntj: containsThread tp j),\n permMapCoherence (getThreadR cntj).1 (getThreadR cnti).2) /\\\n (forall laddr rmap,\n lockRes tp laddr = Some rmap ->\n permMapCoherence rmap.1 (getThreadR cnti).2);\n locks_data_lock_coh:\n forall laddr rmap\n (Hres: lockRes tp laddr = Some rmap),\n (forall j (cntj: containsThread tp j),\n permMapCoherence (getThreadR cntj).1 rmap.2) /\\\n (forall laddr' rmap',\n lockRes tp laddr' = Some rmap' ->\n permMapCoherence rmap'.1 rmap.2);\n lockRes_valid: lr_valid (lockRes tp) (*well-formed locks*)\n }.\n Definition invariant := invariant'.\n\n (** Steps*)\n Inductive dry_step genv {tid0 tp m} (cnt: containsThread tp tid0)\n (Hcompatible: mem_compatible tp m) :\n thread_pool -> mem -> seq mem_event -> Prop :=\n | step_dry :\n forall (tp':thread_pool) c m1 m' (c' : code) ev\n (** Instal the permission's of the thread on non-lock locations*)\n (Hrestrict_pmap: restrPermMap (Hcompatible tid0 cnt).1 = m1)\n (Hinv: invariant tp)\n (Hcode: getThreadC cnt = Krun c)\n (Hcorestep: ev_step Sem genv c m1 ev c' m')\n (** the new data resources of the thread are the ones on the\n memory, the lock ones are unchanged by internal steps*)\n (Htp': tp' = updThread cnt (Krun c') (getCurPerm m', (getThreadR cnt).2)),\n dry_step genv cnt Hcompatible tp' m' ev.\n\n Definition option_function {A B} (opt_f: option (A -> B)) (x:A): option B:=\n match opt_f with\n Some f => Some (f x)\n | None => None\n end.\n Infix \"??\" := option_function (at level 80, right associativity).\n\n Inductive ext_step {isCoarse:bool} (genv:G) {tid0 tp m}\n (cnt0:containsThread tp tid0)(Hcompat:mem_compatible tp m):\n thread_pool -> mem -> sync_event -> Prop :=\n | step_acquire :\n forall (tp' tp'':thread_pool) m0 m1 c m' b ofs\n (pmap : LocksAndResources.lock_info)\n (pmap_tid' : access_map)\n (virtueThread : delta_map * delta_map)\n (Hbounded: if isCoarse then\n ( sub_map virtueThread.1 (getMaxPerm m).2 /\\\n sub_map virtueThread.2 (getMaxPerm m).2)\n else\n True ),\n let newThreadPerm := (computeMap (getThreadR cnt0).1 virtueThread.1,\n computeMap (getThreadR cnt0).2 virtueThread.2) in\n forall\n (Hinv : invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c = Some (LOCK, Vptr b ofs::nil))\n (** install the thread's permissions on lock locations*)\n (Hrestrict_pmap0: restrPermMap (Hcompat tid0 cnt0).2 = m0)\n (** check if the thread has permission to acquire the lock and the lock is free*)\n (Hload: Mem.load Mint32 m0 b (Int.intval ofs) = Some (Vint Int.one))\n (** set the permissions on the lock location equal to the max permissions on the memory*)\n (Hset_perm: setPermBlock (Some Writable)\n b (Int.intval ofs) ((getThreadR cnt0).2) LKSIZE_nat = pmap_tid')\n (Hlt': permMapLt pmap_tid' (getMaxPerm m))\n (Hrestrict_pmap: restrPermMap Hlt' = m1)\n (** acquire the lock*)\n (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.zero) = Some m')\n (HisLock: lockRes tp (b, Int.intval ofs) = Some pmap)\n (Hangel1: permMapJoin pmap.1 (getThreadR cnt0).1 newThreadPerm.1)\n (Hangel2: permMapJoin pmap.2 (getThreadR cnt0).2 newThreadPerm.2)\n (Htp': tp' = updThread cnt0 (Kresume c Vundef) newThreadPerm)\n (** acquiring the lock leaves empty permissions at the resource pool*)\n (Htp'': tp'' = updLockSet tp' (b, Int.intval ofs) (empty_map, empty_map)),\n ext_step genv cnt0 Hcompat tp'' m'\n (acquire (b, Int.intval ofs)\n (Some virtueThread))\n\n | step_release :\n forall (tp' tp'':thread_pool) m0 m1 c m' b ofs virtueThread virtueLP pmap_tid' rmap\n (Hbounded: if isCoarse then\n ( sub_map virtueThread.1 (getMaxPerm m).2 /\\\n sub_map virtueThread.2 (getMaxPerm m).2)\n else\n True )\n (HboundedLP: if isCoarse then\n ( map_empty_def virtueLP.1 /\\\n map_empty_def virtueLP.2 /\\\n sub_map virtueLP.1.2 (getMaxPerm m).2 /\\\n sub_map virtueLP.2.2 (getMaxPerm m).2)\n else\n True ),\n let newThreadPerm := (computeMap (getThreadR cnt0).1 virtueThread.1,\n computeMap (getThreadR cnt0).2 virtueThread.2) in\n forall\n (Hinv : invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c =\n Some (UNLOCK, Vptr b ofs::nil))\n (** install the thread's permissions on lock locations *)\n (Hrestrict_pmap0: restrPermMap (Hcompat tid0 cnt0).2 = m0)\n (Hload: Mem.load Mint32 m0 b (Int.intval ofs) = Some (Vint Int.zero))\n (** set the permissions on the lock location equal to the max permissions on the memory*)\n (Hset_perm: setPermBlock (Some Writable)\n b (Int.intval ofs) ((getThreadR cnt0).2) LKSIZE_nat = pmap_tid')\n (Hlt': permMapLt pmap_tid' (getMaxPerm m))\n (Hrestrict_pmap: restrPermMap Hlt' = m1)\n (** release the lock *)\n (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.one) = Some m')\n (HisLock: lockRes tp (b, Int.intval ofs) = Some rmap)\n (** And the lock is taken*)\n (Hrmap: forall b ofs, rmap.1 !! b ofs = None /\\ rmap.2 !! b ofs = None)\n (Hangel1: permMapJoin newThreadPerm.1 virtueLP.1 (getThreadR cnt0).1)\n (Hangel2: permMapJoin newThreadPerm.2 virtueLP.2 (getThreadR cnt0).2)\n (Htp': tp' = updThread cnt0 (Kresume c Vundef)\n (computeMap (getThreadR cnt0).1 virtueThread.1,\n computeMap (getThreadR cnt0).2 virtueThread.2))\n (Htp'': tp'' = updLockSet tp' (b, Int.intval ofs) virtueLP),\n ext_step genv cnt0 Hcompat tp'' m'\n (release (b, Int.intval ofs)\n (Some virtueLP))\n | step_create :\n forall (tp_upd tp':thread_pool) c b ofs arg virtue1 virtue2\n (Hbounded: if isCoarse then\n ( sub_map virtue1.1 (getMaxPerm m).2 /\\\n sub_map virtue1.2 (getMaxPerm m).2)\n else\n True )\n (Hbounded_new: if isCoarse then\n ( sub_map virtue2.1 (getMaxPerm m).2 /\\\n sub_map virtue2.2 (getMaxPerm m).2)\n else\n True ),\n let threadPerm' := (computeMap (getThreadR cnt0).1 virtue1.1,\n computeMap (getThreadR cnt0).2 virtue1.2) in\n let newThreadPerm := (computeMap empty_map virtue2.1,\n computeMap empty_map virtue2.2) in\n forall\n (Hinv : invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c = Some (CREATE, Vptr b ofs::arg::nil))\n (** we do not need to enforce the almost empty predicate on thread\n spawn as long as it's considered a synchronizing operation *)\n (Hangel1: permMapJoin newThreadPerm.1 threadPerm'.1 (getThreadR cnt0).1)\n (Hangel2: permMapJoin newThreadPerm.2 threadPerm'.2 (getThreadR cnt0).2)\n (Htp_upd: tp_upd = updThread cnt0 (Kresume c Vundef) threadPerm')\n (Htp': tp' = addThread tp_upd (Vptr b ofs) arg newThreadPerm),\n ext_step genv cnt0 Hcompat tp' m\n (spawn (b, Int.intval ofs)\n (Some (getThreadR cnt0, virtue1)) (Some virtue2))\n\n\n | step_mklock :\n forall (tp' tp'': thread_pool) m1 c m' b ofs pmap_tid',\n let: pmap_tid := getThreadR cnt0 in\n forall\n (Hinv : invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c = Some (MKLOCK, Vptr b ofs::nil))\n (** install the thread's data permissions*)\n (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).1 = m1)\n (** lock is created in acquired state*)\n (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.zero) = Some m')\n (** The thread's data permissions are set to Nonempty*)\n (Hdata_perm: setPermBlock\n (Some Nonempty)\n b\n (Int.intval ofs)\n pmap_tid.1\n LKSIZE_nat = pmap_tid'.1)\n (** thread lock permission is increased *)\n (Hlock_perm: setPermBlock\n (Some Writable)\n b\n (Int.intval ofs)\n pmap_tid.2\n LKSIZE_nat = pmap_tid'.2)\n (** Require that [(b, Int.intval ofs)] was not a lock*)\n (HlockRes: lockRes tp (b, Int.intval ofs) = None)\n (Htp': tp' = updThread cnt0 (Kresume c Vundef) pmap_tid')\n (** the lock has no resources initially *)\n (Htp'': tp'' = updLockSet tp' (b, Int.intval ofs) (empty_map, empty_map)),\n ext_step genv cnt0 Hcompat tp'' m' (mklock (b, Int.intval ofs))\n\n | step_freelock :\n forall (tp' tp'': thread_pool) c b ofs pmap_tid' m1 pdata rmap\n (Hbounded: if isCoarse then\n ( bounded_maps.bounded_nat_func' pdata LKSIZE_nat)\n else\n True ),\n let: pmap_tid := getThreadR cnt0 in\n forall\n (Hinv: invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c = Some (FREE_LOCK, Vptr b ofs::nil))\n (** If this address is a lock*)\n (His_lock: lockRes tp (b, (Int.intval ofs)) = Some rmap)\n (** And the lock is taken *)\n (Hrmap: forall b ofs, rmap.1 !! b ofs = None /\\ rmap.2 !! b ofs = None)\n (** Install the thread's lock permissions*)\n (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).2 = m1)\n (** To free the lock the thread must have at least Writable on it*)\n (Hfreeable: Mem.range_perm m1 b (Int.intval ofs) ((Int.intval ofs) + LKSIZE) Cur Writable)\n (** lock permissions of the thread are dropped to empty *)\n (Hlock_perm: setPermBlock\n None\n b\n (Int.intval ofs)\n pmap_tid.2\n LKSIZE_nat = pmap_tid'.2)\n (** data permissions are computed in a non-deterministic way *)\n (Hneq_perms: forall i,\n (0 <= Z.of_nat i < LKSIZE)%Z ->\n Mem.perm_order'' (pdata (S i)) (Some Writable)\n )\n (*Hpdata: perm_order pdata Writable*)\n (Hdata_perm: setPermBlock_var (*=setPermBlockfunc*)\n pdata\n b\n (Int.intval ofs)\n pmap_tid.1\n LKSIZE_nat = pmap_tid'.1)\n (Htp': tp' = updThread cnt0 (Kresume c Vundef) pmap_tid')\n (Htp'': tp'' = remLockSet tp' (b, Int.intval ofs)),\n ext_step genv cnt0 Hcompat tp'' m (freelock (b, Int.intval ofs))\n | step_acqfail :\n forall c b ofs m1\n (Hinv : invariant tp)\n (Hcode: getThreadC cnt0 = Kblocked c)\n (Hat_external: at_external Sem c = Some (LOCK, Vptr b ofs::nil))\n (** Install the thread's lock permissions*)\n (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).2 = m1)\n (** Lock is already acquired.*)\n (Hload: Mem.load Mint32 m1 b (Int.intval ofs) = Some (Vint Int.zero)),\n ext_step genv cnt0 Hcompat tp m (failacq (b, Int.intval ofs)).\n\n Definition threadStep (genv : G): forall {tid0 ms m},\n containsThread ms tid0 -> mem_compatible ms m ->\n thread_pool -> mem -> seq mem_event -> Prop:=\n @dry_step genv.\n\n Lemma threadStep_equal_run:\n forall g i tp m cnt cmpt tp' m' tr,\n @threadStep g i tp m cnt cmpt tp' m' tr ->\n forall j,\n (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n Proof.\n intros. split.\n - intros [cntj [ q running]].\n inversion H; subst.\n assert (cntj':=cntj).\n eapply (cntUpdate (Krun c') (getCurPerm m', (getThreadR cnt)#2) cntj) in cntj'.\n exists cntj'.\n destruct (NatTID.eq_tid_dec i j).\n + subst j; exists c'.\n rewrite gssThreadCode; reflexivity.\n + exists q.\n rewrite gsoThreadCode; auto.\n - intros [cntj' [ q' running]].\n inversion H; subst.\n assert (cntj:=cntj').\n eapply cntUpdate' with(c0:=Krun c')(p:=(getCurPerm m', (getThreadR cnt)#2)) in cntj; eauto.\n exists cntj.\n destruct (NatTID.eq_tid_dec i j).\n + subst j; exists c.\n rewrite <- Hcode.\n f_equal.\n apply cnt_irr.\n + exists q'.\n rewrite gsoThreadCode in running; auto.\n Qed.\n\n Definition syncStep (isCoarse:bool) (genv :G) :\n forall {tid0 ms m},\n containsThread ms tid0 -> mem_compatible ms m ->\n thread_pool -> mem -> sync_event -> Prop:=\n @ext_step isCoarse genv.\n\n\n\n\n Lemma syncstep_equal_run:\n forall b g i tp m cnt cmpt tp' m' tr,\n @syncStep b g i tp m cnt cmpt tp' m' tr ->\n forall j,\n (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n Proof.\n intros b g i tp m cnt cmpt tp' m' tr H j; split.\n - intros [cntj [ q running]].\n destruct (NatTID.eq_tid_dec i j).\n + subst j. generalize running; clear running.\n inversion H; subst;\n match goal with\n | [ H: getThreadC ?cnt = Kblocked ?c |- _ ] =>\n replace cnt with cntj in H by apply cnt_irr;\n intros HH; rewrite HH in H; inversion H\n end.\n + (*this should be easy to automate or shorten*)\n inversion H; subst.\n * exists (cntUpdateL _ _\n (cntUpdate (Kresume c Vundef)\n newThreadPerm\n _ cntj)), q.\n rewrite gLockSetCode.\n rewrite gsoThreadCode; assumption.\n * exists ( (cntUpdateL _ _\n (cntUpdate (Kresume c Vundef)\n (computeMap (getThreadR cnt)#1 virtueThread#1,\n computeMap (getThreadR cnt)#2 virtueThread#2)\n _ cntj))), q.\n rewrite gLockSetCode.\n rewrite gsoThreadCode; assumption.\n * exists (cntAdd _ _ _\n (cntUpdate (Kresume c Vundef)\n threadPerm'\n _ cntj)), q.\n erewrite gsoAddCode . (*i? *)\n rewrite gsoThreadCode; assumption.\n eapply cntUpdate. eauto.\n * exists ( (cntUpdateL _ _\n (cntUpdate (Kresume c Vundef)\n pmap_tid'\n _ cntj))), q.\n rewrite gLockSetCode.\n rewrite gsoThreadCode; assumption.\n * exists ( (cntRemoveL _\n (cntUpdate (Kresume c Vundef)\n pmap_tid'\n _ cntj))), q.\n rewrite gRemLockSetCode.\n rewrite gsoThreadCode; assumption.\n * exists cntj, q; assumption.\n - intros [cntj [ q running]].\n destruct (NatTID.eq_tid_dec i j).\n + subst j. generalize running; clear running.\n inversion H; subst;\n try rewrite gLockSetCode;\n try rewrite gRemLockSetCode;\n try rewrite gssThreadCode;\n try solve[intros HH; inversion HH].\n { (*addthread*)\n assert (cntj':=cntj).\n eapply cntAdd' in cntj'; destruct cntj' as [ [HH HHH] | HH].\n * erewrite gsoAddCode; eauto.\n subst; rewrite gssThreadCode; intros AA; inversion AA.\n * erewrite gssAddCode . intros AA; inversion AA.\n assumption. }\n { (*AQCUIRE*)\n replace cntj with cnt by apply cnt_irr.\n rewrite Hcode; intros HH; inversion HH. }\n + generalize running; clear running.\n inversion H; subst;\n try erewrite <- age_getThreadCode;\n try rewrite gLockSetCode;\n try rewrite gRemLockSetCode;\n try (rewrite gsoThreadCode; [|auto]);\n try (intros HH;\n match goal with\n | [ H: getThreadC ?cnt = Krun ?c |- _ ] =>\n exists cntj, c; exact H\n end).\n (*Add thread case*)\n assert (cntj':=cntj).\n eapply cntAdd' in cntj'; destruct cntj' as [ [HH HHH] | HH].\n * erewrite gsoAddCode; eauto.\n destruct (NatTID.eq_tid_dec i j);\n [subst; rewrite gssThreadCode; intros AA; inversion AA|].\n rewrite gsoThreadCode; auto.\n exists HH, q; assumption.\n * erewrite gssAddCode . intros AA; inversion AA.\n assumption.\n\n\n\n Grab Existential Variables.\n eauto. eauto. eauto.\n Qed.\n\n\n Lemma syncstep_not_running:\n forall b g i tp m cnt cmpt tp' m' tr,\n @syncStep b g i tp m cnt cmpt tp' m' tr ->\n forall cntj q, ~ @getThreadC i tp cntj = Krun q.\n Proof.\n intros.\n inversion H;\n match goal with\n | [ H: getThreadC ?cnt = _ |- _ ] =>\n erewrite (cnt_irr _ cnt);\n rewrite H; intros AA; inversion AA\n end.\n Qed.\n\n\n\n Inductive threadHalted': forall {tid0 ms},\n containsThread ms tid0 -> Prop:=\n | thread_halted':\n forall tp c tid0\n (cnt: containsThread tp tid0)\n (*Hinv: invariant tp*)\n (Hcode: getThreadC cnt = Krun c)\n (Hcant: halted Sem c),\n threadHalted' cnt.\n\n Definition threadHalted: forall {tid0 ms},\n containsThread ms tid0 -> Prop:= @threadHalted'.\n\n\n (* Lemma updCinvariant': forall {tid} ds c (cnt: containsThread ds tid),\n invariant (updThreadC cnt c) <-> invariant ds.\n split.\n { intros INV; inversion INV.\n constructor.\n - generalize no_race; unfold race_free.\n simpl. intros.\n apply no_race0; auto.\n - simpl; assumption.\n - simpl; assumption.\n - simpl; assumption.\n - simpl; assumption. }\n\n { intros INV; inversion INV.\n constructor.\n - generalize no_race; unfold race_free.\n simpl. intros.\n apply no_race0; auto.\n - simpl; assumption.\n - simpl; assumption.\n - simpl; assumption.\n - simpl; assumption. }\n Qed. *)\n\n\n Lemma threadHalt_update:\n forall i j, i <> j ->\n forall tp cnt cnti c' cnt',\n (@threadHalted j tp cnt) <->\n (@threadHalted j (@updThreadC i tp cnti c') cnt') .\n Proof.\n intros; split; intros HH; inversion HH; subst;\n econstructor; eauto.\n erewrite <- (gsoThreadCC H); exact Hcode.\n erewrite (gsoThreadCC H); exact Hcode.\n Qed.\n\n\n Definition one_pos : pos := mkPos NPeano.Nat.lt_0_1.\n\n Definition initial_machine pmap c :=\n ThreadPool.mk\n one_pos\n (fun _ => Krun c)\n (fun _ => (pmap, empty_map)) (*initially there are no locks*)\n empty_lset.\n\n\n Definition init_mach (pmap : option RES.res) (genv:G)\n (v:val)(args:list val):option thread_pool :=\n match initial_core Sem genv v args with\n | Some c =>\n match pmap with\n | Some pmap => Some (initial_machine pmap.1 c)\n | None => None\n end\n | None => None\n end.\n\n Module DryMachineLemmas.\n\n\n (*TODO: This lemma should probably be moved. *)\n Lemma threads_canonical:\n forall ds m i (cnt:ThreadPool.containsThread ds i),\n mem_compatible ds m ->\n isCanonical (ThreadPool.getThreadR cnt).1 /\\\n isCanonical (ThreadPool.getThreadR cnt).2.\n intros.\n destruct (compat_th H cnt);\n eauto using canonical_lt.\n Qed.\n (** most of these lemmas are in DryMachinLemmas*)\n\n (** *Invariant Lemmas*)\n\n (** ** Updating the machine state**)\n (* Manny invaraint lemmas were removed from here. *)\n End DryMachineLemmas.\n\n\n\n (** *More Properties of halted thread*)\n Lemma threadStep_not_unhalts:\n forall g i tp m cnt cmpt tp' m' tr,\n @threadStep g i tp m cnt cmpt tp' m' tr ->\n forall j cnt cnt',\n (@threadHalted j tp cnt) ->\n (@threadHalted j tp' cnt') .\n Proof.\n intros; inversion H; inversion H0; subst.\n destruct (NatTID.eq_tid_dec i j).\n - subst j. simpl in Hcorestep.\n eapply ev_step_ax1 in Hcorestep.\n eapply corestep_not_halted in Hcorestep.\n replace cnt1 with cnt in Hcode0 by apply cnt_irr.\n rewrite Hcode0 in Hcode; inversion Hcode;\n subst c0.\n rewrite Hcorestep in Hcant; inversion Hcant.\n - econstructor; eauto.\n rewrite gsoThreadCode; auto;\n erewrite <- age_getThreadCode; eauto.\n Qed.\n\n\n Lemma syncstep_equal_halted:\n forall b g i tp m cnti cmpt tp' m' tr,\n @syncStep b g i tp m cnti cmpt tp' m' tr ->\n forall j cnt cnt',\n (@threadHalted j tp cnt) <->\n (@threadHalted j tp' cnt').\n Proof.\n intros; split; intros HH; inversion HH; subst;\n econstructor; subst; eauto.\n - destruct (NatTID.eq_tid_dec i j).\n + subst j.\n inversion H;\n match goal with\n | [ H: getThreadC ?cnt = Krun ?c,\n H': getThreadC ?cnt' = Kblocked ?c' |- _ ] =>\n replace cnt with cnt' in H by apply cnt_irr;\n rewrite H' in H; inversion H\n end.\n + inversion H; subst;\n try erewrite <- age_getThreadCode;\n try rewrite gLockSetCode;\n try rewrite gRemLockSetCode;\n try erewrite gsoAddCode; eauto;\n try rewrite gsoThreadCode; try eassumption.\n { (*AQCUIRE*)\n replace cnt' with cnt0 by apply cnt_irr;\n exact Hcode. }\n - destruct (NatTID.eq_tid_dec i j).\n + subst j.\n inversion H; subst;\n match goal with\n | [ H: getThreadC ?cnt = Krun ?c,\n H': getThreadC ?cnt' = Kblocked ?c' |- _ ] =>\n try erewrite <- age_getThreadCode in H;\n try rewrite gLockSetCode in H;\n try rewrite gRemLockSetCode in H;\n try erewrite gsoAddCode in H; eauto;\n try rewrite gssThreadCode in H;\n try solve[inversion H]\n end.\n { (*AQCUIRE*)\n replace cnt with cnt0 by apply cnt_irr;\n exact Hcode. }\n +\n inversion H; subst;\n match goal with\n | [ H: getThreadC ?cnt = Krun ?c,\n H': getThreadC ?cnt' = Kblocked ?c' |- _ ] =>\n try erewrite <- age_getThreadCode in H;\n try rewrite gLockSetCode in H;\n try rewrite gRemLockSetCode in H;\n try erewrite gsoAddCode in H; eauto;\n try rewrite gsoThreadCode in H;\n try solve[inversion H]; eauto\n end.\n { (*AQCUIRE*)\n replace cnt with cnt0 by apply cnt_irr;\n exact Hcode. }\n\n Grab Existential Variables.\n eauto. eauto. eauto.\n Qed.\n\n\n End DryMachineShell.\n\nEnd Concur.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/dry_machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.25091279808829703, "lm_q1q2_score": 0.12937563580411374}} {"text": "(* *********************************************************************)\n(* *)\n(* The Compcert verified compiler *)\n(* *)\n(* Xavier Leroy, INRIA Paris-Rocquencourt *)\n(* Jacques-Henri Jourdan, INRIA Paris-Rocquencourt *)\n(* *)\n(* Copyright Institut National de Recherche en Informatique et en *)\n(* Automatique. All rights reserved. This file is distributed *)\n(* under the terms of the GNU General Public License as published by *)\n(* the Free Software Foundation, either version 2 of the License, or *)\n(* (at your option) any later version. This file is also distributed *)\n(* under the terms of the INRIA Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n\n(** Architecture-dependent parameters for PowerPC *)\n\nRequire Import ZArith.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\n\nDefinition ptr64 := false.\n\nDefinition big_endian := true.\n\nDefinition align_int64 := 8%Z.\nDefinition align_float64 := 8%Z.\n\nDefinition splitlong := true.\n\nLemma splitlong_ptr32: splitlong = true -> ptr64 = false.\nProof.\n unfold splitlong, ptr64; congruence.\nQed.\n\nProgram Definition default_pl_64 : bool * nan_pl 53 :=\n (false, iter_nat 51 _ xO xH).\n\nDefinition choose_binop_pl_64 (s1: bool) (pl1: nan_pl 53) (s2: bool) (pl2: nan_pl 53) :=\n false. (**r always choose first NaN *)\n\nProgram Definition default_pl_32 : bool * nan_pl 24 :=\n (false, iter_nat 22 _ xO xH).\n\nDefinition choose_binop_pl_32 (s1: bool) (pl1: nan_pl 24) (s2: bool) (pl2: nan_pl 24) :=\n false. (**r always choose first NaN *)\n\nDefinition float_of_single_preserves_sNaN := true.\n\nGlobal Opaque ptr64 big_endian splitlong\n default_pl_64 choose_binop_pl_64\n default_pl_32 choose_binop_pl_32\n float_of_single_preserves_sNaN.\n\n(** Can we use the 64-bit extensions to the PowerPC architecture? *)\nParameter ppc64: bool.\n", "meta": {"author": "CertiKOS", "repo": "SingleStackCompCert", "sha": "04eb987a8cc0f428365edaa4dffb2237d02d9500", "save_path": "github-repos/coq/CertiKOS-SingleStackCompCert", "path": "github-repos/coq/CertiKOS-SingleStackCompCert/SingleStackCompCert-04eb987a8cc0f428365edaa4dffb2237d02d9500/powerpc/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.25091277568224823, "lm_q1q2_score": 0.12937562425110877}} {"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Cop Ctypes ClightC.\nRequire Import AsmC.\nRequire SimMemInjInvC SimSymbDropInv.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import AsmregsC.\nRequire Import MatchSimModSem.\nRequire Import StoreArguments StoreArgumentsProps.\nRequire Import AsmStepInj IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import CtypingC.\nRequire Import CopC.\n\nRequire Import MatchSimModSem.\nRequire Import Conventions1C.\n\nRequire Import ClightStepInj.\nRequire Import IdSimExtra IdSimInvExtra IdSimClightExtra.\nRequire Import mktac.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nSection INJINV.\n\n\nLocal Existing Instance SimSymbDropInv.SimMemInvTop.\nLocal Existing Instance SimSymbDropInv.SimSymbDropInv.\nLocal Existing Instance SoundTop.Top.\n\nInductive match_states_clight_inv\n : unit -> Clight.state -> Clight.state -> SimMem.t -> Prop :=\n| match_states_clight_inv_intro\n st_src st_tgt j m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMem.src))\n (MWFTGT: m_tgt = sm0.(SimMem.tgt))\n (MWFINJ: j = sm0.(SimMemInjInv.minj).(SimMemInj.inj))\n (MATCHST: match_states_clight_internal st_src st_tgt j m_src m_tgt)\n (MWF: SimMem.wf sm0)\n :\n match_states_clight_inv\n tt st_src st_tgt sm0\n.\n\nLemma clight_inj_inv_drop\n (clight: Clight.program)\n (WF: Sk.wf (module2 clight))\n :\n exists mp,\n (<>)\n /\\ (<>)\n /\\ (<>)\n.\nProof.\n eexists (ModPair.mk _ _ _); s.\n esplits; eauto. instantiate (1:=SimSymbDropInv.mk bot1 _ _).\n econs; ss; i.\n { econs; ss; i; clarify.\n inv WF. auto. }\n eapply match_states_sim with (match_states := match_states_clight_inv); ss.\n - apply unit_ord_wf.\n - eapply SoundTop.sound_state_local_preservation.\n\n - i. ss. exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n inv INITTGT. inv SAFESRC. inv SIMARGS. inv H. ss.\n exploit match_globals_find_funct; eauto.\n i. clarify.\n esplits; eauto.\n + econs; eauto.\n + refl.\n + econs; eauto. econs; eauto.\n { inv TYP. inv TYP0. eapply inject_list_typify_list; eauto. }\n econs.\n + ss.\n\n - i. ss. exploit SimSymbDropInv_match_globals.\n { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n des. inv SAFESRC. inv SIMARGS. esplits. econs; ss.\n + eapply match_globals_find_funct; eauto.\n + inv TYP. econs; eauto.\n erewrite <- inject_list_length; eauto.\n + ss.\n\n - i. ss. inv MATCH; eauto.\n\n - i. ss. clear SOUND. inv CALLSRC. inv MATCH. inv MATCHST. inv SIMSKENV. ss.\n esplits; eauto.\n + econs; ss; eauto.\n * eapply SimSymbDropInv_find_None; eauto.\n ii. clarify. ss. des. clarify.\n * des. clear EXTERNAL.\n unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs_safe.\n inv INJ. inv SIMSKELINK.\n exploit SIMDEF; eauto. i. des. clarify. des_ifs. esplits; eauto.\n + econs; ss.\n + refl.\n + instantiate (1:=top4). ss.\n\n - i. ss. clear SOUND HISTORY.\n exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n inv AFTERSRC. inv MATCH. inv MATCHST.\n esplits; eauto.\n + econs; eauto. inv SIMRET; ss.\n + inv SIMRET; ss. econs; eauto. econs; eauto.\n { eapply inject_typify; et. }\n ss. eapply match_cont_incr; try eassumption.\n inv MLE. inv MLE1. inv MLE0. inv MLE. etrans; eauto.\n + refl.\n\n - i. ss. inv FINALSRC. inv MATCH. inv MATCHST. inv CONT.\n esplits; eauto.\n + econs.\n + econs; eauto.\n + refl.\n\n - left. i. split.\n + eapply modsem2_receptive.\n + ii. inv MATCH. destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n cinv MWF. cinv WF0. ss.\n exploit clight_step_preserve_injection2; try eassumption.\n { instantiate (1:=cgenv skenv_link_tgt clight). ss. }\n { eapply function_entry2_inject. ss. }\n { inv SIMSKENV. exploit SimSymbDropInv.sim_skenv_symbols_inject; eauto. }\n { inv SIMSKENV. ss. rpapply SimSymbDropInv_match_globals; eauto. } i. des.\n exploit SimMemInjC.parallel_gen; eauto. i. des.\n hexploit SimMemInjInv.le_inj_wf_wf; eauto. intros MWFINV0.\n\n esplits; eauto.\n * left. apply plus_one. econs; ss; eauto.\n eapply modsem2_determinate.\n * instantiate (1:=SimMemInjInv.mk _ _ _). econs; ss; eauto.\n * econs; ss; eauto.\nQed.\n\nEnd INJINV.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/demo/unreadglob/IdSimClightDropInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.22815649691270326, "lm_q1q2_score": 0.12914080617800214}} {"text": "From Coq Require Import String Arith NArith ZArith Eqdep_dec.\n\nFrom Vyper Require FSet Map UInt256.\n\nFrom Vyper Require Import Config Calldag.\nFrom Vyper.L10 Require Import AST Base Callset Descend.\n\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\n\n\nLtac destruct_let_pair\n:= match goal with\n |- (let (_, _) := ?x in _) = let (_, _) := ?x in _ =>\n destruct x\n end.\nLtac destruct_if\n:= match goal with\n |- (if ?x then _ else _) = (if ?x then _ else _) =>\n destruct x\n end.\n\n\nSection Expr.\nContext {C: VyperConfig}.\n\nDefinition storage_var_is_declared (cd: calldag)\n (name: string)\n: bool\n:= match cd_declmap cd name with\n | Some (StorageVarDecl _) => true\n | _ => false\n end.\n\n\nFixpoint interpret_expr {bigger_call_depth_bound smaller_call_depth_bound: nat}\n (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n {cd: calldag}\n (fc: fun_ctx cd bigger_call_depth_bound)\n (do_call: forall\n (fc': fun_ctx cd smaller_call_depth_bound)\n (world: world_state)\n (arg_values: list uint256),\n world_state * expr_result uint256)\n (builtins: string -> option builtin)\n (world: world_state)\n (loc: string_map uint256)\n (e: expr)\n (CallOk: let _ := string_set_impl in \n FSet.is_subset (expr_callset e)\n (decl_callset (fun_decl fc))\n = true)\n{struct e}\n: world_state * expr_result uint256\n:= let fix interpret_expr_list (world: world_state)\n (loc: string_map uint256)\n (e: list expr)\n (CallOk: let _ := string_set_impl in \n FSet.is_subset (expr_list_callset e)\n (decl_callset (fun_decl fc))\n = true)\n {struct e}\n : world_state * expr_result (list uint256)\n := match e as e' return e = e' -> _ with\n | nil => fun _ => (world, ExprSuccess nil)\n | (h :: t)%list => fun E =>\n let (world', result_h) := interpret_expr Ebound fc do_call builtins\n world loc h\n (callset_descend_head E CallOk)\n in match result_h with\n | ExprAbort ab => (world', ExprAbort ab)\n | ExprSuccess x =>\n let (world'', result_t) := interpret_expr_list world' loc t\n (callset_descend_tail E CallOk)\n in (world'', match result_t with\n | ExprAbort _ => result_t\n | ExprSuccess y => ExprSuccess (x :: y)%list\n end)\n end\n end eq_refl\n in match e as e' return e = e' -> _ with\n | Const val => fun _ => (world, ExprSuccess val)\n | LocalVar name => fun _ =>\n (world, match map_lookup loc name with\n | Some val => ExprSuccess val\n | None => expr_error \"undeclared local variable\"\n end)\n | StorageVar name => fun _ =>\n if storage_var_is_declared cd name\n then (world, ExprSuccess (match storage_lookup world name with\n | None => zero256\n | Some x => x\n end))\n else (world, expr_error \"undeclared global variable\")\n | UnOp op a => fun E =>\n let (world', result) := interpret_expr Ebound fc do_call builtins\n world loc a\n (callset_descend_unop E CallOk)\n in (world', match result with\n | ExprSuccess val => interpret_unop op val\n | ExprAbort _ => result\n end)\n | BinOp op a b => fun E =>\n let (world', result_a) := interpret_expr Ebound fc do_call builtins\n world loc a\n (callset_descend_binop_left E CallOk)\n in match result_a with\n | ExprAbort _ => (world', result_a)\n | ExprSuccess x =>\n let (world'', result_b) := interpret_expr Ebound fc do_call builtins\n world' loc b\n (callset_descend_binop_right E CallOk)\n in (world'', match result_b with\n | ExprAbort _ => result_b\n | ExprSuccess y => interpret_binop op x y\n end)\n end\n | IfThenElse cond yes no => fun E =>\n let (world', result_cond) := interpret_expr Ebound fc do_call builtins\n world loc cond\n (callset_descend_if_cond E CallOk)\n in match result_cond with\n | ExprAbort _ => (world', result_cond)\n | ExprSuccess cond_value =>\n if (Z_of_uint256 cond_value =? 0)%Z\n then interpret_expr Ebound fc do_call builtins\n world' loc no\n (callset_descend_if_else E CallOk)\n else interpret_expr Ebound fc do_call builtins\n world' loc yes\n (callset_descend_if_then E CallOk)\n end\n | LogicalAnd a b => fun E =>\n let (world', result_a) := interpret_expr Ebound fc do_call builtins\n world loc a\n (callset_descend_and_left E CallOk)\n in match result_a with\n | ExprAbort _ => (world', result_a)\n | ExprSuccess a_value =>\n if (Z_of_uint256 a_value =? 0)%Z\n then (world', result_a)\n else interpret_expr Ebound fc do_call builtins\n world' loc b\n (callset_descend_and_right E CallOk)\n end\n | LogicalOr a b => fun E =>\n let (world', result_a) := interpret_expr Ebound fc do_call builtins\n world loc a\n (callset_descend_or_left E CallOk)\n in match result_a with\n | ExprAbort msg => (world', result_a)\n | ExprSuccess a_value =>\n if (Z_of_uint256 a_value =? 0)%Z\n then interpret_expr Ebound fc do_call builtins\n world' loc b\n (callset_descend_or_right E CallOk)\n else (world', result_a)\n end\n | PrivateOrBuiltinCall name args => fun E =>\n let (world', result_args) :=\n interpret_expr_list world loc args\n (callset_descend_args E CallOk)\n in match result_args with\n | ExprAbort ab => (world', ExprAbort ab)\n | ExprSuccess arg_values =>\n match fun_ctx_descend fc CallOk Ebound E with\n | Some new_fc => do_call new_fc world' arg_values\n | None => (* can't resolve the function, maybe it's a builtin *)\n match builtins name with\n | Some (existT _ arity b) =>\n (if (arity =? List.length arg_values)%nat as arity_ok \n return _ = arity_ok -> _\n then fun Earity => call_builtin arg_values Earity (b world')\n else fun _ => (world', expr_error \"builtin with wrong arity\"))\n eq_refl\n | None => (world', expr_error \"can't resolve function name\")\n end\n end\n end\n end eq_refl.\n\n(* This is not needed as PropExtensionality covers it.\n But this is an example of induction on expr.\n *)\nLemma interpret_expr_fun_ctx_irrel {bigger_call_depth_bound smaller_call_depth_bound: nat}\n (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n {cd: calldag}\n {fc1 fc2: fun_ctx cd bigger_call_depth_bound}\n (FcOk: fun_name fc1 = fun_name fc2)\n (do_call: forall\n (fc': fun_ctx cd smaller_call_depth_bound)\n (world: world_state)\n (arg_values: list uint256),\n world_state * expr_result uint256)\n (builtins: string -> option builtin)\n (world: world_state)\n (loc: string_map uint256)\n (e: expr)\n (CallOk1: let _ := string_set_impl in \n FSet.is_subset (expr_callset e)\n (decl_callset (fun_decl fc1))\n = true)\n (CallOk2: let _ := string_set_impl in \n FSet.is_subset (expr_callset e)\n (decl_callset (fun_decl fc2))\n = true):\n interpret_expr Ebound fc1 do_call builtins world loc e CallOk1\n =\n interpret_expr Ebound fc2 do_call builtins world loc e CallOk2.\nProof.\nrevert world loc.\ninduction e using expr_ind'; cbn; intros.\n{ trivial. }\n{ trivial. }\n{ trivial. }\n{ (* unop *)\n now rewrite IHe with (CallOk2 := callset_descend_unop eq_refl CallOk2).\n}\n{ (* binop *)\n rewrite IHe1 with (CallOk2 := callset_descend_binop_left eq_refl CallOk2).\n destruct_let_pair.\n destruct e. 2:{ trivial. }\n rewrite IHe2 with (CallOk2 := callset_descend_binop_right eq_refl CallOk2).\n destruct_let_pair.\n trivial.\n}\n{ (* if *)\n rewrite IHe1 with (CallOk2 := callset_descend_if_cond eq_refl CallOk2).\n destruct_let_pair.\n destruct e. 2:{ trivial. }\n destruct_if.\n { now rewrite IHe3 with (CallOk2 := callset_descend_if_else eq_refl CallOk2). }\n now rewrite IHe2 with (CallOk2 := callset_descend_if_then eq_refl CallOk2).\n}\n{ (* and *)\n rewrite IHe1 with (CallOk2 := callset_descend_and_left eq_refl CallOk2).\n destruct_let_pair.\n destruct e. 2:{ trivial. }\n now destruct_if.\n}\n{ (* or *)\n rewrite IHe1 with (CallOk2 := callset_descend_or_left eq_refl CallOk2).\n destruct_let_pair.\n destruct e. 2:{ trivial. }\n now destruct_if.\n}\n(* call *)\nremember (fix interpret_expr_list world loc (e: list expr) CallOk := _) as interpret_expr_list1.\nremember (fix interpret_expr_list world loc (e: list expr) \n (CallOk: FSet.is_subset (expr_list_callset e)\n (decl_callset (fun_decl fc2))\n = true) := _) as interpret_expr_list2.\nassert (L: interpret_expr_list1 world loc args (callset_descend_args eq_refl CallOk1)\n =\n interpret_expr_list2 world loc args (callset_descend_args eq_refl CallOk2)).\n{\n remember (callset_descend_args eq_refl CallOk1) as ListCallOk1.\n remember (callset_descend_args eq_refl CallOk2) as ListCallOk2.\n clear HeqListCallOk1 HeqListCallOk2 CallOk1 CallOk2.\n revert world loc ListCallOk1 ListCallOk2.\n induction args; intros. { now subst. }\n rewrite Heqinterpret_expr_list1. rewrite Heqinterpret_expr_list2. cbn.\n rewrite (List.Forall_inv H \n (callset_descend_head eq_refl ListCallOk1) \n (callset_descend_head eq_refl ListCallOk2)).\n destruct_let_pair.\n destruct e. 2:{ trivial. }\n rewrite<- Heqinterpret_expr_list1.\n rewrite<- Heqinterpret_expr_list2.\n rewrite (IHargs (List.Forall_inv_tail H) w loc\n (callset_descend_tail eq_refl ListCallOk1)\n (callset_descend_tail eq_refl ListCallOk2)).\n now destruct_let_pair.\n}\nclear Heqinterpret_expr_list1 Heqinterpret_expr_list2.\nrewrite L.\ndestruct_let_pair.\ndestruct e. 2:{ trivial. }\nassert (F: fun_ctx_descend fc1 CallOk1 Ebound eq_refl\n =\n fun_ctx_descend fc2 CallOk2 Ebound eq_refl).\n{ apply fun_ctx_descend_irrel. }\nrewrite F.\nnow destruct (fun_ctx_descend fc2 CallOk2 Ebound eq_refl).\nQed.\n\nEnd Expr.\n\nLtac destruct_interpret_expr_irrel\n:= match goal with\n H: fun_name ?fc1 = fun_name ?fc2 \n |- (let (_, _) := interpret_expr ?Ebound ?fc1 ?do_call ?builtins ?world ?loc ?e ?c1 in _)\n =\n (let (_, _) := interpret_expr ?Ebound ?fc2 ?do_call ?builtins ?world ?loc ?e ?c2 in _)\n =>\n rewrite (interpret_expr_fun_ctx_irrel Ebound H do_call builtins\n world loc e c1 c2);\n destruct_let_pair\n end.", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L10/Expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.23934934732271168, "lm_q1q2_score": 0.12900528208949028}} {"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\n\nRequire Import SemanticsFut.\nRequire Import Equivalence.\nRequire Import Equivalences.\nRequire Import ProperLevel.\nRequire Import Defined.\nRequire Import PageType.\nRequire Import Subsumption.\n\n\nLocal Ltac prove_hygiene :=\n repeat (apply hygiene_auto; cbn; repeat2 split; auto);\n eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1, subst_closub;\n try (apply hygiene_var; cbn; auto; done).\n\n\nLemma pwctx_cons_tml :\n forall i m p s s' a G,\n pwctx i s s' G\n -> hygiene clo m\n -> hygiene clo p\n -> hygiene (ctxpred G) a\n -> (i > 0 -> seqhyp (pred i) m p (hyp_tm (subst s a)) (hyp_tm (subst s' a)))\n -> (forall j s'',\n j < i\n -> pwctx j s s'' G\n -> relhyp j false (hyp_tm (subst s' a)) (hyp_tm (subst s'' a)))\n -> (forall j s'',\n j < i\n -> pwctx j s'' s' G\n -> relhyp j true (hyp_tm (subst s a)) (hyp_tm (subst s'' a)))\n -> pwctx i (dot m s) (dot p s') (cons (hyp_tml a) G).\nProof.\nintros i m p s s' a G Hs Hclm Hclp Hcla Hh Hleft Hright.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\napply pwctx_cons; auto.\n {\n simpsub.\n destruct i as [| i].\n {\n apply (seqhyp_tml _#5 (iubase empty_urel)); eauto using subst_closub; try (intro; omega).\n }\n assert (S i > 0) as Hpos by omega.\n invert (Hh Hpos).\n intros R Hal Har Hmp.\n apply (seqhyp_tml _#5 R); eauto using subst_closub.\n }\n\n {\n intros j b s'' Hsmall Hs'.\n destruct b.\n {\n cbn.\n invert Hsmall.\n intros Hji.\n apply Hleft; auto.\n eapply seqctx_pwctx_demote_left; eauto.\n }\n\n {\n cbn.\n invert Hsmall.\n intros Hji.\n so (seqctx_impl_closub _#4 Hs') as (_ & Hcls'').\n destruct j as [| j].\n {\n apply (relhyp_tml _#4 (iubase empty_urel)); eauto using subst_closub; intro; omega.\n }\n exploit (Hleft j s'') as H.\n {\n omega.\n }\n\n {\n cbn in Hs'.\n apply (pwctx_downward (S j)); [omega |].\n refine (seqctx_pwctx_left _#5 _ Hs').\n eapply pwctx_downward; eauto.\n }\n invertc H.\n intros R Hal Har.\n apply (relhyp_tml _#4 R); eauto using subst_closub.\n }\n }\n\n {\n intros j b s'' Hsmall Hs'.\n destruct b.\n {\n cbn.\n invert Hsmall.\n intros Hji.\n apply Hright; auto.\n eapply seqctx_pwctx_demote_right; eauto.\n }\n\n {\n cbn.\n invert Hsmall.\n intros Hji.\n so (seqctx_impl_closub _#4 Hs') as (Hcls'' & _).\n destruct j as [| j].\n {\n apply (relhyp_tml _#4 (iubase empty_urel)); eauto using subst_closub; try (intro; omega).\n }\n exploit (Hright j s'') as H.\n {\n omega.\n }\n\n {\n cbn in Hs'.\n apply (pwctx_downward (S j)); [omega |].\n refine (seqctx_pwctx_right _#5 _ Hs').\n eapply pwctx_downward; eauto.\n }\n invertc H.\n intros R Hal Har.\n apply (relhyp_tml _#4 R); eauto using subst_closub.\n }\n }\nQed.\n\n\nLemma pwctx_cons_tml_seq :\n forall i m p s s' a G,\n pwctx i s s' G\n -> hygiene clo m\n -> hygiene clo p\n -> hygiene (ctxpred G) a\n -> (i > 0 -> seqhyp (pred i) m p (hyp_tm (subst s a)) (hyp_tm (subst s' a)))\n -> (forall i t t',\n pwctx i t t' (promote G)\n -> exists pg R,\n interp pg true i (subst t a) R\n /\\ interp pg false i (subst t' a) R)\n -> pwctx i (dot m s) (dot p s') (cons (hyp_tml a) G).\nProof.\nintros i m p s s' a G Hs Hclm Hclp Hcla Hh Hact.\napply pwctx_cons; auto.\n {\n simpsub.\n so (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\n destruct i as [| i].\n {\n apply (seqhyp_tml _#5 (iubase empty_urel)); eauto using subst_closub; try omega.\n }\n invert (Hh (Nat.lt_0_succ _)).\n intros R Hl Hr Hmp.\n apply (seqhyp_tml _#5 R); eauto using subst_closub.\n }\n\n {\n intros j b u Hsmall Hu.\n destruct b.\n {\n cbn.\n so (pwctx_smaller _#6 Hsmall Hs) as Hsj.\n so (Hact j s s' Hsj) as (pg & R & Hl & Hr).\n so (Hact j s u (seqctx_pwctx_left _#5 Hsj Hu)) as (pg' & R' & Hl' & Hr').\n so (interp_fun _#7 Hl Hl'); subst R'.\n eapply relhyp_tm; eauto using interp_increase, toppg_max.\n }\n\n {\n cbn.\n cbn in Hu.\n so (pwctx_impl_closub _#4 Hs) as (_ & Hcls').\n so (seqctx_impl_closub _#4 Hu) as (_ & Hclu).\n destruct j as [| j].\n {\n apply (relhyp_tml _#4 (iubase empty_urel)); try (intros; omega);\n eapply subst_closub; eauto.\n }\n so (seqctx_promote _#4 Hu) as Hu'.\n so (pwctx_promote _#4 (pwctx_smaller _#6 Hsmall Hs)) as Hsj.\n cbn in Hsj.\n fold (promote G) in Hsj.\n so (Hact j s s' Hsj) as (pg & R & Hl & Hr).\n so (Hact j s u (seqctx_pwctx_left _#5 Hsj Hu')) as (pg' & R' & Hl' & Hr').\n so (interp_fun _#7 Hl Hl'); subst R'.\n apply (relhyp_tml _#4 R); try (eapply subst_closub; eauto);\n intro; cbn; eauto using interp_increase, toppg_max.\n }\n }\n\n {\n intros j b u Hsmall Hu.\n destruct b.\n {\n cbn.\n so (pwctx_smaller _#6 Hsmall Hs) as Hsj.\n so (Hact j s s' Hsj) as (pg & R & Hl & Hr).\n so (Hact j u s' (seqctx_pwctx_right _#5 Hsj Hu)) as (pg' & R' & Hl' & Hr').\n so (interp_fun _#7 Hr Hr'); subst R'.\n eapply relhyp_tm; eauto using interp_increase, toppg_max.\n }\n\n {\n cbn.\n cbn in Hu.\n so (pwctx_impl_closub _#4 Hs) as (Hcls & _).\n so (seqctx_impl_closub _#4 Hu) as (Hclu & _).\n destruct j as [| j].\n {\n apply (relhyp_tml _#4 (iubase empty_urel)); try (intros; omega);\n eapply subst_closub; eauto.\n }\n so (seqctx_promote _#4 Hu) as Hu'.\n so (pwctx_promote _#4 (pwctx_smaller _#6 Hsmall Hs)) as Hsj.\n cbn in Hsj.\n fold (promote G) in Hsj.\n so (Hact j s s' Hsj) as (pg & R & Hl & Hr).\n so (Hact j u s' (seqctx_pwctx_right _#5 Hsj Hu')) as (pg' & R' & Hl' & Hr').\n so (interp_fun _#7 Hr Hr'); subst R'.\n apply (relhyp_tml _#4 R); try (eapply subst_closub; eauto);\n intro; cbn; eauto using interp_increase, toppg_max.\n }\n }\nQed.\n\n\nLemma sound_fut_kind_formation :\n forall G lv k k',\n pseq (promote G) (deq k k' (kuniv lv))\n -> pseq G (deq lv lv pagetp)\n -> pseq G (deq (fut k) (fut k') (kuniv lv)).\nProof.\nintros G lv k l.\nrevert G.\nrefine (seq_pseq_promote 2 [] k [] l 2 true [] _ false [] _ _ _); cbn.\nintros G Hclk Hcll Hseq Hseqlv.\nrewrite -> seq_eqkind in Hseq |- *.\nrewrite -> seq_deq in Hseqlv.\neassert _ as Hlv; [refine (seq_pagetp_invert G lv _) |].\n {\n intros i t t' Ht.\n so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlv & _).\n eauto.\n }\nclear Hseqlv.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\ndestruct i as [| i].\n {\n so (Hlv _#3 Hs) as (pg & Hlvl & Hlvr).\n exists pg, (qfut qone), (iufut0 stop), (pginterp_lt_top _ _ Hlvl).\n simpsub.\n do2 9 split; auto;\n try (apply kinterp_eval_refl; apply interp_kfut_zero; eapply subst_closub; eauto);\n try (apply interp_eval_refl; apply interp_fut_zero; eapply subst_closub; eauto).\n }\nso (pwctx_promote _#4 Hs) as Hs'.\nso (Hseq _#3 Hs') as (pg & K & R & h & Hlvl & Hlvr & Hkl & Hkr & Hll & Hlr & Hklt & Hkrt & Hllt & Hlrt).\nexists pg, (qfut K), (iufut stop (S i) R), h.\nsimpsub.\ndo2 9 split; auto;\ntry (apply kinterp_eval_refl; apply interp_kfut; auto);\ntry (apply interp_eval_refl; apply interp_fut; auto).\nQed.\n\n \nLemma sound_fut_formation :\n forall G a b,\n pseq (promote G) (deqtype a b)\n -> pseq G (deqtype (fut a) (fut b)).\nProof.\nintros G a b.\nrevert G.\nrefine (seq_pseq_promote 2 [] a [] b 1 true [] _ _ _); cbn.\nintros G Hcla Hclb Hseq.\nrewrite -> seq_eqtype in Hseq |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\ndestruct i as [| i].\n {\n exists (iufut0 stop).\n simpsub.\n do2 3 split;\n apply interp_eval_refl; apply interp_fut_zero; eapply subst_closub; eauto.\n }\nso (pwctx_promote _#4 Hs) as Hs'.\nso (Hseq _#3 Hs') as (R & Hal & Har & Hbl & Hbr).\nexists (iufut stop (S i) R).\ndo2 3 split;\napply interp_eval_refl; apply interp_fut; auto.\nQed.\n\n\nLemma sound_fut_formation_univ :\n forall G lv a b,\n pseq (promote G) (deq a b (univ lv))\n -> pseq G (deq lv lv pagetp)\n -> pseq G (deq (fut a) (fut b) (univ lv)).\nProof.\nintros G lv a b.\nrevert G.\nrefine (seq_pseq_promote 2 [] a [] b 2 true [] _ false [] _ _ _); cbn.\nintros G Hcla Hclb Hseq Hseqlv.\nrewrite -> seq_univ in Hseq |- *.\nrewrite -> seq_deq in Hseqlv.\neassert _ as Hlv; [refine (seq_pagetp_invert G lv _) |].\n {\n intros i t t' Ht.\n so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlv & _).\n eauto.\n }\nclear Hseqlv.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\ndestruct i as [| i].\n {\n so (Hlv _#3 Hs) as (pg & Hlvl & Hlvr).\n exists pg, (iufut0 stop).\n do2 5 split; auto;\n apply interp_eval_refl; apply interp_fut_zero; eapply subst_closub; eauto.\n }\nso (pwctx_promote _#4 Hs) as Hs'.\nso (Hseq _#3 Hs') as (pg & R & Hlvl & Hlvr & Hal & Har & Hbl & Hbr).\nexists pg, (iufut stop (S i) R).\nsimpsub.\ndo2 5 split; auto;\napply interp_eval_refl; apply interp_fut; auto.\nQed.\n\n\nLemma sound_fut_intro :\n forall G m n a,\n pseq (promote G) (deq m n a)\n -> pseq G (deq (next m) (next n) (fut a)).\nProof.\nintros G m n a.\nrevert G.\nrefine (seq_pseq_promote 3 [] m [] n [] a 1 true [] _ _ _); cbn.\nintros G Hclm Hcln Hcla Hseq.\nrewrite -> seq_deq in Hseq |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\ndestruct i as [| i].\n {\n exists (iufut0 stop).\n simpsub.\n do2 4 split;\n try (apply interp_eval_refl; apply interp_fut_zero; eapply subst_closub; eauto);\n rewrite -> den_iufut0;\n apply fut_action_next_zero; try prove_hygiene.\n }\nso (pwctx_promote _#4 Hs) as Hs'.\nso (Hseq _#3 Hs') as (R & Hal & Har & Hm & Hn & Hmn).\nexists (iufut stop (S i) R).\nsimpsub.\ndo2 4 split;\ntry (apply interp_eval_refl; apply interp_fut; auto);\napply fut_action_next; auto; omega.\nQed.\n\n\nLemma sound_fut_elim :\n forall G m n a p q b,\n pseq G (deq m n (fut a))\n -> pseq (promote G) (deqtype a a)\n -> pseq (cons (hyp_tml a) G) (deq p q b)\n -> pseq G (deq (subst1 (prev m) p) (subst1 (prev n) q) (subst1 (prev m) b)).\nProof.\nintros G m n a p q b.\nrevert G.\nrefine (seq_pseq_promote 1 [] a 3 false [] _ true [] _ false [_] _ _ _); cbn.\nintros G Hcla Hseqmn Hseqa Hseqpq.\nrewrite -> seq_eqtype in Hseqa.\nrewrite -> seq_deq in Hseqmn, Hseqpq |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqmn _#3 Hs) as (Af & Hal & Har & Hm & Hn & Hmn).\nassert (forall c d,\n rel (den Af) i c d\n -> pwctx i (dot (prev c) s) (dot (prev d) s') (cons (hyp_tml a) G)) as Hs'.\n {\n intros c d Hcd.\n so (urel_closed _#5 Hcd) as (Hclc & Hcld).\n apply pwctx_cons_tml_seq; auto; try prove_hygiene.\n {\n intro Hpos.\n destruct i as [| i]; [omega |].\n cbn [pred].\n simpsubin Hal.\n simpsubin Har.\n invert (basic_value_inv _#6 value_fut Hal).\n intros A Hal' Heq1.\n invert (basic_value_inv _#6 value_fut Har).\n intros A' Har' Heq2.\n so (eqtrans Heq1 (eqsymm Heq2)) as Heq.\n clear Heq2.\n subst Af.\n so (iufut_inj _#5 Heq); subst A'.\n apply (seqhyp_tm _#5 A); auto.\n apply (fut_action_prev _ (S i)).\n exact Hcd.\n }\n\n {\n intros j t t' Ht.\n so (Hseqa _#3 Ht) as (R & Hl & Hr & _).\n exists toppg, R.\n auto.\n }\n }\nclear Hseqmn.\nso (Hseqpq _#3 (Hs' _ _ Hm)) as (B & Hbml & Hbmr & Hmp & _).\nso (Hseqpq _#3 (Hs' _ _ Hn)) as (B' & _ & Hbnr & _ & Hnq & _).\nso (Hseqpq _#3 (Hs' _ _ Hmn)) as (B'' & Hbml' & Hbnr' & _ & _ & Hmnpq).\nso (basic_fun _#7 Hbml Hbml'); subst B''.\nso (basic_fun _#7 Hbnr Hbnr'); subst B'.\nexists B.\nsimpsub.\ndo2 4 split; auto.\nQed.\n\n\nLemma sound_fut_elim_eqtype :\n forall G m n a b c,\n pseq G (deq m n (fut a))\n -> pseq (promote G) (deqtype a a)\n -> pseq (cons (hyp_tml a) G) (deqtype b c)\n -> pseq G (deqtype (subst1 (prev m) b) (subst1 (prev n) c)).\nProof.\nintros G m n a b c.\nrevert G.\nrefine (seq_pseq_promote 1 [] a 3 false [] _ true [] _ false [_] _ _ _); cbn.\nintros G Hcla Hseqmn Hseqa Hseqbc.\nrewrite -> seq_eqtype in Hseqa, Hseqbc |- *.\nrewrite -> seq_deq in Hseqmn.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqmn _#3 Hs) as (Af & Hal & Har & Hm & Hn & Hmn).\nassert (forall p q,\n rel (den Af) i p q\n -> pwctx i (dot (prev p) s) (dot (prev q) s') (cons (hyp_tml a) G)) as Hs'.\n {\n intros p q Hpq.\n so (urel_closed _#5 Hpq) as (Hclp & Hclq).\n apply pwctx_cons_tml_seq; auto; try prove_hygiene.\n {\n intro Hpos.\n destruct i as [| i]; [omega |].\n cbn [pred].\n simpsubin Hal.\n simpsubin Har.\n invert (basic_value_inv _#6 value_fut Hal).\n intros A Hal' Heq1.\n invert (basic_value_inv _#6 value_fut Har).\n intros A' Har' Heq2.\n so (eqtrans Heq1 (eqsymm Heq2)) as Heq.\n clear Heq2.\n subst Af.\n so (iufut_inj _#5 Heq); subst A'.\n apply (seqhyp_tm _#5 A); auto.\n apply (fut_action_prev _ (S i)).\n exact Hpq.\n }\n\n {\n intros j t t' Ht.\n so (Hseqa _#3 Ht) as (R & Hl & Hr & _).\n exists toppg, R.\n auto.\n }\n }\nclear Hseqmn.\nso (Hseqbc _#3 (Hs' _ _ Hm)) as (R & Hmbl & Hmbr & _).\nso (Hseqbc _#3 (Hs' _ _ Hn)) as (R' & _ & _ & Hncl & Hncr).\nso (Hseqbc _#3 (Hs' _ _ Hmn)) as (R'' & Hmbl' & _ & _ & Hncr').\nso (basic_fun _#7 Hmbl Hmbl'); subst R''.\nso (basic_fun _#7 Hncr Hncr'); subst R'.\nexists R.\nsimpsub.\ndo2 3 split; auto.\nQed.\n\n\n(* This almost follows from sound_fut_eta_hyp, but not quite. *)\nLemma sound_fut_eta :\n forall G m a,\n pseq G (deq m m (fut a))\n -> pseq G (deq m (next (prev m)) (fut a)).\nProof.\nintros G m a.\nrevert G.\nrefine (seq_pseq 1 [] m 1 [] _ _ _); cbn.\nintros G Hclm Hseq.\nrewrite -> seq_deq in Hseq |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseq i s s' Hs) as (R & Hfutl & Hfutr & Hm & _).\nexists R.\ndo2 3 split; auto.\nsimpsubin Hfutl.\nsimpsubin Hfutr.\nsimpsub.\ndestruct i as [| i].\n {\n invert (basic_value_inv _#6 value_fut Hfutl).\n intros _ <-.\n rewrite -> den_iufut0 in Hm |- *.\n split.\n {\n apply fut_action_next_zero; prove_hygiene.\n }\n\n {\n destruct Hm as (n & _ & _ & _ & _ & Hsteps & _).\n refine (urel_equiv_1 _#6 _ (equiv_symm _#3 (steps_equiv _#3 Hsteps)) _).\n {\n prove_hygiene.\n }\n so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hsteps (subst_closub _#4 Hcls Hclm))) as H; cbn in H.\n destruct H.\n apply fut_action_next_zero; prove_hygiene.\n }\n }\ninvert (basic_value_inv _#6 value_fut Hfutl).\nintros A Hal Heq1.\ninvert (basic_value_inv _#6 value_fut Hfutr).\nintros A' Har Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq2.\nsubst R.\nso (iufut_inj _#5 Heq); subst A'.\ncbn in Hm.\nsplit.\n {\n apply fut_action_next; auto.\n eapply fut_action_prev; eauto.\n }\n\n {\n destruct Hm as (n & n' & _ & _ & _ & Hsteps & Hsteps' & Hn).\n refine (urel_equiv_1 _#6 _ (equiv_symm _#3 (steps_equiv _#3 Hsteps)) _).\n {\n prove_hygiene.\n }\n apply fut_action_next; auto.\n apply (urel_equiv_2 _#4 n').\n {\n prove_hygiene.\n }\n\n {\n apply equiv_symm.\n eapply equiv_trans.\n {\n apply equiv_prev.\n eapply steps_equiv; eauto.\n }\n apply steps_equiv.\n apply star_one; apply step_prev2.\n }\n apply Hn.\n omega.\n }\nQed.\n\n\nLemma sound_fut_eta_hyp_pre :\n forall G1 G2 a m n b,\n hygiene (ctxpred G1) a\n -> hygiene (ctxpred (G2 ++ hyp_tm (fut a) :: G1)) b\n -> seq (promote G1) (deqtype a a)\n -> seq (substctx (dot (next (var 0)) sh1) G2 ++ cons (hyp_tml a) G1) (deq m n (subst (under (length G2) (dot (next (var 0)) sh1)) b))\n -> seq (G2 ++ cons (hyp_tm (fut a)) G1) (deq (subst (under (length G2) (dot (prev (var 0)) sh1)) m) (subst (under (length G2) (dot (prev (var 0)) sh1)) n) b).\nProof.\nintros G1 G2 a m n b Hcla Hclb Hseqa Hseq.\nrewrite -> seq_eqtype in Hseqa.\neapply subsume_seq_extract; eauto; clear Hseq.\napply subsume_under.\ndo2 2 split.\n {\n intros j.\n rewrite -> !ctxpred_length.\n cbn [length].\n destruct j as [| j].\n {\n simpsub.\n split; try omega.\n intros _.\n apply hygiene_auto; cbn.\n split; auto.\n apply hygiene_var.\n omega.\n }\n\n {\n simpsub.\n split.\n {\n intros H.\n apply hygiene_var.\n omega.\n }\n\n {\n intros H.\n invertc H.\n intro; omega.\n }\n }\n }\n\n {\n intros j.\n rewrite -> !ctxpred_length.\n cbn [length].\n destruct j as [| j].\n {\n simpsub.\n split; try omega.\n intros _.\n apply hygiene_auto; cbn.\n split; auto.\n apply hygiene_var.\n omega.\n }\n\n {\n simpsub.\n split.\n {\n intros H.\n apply hygiene_var.\n omega.\n }\n\n {\n intros H.\n invertc H.\n intro; omega.\n }\n }\n }\nintros i ss ss' Hss.\ninvertc Hss.\nintros p q s s' Hs Hpq Hleft Hright <- <-.\nsimpsubin Hpq.\nso (seqhyp_impl_closed _#5 Hpq) as (Hclp & Hclq).\nassert (exists p' q' A,\n star step p (next p') \n /\\ star step q (next q')\n /\\ (i > 0\n -> interp toppg true (pred i) (subst s a) A\n /\\ interp toppg false (pred i) (subst s' a) A\n /\\ rel (den A) (pred i) p' q')) as H.\n {\n invertc Hpq.\n intros R Hfutl Hfutr Hpq.\n invert (basic_value_inv _#6 value_fut Hfutl).\n {\n intros _ <- <-.\n cbn in Hpq.\n decompose Hpq.\n intros p' q' _ _ _ Hp' Hq' _.\n exists p', q', (iubase empty_urel).\n do2 2 split; auto.\n omega.\n }\n\n {\n intros i' A Hal <- Heq1.\n invert (basic_value_inv _#6 value_fut Hfutr).\n intros A' Har Heq2.\n so (eqtrans Heq1 (eqsymm Heq2)) as Heq; clear Heq2.\n subst R.\n so (iufut_inj _#5 Heq); subst A'.\n cbn in Hpq.\n decompose Hpq.\n intros p' q' _ _ _ Hp' Hq' Hpq'.\n exists p', q', A.\n do2 2 split; auto.\n }\n }\ndestruct H as (p' & q' & A & Hstepsp & Hstepsq & Hif).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsp Hclp)) as H; cbn in H.\ndestruct H as (Hclp' & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepsq Hclq)) as H; cbn in H.\ndestruct H as (Hclq' & _).\ndo2 4 split.\n {\n simpsub.\n apply pwctx_cons_tml_seq; auto; try prove_hygiene.\n {\n intros Hpos.\n so (Hif Hpos) as (Hal & Har & Hpq').\n apply (seqhyp_tm _#5 A); auto.\n eapply urel_equiv; eauto; try prove_hygiene.\n {\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsp.\n }\n apply star_one; apply step_prev2.\n }\n\n {\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsq.\n }\n apply star_one; apply step_prev2.\n }\n }\n\n {\n intros j t t' Ht.\n so (Hseqa _#3 Ht) as (R & Hl & Hr & _).\n eauto.\n }\n }\n\n {\n simpsub.\n apply equivsub_dot; auto using equivsub_refl.\n apply (equiv_trans _ _ (next p')).\n {\n apply equiv_next.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsp.\n }\n apply star_one.\n apply step_prev2.\n }\n\n {\n apply equiv_symm.\n apply steps_equiv; auto.\n }\n }\n\n {\n simpsub.\n apply equivsub_dot; auto using equivsub_refl.\n apply (equiv_trans _ _ (next q')).\n {\n apply equiv_next.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsq.\n }\n apply star_one.\n apply step_prev2.\n }\n\n {\n apply equiv_symm.\n apply steps_equiv; auto.\n }\n }\n\n {\n intros j d uu Hj Huu.\n simpsub.\n simpsubin Huu.\n rewrite -> qpromote_cons in Huu |- *.\n rewrite -> qpromote_hyp_tm.\n invertc Huu.\n intros r u Hu Hr <-.\n simpsub.\n apply seqctx_cons; auto.\n simpsub.\n destruct j as [| j].\n {\n so (seqctx_impl_closub _#4 Hu) as (Hcls & Hclu).\n so (seqhyp_impl_closed _#5 Hr) as (_ & Hclr).\n rewrite -> ctxpred_qpromote in Hcls, Hclu.\n apply (seqhyp_tm _#5 (iufut0 stop)).\n {\n apply interp_eval_refl.\n apply interp_fut_zero; prove_hygiene.\n }\n\n {\n apply interp_eval_refl.\n apply interp_fut_zero; prove_hygiene.\n }\n\n {\n apply (urel_equiv_1 _#3 (next p')); try prove_hygiene.\n {\n apply equiv_symm; apply steps_equiv; eauto.\n }\n apply fut_action_next_zero; auto; prove_hygiene.\n }\n }\n rewrite -> !substh_qpromote_hyp in Hr.\n so (seqhyp_demote_maybe _#7 Hr) as H.\n simpsubin H.\n invertc H.\n intros A' Hal Hau Hr' _ _ _ _.\n apply (seqhyp_tm _#5 (iufut stop (S j) A')).\n {\n apply interp_eval_refl.\n apply interp_fut.\n apply Hal.\n omega.\n }\n\n {\n apply interp_eval_refl.\n apply interp_fut.\n apply Hau.\n omega.\n }\n\n {\n apply (urel_equiv_1 _#3 (next p')); try prove_hygiene.\n {\n apply equiv_symm; apply steps_equiv; eauto.\n }\n apply fut_action_next; auto.\n apply (urel_equiv_1 _#3 (prev p)); try prove_hygiene.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsp.\n }\n apply star_one; apply step_prev2.\n }\n \n {\n apply Hr'.\n omega.\n }\n }\n }\n\n {\n intros j d uu Hj Huu.\n simpsub.\n simpsubin Huu.\n rewrite -> qpromote_cons in Huu |- *.\n rewrite -> qpromote_hyp_tm.\n invertc Huu.\n intros r u Hu Hr <-.\n simpsub.\n apply seqctx_cons; auto.\n simpsub.\n destruct j as [| j].\n {\n so (seqctx_impl_closub _#4 Hu) as (Hclu & Hcls').\n so (seqhyp_impl_closed _#5 Hr) as (Hclr & _).\n rewrite -> ctxpred_qpromote in Hcls', Hclu.\n apply (seqhyp_tm _#5 (iufut0 stop)).\n {\n apply interp_eval_refl.\n apply interp_fut_zero; prove_hygiene.\n }\n\n {\n apply interp_eval_refl.\n apply interp_fut_zero; prove_hygiene.\n }\n\n {\n apply (urel_equiv_2 _#4 (next q')); try prove_hygiene.\n {\n apply equiv_symm; apply steps_equiv; eauto.\n }\n apply fut_action_next_zero; auto; prove_hygiene.\n }\n }\n rewrite -> !substh_qpromote_hyp in Hr.\n so (seqhyp_demote_maybe _#7 Hr) as H.\n simpsubin H.\n invertc H.\n intros A' Hal Hau Hr' _ _ _ _.\n apply (seqhyp_tm _#5 (iufut stop (S j) A')).\n {\n apply interp_eval_refl.\n apply interp_fut.\n apply Hal.\n omega.\n }\n\n {\n apply interp_eval_refl.\n apply interp_fut.\n apply Hau.\n omega.\n }\n\n {\n apply (urel_equiv_2 _#4 (next q')); try prove_hygiene.\n {\n apply equiv_symm; apply steps_equiv; eauto.\n }\n apply fut_action_next; auto.\n apply (urel_equiv_2 _#4 (prev q)); try prove_hygiene.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ prev); auto using step_prev1.\n exact Hstepsq.\n }\n apply star_one; apply step_prev2.\n }\n \n {\n apply Hr'.\n omega.\n }\n }\n }\nQed.\n\n\nLemma sound_fut_eta_hyp :\n forall G1 G2 a m n b,\n pseq (promote G1) (deqtype a a)\n -> pseq (substctx (dot (next (var 0)) sh1) G2 ++ cons (hyp_tml a) G1) (deq m n (subst (under (length G2) (dot (next (var 0)) sh1)) b))\n -> pseq (G2 ++ cons (hyp_tm (fut a)) G1) (deq (subst (under (length G2) (dot (prev (var 0)) sh1)) m) (subst (under (length G2) (dot (prev (var 0)) sh1)) n) b).\nProof.\nintros G1 G2 a m n b (i1, Hseqa) (i2, Hseq).\nso (shut_term _ G1 a) as (i3 & Hcla).\nso (shut_term _ (G2 ++ hyp_tm (fut a) :: G1) b) as (i4 & Hclb).\nso (upper_bound_all 4 i1 i2 i3 i4) as (i & Hi1 & Hi2 & Hi3 & Hi4 & _).\nexists i; intros j Hj.\nautorewrite with canonlist.\neapply sound_fut_eta_hyp_pre; try (finish_pseq j).\nrewrite -> promote_append.\nrewrite -> promote_shut.\napply Hseqa; eauto using le_trans.\nQed.\n\n\nLemma sound_fut_ext :\n forall G a b c m n,\n pseq G (deq m m (fut b))\n -> pseq G (deq n n (fut c))\n -> pseq G (deq (next (prev m)) (next (prev n)) (fut a))\n -> pseq G (deq m n (fut a)).\nProof.\nintros G a b c m n.\nrevert G.\nrefine (seq_pseq 0 3 [] _ [] _ [] _ _ _).\ncbn.\nintros G Hseqm Hseqn Hseq.\nrewrite -> seq_deq in Hseqm, Hseqn, Hseq |- *.\nintros i s s' Hs.\nassert (exists m1 m2,\n hygiene clo (subst s m)\n /\\ hygiene clo (subst s' m)\n /\\ star step (subst s m) (next m1)\n /\\ star step (subst s' m) (next m2)) as (m1 & m2 & Hclm & Hclm' & Hstepm1 & Hstepm2).\n {\n so (Hseqm _ _ _ Hs) as (R & Hl & _ & Hm & _).\n simpsubin Hl.\n invert (basic_value_inv _#6 value_fut Hl).\n {\n intros _ <- <-.\n rewrite -> den_iufut0 in Hm.\n destruct Hm as (m1 & m2 & _ & Hcl & Hcl' & Hstep & Hstep' & _).\n exists m1, m2.\n auto.\n }\n intros i' A _ <- <-.\n rewrite -> den_iufut in Hm.\n destruct Hm as (m1 & m2 & _ & Hcl & Hcl' & Hstep & Hstep' & _).\n exists m1, m2.\n auto.\n }\nassert (exists n1 n2,\n hygiene clo (subst s n)\n /\\ hygiene clo (subst s' n)\n /\\ star step (subst s n) (next n1)\n /\\ star step (subst s' n) (next n2)) as (n1 & n2 & Hcln & Hcln' & Hstepn1 & Hstepn2).\n {\n so (Hseqn _ _ _ Hs) as (R & Hl & _ & Hn & _).\n simpsubin Hl.\n invert (basic_value_inv _#6 value_fut Hl).\n {\n intros _ <- <-.\n rewrite -> den_iufut0 in Hn.\n destruct Hn as (n1 & n2 & _ & Hcl & Hcl' & Hstep & Hstep' & _).\n exists n1, n2.\n auto.\n }\n intros i' A _ <- <-.\n rewrite -> den_iufut in Hn.\n destruct Hn as (n1 & n2 & _ & Hcl & Hcl' & Hstep & Hstep' & _).\n exists n1, n2.\n auto.\n }\nclear Hseqm Hseqn.\nso (Hseq _ _ _ Hs) as (R & Hl & Hr & Hm & Hn & Hmn).\nexists R.\ndo2 2 split; auto.\nsimpsubin Hl.\nsimpsubin Hr.\nsimpsubin Hm.\nsimpsubin Hn.\nsimpsubin Hmn.\ndestruct i as [| i].\n {\n invert (basic_value_inv _#6 value_fut Hl).\n intros _ <-.\n rewrite -> !den_iufut0.\n do2 2 split.\n {\n exists m1, m2.\n do2 5 split; auto.\n intros H.\n omega.\n }\n\n {\n exists n1, n2.\n do2 5 split; auto.\n intros H.\n omega.\n }\n\n {\n exists m1, n2.\n do2 5 split; auto.\n intros H.\n omega.\n }\n }\ninvert (basic_value_inv _#6 value_fut Hl).\nintros A Hal <-.\nrewrite -> !den_iufut in Hm, Hn, Hmn |- *.\ndestruct Hm as (m1' & m2' & _ & _ & _ & Hstep1 & Hstep2 & H).\nso (determinism_normal_value _#3 value_next Hstep1) as Heq.\ninjection Heq.\nintros <-.\nso (H (Nat.lt_0_succ _)) as Hm.\nclear Heq Hstep1 H.\nso (determinism_normal_value _#3 value_next Hstep2) as Heq.\ninjection Heq.\nintros <-.\nclear Heq Hstep2.\ncbn in Hm.\ndestruct Hn as (n1' & n2' & _ & _ & _ & Hstep1 & Hstep2 & H).\nso (determinism_normal_value _#3 value_next Hstep1) as Heq.\ninjection Heq.\nintros <-.\nso (H (Nat.lt_0_succ _)) as Hn.\nclear Heq Hstep1 H.\nso (determinism_normal_value _#3 value_next Hstep2) as Heq.\ninjection Heq.\nintros <-.\nclear Heq Hstep2.\ncbn in Hn.\ndestruct Hmn as (m1' & n2' & _ & _ & _ & Hstep1 & Hstep2 & H).\nso (determinism_normal_value _#3 value_next Hstep1) as Heq.\ninjection Heq.\nintros <-.\nso (H (Nat.lt_0_succ _)) as Hmn.\nclear Heq Hstep1 H.\nso (determinism_normal_value _#3 value_next Hstep2) as Heq.\ninjection Heq.\nintros <-.\nclear Heq Hstep2.\ncbn in Hmn.\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepm1 Hclm)) as H.\ncbn in H.\ndestruct H as (Hclm1 & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepm2 Hclm')) as H.\ncbn in H.\ndestruct H as (Hclm2 & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepn1 Hcln)) as H.\ncbn in H.\ndestruct H as (Hcln1 & _).\nso (hygiene_invert_auto _#5 (steps_hygiene _#4 Hstepn2 Hcln')) as H.\ncbn in H.\ndestruct H as (Hcln2 & _).\nassert (equiv (prev (subst s m)) m1) as Hequivm1.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply star_map'; eauto using step_prev1 with dynamic.\n }\n apply star_one.\n apply step_prev2.\n }\nassert (equiv (prev (subst s' m)) m2) as Hequivm2.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply star_map'; eauto using step_prev1 with dynamic.\n }\n apply star_one.\n apply step_prev2.\n }\nassert (equiv (prev (subst s n)) n1) as Hequivn1.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply star_map'; eauto using step_prev1 with dynamic.\n }\n apply star_one.\n apply step_prev2.\n }\nassert (equiv (prev (subst s' n)) n2) as Hequivn2.\n {\n apply steps_equiv.\n eapply star_trans.\n {\n apply star_map'; eauto using step_prev1 with dynamic.\n }\n apply star_one.\n apply step_prev2.\n }\ndo2 2 split.\n {\n exists m1, m2.\n do2 5 split; auto.\n intros _.\n cbn.\n eapply urel_equiv; eauto.\n }\n\n {\n exists n1, n2.\n do2 5 split; auto.\n intros _.\n cbn.\n eapply urel_equiv; eauto.\n }\n\n {\n exists m1, n2.\n do2 5 split; auto.\n intros _.\n cbn.\n eapply urel_equiv; eauto.\n }\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/SoundFut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.12891362835023992}} {"text": "(** * Induction: Demostracion por Induccion *)\n \n\n(** La siguiente linea importa todas nuestras definiciones del\n capitulo anterior. *)\n\nRequire Export Basics.\n\n(** Para que funcione, necesita usar [coqc] para compilar [Basics.v]\n en [Basics.vo] (Esto es como hacer un archivo .class de un archivo\n .java, o un archivo .o de un .c).\n \n Aqui presentamos dos formas de compilar el codigo:\n \n - CoqIDE:\n \n Abrir [Basics.v].\n En el menu \"Compile\", click en \"Compile Buffer\".\n \n - Linea de comandos:\n \n Ejecute [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Nombrando Casos *)\n\n(** El hecho de que no hay un comando explicito para moverse de una\n rama de un analisis por caso al siguiente puede hacer los scripts\n de prueba dificiles de leer. En pruebas grandes, con casos\n anidados, uno se puede desorientar facilmente cuando se esta\n frente a Coq llendo paso a paso en una prueba. (Imaginese\n tratando de acordarse que los primeros cinco sub-casos pertenecen\n a la primer rama del analisis por caso principal, y los siete\n siguientes pertenencen al segundo...) Un uso disciplinado de\n identacion y comentarios puede ayudar, pero una forma mejor es\n usar la tactica [Case]. *)\n\n(* [Case] no viene por default in Coq: tenemos que definirla nosotros\n mismos. No hay necesidad de entender como funciona -- puede\n simplemente saltear la definicion e ir derecho al ejemplo que\n sigue. Usa ciertas herramientas de Coq que todavia no hemos\n discutido -- la libreria de strings y el comando [Ltac], que nos\n permite declarar tacticas propias. Kudos a Aaron Bohannon por\n este lindo hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n\n(** Aqui hay un ejemplo de como [Case] se usa. Vaya paso a paso en la\n prueba y observe como el contexto cambia. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- aqui *)\n reflexivity.\n Case \"b = false\". (* <---- y aqui *)\n rewrite <- H. \n reflexivity. \nQed.\n\n(** [Case] hace algo muy simple: Simplemente agrega el string que le\n pasemos (\"tageado\" con el identificador \"Case\") al contexto del\n objetivo actual. Cuando se generan sub-objetivos, este string es\n copiado en sus contextos. Cuando el ultimo de los sub-objetivos\n es finalmente demostrado y el siguiente ojetivo de nivel superior\n se activa, este string no va a aparecer mas en el contexto, y\n podremos determinar que hemos terminado con el caso. Tambien,\n como \"sanity check\" (checkeo de sanidad?), si intentamos ejecutar\n un nuevo [Case] mientras estamos resolviendo uno, vamos a obtener\n un mensaje claro de error.\n\n Para casos anidados (e.g., para cuando utilizamos [destruct] en el\n caso creado por otro [destruct]), hay una tactica [SCase] (por\n \"sub-caso\"). *)\n\n(** **** Ejercicio: 2 stars (andb_true_elim2) *)\n(** Demuestre [andb_true_elim2], marcando casos (y sub-casos) cuando\n utilice [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** No hay reglas estrictas y definidas de como una demostracion puede\n ser estructurada en Coq -- en particular, donde se deben quebrar\n las lineas y como las distintas secciones de una demostracion\n deben ser identadas. Sin embargo, si se marca explicitamente con\n [Case] los lugares donde los sub-casos son generados, entonces la\n demostracion puede ser legible independientemente de otros aspectos en\n el formateo de la misma.\n\n Este es un buen lugar para mencionar otro \"tip\" (posiblemente\n obvio) acerca del ancho de las lineas. En general, los usuarios\n principiantes de Coq tienden a ser extremistas, escribiendo o una\n tactica por linea, o pruebas enteras en una linea. El buen\n estilo se encuentra un poco en el medio. En particular, una\n convencion razonable es limitarse a los 80 caracteres por linea.\n Lineas mas largas que esto pueden ser dificiles de leer y pueden\n ser dificiles de imprimir. Muchos editores tienen facilidades\n para enforzar este limite. *)\n\n(* ###################################################################### *)\n(** * Pruebas por Induccion *)\n\n(** Hemos provado en el capitulo anterior que [0] es un elemento\n neutral para [+] a la izquierda usando un argumento simple. El\n hecho de que tambien es neutral a la _derecha_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... no puede ser provado en la misma forma. Aplicando simplemente\n [reflexivity] no funciona: el [n] en [n + 0] es un numero\n desconocido arbitrario, con lo que el [match] en la definicion de\n [+] no puede ser simplificado. *)\n\nProof.\n intros n.\n simpl. (* No hace nada! *)\nAbort.\n\n(** Razonando por casos usando [destruct n] no nos lleva muy lejos: el\n caso [n = 0] funciona, pero en el caso [n = S n'] para algun [n']\n nos quedamos bloqueados de la misma forma. Podemos usar [destruct\n n'] para ir un paso mas alla, pero [n] puede ser arbitrariamente\n grande, con lo que si seguimos de esta forma nunca vamos a\n terminar. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* todo bien hasta aca... *)\n Case \"n = S n'\".\n simpl. (* ...pero aca estamos bloqueados como antes. *)\nAbort.\n\n(** Para demostrar este tipo de teoremas -- de hecho, para demostrar\n casi cualquier teorema sobre numeros, listas, y cualquier otro\n tipo de datos definido inductivamente -- necesitamos un\n razonamiento mas elaborado: _induccion_.\n\n Recuerden el principio de induccion sobre numeros naturales: Si\n [P(n)] es una proposicion involucrando un numero natural [n] y\n queremos ver que P es cierto para _todo_ numero [n], podemos\n razonar de la siguiente forma: \n - mostrar que [P(O)] vale; \n - mostrar que, para cualquier [n'], si [P(n')] vale, entonces vale\n [P(S n')]; \n - concluir que [P(n)] vale para todo [n].\n\n En Coq, estos pasos son iguales, pero el orden es inverso:\n comenzamos con el obejtivo que queremos probar [P(n)] para todo\n [n] y lo dividimos (aplicando la tactica [induction]) en dos\n sub-objetivos: primero [P(O)] luego [P(n') -> P(S n')]. Asi es\n como funciona en el problema que estuvimos trabajando hasta ahora:\n *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Como [destruct], la tactica [induction] toma una clausula [as...]\n que especifica los nombres de las variables a ser introducidas en\n los sub-objetivos. En la primer rama, [n] es reemplazado por [0]\n el objetivo es [0 + 0 = 0], que es cierto por simplificacion. En el\n segundo, [n] es reemplazado por [S n'] y la hipotesis [n' + 0 =\n n'] es agregada al contexto (con el nombre [IHn'], es decir, la\n Hipotesis Inductiva para [n']). El objetivo en este caso es [(S\n n') + 0 = S n'], que se puede simplificar a [S (n' + 0) = S n'],\n que a su cez se puede resolver usando la hipotesis inductiva. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Ejercicio: 2 stars (basic_induction) *)\n\n(** Pruebe los siguientes teoremas usando induccion. Tal ver requiera\n utilizar algun resultado previo. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_n_Sm : forall n m : nat, \n S (n + m) = n + (S m).\nProof. \n (* FILL IN HERE *) Admitted.\n\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n (* FILL IN HERE *) Admitted.\n\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars (double_plus) *)\n\n(** Considere la siguiente funcion, que duplica el argumento: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induccion para probar este simple lema sobre [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof. \n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Ejercicio: 1 star (destruct_induction) *)\n(** Explique brevemente la diferencia entre las tacticas\n [destruct] e [induction]. \n\n(* FILL IN HERE *)\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Pruebas dentro de Pruebas *)\n\n\n(** En Coq, al igual que en los razonamientos matematicos informales,\n las demostraciones largas son usualmente divididas en una\n secuencia de teoremas, con las demostraciones del final utilizando\n los teoremas demostrados anteriormente. Ocasionalmente, sin\n embargo, una demostracion puede necesitar algun hecho (fact) que\n es trivial y de poco interes general para molestarse en darle un\n nombre propio. En tales casos, es conveniente poder establecer y\n demostrar localmente un \"sub-teorema\" en el punto en que debe ser\n utilizado. La tactica [assert] nos permite hacer esto. Por\n ejemplo, en nuestra demostracion del teorema [mult_0_plus] nos\n referimos a otro teorema [plus_O_n]. Podemos utilizar [assert]\n para establecer [plus_O_n] \"in-line\": *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). \n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** La tactica [assert] introduce dos sub-objetivos. El primero es la\n asercion en si misma; al prefijarla con [H:], le hemos dado como\n nombre [H]. (Note que tambien podemos utilizar [as] como hicimos\n con [destruct] e [induction], i.e., [assert (0 + n = n) as H].\n Tambien note que hemos marcado la prueba de esta asercion con un\n [Case], para mejorar la legibilidad de la prueba y para, mientras\n usamos Coq interactivamente, saber que hemos concluido la prueba\n de la asercion observando que el string [\"Proof of assertion\"]\n desaparece del contexto.) El segundo objetivo es el mismo que el\n que teniamos antes de invocar [assert], excepto que ahora tiene\n una hipotesis llamada [H] que establece [0 + n = n]. Es decir,\n [assert] genera un sub-objetivo para demostrar la asercion, y un\n segundo sub-objetivo donde la asercion esta a nuestra mano para\n utilizar y hacer progreso en la prueba principal. *)\n\n(** Actualmente, [assert] nos va a ser util en muchos tipos de\n situaciones. Por ejemplo, suponga que queremos probar que [(n +\n m) + (p + q) = (m + n) + (p + q)]. La unica diferencia entre los\n dos lados del igual es que los argumentos [m] y [n] en el primer\n [+] estan intercambiados, con lo que pareceria que podemos\n utilizar la comutatividad de la suma ([plus_comm]) para reescribir\n uno en otro. Sin embargo, la tactica [rewrite] es un poco\n estupida respecto de _donde_ aplicar la reescritura. Hay tres usos\n de [+] aqui, y resulta que si hacemos [rewrite -> plus_comm] vamos\n a afectar el de mas _afuera_. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* Necesitamos intercambiar (n + m) por (m + n)...\n pareceria que plus_comm debiera funcionar! *)\n rewrite -> plus_comm.\n (* No funciona... Coq reescribio la suma incorrecta! *)\nAbort.\n\n(** Para poder aplicar [plus_comm] en el lugar que queremos, podemos\n introducir un lema local estableciendo [n + m = m + n] (para los\n [m] y [n] particulares que utilizamos en la demostracion), demostrar\n este lema utilizando [plus_comm], y usar luego este lema para reescribir\n el lugar correcto. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Ejercicio: 4 stars (mult_comm) *)\n(** Utilice [assert] para ayudar probar este teorema. No deberia\n necesitar [induction]. *)\n\nTheorem plus_swap : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n\n\n(** Ahora demuestre la conmutatividad de la multiplicacion. (Va a\n necesitar posiblemente demostrar un teorema subsidiario para\n usarlo en este.) Puede encontrar util [plus_swap]. *)\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars, opcional (evenb_n__oddb_Sn) *)\n\n(** Pruebe el siguiente teorema sencillo: *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Mas ejercicios *)\n\n(** **** Ejercicio: 3 stars, opcional (more_exercises) *)\n(** Tome un pedazo de papel. Por cada uno de los siguientes teoremas,\n primero _piense_ acerca de si (a) puede ser demostrado utilizando\n simplemente [rewrite], [simpl] y [reflexivity], o (b) tambien\n requiere analisis por caso ([destruct]), o (c) tambien requiere\n induccion. Escriba su prediccion. Entonces complete las\n demostraciones. (No hay necesidad de entregar el papel, este\n ejercicio es para estimular el pensamiento antes de hackear!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Ejercicio: 2 stars, opcional (beq_nat_refl) *)\n(** Pruebe el siguiente teorema. Poner [true] en el lado izquierdo de\n la igualdad puede verse raro, pero es asi como el teorema esta\n escrito en la libreria estandard de Coq, y nosotros copiamos en\n consecuencia. Como se puede reescribir igualmente en cualquier\n direccion, no vamos a tener problemas usando el teorema, sin\n importar en que forma lo escribamos. *)\n\nTheorem beq_nat_refl : forall n : nat, \n true = beq_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** La tactica [replace] permite especificar un subtermino particular\n a reescribir, y a que se debe reescribir. Mas precisamente,\n [replace (t) with (u)] reemplaza (todas las copias de) la expresion\n [t] en el objetivo por la expresion [u], y genera [t = u] como\n sub-objetivo adicional. Esto es util cuando [rewrite] reescribe una\n parte incorrecta del objetivo.\n\n Utilice la tactica [replace] para demostrar [plus_swap'], similar a\n [plus_swap] pero sin necesitar [assert (n + m = m + n)]. *)\n\nTheorem plus_swap' : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Ejercicio: 3 stars (binary_commute) *)\n(** Recuerde las funciones [increment] y [binary-to-unary] que\n escribio para el ejercicio [binary] en el capitulo [Basics].\n Pruebe que estas funciones conmutan -- es decir, que incrementar\n un numero binario y convertirlo a unitario es igual a convertirlo\n en unario primero y luego incrementarlo.\n\n (Antes de empezar a trabajar en este ejercicio, por favor copie\n sus definiciones del ejercicio [binary] aqui, para que este\n archivo pueda ser evaluado independientemente. Si necesita\n modificar las definiciones para hacer la prueba mas facil,\n sientase libre de hacerlo). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Ejercicio: 5 stars, advanced (binary_inverse) *)\n(** Este ejercicio es una continuacion del ejercicio anterior acerca\n numeros binarios. Usted debe completar las definiciones y\n teoremas del ejercicio previo antes de hacer este ejercicio.\n\n (a) Primero, escriba una funcion para convertir numeros naturales a\n numeros binarios. Luego, pruebe que convertir un numero\n natural a binario, y luego convertir a natural el resultado,\n resulta en el mismo numero.\n\n (b) Tal vez usted considere que tambien podemos probar lo\n contrario, es decir, que convertir un numero binario en natural\n y viceversa resulta en el mismo numero natural. Sin embargo,\n no es asi! Explique por que.\n\n (c) Defina una funcion [normalize] de numeros binarios a numeros\n binarios tal que para cada numero binario b, convertir b a\n numero natural y viceversa resulta en [(normalize b)]. Demuestrelo.\n\n Como antes, sientase en la libertad de cambiar las definiciones si\n asi lo desea. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Material Avanzado *)\n\n(** ** Prueba Formal vs. Informal *)\n\n(** \"Pruebas informales son algoritmos; pruebas formales son codigo.\" *)\n\n(** La pregunta de que exactamente constituye una \"prueba\" de un\n teorema matematico a intrigado a filosofos por milenios. Una\n definicion burda y rapida puede ser: una prueba de una proposicion\n matematica [P] es un texto escrito (o dicho) que infunde en el\n lector (o receptor) la certeza de que [P] es verdad. Es decir,\n una prueba es un acto de comunicacion.\n\n Ahora, la comunicacion en general puede incluir tipos diferentes\n de lectores. En una mano, el \"lector\" puede ser un programa como\n Coq, en cuyo caso la \"creencia\" que es inculcada es un checkeo\n mecanico de que [P] puede ser derivado de un conjunto de reglas\n logicas, y la prueba es una receta que guia al programa para\n realizar este checkeo. Estas recetas son pruebas _formales_.\n\n Alternativamente, el lector puede ser un ser humano, en cuyo caso\n la prueba puede ser escrita en espaniol o cualquier otro lenguaje\n natural, necesariamente _informal_. Aqui, el criterio para el\n exito esta especificado de forma mas difusa. Una \"buena\" prueba\n es una que convence al lector de que [P] vale. Pero la misma\n prueba puede ser leida por muchos lectores diferentes, en los que\n algunos pueden convencerse de cierto argumento, mientras que otros\n pueden ponerlo en duda. Un lector puede ser particularmente\n pedante, inexperto, o simplemente lento; la unica forma de\n convencerlo va a ser haciendo el argumento extremadamente\n puntillosamente. Pero otro lector, conocedor del area, puede\n encontrar estos detalles tan apabullantes, que le hacen perder el\n argumento principal. Lo unico que necesita es que le digan las\n ideas principales, porque es mas facil llenar los detalles por si\n mismo. De ultima, no hay un estandard universal, porque no hay una\n sola forma de escribir una prueba informal de forma tal que\n convenza a todos los lectores. En practica, sin embargo, los\n matematicos han desarrollado una serie de convenciones y modismos\n para escribir acerca de objetos matematicos complejos que, para\n cierta comunidad, hace la comunicacion decentemente fiable. Las\n convenciones utilizadas en esta forma estilizadad de comunicacion\n da paso a estandardes claros para juzgar una prueba buena o mala.\n\n Como estamos usando Coq en este curso, vamos a trabajar\n fuertemente con pruebas formales. Pero eso no significa que\n podemos ignorar las pruebas informales! Las pruebas formales son\n utiles en muchos sentidos, pero no son muy eficientes como\n mechanismo para comunicar ideas entre humanos. *)\n\n(** Por ejemplo, aqui hay un ejemplo de que la suma de los naturales\n es asociativa: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity. \n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq esta perfectamente feliz con esta prueba. Para un humano, sin\n embargo, es dificil entender que esta pasando. Si el lector esta\n acostumbrado a Coq, puede ir paso por paso en su cabeza,\n imaginando cual es el estado del contexto y el objetivo en cada\n paso, pero si la prueba fuera ligeramente mas complicada, esto\n seria completamente imposible. En cambio, un matematico\n escribiria algo asi: *)\n\n(** - _Teorema_: Para cada [n], [m] y [p],\n n + (m + p) = (n + m) + p.\n _Prueba_: Por induccion en [n].\n\n - Primero, suponga [n = 0]. Debemos mostrar \n 0 + (m + p) = (0 + m) + p. \n Esto se desprende de la definicion de [+].\n\n - Siguiente, suponga [n = S n'], donde\n n' + (m + p) = (n' + m) + p.\n Debemos mostrar\n (S n') + (m + p) = ((S n') + m) + p.\n Por definicion de [+], esto es equivalente a\n S (n' + (m + p)) = S ((n' + m) + p),\n que es inmediato por la hipotesis inductiva. [] *)\n\n(** El aspecto general de la prueba es basicamente similar. Y esto no\n es pura casualidad: Coq ha sido diseniado de forma que la tactica\n [induction] genera los mismos sub-objetivos, en el mismo orden,\n que las vinietas que un matematico/a podria escribir. Pero las\n pruebas difieren en los detalles: la prueba formal es mucho mas\n explicita en algunos aspectos (ej., el uso de [reflexivity]) pero\n mucho menos explicita en otros (en particular, el \"estado de la\n prueba\" en cada paso en la prueba en Coq es implicita, mientras\n que en la prueba informal se le recuerda al lector varias veces\n sobre el punto en el que se esta). *)\n\n(** Aca hay una prueba formal con una estructura mas clara: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n']. \n Case \"n = 0\".\n reflexivity. \n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Ejercicio: 2 stars, advanced (plus_comm_informal) *)\n(** Traduzca su prueba de [plus_comm] en una prueba informal. *)\n\n(** Teorema: La adicion es conmutativa.\n \n Prueba: (* FILL IN HERE *)\n[]\n*)\n\n(** **** Ejercicio: 2 stars, opcional (beq_nat_refl_informal) *)\n(** Escriba una prueba informal del siguiente teorema, usando la\n prueba informal de [plus_assoc] como modelo. No se restringa a\n parafrasear las tacticas de Coq en espaniol!\n \n Teorema: [true = beq_nat n n] para cada [n].\n \n Prueba: (* FILL IN HERE *)\n[]\n *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "gciruelos", "repo": "ECI2014T2", "sha": "3d38f7bf1e87732523095ae80ee92556dde99a91", "save_path": "github-repos/coq/gciruelos-ECI2014T2", "path": "github-repos/coq/gciruelos-ECI2014T2/ECI2014T2-3d38f7bf1e87732523095ae80ee92556dde99a91/sp/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.12868985438363867}} {"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** Sharpened ADT for an expression grammar with parentheses *)\nRequire Import Coq.Init.Wf Coq.Arith.Wf_nat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List Coq.Strings.String.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.Wf.\nRequire Import Fiat.Common.Enumerable.\nRequire Import Fiat.Common.LogicFacts.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.Splitters.BruteForce.\nRequire Import Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.BooleanRecognizerFull.\nRequire Import Fiat.Parsers.BooleanRecognizerCorrect.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.ForallChars.\nRequire Import Fiat.Parsers.StringLike.FirstChar.\nRequire Import Fiat.Parsers.StringLike.FirstCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.LastChar.\nRequire Import Fiat.Parsers.StringLike.LastCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.MinimalParseOfParse.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fold.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidProperties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.Refinement.DisjointLemmasEarlyDeclarations.\nRequire Import Fiat.Parsers.Refinement.PossibleTerminalsSets.\nRequire Import Fiat.Common.BoolFacts.\nRequire Fiat.Parsers.Reachable.All.MinimalReachable.\nRequire Fiat.Parsers.Reachable.All.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.All.ReachableParse.\nRequire Fiat.Parsers.Reachable.OnlyFirst.MinimalReachable.\nRequire Fiat.Parsers.Reachable.OnlyFirst.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.OnlyFirst.ReachableParse.\nRequire Fiat.Parsers.Reachable.OnlyLast.MinimalReachable.\nRequire Fiat.Parsers.Reachable.OnlyLast.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.OnlyLast.ReachableParse.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.Core.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.MinimalOfCore.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.OfParse.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_like_scope.\n\nLocal Arguments string_beq : simpl never.\n\nSection search_forward.\n Context {G : pregrammar' Ascii.ascii}\n {HSLM : StringLikeMin Ascii.ascii}\n {HSL : StringLike Ascii.ascii}\n {HSI : StringIso Ascii.ascii}\n {HSLP : StringLikeProperties Ascii.ascii}\n {HSIP : StringIsoProperties Ascii.ascii}\n (pdata : possible_data G).\n\n Local Notation possible_terminals_of nt\n := (@all_possible_ascii_of_nt G pdata nt).\n Local Notation possible_first_terminals_of_production its\n := (@possible_first_ascii_of_production G pdata its).\n Local Notation might_be_empty_of_production its\n := (@might_be_empty_of_pr_production G pdata its).\n\n Lemma terminals_disjoint_search_for_not'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq\n (possible_terminals_of nt)\n (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars__char_in (take n str) (possible_terminals_of nt)\n /\\ ((length str <= n /\\ might_be_empty_of_production its)\n \\/ (for_first_char\n (drop n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt)))\n /\\ n < length str)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.le_dec (length str) n); [ left | right ].\n { split; trivial.\n pose proof (drop_length str n) as H.\n rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption.\n generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP.\n intros.\n eapply might_be_empty_pr_parse_of_production; eassumption. }\n { split; try omega; [].\n eapply first_char_in__impl__for_first_char;\n [\n | apply possible_first_ascii_parse_of_production; eassumption ].\n intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } }\n { apply (all_possible_ascii_of_item_nt pit). }\n Qed.\n\n Lemma terminals_disjoint_search_for_not\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_first_char_such_that\n (might_be_empty_of_production its)\n str\n n\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt))).\n Proof.\n pose proof (terminals_disjoint_search_for_not' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | H1]]; solve [ left; eauto | right; eauto ] ].\n revert H0.\n apply forall_chars__char_in__impl__forall_chars.\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H''.\n apply H''.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption.\n Qed.\n\n Lemma terminals_disjoint_search_for'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars (take n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_first_terminals_of_production its)))\n /\\ ((length str <= n /\\ might_be_empty_of_production its)\n \\/ (first_char_in\n (drop n str)\n (possible_first_terminals_of_production its)\n /\\ n < length str)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.le_dec (length str) n); [ left | right ].\n { split; trivial.\n pose proof (drop_length str n) as H.\n rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption.\n generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP.\n intros.\n eapply might_be_empty_pr_parse_of_production; eassumption. }\n { split; try omega; try assumption.\n apply possible_first_ascii_parse_of_production; assumption. } }\n { eapply forall_chars__char_in__impl__forall_chars.\n { intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. }\n { apply all_possible_ascii_of_item_nt; assumption. } }\n Qed.\n\n Lemma terminals_disjoint_search_for\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_first_char_such_that\n (might_be_empty_of_production its)\n str\n n\n (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production its)).\n Proof.\n pose proof (terminals_disjoint_search_for' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | [H1 ?]]]; [ right | left; split ]; eauto ].\n { revert H0.\n apply forall_chars_Proper; [ reflexivity | ].\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H'.\n apply H'.\n assumption. }\n { revert H1.\n apply first_char_in__impl__for_first_char.\n intros ch H'.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. }\n Qed.\nEnd search_forward.\n\nSection search_backward.\n Context {G : pregrammar' Ascii.ascii}\n {HSLM : StringLikeMin Ascii.ascii}\n {HSL : StringLike Ascii.ascii}\n {HSI : StringIso Ascii.ascii}\n {HSLP : StringLikeProperties Ascii.ascii}\n {HSIP : StringIsoProperties Ascii.ascii}\n (pdata : possible_data G).\n\n Local Notation possible_terminals_of_production its\n := (@all_possible_ascii_of_production G pdata its).\n Local Notation possible_last_terminals_of nt\n := (@possible_last_ascii_of_nt G pdata nt).\n Local Notation might_be_empty_of nt\n := (@might_be_empty_of_pr_nt G pdata nt).\n\n Lemma terminals_disjoint_rev_search_for_not'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars__char_in (drop n str) (possible_terminals_of_production its)\n /\\ ((n = 0 /\\ might_be_empty_of nt)\n \\/ (for_last_char\n (take n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its)))\n /\\ n > 0)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.zerop n); [ left | right ].\n { split; trivial; []; subst.\n eapply might_be_empty_pr_parse_of_item_nt; try eassumption.\n rewrite take_length; reflexivity. }\n { split; try omega; [].\n eapply last_char_in__impl__for_last_char;\n [\n | apply possible_last_ascii_parse_of_item_nt; eassumption ].\n intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } }\n { apply all_possible_ascii_of_parse_of_production; assumption. }\n Qed.\n\n Lemma terminals_disjoint_rev_search_for_not\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_after_last_char_such_that\n str\n n\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its))).\n Proof.\n pose proof (terminals_disjoint_rev_search_for_not' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | H1]];\n destruct_head and;\n try solve [ left; eauto\n | right; eauto\n | assumption\n | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ].\n revert H0.\n apply forall_chars__char_in__impl__forall_chars.\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H''.\n apply H''; clear H''.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption.\n Qed.\n\n Lemma terminals_disjoint_rev_search_for'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars (drop n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_last_terminals_of nt)))\n /\\ ((n = 0 /\\ might_be_empty_of nt)\n \\/ (last_char_in\n (take n str)\n (possible_last_terminals_of nt)\n /\\ n > 0)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.zerop n); [ left | right ].\n { split; trivial; [].\n eapply might_be_empty_pr_parse_of_item_nt; try eassumption.\n rewrite take_length; subst; reflexivity. }\n { split; try omega; try assumption; [].\n apply possible_last_ascii_parse_of_item_nt; assumption. } }\n { eapply forall_chars__char_in__impl__forall_chars.\n { intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | eassumption ]. }\n { apply all_possible_ascii_of_parse_of_production; assumption. } }\n Qed.\n\n Lemma terminals_disjoint_rev_search_for\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_after_last_char_such_that\n str\n n\n (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt)).\n Proof.\n pose proof (terminals_disjoint_rev_search_for' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | [H1 ?]]];\n try solve [ right; eauto\n | left; split; eauto\n | assumption\n | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ].\n { revert H0.\n apply forall_chars_Proper; [ reflexivity | ].\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H'.\n apply H'.\n assumption. }\n { revert H1.\n apply last_char_in__impl__for_last_char.\n intros ch H'.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. }\n Qed.\nEnd search_backward.\n\nLtac get_grammar :=\n lazymatch goal with\n | [ |- context[ParserInterface.split_list_is_complete_idx ?G] ] => G\n end.\n\n(*Ltac pose_rvalid_for G :=\n lazymatch goal with\n | [ H : is_true (grammar_rvalid G) |- _ ] => idtac\n | _ => let Hvalid := fresh \"Hvalid\" in\n assert (Hvalid : is_true (grammar_rvalid G))\n by (vm_compute; reflexivity)\n end.\nLtac pose_rvalid := let G := get_grammar in pose_rvalid_for G.*)\n\nModule Export Exports.\n Export DisjointLemmasEarlyDeclarations.\n (** hide the arguments to Build_disjoint_search_data *)\n Local Arguments FromAbstractInterpretation.Build_fold_grammar_data' {_ _ _ _ _} _ _ : assert.\n Notation precomputed_search_data\n := (FromAbstractInterpretation.Build_fold_grammar_data' _ _).\n\n Ltac do_disjoint_precomputations _ ::=\n let G := get_grammar in\n lazymatch goal with\n | [ |- context[@ParserInterface.split_list_is_complete_idx _ G ?HSLM ?HSL] ]\n => pose (_ : @StringLikeProperties _ HSLM HSL)\n end;\n pose_possible_data_for G.\nEnd Exports.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Refinement/DisjointLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.24220563966531902, "lm_q1q2_score": 0.12866190607420394}} {"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import compcert.common.Values.\nRequire Import Memory.\nRequire Export Maps.\nRequire Import Events.\nRequire Import Globalenvs.\n\nRequire Import sepcomp.mem_lemmas. (*for mem_forward*)\nRequire Import sepcomp.core_semantics.\nRequire Import sepcomp.effect_semantics.\nRequire Import Op.\nRequire Import Registers.\n\nRequire Import sepcomp.RTL.\nRequire Import sepcomp.RTL_coop.\n\nInductive RTL_effstep (ge:genv): (block -> Z -> bool) ->\n RTL_core -> mem -> RTL_core -> mem -> Prop :=\n | rtl_effstep_exec_Inop:\n forall s f sp pc rs m pc',\n (fn_code f)!pc = Some(Inop pc') ->\n RTL_effstep ge EmptyEffect (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs) m\n | rtl_effstep_exec_Iop:\n forall s f sp pc rs m op args res pc' v,\n (fn_code f)!pc = Some(Iop op args res pc') ->\n eval_operation ge sp op rs##args m = Some v ->\n RTL_effstep ge EmptyEffect (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' (rs#res <- v)) m\n | rtl_effstep_exec_Iload:\n forall s f sp pc rs m chunk addr args dst pc' a v,\n (fn_code f)!pc = Some(Iload chunk addr args dst pc') ->\n eval_addressing ge sp addr rs##args = Some a ->\n Mem.loadv chunk m a = Some v ->\n RTL_effstep ge EmptyEffect (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' (rs#dst <- v)) m\n | rtl_effstep_exec_Istore:\n forall s f sp pc rs m chunk addr args src pc' a m',\n (fn_code f)!pc = Some(Istore chunk addr args src pc') ->\n eval_addressing ge sp addr rs##args = Some a ->\n Mem.storev chunk m a rs#src = Some m' ->\n RTL_effstep ge (StoreEffect a (encode_val chunk (rs#src)))\n (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs) m'\n | rtl_effstep_exec_Icall:\n forall s f sp pc rs m sig ros args res pc' fd,\n (fn_code f)!pc = Some(Icall sig ros args res pc') ->\n find_function ge ros rs = Some fd ->\n funsig fd = sig ->\n RTL_effstep ge EmptyEffect\n (RTL_State s f sp pc rs) m\n (RTL_Callstate (Stackframe res f sp pc' rs :: s) fd rs##args) m\n | rtl_effstep_exec_Itailcall:\n forall s f stk pc rs m sig ros args fd m',\n (fn_code f)!pc = Some(Itailcall sig ros args) ->\n find_function ge ros rs = Some fd ->\n funsig fd = sig ->\n Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n RTL_effstep ge (FreeEffect m 0 (f.(fn_stacksize)) stk)\n (RTL_State s f (Vptr stk Int.zero) pc rs) m\n (RTL_Callstate s fd rs##args) m'\n\n(* WE DO NOT TREAT BUILTINS\n | rtl_effstep_exec_Ibuiltin:\n forall s f sp pc rs m ef args res pc' t v m',\n (fn_code f)!pc = Some(Ibuiltin ef args res pc') ->\n external_call ef ge rs##args m t v m' ->\n RTL_effstep ge\n (BuiltinEffect ge (ef_sig ef) (rs##args) m)\n (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' (rs#res <- v)) m'\n*)\n | rtl_effstep_exec_Icond:\n forall s f sp pc rs m cond args ifso ifnot b pc',\n (fn_code f)!pc = Some(Icond cond args ifso ifnot) ->\n eval_condition cond rs##args m = Some b ->\n pc' = (if b then ifso else ifnot) ->\n RTL_effstep ge EmptyEffect\n (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs) m\n | rtl_effstep_exec_Ijumptable:\n forall s f sp pc rs m arg tbl n pc',\n (fn_code f)!pc = Some(Ijumptable arg tbl) ->\n rs#arg = Vint n ->\n list_nth_z tbl (Int.unsigned n) = Some pc' ->\n RTL_effstep ge EmptyEffect\n (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs) m\n | rtl_effstep_exec_Ireturn:\n forall s f stk pc rs m or m',\n (fn_code f)!pc = Some(Ireturn or) ->\n Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n RTL_effstep ge (FreeEffect m 0 (f.(fn_stacksize)) stk)\n (RTL_State s f (Vptr stk Int.zero) pc rs) m\n (RTL_Returnstate s (regmap_optget or Vundef rs)) m'\n | rtl_effstep_exec_function_internal:\n forall s f args m m' stk,\n Mem.alloc m 0 f.(fn_stacksize) = (m', stk) ->\n RTL_effstep ge EmptyEffect\n (RTL_Callstate s (Internal f) args) m\n (RTL_State s\n f\n (Vptr stk Int.zero)\n f.(fn_entrypoint)\n (init_regs args f.(fn_params)))\n m'\n(*no external calls\n | rtl_effstep_exec_function_external:\n forall s ef args res t m m',\n external_call ef ge args m t res m' ->\n RTL_effstep ge (Callstate s (External ef) args) m\n t (Returnstate s res m')*)\n | rtl_effstep_exec_return:\n forall res f sp pc rs s vres m,\n RTL_effstep ge EmptyEffect\n (RTL_Returnstate (Stackframe res f sp pc rs :: s) vres) m\n (RTL_State s f sp pc (rs#res <- vres)) m\n\n | rtl_effstep_sub_val: forall E EE c m c' m',\n (forall b ofs, Mem.valid_block m b ->\n E b ofs = true -> EE b ofs = true) ->\n RTL_effstep ge E c m c' m' ->\n RTL_effstep ge EE c m c' m'.\n\nLemma rtl_eff_exec_Iload':\n forall ge s f sp pc rs m chunk addr args dst pc' rs' a v,\n (fn_code f)!pc = Some(Iload chunk addr args dst pc') ->\n Op.eval_addressing ge sp addr rs##args = Some a ->\n Mem.loadv chunk m a = Some v ->\n rs' = (rs#dst <- v) ->\n RTL_effstep ge EmptyEffect\n (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs') m.\nProof.\n intros. subst rs'. eapply rtl_effstep_exec_Iload; eauto.\nQed.\n\nLemma rtl_eff_exec_Iop':\n forall g s f sp pc rs m op args res pc' rs' v,\n (fn_code f)!pc = Some(Iop op args res pc') ->\n Op.eval_operation g sp op rs##args m = Some v ->\n rs' = (Registers.Regmap.set res v rs) ->\n RTL_effstep g EmptyEffect (RTL_State s f sp pc rs) m\n (RTL_State s f sp pc' rs') m.\nProof.\n intros. subst rs'. eapply rtl_effstep_exec_Iop; eauto.\nQed.\n\nLemma rtl_effax1: forall (M : block -> Z -> bool) g c m c' m',\n RTL_effstep g M c m c' m' ->\n (corestep rtl_coop_sem g c m c' m' /\\\n Mem.unchanged_on (fun (b : block) (ofs : Z) => M b ofs = false) m m').\nProof.\nintros.\n induction H.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Inop; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Iop; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Iload; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Istore; eassumption.\n eapply StoreEffect_Storev; eassumption.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Icall; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Itailcall; eassumption.\n eapply FreeEffect_free; eassumption.\n(* split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Ibuiltin; eassumption.\n eapply ec_builtinEffectPolymorphic; eassumption.*)\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Icond; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Ijumptable; eassumption.\n apply Mem.unchanged_on_refl.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_Ireturn; eassumption.\n eapply FreeEffect_free; eassumption.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_function_internal; eassumption.\n eapply Mem.alloc_unchanged_on; eassumption.\n split. unfold corestep, coopsem; simpl.\n eapply rtl_corestep_exec_return; eassumption.\n apply Mem.unchanged_on_refl.\n (*effstep_sub_val*)\n destruct IHRTL_effstep.\n split; trivial.\n eapply unchanged_on_validblock; try eassumption.\n intros; simpl. remember (E b ofs) as d.\n destruct d; trivial. apply eq_sym in Heqd.\n rewrite (H _ _ H3 Heqd) in H4. discriminate.\nQed.\n\nLemma rtl_effax2: forall g c m c' m',\n corestep rtl_coop_sem g c m c' m' ->\n exists M, RTL_effstep g M c m c' m'.\nProof.\nintros. inv H.\n eexists. eapply rtl_effstep_exec_Inop; eassumption.\n eexists. eapply rtl_effstep_exec_Iop; eassumption.\n eexists. eapply rtl_effstep_exec_Iload; eassumption.\n eexists. eapply rtl_effstep_exec_Istore; eassumption.\n eexists. eapply rtl_effstep_exec_Icall; try eassumption. trivial.\n eexists. eapply rtl_effstep_exec_Itailcall; try eassumption. trivial.\n (* eexists. eapply rtl_effstep_exec_Ibuiltin; eassumption.*)\n eexists. eapply rtl_effstep_exec_Icond; try eassumption. trivial.\n eexists. eapply rtl_effstep_exec_Ijumptable; eassumption.\n eexists. eapply rtl_effstep_exec_Ireturn; eassumption.\n eexists. eapply rtl_effstep_exec_function_internal; eassumption.\n eexists. eapply rtl_effstep_exec_return.\nQed.\n\n(*\nLemma RTL_effstep_sub: forall g U V c m c' m'\n (UV: forall b ofs, U b ofs = true -> V b ofs = true),\n (RTL_effstep g U c m c' m' -> RTL_effstep g V c m c' m').\nQed.\n*)\n(*\nDefinition cmin_effstep ge (E:block -> Z -> bool)\n (c : RTL_core) m (c' : RTL_core) m': Prop :=\n coopstep g c m c' m' /\\ Mem.unchanged_on (fun b ofs => E b ofs = false) m m'.\n*)\n\nProgram Definition rtl_eff_sem :\n @EffectSem genv RTL_core.\neapply Build_EffectSem with (sem := rtl_coop_sem)(effstep:=RTL_effstep).\napply rtl_effax1.\napply rtl_effax2.\nintros.\neapply rtl_effstep_sub_val; eassumption.\nDefined.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit_shmem/compcert_adapt/RTL_eff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.23370635691404026, "lm_q1q2_score": 0.12777618168623894}} {"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv While.\nFrom DiSeL\nRequire Import CalculatorProtocol CalculatorInvariant.\nFrom DiSeL\nRequire Import CalculatorClientLib CalculatorServerLib.\n\nExport CalculatorProtocol.\n\nSection DelegatingCalculator.\n\nVariables (l1 l2 : Label).\nHypothesis (lab_disj : l2 != l1).\n\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nVariables (cs1 cls1 : seq nid).\nVariables (cs2 cls2 : seq nid).\nNotation nodes1 := (cs1 ++ cls1).\nNotation nodes2 := (cs2 ++ cls2).\nHypothesis Huniq1 : uniq nodes1.\nHypothesis Huniq2 : uniq nodes2.\n\n(* Protocol I'm a server in *)\nNotation cal1 := (cal_with_inv l1 f prec cs1 cls1).\nNotation cal2 := (cal_with_inv l2 f prec cs2 cls2).\n\nNotation W1 := (mkWorld cal1).\nNotation W2 := (mkWorld cal2).\n\n(* Composite world *)\nDefinition V := W1 \\+ W2.\nLemma validV : valid V.\nProof.\nrewrite /V; apply/andP=>/=.\nsplit; first by rewrite validPtUn/= validPt/= domPt inE/=.\nby rewrite unitR valid_unit.\nQed.\n\n(* This server node *)\nVariable sv : nid.\n(* It's a server in protocol cal1 *)\nHypothesis Hs1 : sv \\in cs1.\n(* It's a client in protocol cal2 *)\nHypothesis Hc2 : sv \\in cls2.\n(* Delegate server *)\nVariable sd : nid.\nHypothesis Hs2 : sd \\in cs2.\n\nNotation loc i k := (getLocal sv (getStatelet i k)).\nNotation loc1 i := (loc i l1).\nNotation loc2 i := (loc i l2).\n\n(* Delegate computation to someone else *)\nDefinition delegate_f := compute_f l2 f prec cs2 cls2 _ Hc2 sd.\n\nNotation cal_ii := (ii l1 f prec cs1 cls1).\n\nDefinition receive_msg :=\n with_inv cal_ii (blocking_receive_req l1 f prec cs1 cls1 _ Hs1).\nDefinition send_ans to args ans :=\n with_inv cal_ii (send_answer l1 f prec cs1 cls1 _ Hs1 to args ans).\n\nDefinition delegating_body_spec :=\n forall _ : unit,\n DHT [sv, V]\n (fun i =>\n loc1 i = st :-> ([::]:reqs) /\\\n loc2 i = st :-> ([::]:reqs), \n fun (r : unit) m =>\n loc1 m = st :-> ([::]:reqs) /\\\n loc2 m = st :-> ([::]:reqs)).\n\nProgram Definition delegating_body :\n delegating_body_spec := fun (_ : unit) =>\n Do _ (\n r <-- uinject (receive_msg);\n let: (from, args) := r in\n (* Delegate computations *)\n ans <-- uinject (delegate_f args);\n uinject (send_ans from args ans);;\n ret sv V tt).\n\nLemma hook_complete_unit (c : context) : hook_complete (c, Unit).\nProof. by move=>????; rewrite dom0. Qed.\n\nLemma hooks_consistent_unit (c : context) : hooks_consistent c Unit.\nProof. by move=>????; rewrite dom0. Qed.\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectL V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nDefined.\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectR V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nQed.\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectL V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nDefined.\n\nLemma hcomp l : hook_complete (mkWorld l).\nProof. by move=>????; rewrite dom0. Qed.\n\nNext Obligation.\nmove=>i/=[K1 L1]; apply: vrf_coh=>CD1; apply: step.\nmove: (coh_split CD1 (hcomp cal1) (hcomp cal2))=>[i1[j1]][C1 D1 Z]; subst i.\napply: inject_rule=>//.\nhave E1 : loc (i1 \\+ j1) l1 = loc i1 l1\n by rewrite (locProjL CD1 _ C1)// domPt inE/=.\nrewrite E1 in K1.\napply: with_inv_rule=>//.\napply: (gh_ex (g:=[::])).\napply: call_rule=>//[[from args]] i2/=[K2]H1 H2 _ j2 CD2 R1.\nhave E2 : loc (i1 \\+ j1) l2 = loc j1 l2.\n by rewrite (locProjR CD1 _ D1)// domPt inE/=.\n(* Adapt the second protocol's view *)\nrewrite E2 -(rely_loc' l2 R1) in L1.\napply: step; clear C1 D1.\nhave D2: j2 \\In Coh W2 by case: (rely_coh R1)=>/= _; rewrite injExtL//(cohW CD1). \nclear R1; rewrite joinC; apply: inject_rule=>//.\napply: call_rule=>//ans j3[L3]F D3 i3 CD3/= R2.\nhave C3: i3 \\In Coh W1 by case: (rely_coh R2)=>/= _; rewrite injExtR//(cohW CD3). \napply: step; rewrite joinC. \nrewrite -(rely_loc' _ R2) in K2; move:K2=>K3; clear R2.\napply: inject_rule=>//; apply: with_inv_rule=>//.\napply: (gh_ex (g:=[:: (from, sv, args)])).\napply: call_rule; first by rewrite inE eqxx.\nmove=>_ i4 [K4 _] _ j4 CD4 R3.\nrewrite -(rely_loc' _ R3) in L3; move: L3=>L4.\napply: ret_rule=>m R _; rewrite (rely_loc' _ R).\nmove/rely_coh: (R3)=>[]; rewrite injExtL ?(cohW CD2)//.\nmove=>_ D4; clear R3; rewrite !(rely_loc' _ R); clear R.\nhave X: l2 \\in dom W2.1 by rewrite domPt inE eqxx.\nrewrite (@locProjR _ _ _ _ _ CD4 X D4); split=>//.\nhave X': l1 \\in dom W1.1 by rewrite domPt inE eqxx.\nrewrite /= eqxx in K4; rewrite (@locProjL _ _ _ _ _ CD4 X' _)//.\nby apply: (cohUnKL CD4 D4); apply: hook_complete_unit.\nQed.\n\nDefinition delegating_server_loop_cond (res : unit) := true.\n\nDefinition delegating_server_loop_inv :=\n fun (_ r : unit) i =>\n loc1 i = st :-> ([::]:reqs) /\\\n loc2 i = st :-> ([::]:reqs).\n\nProgram Definition delegating_server_loop :\n DHT [sv, V]\n (fun i => loc1 i = st :-> ([::]:reqs) /\\\n loc2 i = st :-> ([::]:reqs),\n fun (r : unit) m => False) :=\n Do _ (@while sv V _ _ delegating_server_loop_cond delegating_server_loop_inv _\n (fun r => Do _ (delegating_body r))) tt.\n\nNext Obligation. by apply: with_spec (x x0). Defined.\nNext Obligation.\nby move:H; rewrite /delegating_server_loop_inv !(rely_loc' _ H0).\nQed.\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation.\nby apply: ghC=>i1 s[H1 H2] C1/=; apply: call_rule.\nQed.\nNext Obligation.\nmove=>i/=E1; apply: call_rule'=>//.\n- by move=>C1; exists tt=>//. \nby move=>s' m/(_ s')/=; case.\nQed. \n\nEnd DelegatingCalculator.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/Calculator/DelegatingCalculatorServer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.21469142413688416, "lm_q1q2_score": 0.12724043638250424}} {"text": "Require Import CoqlibC.\nRequire Import SmallstepC.\nRequire Import Simulation.\nRequire Import ModSem AsmregsC GlobalenvsC MemoryC ASTC.\nRequire Import Skeleton SimModSemLift SimMem SimMemLift SimSymb.\nRequire Import Sound Preservation ModSemProps.\n\nSet Implicit Arguments.\n\n\n\n\n\nSection MATCHSIMFORWARD.\n\n Context {SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n Context {SML: SimMemLift.class SM}.\n\n Variable msp: ModSemPair.t.\n Variable index: Type.\n Variable order: index -> index -> Prop.\n Hypothesis WFORD: well_founded order.\n Let ms_src: ModSem.t := msp.(ModSemPair.src).\n Let ms_tgt: ModSem.t := msp.(ModSemPair.tgt).\n Variable sidx: Type.\n Hypothesis INHAB: inhabited sidx.\n Variable sound_states: sidx -> Sound.t -> mem -> ms_src.(state) -> Prop.\n Hypothesis PRSV: forall si, local_preservation ms_src (sound_states si).\n\n Variable match_states: forall\n (idx: index) (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm0: SimMem.t),\n Prop.\n\n Variable match_states_at: forall\n (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm_at sm_arg: SimMem.t),\n Prop.\n\n (* you maintain some kind of `ownership` here. *)\n (* normal ownership: if I alloced, I can free that *)\n (* here: if I freed, I can unfree that *)\n Variable has_footprint: forall\n (st_init_src: ms_src.(ModSem.state)) (st_init_tgt: ms_tgt.(ModSem.state)) (sm0: SimMem.t),\n Prop.\n\n Variable mle_excl: forall\n (st_init_src: ms_src.(ModSem.state)) (st_init_tgt: ms_tgt.(ModSem.state)) (sm0: SimMem.t) (sm1: SimMem.t),\n Prop.\n\n Hypothesis FOOTEXCL: forall st_at_src st_at_tgt sm0 sm1 sm2\n (MWF: SimMem.wf sm0)\n (FOOT: has_footprint st_at_src st_at_tgt sm0)\n (MLEEXCL: (mle_excl st_at_src st_at_tgt) sm1 sm2)\n (MLE: SimMem.le sm0 sm1),\n <>.\n\n Hypothesis (EXCLPRIV: forall st_init_src st_init_tgt sm0 sm1\n (MWF: SimMem.wf sm0)\n (EXCL: mle_excl st_init_src st_init_tgt sm0 sm1),\n <>).\n\n Inductive match_states_at_helper\n (idx_at: index) (st_src0: ms_src.(ModSem.state)) (st_tgt0: ms_tgt.(ModSem.state)) (sm_at sm_arg: SimMem.t): Prop :=\n | match_states_at_intro\n (MATCH: match_states idx_at st_src0 st_tgt0 sm_at)\n args_src args_tgt\n (CALLSRC: ms_src.(ModSem.at_external) st_src0 args_src)\n (CALLTGT: ms_tgt.(ModSem.at_external) st_tgt0 args_tgt)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (MLE: SimMem.le sm_at sm_arg)\n (MWF: SimMem.wf sm_arg)\n (MATCHARG: match_states_at st_src0 st_tgt0 sm_at sm_arg).\n (* (FOOT: has_footprint st_src0 st_tgt0 sm_at) *)\n\n Hypothesis INITBSIM: forall sm_arg args_src args_tgt st_init_tgt\n (SIMSKENV: ModSemPair.sim_skenv msp sm_arg)\n (MWF: SimMem.wf sm_arg)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (INITTGT: ms_tgt.(ModSem.initial_frame) args_tgt st_init_tgt)\n (SAFESRC: exists _st_init_src, ms_src.(ModSem.initial_frame) args_src _st_init_src),\n exists st_init_src sm_init idx_init,\n (<>) /\\\n (<>) /\\\n (<>).\n\n Hypothesis INITPROGRESS: forall sm_arg args_src args_tgt\n (SIMSKENV: ModSemPair.sim_skenv msp sm_arg)\n (MWF: SimMem.wf sm_arg)\n (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n (SAFESRC: exists st_init_src, ms_src.(ModSem.initial_frame) args_src st_init_src),\n exists st_init_tgt, (<>).\n\n Hypothesis ATMWF: forall idx0 st_src0 st_tgt0 sm0\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (CALLSRC: ms_src.(ModSem.is_call) st_src0),\n <>.\n\n Hypothesis ATFSIM: forall idx0 st_src0 st_tgt0 sm0 args_src\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (CALLSRC: ms_src.(ModSem.at_external) st_src0 args_src)\n (SOUND: forall si, exists su0 m_init, (sound_states si) su0 m_init st_src0),\n exists args_tgt sm_arg,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Hypothesis AFTERFSIM: forall idx0 st_src0 st_tgt0 sm0 sm_arg sm_ret retv_src retv_tgt st_src1\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (MLE: SimMem.le sm0 sm_arg)\n (* (MWF: SimMem.wf sm_arg) *)\n (MLE: SimMem.le (SimMemLift.lift sm_arg) sm_ret)\n (MWF: SimMem.wf sm_ret)\n (SIMRET: SimMem.sim_retv retv_src retv_tgt sm_ret)\n (AFTERSRC: ms_src.(ModSem.after_external) st_src0 retv_src st_src1)\n (SOUND: forall si, exists su0 m_init, (sound_states si) su0 m_init st_src0)\n\n (* history *)\n (HISTORY: match_states_at_helper idx0 st_src0 st_tgt0 sm0 sm_arg)\n\n (* just helpers *)\n (MWFAFTR: SimMem.wf (SimMemLift.unlift sm_arg sm_ret))\n (MLEAFTR: SimMem.le sm_arg (SimMemLift.unlift sm_arg sm_ret)),\n exists sm_after idx1 st_tgt1,\n (<>) /\\\n forall (MLE: SimMem.le sm0 sm_after) (* helper *),\n ((<>) /\\\n (<>)).\n\n Hypothesis FINALFSIM: forall idx0 st_src0 st_tgt0 sm0 retv_src\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (FINALSRC: ms_src.(ModSem.final_frame) st_src0 retv_src),\n exists sm_ret retv_tgt,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Let STEPFSIM idx0 st_src0 st_tgt0 sm0 :=\n (<>) /\\\n (<>) /\\\n (<> \\/\n <>)\n /\\ (<>)\n (* Note: We require le for mle_preserves_sim_ge, but we cannot require SimMem.wf, beacuse of DCEproof *)\n /\\ (<>)>>).\n\n Let STEPBSIM idx0 st_src0 st_tgt0 sm0 :=\n (< ModSem.is_step ms_tgt st_tgt0>>) /\\\n (<> \\/\n <>)\n /\\ (<>)\n (* Note: We require le for mle_preserves_sim_ge, but we cannot require SimMem.wf, beacuse of DCEproof *)\n /\\ (<>)>>).\n\n Hypothesis STEPSIM: forall idx0 st_src0 st_tgt0 sm0\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (NOTCALL: ~ ModSem.is_call ms_src st_src0)\n (NOTRET: ~ ModSem.is_return ms_src st_src0)\n (MATCH: match_states idx0 st_src0 st_tgt0 sm0)\n (SOUND: forall si, exists su0 m_init, (sound_states si) su0 m_init st_src0),\n STEPFSIM idx0 st_src0 st_tgt0 sm0 \\/ STEPBSIM idx0 st_src0 st_tgt0 sm0.\n\n Hypothesis BAR: bar_True.\n\n Lemma match_states_lxsim\n i0 st_src0 st_tgt0 sm0\n (SIMSKENV: ModSemPair.sim_skenv msp sm0)\n (* (MWF: SimMem.wf sm0) *)\n (* (MCOMPAT: mem_compat st_src0 st_tgt0 sm0) *)\n (MATCH: match_states i0 st_src0 st_tgt0 sm0):\n (* su0 *)\n (* <> *)\n < forall si, exists su0 m_init, sound_states si su0 m_init st)\n has_footprint mle_excl\n (Ord.lift_idx (wf_lex_ord WFORD lt_wf) (i0, 1%nat)) st_src0 st_tgt0 sm0>>.\n Proof.\n (* move su0 at top. *)\n revert_until BAR. pcofix CIH. i. pfold. ii.\n generalize (classic (ModSem.is_call ms_src st_src0)). intro CALLSRC; des.\n { (* CALL *)\n - (* u in CALLSRC. des. *)\n exploit ATMWF; eauto. i; des. ii. eapply lxsim_at_external; eauto. ii. clear CALLSRC.\n exploit ATFSIM; eauto. { ii. eapply SUSTAR; eauto. eapply star_refl. } i; des.\n (* determ_tac ModSem.at_external_dtm. clear_tac. *)\n esplits; eauto. i. exploit AFTERFSIM; try apply SAFESRC; try apply SIMRET; eauto.\n { ii. eapply SUSTAR. eapply star_refl. }\n { econs; eauto. }\n { eapply SimMemLift.unlift_wf; eauto. }\n { eapply SimMemLift.lift_spec; eauto. }\n i; des.\n assert(MLE3: SimMem.le sm0 sm_after).\n { eapply FOOTEXCL; et. etrans; et. eapply SimMemLift.lift_spec; et. }\n spc H1. des. esplits; eauto. right.\n eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto.\n apply rtc_once. left. et.\n }\n }\n generalize (classic (ModSem.is_return ms_src st_src0)). intro RETSRC; des.\n { (* RETURN *)\n u in RETSRC. des. exploit FINALFSIM; eauto. i; des. ii.\n eapply lxsim_final; try apply SIMRET; eauto.\n }\n exploit STEPSIM; eauto. { ii. eapply SUSTAR; eauto. eapply star_refl. } clear STEPSIM. intro STEPSIM.\n destruct STEPSIM as [STEPFSIM0|STEPBSIM0].\n { eapply lxsim_step_forward; eauto. i.\n r in STEPFSIM0. des.\n esplits; eauto. econs 1; eauto. ii. exploit STEPFSIM1; eauto. i; des_safe. esplits; eauto.\n - des.\n + left. eauto.\n + right. esplits; eauto. eapply Ord.lift_idx_spec; eauto. econs 1; eauto.\n - left. pfold. ii. eapply lxsim_step_backward; eauto. ii.\n econs 2; eauto.\n { esplits; eauto. eapply Ord.lift_idx_spec; eauto. econs 2; eauto. }\n { refl. }\n right. eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n }\n { rr in STEPBSIM0.\n eapply lxsim_step_backward; eauto. ii. des.\n econs 1; eauto.\n - ii. exploit STEPBSIM1; eauto. i; des_safe. esplits; eauto.\n + des.\n * left. eauto.\n * right. esplits; eauto. eapply Ord.lift_idx_spec; eauto. econs 1; eauto.\n + right. eapply CIH; [..|eauto].\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n - eapply PROGRESS; eauto.\n }\n Qed.\n\n Theorem match_states_sim: <>.\n Proof.\n eapply sim_mod_sem_implies; et. inv INHAB. econs; eauto.\n { i. eapply local_preservation_noguarantee_weak; eauto. }\n ii; ss. folder.\n exploit SimSymb.sim_skenv_func_bisim; eauto. { apply SIMSKENV. } intro FSIM; des.\n inv FSIM. exploit FUNCFSIM; eauto. { apply SimMem.sim_args_sim_fptr; et. } i; des.\n split; ii.\n - exploit INITBSIM; eauto. i; des.\n esplits; eauto.\n eapply match_states_lxsim; eauto.\n { eapply ModSemPair.mfuture_preserves_sim_skenv; try apply SIMSKENV; eauto. apply rtc_once; eauto. }\n - exploit INITPROGRESS; eauto.\n Unshelve.\n all: ss.\n Qed.\n\nEnd MATCHSIMFORWARD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/proof/MatchSimModSemExcl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.2337063569140403, "lm_q1q2_score": 0.12687059675573814}} {"text": "Require Import RelationClasses. \nRequire Import List. \n\nRequire Import sflib. \nFrom Paco Require Import paco. \n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import Coqlib.\nRequire Import LibTactics.\nRequire Import Integers.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics. \n\nRequire Import Kildall.\nRequire Import CorrectOpt.\n\nRequire Import Language.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import WFConfig.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import LocalSim.\nRequire Import MemoryMerge.\n\nRequire Import CompAuxDef.\nRequire Import MemoryProps.\nRequire Import promiseCertifiedAux.\nRequire Import ConsistentProp.\nRequire Import Mem_at_eq_lemmas.\nRequire Import ConsistentStableEnv.\nRequire Import ConsistentLemmas.\n\nRequire Import DetLoop.\nRequire Import LICM.\nRequire Import Lib_Step.\nRequire Import LICMProofMState.\nRequire Import LICMProofStep.\nRequire Import CSEProof.\n \n(** * Correctness Proof of Loop Invariant Code Motion *)\n(** ** Well-Formed Invariant *)\n(** The invariant [I_linv] is well-formed. *)\nLemma WF_I_linv: wf_I I_linv.\nProof.\n unfold wf_I. ii.\n destruct S; ss. des.\n econs; eauto; subst.\n - ii. unfold spec_inj. rewrite MSG.\n inv MEM_LE. exploit COMPLETE; eauto. i. des1.\n do 3 eexists. splits; eauto.\n - ii. unfold spec_inj in *. destruct (Memory.get loc t T_MEM) eqn:Heqe; ss.\n destruct p. destruct t1; ss. inv INJ.\n inv MEM_LE. exploit COMPLETE; eauto.\n - unfold spec_inj; ii.\n destruct (Memory.get loc t1 T_MEM) eqn:Heqe1; ss. destruct p. destruct t0; ss. inv INJ1.\n destruct (Memory.get loc t2 T_MEM) eqn:Heqe2; ss. destruct p. destruct t1; ss. inv INJ2.\n eauto.\nQed.\n\nLemma I_linv_hold_init\n lo:\n I_linv lo inj_init (Build_Rss TimeMap.bot Memory.init TimeMap.bot Memory.init).\nProof.\n econs; eauto. eapply mem_id_le_identity; eauto.\n split. eapply View.TimeMap.le_PreOrder_obligation_1; eauto.\n eapply functional_extensionality. ii.\n eapply functional_extensionality. ii.\n unfold inj_init, spec_inj.\n des_if; subst. unfold Memory.init. ss.\n unfold Memory.init; ss. unfold Memory.get.\n rewrite Cell.init_get. des_if; eauto.\n ss.\nQed. \n\nLemma match_state_implies_SI\n inj lo b\n state_tgt lc_tgt sc_tgt mem_tgt\n state_src lc_src sc_src mem_src\n (MATCH_STATE: match_state_linv inj lo b\n (Thread.mk rtl_lang state_tgt lc_tgt sc_tgt mem_tgt)\n (Thread.mk rtl_lang state_src lc_src sc_src mem_src)):\n SI inj lo (state_tgt, lc_tgt, mem_tgt) (state_src, lc_src, mem_src) (@dset_init nat).\nProof.\n inv MATCH_STATE; ss. do 2 des1.\n assert (INCR_INJ: incr_inj inj inj').\n {\n des; subst. unfold incr_inj; ii; eauto.\n unfold incr_inj; ii; eauto.\n }\n clear ATM_BIT.\n econs; eauto; ss.\n - ii. unfold incr_inj in INCR_INJ. exploit INCR_INJ; eauto.\n ii. subst. unfold spec_inj in H1.\n destruct (Memory.get loc t mem_tgt) eqn:GET_MEM; ss.\n destruct p. destruct t1; ss. inv H1.\n clear - TVIEW_LE H0. inv TVIEW_LE.\n inv CUR. unfold TimeMap.le in RLX.\n specialize (RLX loc).\n auto_solve_time_rel.\n - exists (@dset_init nat). split.\n ii. rewrite dset_gempty in H; ss.\n econs; eauto.\n ii. rewrite dset_gempty in H; ss.\n ii. exploit PRM_INDOM; eauto. ii; des1.\n exploit INCR_INJ; eauto. ii; subst.\n unfold spec_inj in H1.\n destruct (Memory.get loc t mem_tgt) eqn:GET; ss.\n destruct p. destruct t1; ss. inv H1.\n exists to' f val R. split; eauto.\n ii. exploit PRM_INDOM; eauto. ii; des.\n assert (t' = to').\n {\n eapply INCR_INJ in H0. subst.\n exploit spec_inj_identity_inj; eauto.\n }\n subst.\n exists to'. splits; eauto.\n - subst.\n eapply mem_id_le_2_mem_at_eq; eauto.\nQed.\n\nLemma match_state_linv_implies_sim:\n forall inj lo b\n state_tgt lc_tgt sc_tgt mem_tgt\n state_src lc_src sc_src mem_src\n (MATCH_STATE: match_state_linv inj lo b\n (Thread.mk rtl_lang state_tgt lc_tgt sc_tgt mem_tgt)\n (Thread.mk rtl_lang state_src lc_src sc_src mem_src)),\n @local_sim_state nat lt rtl_lang I_linv lo inj dset_init b\n (Thread.mk rtl_lang state_tgt lc_tgt sc_tgt mem_tgt)\n (Thread.mk rtl_lang state_src lc_src sc_src mem_src).\nProof.\n cofix COFIX_HP.\n introv MATCH_STATE. \n destruct (classic (Local.promise_consistent lc_tgt)) as [PROMS_CONS | NOT_PROM_CONS].\n 2: {\n eapply local_sim_state_tgt_not_prm_consistent_intro; eauto.\n }\n assert (CONS_SRC: Local.promise_consistent lc_src).\n {\n clear - MATCH_STATE PROMS_CONS. inv MATCH_STATE; ss.\n clear - PROMS_CONS TVIEW_LE. unfold Local.promise_consistent in *; ss.\n ii. exploit PROMS_CONS; eauto. i.\n inv TVIEW_LE. inv CUR; ss. unfold TimeMap.le in *; ss.\n specialize (RLX loc).\n auto_solve_time_rel.\n }\n destruct (classic (Thread.is_abort (Thread.mk rtl_lang state_src lc_src sc_src mem_src) lo)).\n eapply local_sim_state_abort_intro; eauto.\n\n eapply local_sim_state_step_intro.\n - eapply match_state_implies_SI; eauto.\n - introv THRD_STEP. splits.\n {\n (* atomic or out step *)\n introv THRD_AT_OR_OUT.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply atomic_or_out_step_case in THRD_STEP; eauto. des.\n do 4 eexists.\n split. eauto. split. eauto.\n split. eauto. split. eapply COFIX_HP; eauto.\n eauto. \n }\n {\n (* non-atomic step *)\n introv NA_STEP. destruct te; ss.\n + (* silent *)\n inv THRD_STEP; ss. inv STEP.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply silent_step_case in STEP; eauto. des; tryfalse.\n eexists. exists (@dset_init nat) (@dset_init nat) (@dset_init nat).\n splits.\n {\n eapply dset_become_na_read. ii; ss. eauto.\n }\n {\n eapply Thread_na_steps_to_na_steps_dset; eauto.\n }\n {\n econs. introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n }\n {\n eapply COFIX_HP; eauto.\n }\n + (* non-atomic read *)\n destruct ord; tryfalse.\n inv THRD_STEP; ss. inv STEP.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply na_read_step_case in STEP; eauto.\n des.\n eexists. exists (@dset_init nat) (@dset_init nat) (@dset_init nat).\n splits.\n {\n eapply dset_become_na_read. ii; ss. eauto.\n }\n {\n eapply Thread_na_steps_to_na_steps_dset; eauto.\n }\n {\n econs. introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n }\n {\n eapply COFIX_HP; eauto.\n }\n + (* non-atomic write *)\n destruct ord; tryfalse.\n inv THRD_STEP; ss. inv STEP.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply na_write_step_case in STEP; eauto.\n des.\n do 2 eexists. exists (@dset_init nat) (@dset_init nat).\n splits.\n {\n econs; eauto.\n }\n {\n instantiate (2 := 5%nat).\n eapply Operators_Properties.clos_rt1n_step.\n eapply na_steps_dset_write. eapply STEP.\n right. exists to. rewrite dset_remove_add; eauto.\n }\n {\n econs. introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n introv DSET_GET. rewrite dset_gempty in DSET_GET. tryfalse.\n }\n {\n eapply COFIX_HP; eauto.\n }\n }\n {\n (* promise step *)\n introv PROM_STEP. ii; subst.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply promise_step_case in THRD_STEP; eauto. clear PROM_STEP.\n des.\n do 2 eexists. split. eauto. split. eauto.\n eapply COFIX_HP. eauto.\n }\n {\n (* pf promise step *)\n introv PF_PROM_STEP. ii; subst.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n destruct e_tgt'.\n renames state to state_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n destruct lc_tgt' as (tview_tgt' & prm_tgt').\n eapply pf_promise_step_case in THRD_STEP; eauto.\n des.\n eexists. split; eauto.\n }\n - ii; subst.\n split.\n {\n clear - MATCH_STATE. inv MATCH_STATE. destruct ATM_BIT.\n destruct H; tryfalse. destruct H; subst. eauto.\n }\n {\n introv RELY INV.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n eapply rely_step_case in RELY; eauto.\n }\n - introv THRD_DONE.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n lets MATCH_STATE': MATCH_STATE.\n eapply done_step_case in MATCH_STATE; eauto. des.\n eexists. exists inj'.\n splits; eauto.\n - introv THRD_ABORT.\n destruct lc_tgt as (tview_tgt & prm_tgt).\n destruct lc_src as (tview_src & prm_src).\n lets MATCH_STATE': MATCH_STATE.\n eapply abort_step_case in MATCH_STATE; eauto.\nQed.\n\n(** ** Correctness of the Loop Invariant Code Motion *)\n(** [LInv] is verified. *)\nTheorem verif_linv:\n forall code_s code_t lo,\n LInv lo code_s = Some code_t \n ->\n @local_sim nat lt rtl_lang I_linv lo code_t code_s.\nProof.\n ii. econs.\n - (* well_founded index *)\n eapply nat_lt_is_well_founded.\n - (* well-formed I_linv *)\n eapply WF_I_linv; eauto.\n - (* I_linv holds in initial state *)\n eapply I_linv_hold_init; eauto.\n - (* local simulation *)\n introv TGT_INIT.\n unfold Language.init in *; ss.\n unfold State.init in *; ss.\n destruct (code_t ! fid) eqn:FUNC_T; ss. destruct f; ss.\n renames c to cdhp_t. renames f to l_t.\n destruct (cdhp_t ! l_t) eqn:ENTRY_BB_T; ss. inv TGT_INIT; ss.\n unfold LInv in H. inv H.\n rewrite PTree.gmap in FUNC_T. unfold option_map in FUNC_T.\n destruct (code_s ! fid) eqn:SCODE_GET; ss.\n unfold det_loop_invs in FUNC_T.\n rewrite PTree.gmap in FUNC_T. unfold option_map in FUNC_T.\n rewrite SCODE_GET in FUNC_T. inv FUNC_T.\n destruct f as (cdph_s & l_s). renames t to BB_t.\n destruct (cdph_s ! l_s) eqn:CDHP_S.\n {\n renames t to BB_s.\n eapply transC_prop in H0; eauto.\n 2: { instantiate (1 := lo). right. exists BB_s. split; eauto. }\n do 7 des1.\n eexists. split; eauto.\n eapply match_state_linv_implies_sim.\n econs; eauto.\n {\n eapply I_linv_hold_init; eauto.\n }\n {\n econs; eauto. 2: { econs; eauto. }\n des1.\n {\n des1.\n rewrite CDHP_S in GET_BB_S. symmetry in GET_BB_S. inv GET_BB_S.\n eapply EXEC_NOT_PH; eauto.\n unfold det_loop_invs.\n rewrite PTree.gmap. unfold option_map. rewrite SCODE_GET.\n rewrite CDHP_S. eauto.\n ii. eapply reg_in_blk_in_cdhp; eauto.\n }\n {\n des1. \n eapply EXEC_PH with (f := fid); eauto.\n unfold det_loop_invs.\n rewrite PTree.gmap. unfold option_map.\n rewrite SCODE_GET. rewrite CDHP_S. eauto.\n }\n }\n {\n eapply TView.TView.le_PreOrder_obligation_1; eauto.\n }\n {\n ii. rewrite Memory.bot_get in H. ss.\n }\n {\n eapply Local.wf_init; eauto.\n }\n {\n unfold Memory.closed_timemap. ii.\n unfold TimeMap.bot.\n unfold Memory.get, Memory.init.\n rewrite Cell.init_get. des_if; ss; eauto.\n unfold Message.elt. eauto.\n }\n {\n eapply Memory.init_closed; eauto.\n }\n {\n eapply Local.wf_init; eauto.\n }\n {\n unfold Memory.closed_timemap. ii.\n unfold TimeMap.bot.\n unfold Memory.get, Memory.init.\n rewrite Cell.init_get. des_if; ss; eauto.\n unfold Message.elt. eauto.\n }\n {\n eapply Memory.init_closed; eauto.\n }\n }\n {\n ss.\n assert (GET_EMPTY: (PTree.empty positive) ! l_s = None).\n rewrite PTree.gempty. eauto.\n rewrite GET_EMPTY in H0; ss. inv H0. tryfalse.\n }\nQed.\n\n(** Loop invariant code motion optimizer is correct. *)\nTheorem correct_licm:\n Correct licm.\nProof.\n unfold licm.\n eapply correct_optimizer_transitive; eauto.\n eapply correct_cse; eauto.\n eapply Verif_implies_Correctness.\n unfolds Verif. intros. exists I_linv nat lt. \n eapply verif_linv; eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/LICMProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.12643650157613695}} {"text": "Require Import FunInd.\nRequire Import Zwf CoqlibC Maps Integers Floats Lattice.\nRequire Import Compopts AST.\nRequire Import Values MemoryC Globalenvs Events.\nRequire Import Registers RTL.\nRequire Import sflib.\n(** newly added **)\nRequire Export ValueDomain.\nRequire Import Skeleton.\nRequire Import Sound UnreachC.\nRequire Import ModSem.\n\n(* TODO: remove redundancy, move it to ValueDomain maybe *)\nDefinition bc2su (bc: block_classification) (ge_nb: block) (nb: block): Unreach.t :=\n Unreach.mk (fun blk => if plt blk nb then block_class_eq (bc blk) BCinvalid else false) ge_nb nb.\n\nLemma sound_state_sound_args\n bc m0 p skenv_link vs_arg rm (ge: genv)\n (GENV: ge = (SkEnv.revive (SkEnv.project skenv_link (Sk.of_program fn_sig p)) p))\n (ARGS: forall v : val, In v vs_arg -> vmatch bc v Vtop)\n (RO: romatch bc m0 rm)\n (MM: mmatch bc m0 mtop)\n (GE: genv_match bc ge)\n (NOSTK: forall b, bc b <> BCstack)\n fptr_arg sg_arg\n (SIG: exists skd, Genv.find_funct skenv_link fptr_arg = Some skd /\\ Sk.get_csig skd = sg_arg):\n args' (bc2su bc ge.(Genv.genv_next) m0.(Mem.nextblock)) (Args.mk fptr_arg vs_arg m0).\nProof.\n { r. s. esplits; eauto.\n - des. unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs. ss. r. ii; clarify. ss.\n r in GE. des. specialize (GE0 blk). exploit GE0; eauto.\n { ss. eapply Genv.genv_defs_range; eauto. }\n i; des.\n (* exploit sound_stack_unreach_compat; eauto. intro CPT. des. *)\n (* inv SU. ss. *)\n esplits; eauto.\n + ii. des_ifs. des_sumbool. congruence.\n + inv MM. eapply mmatch_below; eauto. rewrite H; ss.\n - rewrite Forall_forall. i. spcN 1 ARGS. spc ARGS. ii; clarify.\n assert(BCV: bc blk <> BCinvalid).\n { inv ARGS; ss. inv H1; ss. }\n esplits; eauto.\n + u. ii. des_ifs. des_sumbool. ss.\n + inv MM. eapply mmatch_below; eauto.\n - inv MM. econs; eauto.\n + ii. clarify.\n assert(BCV: bc blk <> BCinvalid).\n { u in PUB. ii. rewrite H in *. ss. exploit Mem.perm_valid_block; eauto. i; des. des_ifs. }\n assert(BCV0: bc blk0 <> BCinvalid).\n {\n exploit mmatch_top; eauto.\n (* spcN 0%nat mmatch_top. spc mmatch_top. inv mmatch_top. *)\n intro SM. inv SM.\n specialize (H0 ofs%Z blk0 ofs0 q n).\n exploit H0.\n { eapply Mem_loadbytes_succeeds; et. }\n intro PM.\n inv PM. ss.\n }\n esplits; eauto.\n { u. des_ifs. i; des_sumbool; ss. }\n s. eapply mmatch_below; eauto.\n + u. ii. des_ifs.\n + ss. r in GE. ss. des. r in mmatch_below.\n apply NNPP. ii. apply Pos.lt_nle in H.\n exploit GE0; eauto. i; des.\n exploit mmatch_below; eauto. { rewrite H0; ss. } i; des. xomega.\n - econs; ss; i; des_ifs. r in GE. des. ss. des_sumbool. apply NNPP. ii.\n exploit (GE0 x0); eauto. { xomega. } i; des. congruence.\n }\nQed.\n\n(* copied from above *)\nLemma sound_state_sound_retv\n bc m_ret p skenv_link v_ret rm (ge: genv)\n (GENV: ge = (SkEnv.revive (SkEnv.project skenv_link (Sk.of_program fn_sig p)) p))\n (RES: vmatch bc v_ret Vtop)\n (RO: romatch bc m_ret rm)\n (MM: mmatch bc m_ret mtop)\n (GE: genv_match bc ge)\n (NOSTK: forall b, bc b <> BCstack):\n Sound.retv (bc2su bc ge.(Genv.genv_next) m_ret.(Mem.nextblock)) (Retv.mk v_ret m_ret).\nProof.\n { r. s. esplits; eauto.\n - ii; clarify.\n assert(BCV: bc blk <> BCinvalid).\n { inv RES; ss. inv H0; ss. }\n esplits; eauto.\n + u. ii. des_ifs. des_sumbool. ss.\n + inv MM. eapply mmatch_below; eauto.\n - inv MM. econs; eauto.\n + ii. clarify.\n assert(BCV: bc blk <> BCinvalid).\n { u in PUB. ii. rewrite H in *. ss. exploit Mem.perm_valid_block; eauto. i; des. des_ifs. }\n assert(BCV0: bc blk0 <> BCinvalid).\n {\n exploit mmatch_top; eauto.\n (* spcN 0%nat mmatch_top. spc mmatch_top. inv mmatch_top. *)\n intro SM. inv SM.\n specialize (H0 ofs blk0 ofs0 q n).\n exploit H0.\n { eapply Mem_loadbytes_succeeds; et. }\n intro PM. inv PM. ss.\n }\n esplits; eauto.\n { u. des_ifs. i; des_sumbool; ss. }\n s. eapply mmatch_below; eauto.\n + u. ii. des_ifs.\n + ss. r in GE. ss. des. r in mmatch_below.\n apply NNPP. ii. apply Pos.lt_nle in H.\n exploit GE0; eauto. i; des.\n exploit mmatch_below; eauto. { rewrite H0; ss. } i; des. xomega.\n - econs; eauto; ss; i; des_ifs. des_sumbool.\n rr in GE. des. apply NNPP. ii.\n exploit (GE0 x0); eauto.\n { unfold fundef in *. xomega. }\n i; des. congruence.\n }\nQed.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/ValueDomainC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.23370636758849894, "lm_q1q2_score": 0.12596381069806895}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Low Level Specification *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n(** This file provide the contextual refinement proof between MBoot layer and MALInit layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import PrimSemantics.\nRequire Import Conventions.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import AbstractDataType.\n\nRequire Import PIPC.\n\nLocal Open Scope string_scope.\nLocal Open Scope error_monad_scope.\nLocal Open Scope Z_scope.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n Context `{real_params: RealParams}.\n\n Notation LDATA := RData.\n\n Notation LDATAOps := (cdata LDATA).\n\n Inductive elf_load_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sprimcall_sem (mem := mwd LDATAOps):=\n | elf_load_spec_low_intro s (m'0: mwd LDATAOps) n be ofse sig rs b:\n find_symbol s elf_load = Some b ->\n rs PC = Vptr b Int.zero ->\n (exists elf_id, find_symbol s elf_id = Some be) ->\n sig = mksignature (AST.Tint::AST.Tint::nil) None cc_default ->\n extcall_arguments rs m'0 sig (Vptr be ofse :: Vint n :: nil) ->\n asm_invariant (mem := mwd LDATAOps) s rs m'0 ->\n elf_load_spec_low_step s rs m'0 (rs#RA<- Vundef#PC <- (rs#RA)) m'0.\n\n Inductive uctx_get_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n uctx_get_spec_low_intro s (WB: _ -> Prop) (m'0: mwd LDATAOps) b0 n ofs v:\n find_symbol s UCTX_LOC = Some b0 ->\n Mem.load Mint32 m'0 b0 ((Int.unsigned n) * UCTXT_SIZE * 4 + Int.unsigned ofs * 4) = Some (Vint v) ->\n 0 <= (Int.unsigned n) < num_proc ->\n is_UCTXT_ptr (Int.unsigned ofs) = false ->\n kernel_mode (snd m'0) ->\n uctx_get_spec_low_step s WB (Vint n :: Vint ofs :: nil) m'0 (Vint v) m'0.\n\n Inductive uctx_set_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n uctx_set_spec_low_intro s (WB: _ -> Prop) (m'0 m0: mwd LDATAOps) b0 n ofs v:\n find_symbol s UCTX_LOC = Some b0 ->\n Mem.store Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + Int.unsigned ofs * 4) (Vint v) = Some m0 ->\n 0 <= (Int.unsigned n) < num_proc ->\n is_UCTXT_ptr (Int.unsigned ofs) = false ->\n kernel_mode (snd m'0) ->\n uctx_set_spec_low_step s WB (Vint n :: Vint ofs :: Vint v :: nil) m'0 Vundef m0.\n\n Inductive uctx_set_eip_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n uctx_set_eip_spec_low_intro s (WB: _ -> Prop) (m'0 m0: mwd LDATAOps) b0 n bf ofs:\n find_symbol s UCTX_LOC = Some b0 ->\n Mem.store Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EIP * 4) (Vptr bf ofs) = Some m0 ->\n 0 <= (Int.unsigned n) < num_proc ->\n (exists fun_id, find_symbol s fun_id = Some bf) ->\n kernel_mode (snd m'0) ->\n uctx_set_eip_spec_low_step s WB (Vint n :: Vptr bf ofs :: nil) m'0 Vundef m0.\n\n Inductive save_uctx_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sextcall_sem (mem := mwd LDATAOps) :=\n save_uctx_spec_low_intro s (WB: _ -> Prop) \n (m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 \n m15 m16 m17: mwd LDATAOps) \n u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16 b1 n:\n find_symbol s UCTX_LOC = Some b1 ->\n Mem.store Mint32 m0 b1 (UCTXT_SIZE * 4 * n + 4 * U_EDI) (Vint u0) = Some m1 ->\n Mem.store Mint32 m1 b1 (UCTXT_SIZE * 4 * n + 4 * U_ESI) (Vint u1) = Some m2 ->\n Mem.store Mint32 m2 b1 (UCTXT_SIZE * 4 * n + 4 * U_EBP) (Vint u2) = Some m3 ->\n Mem.store Mint32 m3 b1 (UCTXT_SIZE * 4 * n + 4 * U_OESP) (Vint u3) = Some m4 ->\n Mem.store Mint32 m4 b1 (UCTXT_SIZE * 4 * n + 4 * U_EBX) (Vint u4) = Some m5 ->\n Mem.store Mint32 m5 b1 (UCTXT_SIZE * 4 * n + 4 * U_EDX) (Vint u5) = Some m6 ->\n Mem.store Mint32 m6 b1 (UCTXT_SIZE * 4 * n + 4 * U_ECX) (Vint u6) = Some m7 ->\n Mem.store Mint32 m7 b1 (UCTXT_SIZE * 4 * n + 4 * U_EAX) (Vint u7) = Some m8 ->\n Mem.store Mint32 m8 b1 (UCTXT_SIZE * 4 * n + 4 * U_ES) (Vint u8) = Some m9 ->\n Mem.store Mint32 m9 b1 (UCTXT_SIZE * 4 * n + 4 * U_DS) (Vint u9) = Some m10 ->\n Mem.store Mint32 m10 b1 (UCTXT_SIZE * 4 * n + 4 * U_TRAPNO) (Vint u10) = Some m11 -> \n Mem.store Mint32 m11 b1 (UCTXT_SIZE * 4 * n + 4 * U_ERR) (Vint u11) = Some m12 ->\n Mem.store Mint32 m12 b1 (UCTXT_SIZE * 4 * n + 4 * U_EIP) (Vint u12) = Some m13 ->\n Mem.store Mint32 m13 b1 (UCTXT_SIZE * 4 * n + 4 * U_CS) (Vint u13) = Some m14 ->\n Mem.store Mint32 m14 b1 (UCTXT_SIZE * 4 * n + 4 * U_EFLAGS) (Vint u14) = Some m15 -> \n Mem.store Mint32 m15 b1 (UCTXT_SIZE * 4 * n + 4 * U_ESP) (Vint u15) = Some m16 ->\n Mem.store Mint32 m16 b1 (UCTXT_SIZE * 4 * n + 4 * U_SS) (Vint u16) = Some m17 ->\n cid (snd m0) = n ->\n kernel_mode (snd m0) ->\n pg (snd m0) = true ->\n save_uctx_spec_low_step s WB (Vint u0::Vint u1::Vint u2::Vint u3::Vint u4::Vint u5::Vint u6::\n Vint u7::Vint u8::Vint u9::Vint u10::Vint u11::Vint u12::Vint u13\n ::Vint u14::Vint u15::Vint u16::nil) m0 Vundef m17.\n\n Inductive restore_uctx_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n sprimcall_sem (mem := mwd LDATAOps):=\n restore_uctx_spec_low_intro s v0 v1 v2 v4 v5 v6 v7 v8 v9\n (m'0: mem) b0 n rs rs' labd labd' sig b:\n find_symbol s restore_uctx = Some b ->\n rs PC = Vptr b Int.zero ->\n find_symbol s UCTX_LOC = Some b0 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EDI) = Some v0 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ESI * 4) = Some v1 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EBP * 4) = Some v2 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EBX * 4) = Some v4 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EDX * 4) = Some v5 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ECX * 4) = Some v6 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EAX * 4) = Some v7 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_ESP * 4) = Some v8 ->\n Mem.load Mint32 m'0 b0 (Int.unsigned n * UCTXT_SIZE * 4 + U_EIP * 4) = Some v9 ->\n rs' = (undef_regs (CR ZF :: CR CF :: CR PF :: CR SF :: CR OF \n :: IR ECX :: IR EAX :: RA :: nil) \n (undef_regs (List.map preg_of destroyed_at_call) rs)) ->\n trapout_spec labd = Some labd' ->\n cid labd = Int.unsigned n ->\n kernel_mode labd ->\n asm_invariant (mem := mwd LDATAOps) s rs (m'0, labd) ->\n high_level_invariant labd ->\n sig = mksignature (AST.Tint::nil) None cc_default ->\n extcall_arguments rs m'0 sig (Vint n ::nil) ->\n restore_uctx_spec_low_step s rs (m'0, labd)\n (rs'#Asm.EDI <- v0 #Asm.ESI <- v1 #Asm.EBP <- v2 #Asm.ESP<- v8#Asm.EBX <- v4\n #EDX<- v5 #ECX<-v6 #EAX <- v7# PC <- v9) (m'0, labd').\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n Definition uctx_get_spec_low: compatsem LDATAOps :=\n csem uctx_get_spec_low_step (type_of_list_type (Tint32::Tint32::nil)) Tint32.\n\n Definition uctx_set_spec_low: compatsem LDATAOps :=\n csem uctx_set_spec_low_step (type_of_list_type (Tint32::Tint32::Tint32::nil)) Tvoid.\n\n Definition uctx_set_eip_spec_low: compatsem LDATAOps :=\n csem uctx_set_eip_spec_low_step (type_of_list_type (Tint32::Tpointer Tvoid noattr::nil)) Tvoid.\n\n Definition elf_load_spec_low: compatsem LDATAOps :=\n asmsem_withsig elf_load elf_load_spec_low_step (mksignature (AST.Tint::AST.Tint::nil) None cc_default).\n\n Definition save_uctx_spec_low: compatsem LDATAOps :=\n csem save_uctx_spec_low_step (type_of_list_type \n (Tint32::Tint32::Tint32::Tint32::\n Tint32::Tint32::Tint32::Tint32::\n Tint32::Tint32::Tint32::Tint32::\n Tint32::Tint32::Tint32::Tint32::\n Tint32::nil)) Tvoid.\n\n Definition restore_uctx_spec_low: compatsem LDATAOps :=\n asmsem_withsig restore_uctx restore_uctx_spec_low_step (mksignature (AST.Tint::nil) None cc_default).\n \n (*Definition MSpec : compatlayer LDATAOps :=\n uctx_get ↦ uctx_get_spec_low\n ⊕ uctx_set ↦ uctx_set_spec_low\n ⊕ uctx_set_eip ↦ uctx_set_eip_spec_low\n ⊕ restore_uctx ↦ restore_uctx_spec_low\n ⊕ save_uctx ↦ save_uctx_spec_low\n ⊕ elf_load ↦ elf_load_spec_low.\n \n Definition MVar : compatlayer LDATAOps :=\n UCTX_LOC ↦ mkglobvar (Tarray Tint32 (num_proc * UCTXT_SIZE * 4) (mk_attr false None))\n (Init_space (num_proc * UCTXT_SIZE * 4) :: nil) false false.*)\n\n End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/UCtxtIntroGenSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.23370635157681108, "lm_q1q2_score": 0.12596380206803787}} {"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Coq.Classes.RelationClasses Lia Program.\nFrom Fairness Require Export\n ITreeLib WFLibLarge FairBeh NatStructsLarge Mod pind Axioms\n Linking WMM Red IRed WeakestAdequacy FairLock Concurrency.\nFrom PromisingLib Require Import Loc Event.\nFrom PromisingSEQ Require Import View.\nFrom Ordinal Require Export ClassicalHessenberg.\nRequire Import Coq.Numbers.BinNums.\n\n\nSet Implicit Arguments.\n\nSection INIT.\n\n Definition loc_X: Loc.t := Loc.of_nat 2.\n\n Definition const_0: Const.t := Const.of_Z (BinIntDef.Z.of_nat 0).\n Definition const_42: Const.t := Const.of_Z (BinIntDef.Z.of_nat 42).\n\nEnd INIT.\n\nModule ClientImpl.\n\n Definition thread1:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n let tvw := View.bot in\n tvw <- (OMod.call \"lock\" (tvw: View.t));;\n tvw <- (OMod.call \"store\" (tvw: View.t, loc_X, const_42, Ordering.plain));;\n `tvw: View.t <- (OMod.call \"unlock\" (tvw: View.t));;\n _ <- trigger Yield;;\n Ret tt.\n\n Definition thread2:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n let tvw := View.bot in\n val_x <- ITree.iter\n (fun (tvw: View.t) =>\n tvw <- (OMod.call \"lock\" (tvw: View.t));;\n '(tvw, x) <- (OMod.call \"load\" (tvw: View.t, loc_X, Ordering.plain));;\n `tvw: View.t <- (OMod.call \"unlock\" (tvw: View.t));;\n b <- unwrap (Const.eqb const_0 x);;\n if (b: bool) then Ret (inl tvw) else Ret (inr x)) tvw;;\n b <- unwrap (Const.eqb const_42 val_x);;\n if (b: bool) then\n _ <- trigger Yield;;\n _ <- trigger (Observe 0 [42]);;\n _ <- trigger Yield;;\n Ret tt\n else UB.\n\n Definition omod: Mod.t :=\n Mod.mk\n tt\n (Mod.get_funs [(\"thread1\", Mod.wrap_fun thread1);\n (\"thread2\", Mod.wrap_fun thread2)])\n .\n\n Definition mod: Mod.t :=\n OMod.close\n (omod)\n (ModAdd WMem.mod AbsLockW.mod)\n .\n\nEnd ClientImpl.\n\nModule ClientSpec.\n Definition thread1:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n _ <- trigger Yield;; Ret tt.\n\n Definition thread2:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n _ <- trigger Yield;;\n _ <- trigger (Observe 0 [42]);;\n _ <- trigger Yield;;\n Ret tt.\n\n Definition mod: Mod.t :=\n Mod.mk\n tt\n (Mod.get_funs [(\"thread1\", Mod.wrap_fun thread1);\n (\"thread2\", Mod.wrap_fun thread2)])\n .\n\nEnd ClientSpec.\n\n\n\nFrom Fairness Require Import\n IProp IPM Weakest ModSim PCM MonotonePCM StateRA FairRA NatStructs NatMapRA.\n\nSection LEMMA.\n\n Context `{Σ: GRA.t}.\n Variable A: Type.\n Context `{EXCL: @GRA.inG (Excl.t A) Σ}.\n\n Lemma excl_unique\n a0 a1\n :\n (OwnM (Excl.just a0: Excl.t A))\n -∗\n (OwnM (Excl.just a1: Excl.t A))\n -∗\n ⌜False⌝%I.\n Proof.\n iIntros \"I1 I2\". iCombine \"I1 I2\" as \"C\". iPoseProof (OwnM_valid with \"C\") as \"%C\". exfalso. ur in C. ss.\n Qed.\n\nEnd LEMMA.\n\nSection SIM.\n\n Context `{Σ: GRA.t}.\n\n Context `{MONORA: @GRA.inG monoRA Σ}.\n Context `{THDRA: @GRA.inG ThreadRA Σ}.\n Context `{STATESRC: @GRA.inG (stateSrcRA (unit)) Σ}.\n Context `{STATETGT: @GRA.inG (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod)))) Σ}.\n Context `{IDENTSRC: @GRA.inG (identSrcRA (void)) Σ}.\n Context `{IDENTTGT: @GRA.inG (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ}.\n\n Context `{OBLGRA: @GRA.inG ObligationRA.t Σ}.\n Context `{ARROWRA: @GRA.inG (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ}.\n Context `{EDGERA: @GRA.inG EdgeRA Σ}.\n Context `{ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ}.\n\n Context `{WMEMRA: @GRA.inG wmemRA Σ}.\n\n Context `{EXCL: @GRA.inG (Excl.t unit) Σ}.\n Context `{EXCL2: @GRA.inG (Excl.t (unit * unit)) Σ}.\n Context `{ONESHOTRA: @GRA.inG (OneShot.t nat) Σ}.\n Context `{REGIONRA: @GRA.inG (Region.t (thread_id * nat)) Σ}.\n Context `{CONSENTRA: @GRA.inG (@FiniteMap.t (Consent.t nat)) Σ}.\n Context `{AUTHNRA: @GRA.inG (Auth.t (Excl.t nat)) Σ}.\n Context `{AUTHVWRA: @GRA.inG (Auth.t (Excl.t View.t)) Σ}.\n Context `{AUTHVWRA2: @GRA.inG (Auth.t (Excl.t (View.t * unit))) Σ}.\n Context `{AUTHNMNRA: @GRA.inG (Auth.t (NatMapRALarge.t nat)) Σ}.\n\n Definition thread1_will_write (tvw: View.t) : iProp :=\n ∃ k, (∃ n, ObligationRA.black k n)\n ∗\n (ObligationRA.correl_thread k 1%ord)\n ∗\n (OwnM (OneShot.shot k))\n ∗\n ((ObligationRA.pending k (/2)%Qp ∗ wpoints_to loc_X const_0 tvw)\n ∨\n (ObligationRA.shot k ∗ wpoints_to loc_X const_42 tvw)).\n\n Definition o_w_cor: Ord.t := (Ord.omega × Ord.omega)%ord.\n\n Definition lock_will_unlock : iProp :=\n ∃ (own: bool) (tvw: View.t) (ing: bool) (mem: WMem.t) (wobl: NatMap.t nat) (j: nat),\n (OwnM (Auth.black (Some wobl: NatMapRALarge.t nat)))\n ∗\n ((OwnM (Auth.black (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.black (Excl.just (tvw, tt): Excl.t (View.t * unit)%type))))\n ∗\n (wmemory_black mem)\n ∗\n (St_tgt (tt, (mem, (((own, tvw), ing), key_set wobl))))\n ∗\n (FairRA.blacks (fun id => exists t, (id = (inr (inr (inr t)))) /\\ (~ NatMap.In t wobl)))\n ∗\n (natmap_prop_sum wobl\n (fun tid idx =>\n (own_thread tid)\n ∗\n (ObligationRA.correl (inr (inr (inr tid))) idx o_w_cor)\n ∗\n (ObligationRA.pending idx 1)\n ∗\n (ObligationRA.duty (inr (inr (inr tid))) [(idx, o_w_cor)])\n ))\n ∗\n (\n ((⌜own = false⌝)\n ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n (* points_to view *)\n ∗ (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n (* argument-passing view *)\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit)%type)))\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n )\n ∨\n ((⌜own = true⌝)\n ∗ (ObligationRA.pending j 1)\n ∗ (ObligationRA.black j o_w_cor)\n ∗ (ObligationRA.correl_thread j 1%ord)\n ∗ (natmap_prop_sum wobl (fun _ idx => ObligationRA.amplifier j idx 1%ord))\n )\n )\n ∗\n (\n ((⌜ing = false⌝)\n ∗ (OwnM (Excl.just (tt, tt): Excl.t (unit * unit)%type))\n )\n ∨\n ((⌜ing = true⌝)\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n (* ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat))) *)\n (* ∗ (∃ tvw', (OwnM (Auth.white (Excl.just tvw': Excl.t View.t))) ∗ (⌜View.le tvw tvw'⌝)) *)\n )\n )\n .\n\n Let I: list iProp :=\n [(∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t)))\n ∗ (thread1_will_write tvw))%I;\n lock_will_unlock].\n\n Section INITIAL.\n\n Variable tid1 tid2 : nat.\n Let init_ord := (((((Ord.omega × Ord.omega) × Ord.omega) ⊕ ((Ord.S Ord.O) × (o_w_cor))) ⊕ 10)%ord).\n Let init_ths :=\n (NatStructsLarge.NatMap.add tid1 tt\n (NatStructsLarge.NatMap.add tid2 tt\n (NatStructsLarge.NatMap.empty unit))).\n\n Lemma init_sat Invs (H_TID : tid1 <> tid2) :\n (\n OwnM (OneShot.pending nat 1)\n ) ∗ (\n OwnM (Auth.black (Some (NatMap.empty nat) : NatMapRALarge.t nat))\n ∗ OwnM (Auth.black (Excl.just 0 : Excl.t nat))\n ∗ OwnM (Auth.white (Excl.just 0 : Excl.t nat))\n ∗ OwnM (Auth.black (Excl.just View.bot : Excl.t View.t))\n ∗ OwnM (Auth.white (Excl.just View.bot : Excl.t View.t))\n ∗ OwnM (Auth.black (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ∗ OwnM (Auth.white (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ∗ OwnM (Excl.just (tt,tt): Excl.t (unit * unit))\n ∗ OwnM (Excl.just () : Excl.t unit)\n ∗ OwnM (wmem_init_res loc_X (Loc.of_nat 5)))\n ∗\n WSim.initial_prop ClientSpec.mod ClientImpl.mod init_ths init_ord\n ⊢\n MUpd Invs (fairI (ident_tgt:=Mod.ident ClientImpl.mod)) [] [] (\n (∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t))) ∗ (thread1_will_write tvw))\n ∗\n (lock_will_unlock)\n ∗\n (∃ k, (own_thread tid1)\n ∗ (ObligationRA.duty (inl tid1) [(k, Ord.from_nat 1)])\n ∗ (ObligationRA.taxes [(k, Ord.from_nat 1)] init_ord)\n ∗ (OwnM (OneShot.shot k))\n ∗ (ObligationRA.pending k (/ 2))\n )\n ∗\n ((own_thread tid2) ∗ (ObligationRA.duty (inl tid2) []))\n ).\n Proof.\n iIntros \"(PEND & (B1 & B2 & W2 & B3 & W3 & B4 & W4 & E1 & E2 & E3) & INIT)\".\n iPoseProof (wmem_init_res_prop with \"E3\") as \"[[WPOINTS _] MBLACK]\".\n\n iMod (ObligationRA.alloc ((1 × Ord.omega) ⊕ ((1 × Ord.omega) × init_ord))%ord) as \"[% [[OBLIG1 OBLIG2] OBLIG3]]\".\n iMod (OwnM_Upd (OneShot.pending_shot k) with \"PEND\") as \"#SHOT\".\n rewrite <- Qp.inv_half_half.\n iPoseProof (ObligationRA.pending_split _ (/ 2)%Qp (/ 2)%Qp with \"OBLIG3\") as \"[OBPEND1 OBPEND2]\".\n\n unfold WSim.initial_prop.\n iDestruct \"INIT\" as \"[[[[[INIT0 INIT1] INIT2] INIT3] INIT4] INIT5]\".\n (* make thread_own, duty *)\n assert (NatStructsLarge.NatMap.find tid1 init_ths = Some tt).\n { unfold init_ths. apply NatStructsLarge.nm_find_add_eq. }\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT2\") as \"[DU1 INIT2]\".\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT3\") as \"[TH1 INIT3]\".\n clear H.\n assert (NatStructsLarge.NatMap.find tid2 (NatStructsLarge.NatMap.remove tid1 init_ths) = Some tt).\n { unfold init_ths.\n rewrite NatStructsLarge.NatMapP.F.remove_neq_o; ss.\n rewrite NatStructsLarge.nm_find_add_neq; ss.\n rewrite NatStructsLarge.nm_find_add_eq. ss.\n }\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT2\") as \"[DU2 INIT2]\".\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT3\") as \"[TH2 INIT3]\".\n clear H.\n\n iPoseProof (ObligationRA.white_split_eq with \"OBLIG2\") as \"[O0 O1]\".\n iPoseProof (ObligationRA.duty_alloc with \"DU1 O0\") as \"> DU\".\n iPoseProof (ObligationRA.duty_correl with \"DU\") as \"#CORREL\".\n { ss. eauto. }\n\n iSplitL \"B3 OBLIG1 SHOT OBPEND1 WPOINTS\".\n { unfold thread1_will_write.\n iModIntro. iExists View.bot. iFrame. iExists k.\n iSplitL \"OBLIG1\". { iExists _. iFrame. }\n iSplitR. { iExists _. eauto. }\n iSplitL \"SHOT\". { iApply \"SHOT\". }\n iLeft. iFrame. iApply (init_points_to_wpoints_to with \"WPOINTS\").\n }\n\n (*\n Check FairRA.blacks_unfold.\n Search FairRA.blacks.\n set (s0 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => False%type\n | inr _ => True%type\n end).\n set (s1 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => i = inl tid1\n | inr _ => True%type\n end).\n set (s2 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => i = inl tid1 \\/ i = inl tid2\n | inr _ => True%type\n end).\n Check FairRA.blacks_unfold s1 s0.\n *)\n (* iPoseProof (FairRA.blacks_unfold s1 s0 with \"BLACK\") as \"BLACK\". *)\n\n (* FairRA.blacks_unfold *)\n (* black_to_duty *)\n\n iSplitL \"B1 B2 W2 W3 B4 W4 E1 E2 MBLACK INIT1 INIT5\".\n { unfold lock_will_unlock.\n iExists false, View.bot, false, WMem.init, (NatMap.empty nat), 0.\n iModIntro.\n iFrame.\n iSplitL \"INIT5\". { ss. unfold OMod.closed_st_init, Mod.st_init. ss.\n rewrite key_set_empty_empty_eq. iFrame. }\n iSplitL \"INIT1\". { iApply FairRA.blacks_impl.\n 2: { iFrame. }\n i. des. subst. ss. }\n iSplitR. { ss. }\n iSplitL \"W2 W3 W4 E2\". { iLeft. iFrame. ss. }\n { iLeft. iFrame. ss. }\n }\n\n iSplitL \"O1 OBPEND2 TH1 DU\".\n { iExists k. iSplitL \"TH1\"; ss. iModIntro. iFrame. auto. }\n iModIntro. iFrame.\n Qed.\n\n (*\n Definition thread1_will_write (tvw: View.t) : iProp :=\n ∃ k, (∃ n, ObligationRA.black k n)\n ∗\n (ObligationRA.correl_thread k 1%ord)\n ∗\n (OwnM (OneShot.shot k))\n ∗\n ((ObligationRA.pending k (/2)%Qp ∗ wpoints_to loc_X const_0 tvw)\n ∨\n (ObligationRA.shot k ∗ wpoints_to loc_X const_42 tvw)).\n\n\n Definition lock_will_unlock : iProp :=\n ∃ (own: bool) (tvw: View.t) (ing: bool) (mem: WMem.t) (wobl: NatMap.t nat) (j: nat),\n (OwnM (Auth.black (Some wobl: NatMapRALarge.t nat)))\n ∗\n ((OwnM (Auth.black (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.black (Excl.just (tvw, tt): Excl.t (View.t * unit)%type))))\n ∗\n (wmemory_black mem)\n ∗\n (St_tgt (tt, (mem, (((own, tvw), ing), key_set wobl))))\n ∗\n (FairRA.blacks (fun id => exists t, (id = (inr (inr (inr t)))) /\\ (~ NatMap.In t wobl)))\n ∗\n (natmap_prop_sum wobl\n (fun tid idx =>\n (own_thread tid)\n ∗\n (ObligationRA.correl (inr (inr (inr tid))) idx o_w_cor)\n ∗\n (ObligationRA.pending idx 1)\n ∗\n (ObligationRA.duty (inr (inr (inr tid))) [(idx, o_w_cor)])\n ))\n ∗\n (\n ((⌜own = false⌝)\n ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit)%type)))\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n )\n ∨\n (* ((⌜own = true⌝) *)\n (* ∗ (ObligationRA.pending j 1) *)\n (* ∗ (ObligationRA.black j o_w_cor) *)\n (* ∗ (ObligationRA.correl_thread j 1%ord) *)\n (* ∗ (natmap_prop_sum wobl (fun _ idx => ObligationRA.amplifier j idx 1%ord)) *)\n (* ) *)\n )\n ∗\n (\n ((⌜ing = false⌝)\n ∗ (OwnM (Excl.just (tt, tt): Excl.t (unit * unit)%type))\n )\n ∨\n (* ((⌜ing = true⌝) *)\n (* ∗ (OwnM (Excl.just tt: Excl.t unit)) *)\n (* ) *)\n )\n .\n *)\n End INITIAL.\n\n Lemma AbsLock_lock\n R_src R_tgt tid\n (src: thread void (sE unit) R_src)\n tgt\n r g\n (Q: R_src -> R_tgt -> iProp)\n (l: list (nat * Ord.t)%type)\n (num_line: nat)\n (tvw0: View.t)\n :\n ((own_thread tid)\n ∗\n (ObligationRA.duty (inl tid) l)\n ∗\n (ObligationRA.taxes\n l ((((Ord.omega × Ord.omega) × Ord.omega)\n ⊕\n ((Ord.S Ord.O) × (o_w_cor)))\n ⊕ 9)%ord))\n ∗\n (∀ tvw1,\n ((⌜View.le tvw0 tvw1⌝)\n ∗\n (own_thread tid)\n ∗\n (∃ j, (ObligationRA.duty (inl tid) ((j, Ord.S Ord.O) :: l))\n ∗\n (ObligationRA.white j (Ord.omega × (Ord.from_nat num_line))%ord)\n ∗\n (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n )\n ∗\n (∃ tvw,\n (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit))))\n ∗ (⌜(View.le tvw tvw1)⌝)\n )\n ∗\n (OwnM (Excl.just tt: Excl.t unit))\n )\n -∗\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tgt tvw1)))\n ⊢\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tvw' <- (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (R:=View.t) (OMod.call \"lock\" tvw0));; (tgt tvw'))).\n Proof.\n Opaque key_set.\n iIntros \"[[TH [DUTY TAXES]] SIM]\".\n rewrite close_itree_call. ss. rred. unfold OMod.emb_callee, emb_r. rewrite <- map_event_compose. rewrite <- plmap_compose.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"TAXES\".\n { eapply Hessenberg.lt_add_r. apply OrdArith.lt_from_nat. instantiate (1:=8). auto. }\n iMod \"TAXES\". iDestruct \"TAXES\" as \"[TAXES TAX]\".\n\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n unfold AbsLockW.lock_fun, Mod.wrap_fun. rred.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"TAXES\".\n { eapply Hessenberg.lt_add_r. apply OrdArith.lt_from_nat. instantiate (1:=7). auto. }\n iMod \"TAXES\". iDestruct \"TAXES\" as \"[TAXES TAX]\".\n\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tidR. rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iPoseProof (ObligationRA.alloc\n (((Ord.omega × Ord.omega) × Ord.omega)\n ⊕ ((Ord.S Ord.O) × (o_w_cor)))%ord) as \"A\".\n iMod \"A\" as \"[% [[MYB MYW] PEND]]\".\n iPoseProof (ObligationRA.white_split_eq with \"MYW\") as \"[MYW YOUW]\".\n iDestruct \"I1\" as \"[BLKS [SUM [CASES INGS]]]\".\n\n iAssert (⌜~ NatMap.In tid wobl⌝)%I as \"%\".\n { iAssert (⌜(NatMap.In tid wobl)⌝ ∨ ⌜(~ NatMap.In tid wobl)⌝)%I as \"%\".\n { iPureIntro. pose NatMapP.F.In_dec. specialize (s _ wobl tid). destruct s; auto. }\n destruct H as [IN | NI].\n 2: auto.\n iPoseProof (natmap_prop_sum_impl with \"SUM\") as \"SUM\".\n { instantiate (1:= fun tid0 idx => own_thread tid0). i. iIntros \"[F1 F2]\". iFrame. }\n apply NatMapP.F.in_find_iff in IN.\n destruct (NatMap.find tid wobl) eqn:FIND; ss.\n iPoseProof (natmap_prop_sum_in with \"SUM\") as \"TH2\". eauto.\n iPoseProof (own_thread_unique with \"TH TH2\") as \"F\". iPure \"F\" as F. ss.\n }\n\n (* update ObligationRA.duty: get [] by black_to_duty, update with MYW; then correl *)\n set (blks2 :=\n (λ id : nat + (Mod.ident ClientImpl.omod + (Mod.ident (WMem.mod) + NatMap.key)),\n (∃ t : NatMap.key, id = inr (inr (inr t)) ∧ ¬ NatMap.In (elt:=nat) t (NatMap.add tid k wobl))%type)).\n iPoseProof (FairRA.blacks_unfold with \"BLKS\") as \"[BLKS MYDUTY]\".\n { instantiate (1:=inr (inr (inr tid))). instantiate (1:=blks2). i. des.\n { subst blks2. ss. des. esplits; eauto. ii; apply IN0. apply NatMapP.F.add_in_iff; auto. }\n { subst blks2. ss. esplits; eauto. }\n }\n { subst blks2. ss. ii. des. clarify. apply H1. apply NatMapP.F.add_in_iff. auto. }\n iPoseProof (black_to_duty with \"MYDUTY\") as \"MYDUTY\".\n iPoseProof (ObligationRA.duty_alloc with \"MYDUTY\") as \"MYDUTY\".\n iPoseProof (\"MYDUTY\" with \"MYW\") as \"> MYDUTY\".\n iPoseProof (ObligationRA.duty_correl with \"MYDUTY\") as \"# MYCOR\".\n { ss. left; eauto. }\n\n (* make (Auth.white singleton tid k) and update wobl *)\n iPoseProof (OwnM_Upd with \"B1\") as \"OWN1\".\n { eapply Auth.auth_alloc. instantiate (1:=NatMapRALarge.singleton tid k).\n instantiate (1:=Some (NatMap.add tid k wobl)). eapply NatMapRALarge.add_local_update.\n eapply NatMapP.F.not_find_in_iff; auto.\n }\n iMod \"OWN1\" as \"[OWNB1 MYSING]\".\n\n (* need to make amp; need ObligationRA.black j *)\n iAssert (\n (\n (⌜own = false⌝ **\n (OwnM (Auth.white (Excl.just j: Excl.t nat))\n ** (OwnM (Auth.white (Excl.just tvw: Excl.t View.t))\n ** (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit))) ** OwnM (Excl.just tt: Excl.t unit)))\n ))\n ∨ (⌜own = true⌝ **\n (ObligationRA.pending j 1 **\n (ObligationRA.black j o_w_cor **\n (ObligationRA.correl_thread j 1 **\n natmap_prop_sum wobl (λ _ idx : nat, ObligationRA.amplifier j idx 1))))))\n ∗\n #=( ObligationRA.edges_sat )=>((⌜own = true⌝) -∗ (ObligationRA.amplifier j k 1))\n )%I\n with \"[CASES YOUW]\" as \"[CASES AMP]\".\n { iDestruct \"CASES\" as \"[OWNF | [OT [PEND [JBLK [JCOR ALLAMP]]]]]\".\n { iDestruct \"OWNF\" as \"[% OW]\". iSplitL \"OW\". iLeft. iFrame. auto.\n iModIntro. iIntros \"OT\". iPure \"OT\" as OT. clarify.\n }\n iPoseProof (\"JBLK\") as \"# JBLK\". iSplitR \"YOUW\".\n { iRight. iFrame. auto. }\n iPoseProof (ObligationRA.amplifier_intro with \"JBLK\") as \"AMP\".\n iPoseProof (\"AMP\" with \"YOUW\") as \"AMP2\". iMod \"AMP2\". iModIntro.\n iIntros \"OT\". iFrame.\n }\n iMod \"AMP\".\n\n (* now close invariant *)\n iMod (\"K1\" with \"[TH OWNB1 B2 MEM SUM CASES INGS STGT PEND BLKS MYDUTY MYCOR AMP]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw, ing, mem, (NatMap.add tid k wobl), j. iFrame.\n rewrite key_set_pull_add_eq. iFrame. iSplitL \"SUM TH MYDUTY MYCOR PEND\".\n { iApply (natmap_prop_sum_add with \"SUM\"). iFrame. auto. }\n iDestruct \"CASES\" as \"[OWNF | [OT [PEND [JBLK [JCOR ALLAMP]]]]]\". iFrame.\n iRight. iPure \"OT\" as OT. iFrame. iSplit; auto.\n iApply (natmap_prop_sum_add with \"ALLAMP\"). iApply \"AMP\". auto.\n }\n { msubtac. }\n\n (* induction *)\n rred. iApply stsim_discard.\n { instantiate (1:=topset I). msubtac. }\n remember (((Ord.omega × Ord.omega) × Ord.omega)\n ⊕ Ord.S Ord.O × o_w_cor)%ord as wd.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAXKEEP]\".\n { instantiate (1:= (wd ⊕ 6)%ord). apply Hessenberg.lt_add_r.\n apply OrdArith.lt_from_nat. lia.\n }\n remember (wd ⊕ 6)%ord as credit.\n assert (RICH: (wd < credit)%ord).\n { subst; apply Hessenberg.add_lt_l. rewrite <- Ord.from_nat_O.\n apply OrdArith.lt_from_nat. lia.\n }\n clear Heqwd Heqcredit.\n clear own mem blks2 j H wobl. iClear \"MYCOR\".\n iStopProof. revert l k credit RICH. pattern wd. revert wd.\n apply (well_founded_induction Ord.lt_well_founded). intros wd IH. intros l k credit RICH.\n iIntros \"[SIM [DUTY [MYB [MYW [TAXES TAXKEEP]]]]]\".\n rewrite unfold_iter_eq. rred.\n\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\". eauto.\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY WTH\". rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n destruct own.\n\n (* someone is holding the lock *)\n { rred. iApply stsim_tauR. rred.\n\n iAssert (⌜NatMap.find tid wobl = Some k⌝)%I as \"%\".\n { iPoseProof (OwnM_valid with \"[MYW B1]\") as \"%\".\n { instantiate (1:= (Auth.black (Some wobl: NatMapRALarge.t nat)) ⋅ (Auth.white (NatMapRALarge.singleton tid k: NatMapRALarge.t nat))). iSplitL \"B1\"; iFrame. }\n eapply Auth.auth_included in H. eapply NatMapRALarge.extends_singleton_iff in H.\n auto.\n }\n rename H into FIND.\n\n iDestruct \"I1\" as \"[BLKS [SUM [CASES INGS]]]\".\n iDestruct \"CASES\" as \"[[%OWNF [LOCK EXCL]] | [%OWNT [JPEND [JBLK [#JCOR AMPs]]]]]\".\n { inversion OWNF. }\n\n (* induction *)\n { iAssert (ObligationRA.amplifier j k 1)%I with \"[AMPs]\" as \"#AMP\".\n { iPoseProof (natmap_prop_remove_find with \"AMPs\") as \"[# AMP AMPs]\".\n { eapply FIND. }\n auto.\n }\n iPoseProof (ObligationRA.correl_thread_correlate with \"JCOR WTH\") as \"> DEC\".\n iDestruct \"DEC\" as \"[DEC | DONE]\"; cycle 1.\n { iPoseProof (ObligationRA.pending_not_shot with \"JPEND DONE\") as \"CONTRA\". auto. }\n { iPoseProof (ObligationRA.amplifier_amplify with \"AMP DEC\") as \"> DEC\".\n iPoseProof (ObligationRA.black_white_decr with \"MYB DEC\") as \"> [% [MYB %]]\".\n assert (RENEW: (o2 < wd)%ord).\n { eapply Ord.lt_le_lt. 2: eauto. apply Hessenberg.add_lt_l.\n rewrite <- Ord.from_nat_O. rewrite <- Jacobsthal.mult_from_nat.\n apply OrdArith.lt_from_nat. ss.\n }\n iMod (\"K1\" with \"[B1 B2 MEM STGT BLKS SUM JPEND JBLK AMPs INGS]\") as \"_\".\n { unfold lock_will_unlock. iExists true, tvw1, ing0, mem, wobl, j. iFrame.\n iRight. iFrame. iSplit; auto.\n }\n { msubtac. }\n iApply IH. eapply RENEW. eapply RENEW.\n iFrame.\n }\n }\n }\n\n (* no one is holding the lock *)\n { rred.\n iClear \"TAXES\". clear IH credit RICH.\n iApply stsim_getR. iSplit. iFrame. rred.\n iDestruct \"I1\" as \"[BLKS [SUM [[[%VW [LOCK EXCL]] | [%CONTRA _]] INGS]]]\".\n 2:{ inversion CONTRA. }\n inv VW.\n iDestruct \"INGS\" as \"[[%INGF INGEX] | [_ CONTRA]]\".\n 2:{ iDestruct \"EXCL\" as \"[_ [_ EXCL]]\". iPoseProof (excl_unique with \"EXCL CONTRA\") as \"%C\". inv C. }\n subst. rred.\n\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw'. rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iAssert (⌜NatMap.find tid wobl = Some k⌝)%I as \"%\".\n { iPoseProof (OwnM_valid with \"[MYW B1]\") as \"%\".\n { instantiate (1:= (Auth.black (Some wobl: NatMapRALarge.t nat)) ⋅ (Auth.white (NatMapRALarge.singleton tid k: NatMapRALarge.t nat))). iSplitL \"B1\"; iFrame. }\n eapply Auth.auth_included in H. eapply NatMapRALarge.extends_singleton_iff in H.\n auto.\n }\n rename H into FIND.\n\n iPoseProof (natmap_prop_remove_find with \"SUM\") as \"[[MYTH [_ [MYPEND MYDUTY]]] SUM]\".\n eapply FIND. iPoseProof (ObligationRA.pending_shot with \"MYPEND\") as \"> MYDONE\".\n iPoseProof (ObligationRA.duty_done with \"MYDUTY MYDONE\") as \"> MYDUTY\".\n iApply (stsim_fairR with \"[MYDUTY]\").\n 4:{ instantiate (1:=[(inr (inr tid), [])]). ss. iFrame. }\n { clear. i. unfold prism_fmap in *. des_ifs. ss. eapply Prism.review_preview in Heq. auto. }\n { instantiate (1:= List.map (fun '(j, _) => inr (inr j)) (NatMap.elements (NatMap.remove tid (key_set wobl)))). clear. i. unfold prism_fmap.\n assert (A: exists j, (i = inr (inr j)) /\\ (NatMap.In j (NatMap.remove tid (key_set wobl)))).\n { apply in_map_iff in IN. des. des_ifs. destruct u. esplits; eauto.\n remember (NatMap.remove tid (key_set wobl)) as M. clear HeqM.\n apply NatMapP.F.elements_in_iff. exists (). apply SetoidList.InA_alt.\n exists (k, ()). ss.\n }\n des. subst. unfold Prism.preview; ss. des_ifs.\n exfalso. eapply NatMap.remove_1. reflexivity. eapply A0.\n }\n { eapply FinFun.Injective_map_NoDup.\n { unfold FinFun.Injective. i. des_ifs. destruct u, u0. ss. }\n apply NoDupA_NoDup. apply NatMap.elements_3w.\n }\n iIntros \"MYDUTY WHITES\". rred.\n\n (* close invariant *)\n iPoseProof (OwnM_Upd with \"[B1 MYW]\") as \"> B1\".\n 2:{ instantiate (1:= (Auth.black (Some wobl: NatMapRALarge.t nat)) ⋅ (Auth.white (NatMapRALarge.singleton tid k: NatMapRALarge.t nat))). iSplitL \"B1\"; iFrame. }\n { eapply Auth.auth_dealloc. eapply NatMapRALarge.remove_local_update. }\n rewrite <- key_set_pull_rm_eq in *. remember (NatMap.remove tid wobl) as new_wobl.\n\n iPoseProof (MonotonePCM.list_prop_sum_cons_unfold with \"MYDUTY\") as \"[MYDUTY _]\".\n iPoseProof (duty_to_black with \"MYDUTY\") as \"MYBEX\".\n iPoseProof (FairRA.blacks_fold with \"[BLKS MYBEX]\") as \"BLKS\".\n 2:{ iFrame. }\n { instantiate (1:=\n (λ id : nat + (Mod.ident ClientImpl.omod + (Mod.ident (WMem.mod) + NatMap.key)),\n ∃ t : NatMap.key, id = inr (inr (inr t)) ∧ ¬ NatMap.In (elt:=nat) t new_wobl)).\n i. ss. des. destruct (tid_dec t tid) eqn:DEC.\n - clarify. auto.\n - left. esplits; eauto. ii. apply IN0. subst. apply NatMapP.F.remove_in_iff.\n split; auto.\n }\n\n ss. repeat (unfold Lens.set; ss).\n iClear \"MYB\".\n clear Heqnew_wobl FIND wd k wobl.\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (ObligationRA.alloc o_w_cor) as \"> [% [[NEWB NEWW] NEWP]]\".\n iPoseProof (OwnM_Upd with \"[B2 LOCK]\") as \"> B2\".\n 2:{ instantiate (1:= (Auth.black (Excl.just j: Excl.t nat)) ⋅ (Auth.white (Excl.just j: Excl.t nat))). iSplitL \"B2\"; iFrame. }\n { eapply Auth.auth_update. do 2 instantiate (1:=Excl.just k).\n clear. ii. des. split.\n - ur. ss.\n - ur. ur in FRAME. des_ifs.\n }\n iDestruct \"B2\" as \"[B2 LOCK]\". clear j.\n\n iAssert (natmap_prop_sum new_wobl (fun tid0 idx => ObligationRA.correl (inr (inr (inr tid0))) idx (Ord.omega × Ord.omega)%ord)) with \"[SUM]\" as \"#CORs\".\n { iApply natmap_prop_sum_impl. 2: iFrame.\n i. iIntros \"[_ [CORS _]]\". iFrame.\n }\n iPoseProof (ObligationRA.white_mon with \"NEWW\") as \"> NEWW\".\n { unfold o_w_cor. instantiate (1:= (Ord.omega × (Ord.S (Ord.S num_line)))%ord).\n apply Ord.lt_le. apply Jacobsthal.lt_mult_r.\n rewrite <- Ord.from_nat_S. rewrite <- Ord.from_nat_S. apply Ord.omega_upperbound.\n rewrite <- Ord.from_nat_O. apply Ord.omega_upperbound.\n }\n iPoseProof (ObligationRA.white_eq with \"NEWW\") as \"NEWW\".\n { apply Jacobsthal.mult_S. }\n iPoseProof (ObligationRA.white_split_eq with \"NEWW\") as \"[NEWW1 NEWW2]\".\n iPoseProof (ObligationRA.white_eq with \"NEWW2\") as \"NEWW2\".\n { apply Jacobsthal.mult_S. }\n iPoseProof (ObligationRA.white_split_eq with \"NEWW2\") as \"[NEWWTAX NEWW2]\".\n iPoseProof (ObligationRA.white_eq with \"NEWW1\") as \"NEWW1\".\n { symmetry. apply Jacobsthal.mult_1_l. }\n iPoseProof (ObligationRA.duty_alloc with \"DUTY NEWW1\") as \"> DUTY\".\n iPoseProof (ObligationRA.duty_correl_thread with \"DUTY\") as \"#NEWCORTH\".\n { ss. left; eauto. }\n\n (* need amps == need pendings; *)\n iAssert (natmap_prop_sum new_wobl (fun k _ => FairRA.white (inr (inr (inr k))) 1))%I with \"[WHITES]\" as \"WHITES\".\n { Transparent key_set. unfold key_set. rewrite <- list_map_elements_nm_map. unfold natmap_prop_sum.\n remember (NatMap.elements new_wobl) as ml. clear Heqml. rewrite List.map_map.\n iClear \"CORs NEWCORTH\". clear. iStopProof. induction ml.\n { iIntros \"SUM\". ss. }\n ss. des_ifs. iIntros \"[WH SUM]\". iFrame. iApply IHml. auto.\n }\n iPoseProof (natmap_prop_sum_impl2 with \"[WHITES]\") as \"CASES\".\n 2:{ iSplitR \"WHITES\". iApply \"CORs\". iApply \"WHITES\". }\n { i. ss. iIntros \"[COR WH]\". iApply (ObligationRA.correl_correlate with \"COR WH\"). }\n Unshelve. 2,3: auto.\n iPoseProof (natmap_prop_sum_pull_bupd with \"CASES\") as \"CASES\". iMod \"CASES\".\n iPoseProof (natmap_prop_sum_or_cases_l with \"CASES\") as \"[WHITEs|SHOT]\"; cycle 1.\n { iDestruct \"SHOT\" as \"[% [% [%FIND SHOT]]]\".\n iPoseProof (natmap_prop_sum_in with \"SUM\") as \"[_ [_ [PEND _]]]\". eapply FIND.\n iPoseProof (ObligationRA.pending_not_shot with \"PEND SHOT\") as \"FALSE\". ss.\n }\n iPoseProof \"NEWB\" as \"#NEWB\".\n iPoseProof (natmap_prop_sum_sepconj with \"[WHITEs]\") as \"WHITEs\".\n { iSplitR \"WHITEs\". 2: iApply \"WHITEs\".\n instantiate (1:=fun _ _ => ObligationRA.black k o_w_cor).\n iClear \"CORs NEWCORTH\". unfold natmap_prop_sum. remember (NatMap.elements new_wobl) as ml.\n clear. iStopProof. induction ml; ss. auto.\n iIntros \"#BLK\". des_ifs. iSplit; auto. iApply IHml. auto.\n }\n iPoseProof (natmap_prop_sum_impl with \"WHITEs\") as \"AMPs\".\n { i. ss. iIntros \"[BLK WHI]\".\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { symmetry. apply Jacobsthal.mult_1_l. }\n iPoseProof (ObligationRA.amplifier_intro with \"BLK WHI\") as \"AMP\". iApply \"AMP\".\n }\n iPoseProof (natmap_prop_sum_pull_bupd with \"AMPs\") as \"> AMPs\".\n\n iDestruct \"EXCL\" as \"[EXCL [EXCL2 EXCL3]]\".\n iPoseProof (black_white_update with \"B3 EXCL2\") as \">[B3 EXCL2]\".\n instantiate (1:= (tvw1, tt)).\n\n iMod (\"K1\" with \"[B1 B2 B3 MEM STGT BLKS SUM NEWP AMPs INGEX]\") as \"_\".\n { unfold lock_will_unlock. iExists true, tvw1, false, mem, new_wobl, k. iFrame. iSplitR \"INGEX\".\n - iRight. iFrame. auto.\n - iLeft. iFrame. auto.\n }\n { msubtac. }\n iApply stsim_discard. instantiate (1:=topset I). msubtac.\n\n iApply (stsim_yieldR with \"[DUTY TAXKEEP NEWWTAX]\"). msubtac.\n { iSplitL \"DUTY\". iFrame. iFrame. iApply ObligationRA.white_eq.\n { symmetry. apply Jacobsthal.mult_1_l. }\n iFrame.\n }\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n\n (* iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [I0B I0]]\". *)\n (* iDestruct \"I0\" as \"[% I0]\". iDestruct \"I0\" as \"[I01 [I02 [I03 I04]]]\". *)\n (* iPoseProof (black_white_equal with \"I0B EXCL\") as \"%\". subst. *)\n (* iAssert ( *)\n (* ((ObligationRA.pending k0 (/ 2) ** wpoints_to loc_X const_0 tvw1) *)\n (* ∨ (ObligationRA.shot k0 ** wpoints_to loc_X const_42 tvw1)) *)\n (* -∗ *)\n (* ((ObligationRA.pending k0 (/ 2) ** wpoints_to loc_X const_0 tvw') *)\n (* ∨ (ObligationRA.shot k0 ** wpoints_to loc_X const_42 tvw')) *)\n (* )%I with \"[]\" as \"I04a\". *)\n (* { iIntros \"I\". iDestruct \"I\" as \"[[A B] | [A B]]\". *)\n (* - iLeft. iFrame. iApply wpoints_to_view_mon. 2: iFrame. *)\n (* etrans. 2: eapply l0. apply View.join_r. *)\n (* - iRight. iFrame. iApply wpoints_to_view_mon. 2: iFrame. *)\n (* etrans. 2: eapply l0. apply View.join_r. *)\n (* } *)\n (* iPoseProof (\"I04a\" with \"I04\") as \"I04\". *)\n (* iPoseProof (black_white_update with \"I0B EXCL\") as \">[I0B EXCL]\". *)\n (* instantiate (1:= tvw1). *)\n (* iMod (\"K0\" with \"[I0B I01 I02 I03 I04]\") as \"_\". *)\n (* { iExists tvw1. iFrame. unfold thread1_will_write. iExists k0. iFrame. } *)\n (* msubtac. *)\n\n iPoseProof (\"SIM\" with \"[MYTH DUTY NEWW2 EXCL EXCL2 EXCL3 LOCK]\") as \"SIM\".\n { instantiate (1:= tvw'). iFrame. iSplit.\n { iPureIntro. etrans. 2: eapply l0. apply View.join_l. }\n iSplitL \"DUTY NEWW2 LOCK\". iExists k. iFrame.\n iExists _. iFrame. iPureIntro.\n etrans. 2: eapply l0. apply View.join_r.\n }\n iApply stsim_reset. iFrame.\n }\n\n Qed.\n\n Lemma AbsLock_unlock\n R_src R_tgt tid\n (src: thread void (sE unit) R_src)\n tgt\n r g\n (Q: R_src -> R_tgt -> iProp)\n l\n (tvw0 lvw: View.t)\n :\n ((OwnM (Excl.just tt: Excl.t unit))\n ∗\n (OwnM (Auth.white (Excl.just tvw0: Excl.t View.t)))\n ∗\n ((OwnM (Auth.white (Excl.just (lvw, tt): Excl.t (View.t * unit)))) ∗ (⌜View.le lvw tvw0⌝))\n ∗\n (∃ k, (ObligationRA.duty (inl tid) ((k, Ord.S Ord.O) :: l))\n ∗ (OwnM (Auth.white (Excl.just k: Excl.t nat)))\n ∗ (ObligationRA.taxes ((k, Ord.S Ord.O) :: l) 4%ord))\n )\n ∗\n (∀ tvw1,\n ((ObligationRA.duty (inl tid) l)\n ∗ (⌜View.le tvw0 tvw1⌝)\n )\n -∗\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tgt tvw1)))\n ⊢\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tvw' <- OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (R:=View.t) (OMod.call \"unlock\" tvw0);; (tgt tvw'))).\n Proof.\n iIntros \"[[EXCLTT [EXCL [[EXCL2 %LVW] [% [DUTY [LOCK TAXES]]]]]] SIM]\".\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\".\n { instantiate (1:= 3%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX1]\".\n { instantiate (1:= 2%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX2]\".\n { instantiate (1:= 1%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_single_is_tax with \"TAXES\") as \"TAX3\".\n\n rewrite close_itree_call. ss. rred. unfold OMod.emb_callee, emb_r. rewrite <- map_event_compose. rewrite <- plmap_compose.\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n unfold AbsLockW.unlock_fun, Mod.wrap_fun. rred.\n iApply (stsim_yieldR with \"[DUTY TAX1]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT [BLKS [SUM [[CONTRA | CASE] INGS]]]]]]]\".\n { iDestruct \"CONTRA\" as \"[_ [_ [EXCL3 _]]]\".\n iPoseProof (white_white_excl with \"EXCL EXCL3\") as \"%FF\". inversion FF.\n }\n iDestruct \"CASE\" as \"[% [JPEND [JBLK [JCOR AMPs]]]]\". subst own.\n iApply stsim_getR. iSplit. iFrame. ss.\n\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (black_white_equal with \"B3 EXCL2\") as \"%EQ\". inv EQ.\n destruct (excluded_middle_informative (View.le lvw tvw0)).\n 2:{ rred. exfalso. clarify. }\n\n rred. iDestruct \"INGS\" as \"[[%INGF INGEXCL] | [_ CONTRA]]\".\n 2:{ iPoseProof (excl_unique with \"EXCLTT CONTRA\") as \"%FF\". inv FF. }\n subst ing. rred. ss. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred. ss. repeat (unfold Lens.set; ss).\n\n iPoseProof (black_white_equal with \"B2 LOCK\") as \"%EQ\". subst k.\n iMod (\"K1\" with \"[EXCLTT B1 B2 B3 MEM BLKS SUM STGT JPEND JBLK JCOR AMPs]\") as \"_\".\n { unfold lock_will_unlock. iExists true, lvw, true, mem, wobl, j. iFrame. iSplitR \"EXCLTT\".\n - iRight. iSplit. auto. iFrame.\n - iRight. iSplit. auto. iFrame.\n }\n msubtac.\n iApply (stsim_yieldR with \"[DUTY TAX2]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT [BLKS [SUM [[CONTRA | CASE] INGS]]]]]]]\".\n { iDestruct \"CONTRA\" as \"[_ [_ [_ [CONTRA _]]]]\".\n iPoseProof (white_white_excl with \"EXCL2 CONTRA\") as \"%FF\". inversion FF.\n }\n iDestruct \"CASE\" as \"[% [JPEND [JBLK [JCOR AMPs]]]]\". subst own.\n\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (black_white_equal with \"B3 EXCL2\") as \"%EQ\". inv EQ.\n iDestruct \"INGS\" as \"[[_ CONTRA] | [%INGT EXCLTT]]\".\n { iPoseProof (excl_unique with \"INGEXCL CONTRA\") as \"%FF\". inv FF. }\n subst ing. rred.\n\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw_V. rewrite put_rmw. rred.\n (* iApply stsim_chooseR. iIntros \"%\". rename x into tvw_V. rred. *)\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw'. rred.\n\n iPoseProof (black_white_equal with \"B2 LOCK\") as \"%\". subst.\n iPoseProof (black_white_update with \"B3 EXCL2\") as \">[B3 EXCL2]\".\n instantiate (1:= (tvw_V, tt)).\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [I0B I0]]\".\n iDestruct \"I0\" as \"[% I0]\". iDestruct \"I0\" as \"[I01 [I02 [I03 I04]]]\".\n iPoseProof (black_white_equal with \"I0B EXCL\") as \"%\". subst.\n iAssert (\n ((ObligationRA.pending k (/ 2) ** wpoints_to loc_X const_0 tvw0)\n ∨ (ObligationRA.shot k ** wpoints_to loc_X const_42 tvw0))\n -∗\n ((ObligationRA.pending k (/ 2) ** wpoints_to loc_X const_0 tvw_V)\n ∨ (ObligationRA.shot k ** wpoints_to loc_X const_42 tvw_V))\n )%I with \"[]\" as \"I04a\".\n { iIntros \"I\". iDestruct \"I\" as \"[[A B] | [A B]]\".\n - iLeft. iFrame. iApply wpoints_to_view_mon. 2: iFrame. auto.\n - iRight. iFrame. iApply wpoints_to_view_mon. 2: iFrame. auto.\n }\n iPoseProof (\"I04a\" with \"I04\") as \"I04\".\n iPoseProof (black_white_update with \"I0B EXCL\") as \">[I0B EXCL]\".\n instantiate (1:= tvw_V).\n\n iMod (\"K0\" with \"[I0B I01 I02 I03 I04]\") as \"_\".\n { iExists tvw_V. iFrame. unfold thread1_will_write. iExists k. iFrame. }\n iMod (\"K1\" with \"[INGEXCL EXCLTT EXCL EXCL2 LOCK B1 B2 B3 MEM BLKS SUM STGT]\") as \"_\".\n { unfold lock_will_unlock. iExists false, tvw_V, false, mem0, wobl0, j. iFrame. iSplitR \"INGEXCL\".\n - iLeft. iSplit. auto. iFrame.\n - iLeft. iSplit. auto. iFrame.\n }\n { msubtac. }\n iPoseProof (ObligationRA.pending_shot with \"JPEND\") as \"> SHOT\".\n iPoseProof (ObligationRA.duty_done with \"DUTY SHOT\") as \"> DUTY\".\n\n (* iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw''. rred. *)\n (* iApply stsim_tauR. rred. *)\n\n iApply (stsim_yieldR with \"[DUTY TAX3]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iPoseProof (ObligationRA.tax_cons_unfold with \"TAX3\") as \"[_ TAX2]\". iFrame.\n }\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_reset. iApply \"SIM\". iFrame.\n iPureIntro. etrans. 2: eapply l2. auto.\n\n Qed.\n\n Lemma correct_thread1 tid:\n (∃ k, (own_thread tid)\n ∗ (ObligationRA.duty (inl tid) [(k, Ord.from_nat 1)])\n ∗ (ObligationRA.taxes\n [(k, Ord.from_nat 1)]\n ((((Ord.omega × Ord.omega) × Ord.omega) ⊕ ((Ord.S Ord.O) × (o_w_cor))) ⊕ 10)%ord\n )\n ∗ (OwnM (OneShot.shot k))\n ∗ (ObligationRA.pending k (/ 2))\n )\n ⊢\n (stsim I tid (topset I) ibot7 ibot7\n (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n false false\n (ClientSpec.thread1 tt)\n (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (ClientImpl.thread1 tt))).\n Proof.\n iIntros \"[% [TH [DUTY [TAXES [#KSHOT KPENDh]]]]]\".\n unfold ClientSpec.thread1, ClientImpl.thread1. rred.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\".\n { apply Hessenberg.lt_add_r. instantiate (1:=9). apply OrdArith.lt_from_nat. auto. }\n iApply AbsLock_lock. iFrame.\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:=9). rred.\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1 TAX]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY _\". rred. unfold WMem.store_fun, Mod.wrap_fun. rred.\n\n iopen 0 \"I0\" \"K0\".\n iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw0.\n\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n 2:{ iDestruct \"i0SHOT\" as \"[i0SHOT PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"KPENDh i0SHOT\") as \"FALSE\". ss.\n }\n iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_sum with \"KPENDh i0PENDh\") as \"KPEND\".\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\". rred.\n destruct x. destruct x as [[[lc1 to] sc1] mem1]. des. rename y into WRITE.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_store with \"i1MEM i0PTR\") as \"[%VW2 >[i1MEM i0PTR]]\".\n eapply WRITE. eauto. eauto. eauto. eauto.\n\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n (* instantiate (1:= [inr (inl (loc_X, to))]) in IN. *)\n (* inv IN; ss. des_ifs. *)\n { econs. }\n { auto. }\n iIntros \"_ _\". rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"i1STGT\"). iIntros \"i1STGT\". rred. iApply stsim_tauR. rred.\n\n rewrite Qp.inv_half_half.\n iPoseProof (ObligationRA.pending_shot with \"KPEND\") as \"> #OBLKSHOT\".\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists (TView.TView.cur tview). iFrame.\n unfold thread1_will_write. iExists k. iFrame. iSplitR; auto. }\n\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, _, wobl, j0. iFrame. }\n msubtac.\n\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n\n iPoseProof (ObligationRA.duty_permutation with \"DUTY\") as \"DUTY\".\n { eapply perm_swap. }\n iPoseProof (ObligationRA.duty_done with \"DUTY OBLKSHOT\") as \"> DUTY\".\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"EXCL EXCL2 EXCLTT LOCK WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. eapply VW1. auto. }\n iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW3]\". rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_ret. iApply MUpd_intro. iFrame. auto.\n\n Qed.\n\n Lemma correct_thread2 tid:\n ((own_thread tid)\n ∗ (ObligationRA.duty (inl tid) [])\n )\n ⊢\n (stsim I tid (topset I) ibot7 ibot7\n (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n false false\n (ClientSpec.thread2 tt)\n (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (ClientImpl.thread2 tt))).\n Proof.\n iIntros \"[MYTH DUTY]\".\n unfold ClientSpec.thread2, ClientImpl.thread2. rred.\n iopen 0 \"I0\" \"K0\".\n iDestruct \"I0\" as \"[% [EXCLB I0]]\". iDestruct \"I0\" as \"[% [[% #KBLK] [#KCOR [#KSHOT I0]]]]\".\n iMod (\"K0\" with \"[EXCLB I0]\") as \"_\".\n { iExists tvw. iFrame. unfold thread1_will_write. iExists k. iFrame. auto. }\n { msubtac. }\n\n (* induction *)\n rred. iApply stsim_discard.\n { instantiate (1:=topset I). msubtac. }\n remember View.bot as tvw_base. clear tvw Heqtvw_base.\n iStopProof. revert tid k tvw_base. pattern n. revert n.\n apply (well_founded_induction Ord.lt_well_founded). intros n IH. intros.\n iIntros \"[#[KBLK [KCOR KSHOT]] [MYTH DUTY]]\".\n rewrite unfold_iter_eq. rred.\n iApply AbsLock_lock. iSplitL \"MYTH DUTY\".\n { iFrame. }\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:= 9). rred.\n\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY OWHTH\". rred. unfold WMem.load_fun, Mod.wrap_fun. rred.\n\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw0.\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n\n (* iterate case *)\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW2 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR i0PENDh]\") as \"_\".\n { iExists (TView.TView.cur tview). iFrame. unfold thread1_will_write. iExists k. iFrame. iSplitR; auto. iLeft; iFrame. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW3]\". rred. iApply stsim_tauR. rred.\n iClear \"i0KSHOT\".\n iPoseProof (ObligationRA.correl_thread_correlate with \"KCOR OWHTH\") as \"> [KWHI|#KDONE]\".\n (* thread 1 not done; induction *)\n { iPoseProof (ObligationRA.black_white_decr_one with \"KBLK KWHI\") as \"> [% [#KBLK2 %DECR]]\".\n iClear \"KBLK\". iApply stsim_reset. iApply IH. apply DECR. iFrame. eauto.\n }\n\n (* thread 1 done; exit *)\n { iClear \"KBLK KCOR\". clear_upto I.\n rewrite unfold_iter_eq. rred.\n iApply stsim_reset. iApply AbsLock_lock. iSplitL \"MYTH DUTY\".\n { iFrame. }\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:= 9). rred.\n\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"i0PENDh KDONE\") as \"FALSE\". ss.\n }\n iDestruct \"i0SHOT\" as \"[_ i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n msubtac.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY _\". rred. unfold WMem.load_fun, Mod.wrap_fun. rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iClear \"i0KSHOT\". iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"i0PENDh KDONE\") as \"FALSE\". ss.\n }\n iDestruct \"i0SHOT\" as \"[_ i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw4.\n\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW3 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw3, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 promises to released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW4]\". rred.\n\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_observe. iIntros. rred.\n iApply stsim_tauR. rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_ret.\n iApply MUpd_intro. iFrame. auto.\n }\n }\n\n { iDestruct \"i0SHOT\" as \"[#KDONE i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW3 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 promises to released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW4]\". rred.\n\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_observe. iIntros. rred.\n iApply stsim_tauR. rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_ret.\n iApply MUpd_intro. iFrame. auto.\n }\n\n Qed.\n\nEnd SIM.\n\nFrom Fairness Require Import WeakestAdequacy.\n\nModule LockClientWCorrect.\n Definition config := [(\"thread1\", tt↑); (\"thread2\", tt↑)].\n\n Local Instance Σ: GRA.t:=\n GRA.of_list [monoRA;\n ThreadRA;\n (stateSrcRA (unit));\n (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))));\n (identSrcRA (void));\n (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type);\n ObligationRA.t;\n (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type);\n EdgeRA;\n (@FiniteMap.t (OneShot.t unit));\n wmemRA;\n (Excl.t unit);\n (Excl.t (unit * unit));\n (OneShot.t nat);\n (Region.t (thread_id * nat));\n (@FiniteMap.t (Consent.t nat));\n (Auth.t (Excl.t nat));\n (Auth.t (Excl.t View.t));\n (Auth.t (Excl.t (View.t * unit)));\n (Auth.t (NatMapRALarge.t nat))].\n\n Local Instance MONORA: @GRA.inG monoRA Σ := (@GRA.InG _ _ 0 (@eq_refl _ _)).\n Local Instance THDRA: @GRA.inG ThreadRA Σ := (@GRA.InG _ _ 1 (@eq_refl _ _)).\n Local Instance STATESRC: @GRA.inG (stateSrcRA (unit)) Σ := (@GRA.InG _ _ 2 (@eq_refl _ _)).\n Local Instance STATETGT: @GRA.inG (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod)))) Σ := (@GRA.InG _ _ 3 (@eq_refl _ _)).\n Local Instance IDENTSRC: @GRA.inG (identSrcRA (void)) Σ := (@GRA.InG _ _ 4 (@eq_refl _ _)).\n Local Instance IDENTTGT: @GRA.inG (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ := (@GRA.InG _ _ 5 (@eq_refl _ _)).\n Local Instance OBLGRA: @GRA.inG ObligationRA.t Σ := (@GRA.InG _ _ 6 (@eq_refl _ _)).\n Local Instance ARROWRA: @GRA.inG (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ := (@GRA.InG _ _ 7 (@eq_refl _ _)).\n Local Instance EDGERA: @GRA.inG EdgeRA Σ := (@GRA.InG _ _ 8 (@eq_refl _ _)).\n Local Instance ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ := (@GRA.InG _ _ 9 (@eq_refl _ _)).\n Local Instance WMEMRA: @GRA.inG wmemRA Σ := (@GRA.InG _ _ 10 (@eq_refl _ _)).\n Local Instance EXCL: @GRA.inG (Excl.t unit) Σ := (@GRA.InG _ _ 11 (@eq_refl _ _)).\n Local Instance EXCL2: @GRA.inG (Excl.t (unit * unit)) Σ := (@GRA.InG _ _ 12 (@eq_refl _ _)).\n Local Instance ONESHOTRA: @GRA.inG (OneShot.t nat) Σ := (@GRA.InG _ _ 13 (@eq_refl _ _)).\n Local Instance REGIONRA: @GRA.inG (Region.t (thread_id * nat)) Σ := (@GRA.InG _ _ 14 (@eq_refl _ _)).\n Local Instance CONSENTRA: @GRA.inG (@FiniteMap.t (Consent.t nat)) Σ := (@GRA.InG _ _ 15 (@eq_refl _ _)).\n Local Instance AUTHNRA: @GRA.inG (Auth.t (Excl.t nat)) Σ := (@GRA.InG _ _ 16 (@eq_refl _ _)).\n Local Instance AUTHVWRA: @GRA.inG (Auth.t (Excl.t View.t)) Σ := (@GRA.InG _ _ 17 (@eq_refl _ _)).\n Local Instance AUTHVWRA2: @GRA.inG (Auth.t (Excl.t (View.t * unit))) Σ := (@GRA.InG _ _ 18 (@eq_refl _ _)).\n Local Instance AUTHNMNRA: @GRA.inG (Auth.t (NatMapRALarge.t nat)) Σ := (@GRA.InG _ _ 19 (@eq_refl _ _)).\n\n\n Let init_res :=\n (GRA.embed (OneShot.pending nat 1))\n ⋅ GRA.embed (Auth.black (Some (NatMap.empty nat) : NatMapRALarge.t nat))\n ⋅ GRA.embed (Auth.black (Excl.just 0 : Excl.t nat) ⋅ Auth.white (Excl.just 0 : Excl.t nat))\n ⋅ GRA.embed (Auth.black (Excl.just View.bot : Excl.t View.t) ⋅ Auth.white (Excl.just View.bot : Excl.t View.t))\n ⋅ GRA.embed (Auth.black (Excl.just (View.bot, ()) : Excl.t (View.t * unit))\n ⋅ Auth.white (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ⋅ GRA.embed (Excl.just (tt,tt): Excl.t (unit * unit))\n ⋅ GRA.embed (Excl.just () : Excl.t unit)\n ⋅ GRA.embed (wmem_init_res loc_X (Loc.of_nat 5))\n .\n\n Lemma correct:\n UserSim.sim ClientSpec.mod ClientImpl.mod (prog2ths ClientSpec.mod config) (prog2ths ClientImpl.mod config).\n Proof.\n eapply WSim.whole_sim_implies_usersim. econs.\n { instantiate (1:=init_res). rr. splits.\n { unfold init_res, default_initial_res. disj_tac. }\n { ndtac. }\n { unfold init_res. grawf_tac.\n { ur. auto. }\n { ur. split; auto.\n { eexists. eapply URA.unit_idl. }\n { ur. auto. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. ss. }\n { ur. ss. }\n { apply wmem_init_res_wf. ss. }\n }\n }\n unfold init_res. repeat rewrite <- GRA.embed_add.\n eexists _. iIntros \"[[[[[[[[A B] [C0 C1]] [D0 D1]] [E0 E1]] F] G] H] M]\".\n iModIntro.\n iExists [(∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t)))\n ∗ (thread1_will_write tvw))%I;\n lock_will_unlock].\n iPoseProof (init_sat with \"[A B C0 C1 D0 D1 E0 E1 F G H M]\") as \"> [[% [H0 H1]] [H2 [[% [H3 [H5 [H6 [H7 H8]]]]] H4]]]\".\n { instantiate (1:=1). instantiate (1:=0). ss. }\n { iFrame. }\n iIntros \"INIT\".\n iModIntro. ss. iFrame. iSplitL \"H0 H1\".\n { unfold nth_default. ss. iExists _. iFrame. }\n unfold MonotonePCM.natmap_prop_sum. ss.\n iSplitL \"H3 H5 H6 H7 H8\".\n { unfold fn2th. ss. unfold Mod.wrap_fun. lred. rred.\n iApply stsim_bind_top. iApply (stsim_wand with \"[H3 H5 H6 H7 H8]\").\n { iApply correct_thread1. iExists k. iFrame. }\n { iIntros (? ?) \"[H %]\". iModIntro. rred. iApply stsim_ret. iModIntro.\n iFrame. subst. auto.\n }\n }\n { unfold fn2th. ss. unfold Mod.wrap_fun. iSplitL; auto. lred. rred.\n iApply stsim_bind_top. iApply (stsim_wand with \"[H4]\").\n { iApply correct_thread2. iFrame. }\n { iIntros (? ?) \"[H %]\". iModIntro. rred. iApply stsim_ret. iModIntro.\n iFrame. subst. auto.\n }\n }\n Qed.\nEnd LockClientWCorrect.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/example/LockClientW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.21206881431678096, "lm_q1q2_score": 0.12568610008588932}} {"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import AMemory.\nRequire Import ALocal.\nRequire Import AThread.\n\nSet Implicit Arguments.\n\nModule APFConfiguration.\n\n Inductive step: forall (e:MachineEvent.t) (tid:Ident.t) (c1 c2: Configuration.t), Prop :=\n | step_intro\n e tid c1 lang st1 lc1 e2 st3 lc3 sc3 memory3\n (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n (STEPS: rtc (tau (@AThread.program_step _)) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n (STEP: AThread.program_step e e2 (Thread.mk _ st3 lc3 sc3 memory3)):\n step (ThreadEvent.get_machine_event e) tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) (Configuration.threads c1)) sc3 memory3)\n .\n #[export]\n Hint Constructors step: core.\n\n Definition step_all (c0 c1: Configuration.t) :=\n union (fun e => union (step e)) c0 c1.\n #[export]\n Hint Unfold step_all: core.\n\n Inductive opt_step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n | step_none\n tid c:\n opt_step MachineEvent.silent tid c c\n | step_some\n e tid c1 c2\n (STEP: step e tid c1 c2):\n opt_step e tid c1 c2\n .\n #[export]\n Hint Constructors opt_step: core.\n\n Lemma step_future\n e tid c1 c2\n (STEP: step e tid c1 c2)\n (WF1: Configuration.wf c1):\n Configuration.wf c2.\n Proof.\n inv WF1. inv WF. inv STEP; s.\n exploit THREADS; ss; eauto. i.\n exploit AThread.rtc_tau_step_future.\n { eapply rtc_implies; try apply STEPS. eapply tau_mon.\n i. econs. econs 2; eauto. } all: eauto. s. i. des.\n exploit AThread.step_future.\n { econs 2; eauto. } all: eauto. s. i. des.\n econs; ss. econs.\n i. Configuration.simplify.\n - exploit THREADS; try apply TH1; eauto. i. des.\n exploit AThread.rtc_tau_step_disjoint.\n { eapply rtc_implies; try apply STEPS. eapply tau_mon.\n i. econs. econs 2; eauto. } all: eauto. i. des.\n exploit AThread.step_disjoint.\n { econs 2; eauto. } all: eauto. i. des. ss.\n symmetry. auto.\n - exploit THREADS; try apply TH2; eauto. i. des.\n exploit AThread.rtc_tau_step_disjoint.\n { eapply rtc_implies; try apply STEPS. eapply tau_mon.\n i. econs. econs 2; eauto. } all: eauto. i. des.\n exploit AThread.step_disjoint.\n { econs 2; eauto. } all: eauto. i. des. ss.\n - eapply DISJOINT; [|eauto|eauto]. auto.\n - i. Configuration.simplify.\n exploit THREADS; try apply TH; eauto. i.\n exploit AThread.rtc_tau_step_disjoint.\n { eapply rtc_implies; try apply STEPS. eapply tau_mon.\n i. econs. econs 2; eauto. } all: eauto. i. des.\n exploit AThread.step_disjoint.\n { econs 2; eauto. } all: eauto. i. des. ss.\n Qed.\n\n Lemma write_no_promise mem0 loc from to val released prom1 mem1 kind\n (WRITE: AMemory.write Memory.bot mem0 loc from to val released prom1 mem1 kind)\n :\n <> /\\ <>.\n Proof.\n inv WRITE. inv PROMISE.\n - split; auto. eapply MemoryFacts.add_remove_eq; eauto.\n - eapply Memory.split_get0 in PROMISES. des.\n erewrite Memory.bot_get in GET0. clarify.\n - eapply Memory.lower_get0 in PROMISES. des.\n erewrite Memory.bot_get in GET. clarify.\n - eapply Memory.remove_get0 in PROMISES. des.\n erewrite Memory.bot_get in GET. clarify.\n Qed.\n\n Lemma program_step_no_promise lang (th0 th1: Thread.t lang) e\n (STEP: AThread.program_step e th0 th1)\n (NOPROMISE: (Local.promises (Thread.local th0)) = Memory.bot)\n :\n (Local.promises (Thread.local th1)) = Memory.bot.\n Proof.\n inv STEP. inv LOCAL; ss.\n - inv LOCAL0. ss.\n - inv LOCAL0. rewrite NOPROMISE in WRITE.\n eapply write_no_promise in WRITE. des. auto.\n - inv LOCAL1. inv LOCAL2. rewrite NOPROMISE in WRITE.\n eapply write_no_promise in WRITE. des. auto.\n - inv LOCAL0. ss.\n - inv LOCAL0. ss.\n Qed.\n\n Lemma program_steps_no_promise lang (th0 th1: Thread.t lang)\n (STEP: rtc (tau (@AThread.program_step lang)) th0 th1)\n (NOPROMISE: (Local.promises (Thread.local th0)) = Memory.bot)\n :\n (Local.promises (Thread.local th1)) = Memory.bot.\n Proof.\n ginduction STEP; ss. i. eapply IHSTEP. inv H.\n eapply program_step_no_promise; eauto.\n Qed.\n\n Lemma no_promise_spec c\n (NOPROMISE: ~ Configuration.has_promise c)\n tid st lc\n (FIND: IdentMap.find tid (Configuration.threads c) = Some (st, lc))\n :\n (Local.promises lc) = Memory.bot.\n Proof.\n eapply Memory.ext. i. rewrite Memory.bot_get.\n destruct (Memory.get loc ts (Local.promises lc)) as [[from msg]|] eqn:GET; auto.\n exfalso. eapply NOPROMISE. econs; eauto.\n Qed.\n\n Lemma configuration_step_no_promise c0 c1 tid e\n (NOPROMISE: ~ Configuration.has_promise c0)\n (STEP: step tid e c0 c1)\n :\n ~ Configuration.has_promise c1.\n Proof.\n inv STEP. ii. inv H. ss. rewrite IdentMap.gsspec in FIND. des_ifs.\n - eapply no_promise_spec in TID; eauto.\n eapply program_steps_no_promise in STEPS; eauto.\n eapply program_step_no_promise in STEP0; eauto.\n ss. rewrite STEP0 in *. rewrite Memory.bot_get in *. clarify.\n - eapply NOPROMISE. econs; eauto.\n Qed.\n\nEnd APFConfiguration.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/pf/APF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24220563966531902, "lm_q1q2_score": 0.1248860515118709}} {"text": "Require Import FSets.\nRequire Import CoqlibC Maps Ordered Errors Lattice Kildall Integers.\nRequire Import AST Linking.\nRequire Import Values Memory Events Globalenvs Smallstep.\nRequire Import Op Locations LTLC LinearC.\nRequire Import Linearize.\nRequire Import sflib.\n(** newly added **)\nRequire Export Linearizeproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem ModSemProps.\nRequire SimMemId.\nRequire SoundTop.\nRequire Import LiftDummy.\nRequire Import JunkBlock.\n\nSet Implicit Arguments.\n\n\n\nDefinition strong_wf_tgt (st_tgt0: Linear.state): Prop :=\n exists sg_init ls_init, last_option (LinearC.get_stack st_tgt0) = Some (Linear.dummy_stack sg_init ls_init).\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariable prog: LTL.program.\nVariable tprog: Linear.program.\nLet md_src: Mod.t := (LTLC.module prog).\nLet md_tgt: Mod.t := (LinearC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\nHypothesis TRANSL: match_prog prog tprog.\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat) (st_src0: LTL.state) (st_tgt0: Linear.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: Linearizeproof.match_states st_src0 st_tgt0)\n (MCOMPATSRC: (LTLC.get_mem st_src0) = sm0.(SimMem.src))\n (MCOMPATTGT: (LinearC.get_mem st_tgt0) = sm0.(SimMem.tgt))\n (DUMMYTGT: strong_wf_tgt st_tgt0)\n (MEASURE: measure st_src0 = idx).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun _ f tf => transf_fundef f = OK tf) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nTheorem sim_modsem: ModSemPair.sim msp.\nProof.\n eapply match_states_sim with (match_states := match_states) (match_states_at := top4) (sound_state := SoundTop.sound_state);\n eauto; ii; ss.\n - instantiate (1:= Nat.lt). apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation.\n - (* init bsim *)\n inv INITTGT. destruct sm_arg; ss. clarify.\n inv SIMARGS; ss. clarify.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des. folder.\n exploit (bsim_internal_funct_id SIMGE); et. i; des.\n generalize (sig_preserved fd_src (Internal fd) MATCH); intro SGEQ. ss.\n destruct fd_src; ss.\n eexists. eexists (SimMemId.mk _ _). esplits; cycle 2.\n + econs; eauto; ss.\n * inv TYP. rpapply match_states_call; eauto.\n { instantiate (1:= [LTL.dummy_stack (fn_sig fd) ls_init]). econs; eauto; econs; et. }\n * rr. ss. esplits; et.\n (* * ss. esplits; et. *)\n + rewrite SGEQ.\n rpapply LTLC.initial_frame_intro; revgoals; [ f_equal; et | .. ]; ss; eauto with congruence.\n + ss.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. unfold bind in *. folder. des_ifs.\n inv TYP. unfold transf_function in *. unfold bind in *. des_ifs.\n destruct sm_arg; ss. clarify. esplits; eauto. econs; eauto; ss.\n - (* call wf *)\n inv MATCH; ss. destruct sm0; ss. clarify.\n u in CALLSRC. des. inv CALLSRC. inv MATCHST; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify. inv CALLSRC. inv MATCHST; ss.\n folder. esplits; eauto.\n + econs; eauto.\n * folder. des. r in TRANSL. r in TRANSL.\n exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.\n { apply SIMSKENV. }\n intro GE. apply (fsim_external_funct_id GE); ss.\n + econs; ss; eauto.\n * instantiate (1:= SimMemId.mk _ _). ss.\n * ss.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; eauto.\n + econs; eauto.\n + econs; ss; eauto.\n * econs; eauto.\n { clear - H5. inv H5.\n { econs; et. }\n ss. des_ifs. econs; et. inv H; econs; et.\n }\n * clear - DUMMYTGT. unfold strong_wf_tgt in *. des. destruct ts; ss. unfold dummy_stack, dummy_function in *. des_ifs; ss; clarify; esplits; et.\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss.\n inv H3; ss. inv H4; ss. destruct sm0; ss. clarify.\n eexists (SimMemId.mk _ _). esplits; ss; eauto; try (econs; ss; eauto).\n rr in DUMMYTGT. des. ss. clarify.\n assert(sg_init = sg_init0).\n { inv H1; ss. unfold transf_function, bind in *. des_ifs. }\n clarify.\n (* repeat f_equal; et. *)\n - left; i.\n esplits; eauto.\n { apply LTLC.modsem_receptive; et. }\n inv MATCH.\n ii. r in STEPSRC; des. hexploit (@transf_step_correct prog skenv_link skenv_link); eauto.\n { inv SIMSKENV. inv SIMSKELINK. ss. }\n { apply make_match_genvs; eauto. apply SIMSKENV. }\n i; des.\n + exploit (lift_plus Linear.step (fun st => get_stack st <> []) strong_wf_tgt); ss; et.\n { intros st X Y. rr in X. des. rewrite Y in *. ss. }\n { i. folder. unfold strong_wf_tgt in *. des. inv HSTEP; ss; eauto.\n - des_ifs; ss; eauto.\n - des_ifs; ss; eauto. right. ii. inv HSTEP0; ss. }\n { ii. unfold strong_wf_tgt in *; des. inv HSTEP; try inv STACKS; ss; clarify; et; des_ifs; et. }\n { intro T. inv H0; ss; clarify; try inv STACKS; ss; try inv H1; ss. }\n intro TT; des.\n esplits; eauto.\n * left. eapply spread_dplus; eauto.\n { eapply modsem_determinate; eauto. }\n * instantiate (1:= SimMemId.mk _ _). econs; ss.\n + clarify. esplits; et.\n * right. esplits; et.\n { eapply star_refl. }\n * instantiate (1:= SimMemId.mk _ _). econs; ss.\n\nUnshelve.\n all: ss; try (by econs).\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariable prog: LTL.program.\nVariable tprog: Linear.program.\nHypothesis TRANSL: match_prog prog tprog.\nDefinition mp: ModPair.t := SimSymbId.mk_mp (LTLC.module prog) (LinearC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. eapply Sk.match_program_eq; eauto. ii. destruct f1; ss.\n + clarify. right. unfold bind in MATCH. des_ifs. esplits; eauto. unfold transf_function in *. monadInv Heq. ss.\n + clarify. left. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nUnshelve.\n all: ss.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/LinearizeproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.23370635157681108, "lm_q1q2_score": 0.1241470045745846}} {"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils lib.fmap_utils.\nRequire Import common.types.\nRequire Import symbolic.symbolic.\nRequire Import symbolic.exec.\nRequire Import concrete.concrete.\nRequire Import concrete.exec.\nRequire Import cfi.classes.\nRequire Import cfi.concrete.\nRequire Import cfi.symbolic.\nRequire Import cfi.preservation.\nRequire Import cfi.rules.\nRequire Import symbolic.backward.\nRequire Import symbolic.forward.\nRequire Import symbolic.refinement_common.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Refinement.\n\nContext {mt : machine_types}\n {ops : machine_ops mt}\n {opss : machine_ops_spec ops}\n {ids : @classes.cfi_id mt}\n {e : rules.fencodable mt rules.cfi_tags}.\n\nVariable cfg : id -> id -> bool.\n\nInstance sp : Symbolic.params := Sym.sym_cfi cfg.\n\nVariable stable : Symbolic.syscall_table mt.\nVariable mi : refinement_common.monitor_invariant.\n\nDefinition masks := symbolic.rules.masks.\n\n(*Used for our invariants*)\nHypothesis syscall_preserves_instruction_tags :\n forall sc st st',\n Sym.instructions_tagged (cfg := cfg) (Symbolic.mem st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.instructions_tagged (cfg := cfg) (Symbolic.mem st').\n\nHypothesis syscall_preserves_valid_jmp_tags :\n forall sc st st',\n Sym.valid_jmp_tagged stable (Symbolic.mem st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.valid_jmp_tagged stable (Symbolic.mem st').\n\nHypothesis syscall_preserves_entry_tags :\n forall sc st st',\n Sym.entry_points_tagged stable (Symbolic.mem st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.entry_points_tagged stable (Symbolic.mem st').\n\n(*TODO: Remove this hypothesis, as soon as we get kinds for tags*)\nHypothesis syscall_preserves_register_tags :\n forall sc st st',\n Sym.registers_tagged (cfg:=cfg) (Symbolic.regs st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.registers_tagged (Symbolic.regs st').\n\nHypothesis syscall_preserves_jump_tags :\n forall sc st st',\n Sym.jumps_tagged (cfg:=cfg) (Symbolic.mem st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.jumps_tagged (Symbolic.mem st').\n\nHypothesis syscall_preserves_jal_tags :\n forall sc st st',\n Sym.jals_tagged (cfg:=cfg) (Symbolic.mem st) ->\n Symbolic.sem sc st = Some st' ->\n Sym.jals_tagged (Symbolic.mem st').\n\nDefinition refine_state_no_inv (sst : Symbolic.state mt) (cst : Concrete.state mt) :=\n @refine_state_weak mt ops sp _ mi stable sst cst.\n\nDefinition refine_state (sst : Symbolic.state mt) (cst : Concrete.state mt) :=\n @refine_state_weak mt ops sp _ mi stable sst cst /\\\n Sym.invariants stable sst.\n\nDefinition is_user k (x : atom (mword mt) (mword mt)) :=\n oapp (fun t => rules.tag_of_wtag t : bool)\n false (@rules.fdecode _ _ e k (taga x)).\n\nDefinition coerce k (x : atom (mword mt) (mword mt)) : atom (mword mt) (Symbolic.tag_type cfi_tags k) :=\n match obind (fun t => rules.tag_of_wtag t) (rules.fdecode k (taga x)) with\n | Some tg => (vala x)@tg\n | _ => (vala x)@(Conc.cast' k DATA) (*this is unreachable in our case, dummy value*)\n end.\n\nLemma mem_refinement_equiv :\n forall (smem : Symbolic.memory mt sp) cmem cmem',\n refinement_common.refine_memory smem cmem ->\n Conc.equiv cmem cmem' ->\n exists (smem' : Symbolic.memory mt sp),\n refinement_common.refine_memory smem' cmem' /\\\n Sym.equiv smem smem'.\nProof.\n intros smem cmem cmem' REF EQUIV.\n exists (mapm (coerce Symbolic.M) (filterm [fun _ => is_user Symbolic.M] cmem')).\n split.\n { (*refinement proof*)\n split.\n { move=> addr v ct t /= DEC CGET.\n rewrite mapmE /= filtermE /=.\n by rewrite CGET /is_user /= DEC /= /coerce DEC. }\n { move=> addr v t /=.\n rewrite mapmE /= filtermE /=.\n case CGET: (getm cmem' addr) => [[cv ctg]|] //=.\n rewrite /is_user /=.\n case DEC: (rules.fdecode _ _) => [[t'|]|] //=.\n rewrite /coerce /= DEC. move=> [? ?]. subst cv t'.\n eauto. } }\n { (*equiv proof*)\n unfold Sym.equiv, pointwise.\n intro addr.\n unfold Conc.equiv in EQUIV. unfold pointwise in EQUIV.\n specialize (EQUIV addr). simpl.\n case SGET: (smem addr) => [[v utg]|] //=.\n - unfold refinement_common.refine_memory in REF.\n have [ctg DEC CGET] := proj2 REF addr v utg SGET.\n rewrite CGET in EQUIV.\n case CGET': (cmem' addr) EQUIV=> [a|] //= EQUIV.\n destruct a as [v' ctg'].\n destruct EQUIV\n as [v0 v'' ct ut ct' ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst.\n * inv EQ1. inv EQ2.\n rewrite mapmE /= filtermE /= CGET' /= /is_user /= DEC2 /= /coerce /= DEC2.\n rewrite /= DEC1 in DEC.\n move: DEC => [?]. by subst.\n * inv EQ. simpl in NEQ.\n suff: False by [].\n apply: NEQ.\n rewrite /= in DEC. rewrite DEC.\n by eauto.\n - case CGET: (cmem addr) EQUIV => [[v ctg]|] EQUIV /=.\n + unfold refinement_common.refine_memory in REF.\n rewrite mapmE /= filtermE /=.\n case CGET': (cmem' addr) EQUIV => [a|] //= EQUIV.\n rewrite /is_user /=.\n destruct EQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst; simpl.\n { inv EQ1.\n by rewrite (proj1 REF _ _ _ _ DEC1 CGET) in SGET. }\n { case DEC: (rules.fdecode _ _) => [[ut|]|] //=.\n apply: NEQ => /=.\n by rewrite DEC; eauto. }\n + case CGET': (cmem' addr) EQUIV => [?|] //= EQUIV.\n rewrite mapmE /= filtermE /=.\n rewrite CGET'. simpl. constructor.\n }\nQed.\n\nLemma reg_refinement_equiv :\n forall (sregs : Symbolic.registers mt sp) cregs cregs' cmem,\n refinement_common.refine_registers sregs cregs cmem ->\n Conc.reg_equiv cregs cregs' ->\n exists (sregs' : Symbolic.registers mt sp),\n refinement_common.refine_registers sregs' cregs' cmem /\\\n Sym.equiv sregs sregs'.\nProof.\n intros sreg creg creg' cmem REF EQUIV.\n exists (mapm (coerce Symbolic.R) (filterm [fun _ => is_user Symbolic.R] creg')).\n split.\n { (*Refinement proof*)\n split.\n { move=> n v ctg tg /= DEC CGET'.\n by rewrite mapmE /= filtermE /=\n CGET' /= /is_user /= DEC /= /coerce /= DEC. }\n { move=> n v tg.\n rewrite mapmE /= filtermE /=.\n case CGET': (creg' n)=> [[v' t']|] //=.\n rewrite /is_user /= /coerce /=.\n case CTG: (rules.fdecode _ _) => [ut|] //=.\n rewrite CTG /= => - [? ?]. subst v' ut.\n by eauto. }\n }\n { (*equiv proof*)\n unfold Sym.equiv, pointwise.\n intro n.\n unfold Conc.reg_equiv in EQUIV.\n specialize (EQUIV n).\n destruct EQUIV as ([v1 t1] & [v2 t2] & E1 & E2 & EQUIV).\n destruct (getm sreg n) eqn:SGET; simpl in SGET; rewrite SGET.\n - destruct a as [v utg].\n move: (proj2 REF n v utg SGET) => [ctg DEC CGET].\n rewrite CGET in E1. inversion E1; subst v1 t1; clear E1.\n rewrite mapmE /= filtermE /=.\n destruct EQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst.\n * inv EQ1. inv EQ2. rewrite /= DEC1 in DEC. inv DEC.\n unfold is_user, coerce, rules.is_user.\n by rewrite E2 /= DEC2 /= DEC2.\n * inv EQ. simpl in NEQ.\n suff: False by [].\n by apply: NEQ; eexists; eauto.\n - rewrite mapmE /= filtermE /=.\n rewrite E2. simpl.\n destruct EQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst.\n + inv EQ1.\n rewrite /is_user /coerce /=.\n case DEC: (rules.fdecode _ _) => [?|] //=.\n by rewrite (proj1 REF _ _ _ _ DEC1 E1) in SGET.\n + inv EQ.\n rewrite /is_user /coerce /=.\n case DEC: (rules.fdecode _ t2) => [?|] //=.\n apply: NEQ.\n by rewrite /= DEC; eauto.\n }\nQed.\n\n(*Monitor invariants preserved by attacker*)\nLemma mvec_in_monitor_preserved_by_equiv\n (mem : Concrete.memory mt) (mem' : Concrete.memory mt) :\n refinement_common.mvec_in_monitor mem ->\n Conc.equiv mem mem' ->\n refinement_common.mvec_in_monitor mem'.\nProof.\n intros INV MEQUIV.\n unfold refinement_common.mvec_in_monitor.\n intros addr INMVEC.\n specialize (INV addr).\n apply INV in INMVEC.\n destruct INMVEC as [v GET].\n unfold Conc.equiv, pointwise in MEQUIV.\n specialize (MEQUIV addr).\n rewrite GET in MEQUIV.\n destruct (getm mem') eqn:GET'.\n - destruct MEQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst.\n + inversion EQ1; subst. eauto.\n by rewrite rules.fdecode_monitor_tag in DEC1.\n + eexists; reflexivity.\n - destruct MEQUIV.\nQed.\n\nLemma wf_entry_points_preserved_by_equiv\n (mem : Concrete.memory mt) (mem' : Concrete.memory mt) :\n refinement_common.wf_entry_points stable mem ->\n Conc.equiv mem mem' ->\n refinement_common.wf_entry_points stable mem'.\nProof.\n intros INV MEQUIV.\n intros addr stg.\n specialize (INV addr stg).\n specialize (MEQUIV addr).\n split.\n { intro SCALL.\n apply INV in SCALL.\n case: (mem addr) INV MEQUIV SCALL => [[v ctg]|] INV MEQUIV SCALL; last by [].\n case: (mem' addr) MEQUIV => [[v' ctg']|] MEQUIV; last by [].\n destruct MEQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV|NEQ EQ]; subst.\n - inv EQ1. inv EQ2.\n by rewrite /= DEC1 andbF in SCALL.\n - simpl in *. inv EQ. assumption.\n }\n { intro CALL.\n case: (mem' addr) INV MEQUIV CALL => [[v' ctg']|] //= INV MEQUIV CALL.\n case: (mem addr) INV MEQUIV => [[v ctg]|] //= INV MEQUIV.\n inversion MEQUIV\n as [v0 v'' ? ? ? ut' EQ1 DEC1 EQ2 DEC2 SEQUIV| NEQ EQ]; subst.\n + inv EQ1. inv EQ2.\n move/andP in CALL.\n destruct CALL as [? CALL].\n by rewrite /= DEC2 in CALL.\n + simpl in *. inv EQ. apply INV in CALL.\n assumption.\n }\nQed.\n\n(*Q: Do we want to prove anything about this? Maybe using the other assumptions\n on mi?*)\nHypothesis mi_preserved_by_equiv :\n forall mem mem' reg reg' cache int,\n refinement_common.monitor_invariant_statement mi mem reg cache int ->\n Conc.equiv mem mem' ->\n Conc.reg_equiv reg reg' ->\n refinement_common.monitor_invariant_statement mi mem' reg' cache int.\n\nHint Resolve mvec_in_monitor_preserved_by_equiv.\nHint Resolve wf_entry_points_preserved_by_equiv.\n\nLemma backwards_simulation_attacker_aux sst cst cst' :\n refine_state_no_inv sst cst ->\n Conc.step_a cst cst' ->\n exists sst',\n Sym.step_a sst sst' /\\\n refine_state_no_inv sst' cst'.\nProof.\n case: sst => smem sregs [pc tpc] int.\n case: cst => cmem cregs cache [pc' ctpc] epc.\n intros REF STEP.\n inversion STEP; subst.\n unfold refine_state in REF.\n destruct REF as [REF | CONTRA].\n move: tpc INUSER REF STEP => tpc' INUSER REF STEP.\n - destruct REF as [? ? REFM REFR ? ? WFENTRY ?].\n destruct (mem_refinement_equiv REFM MEQUIV) as [smem' [REFM' SMEQUIV]].\n destruct (reg_refinement_equiv REFR REQUIV) as [sreg' [REFR' SREQUIV]].\n eexists; split; [idtac | left]; econstructor; eauto.\n - case: CONTRA => [? [? [? [? CONTRA]]]].\n clear REQUIV MEQUIV.\n unfold refinement_common.monitor_exec in CONTRA.\n apply restricted_exec_snd in CONTRA.\n rewrite /refinement_common.in_monitor\n /= /Concrete.is_monitor_tag in CONTRA.\n move/eqP in CONTRA. rewrite /Concrete.pct /= in CONTRA. subst ctpc.\n by rewrite rules.fdecode_monitor_tag in INUSER.\nQed.\n\nTheorem backwards_simulation_attacker sst cst cst' :\n refine_state sst cst ->\n Conc.step_a cst cst' ->\n exists sst',\n Sym.step_a sst sst' /\\\n refine_state sst' cst'.\nProof.\n intros REF STEP.\n destruct REF as [REF INV];\n destruct (backwards_simulation_attacker_aux REF STEP) as [sst' [SSTEP REF']];\n eexists; split; [eassumption | split];\n eauto using Sym.invariants_preserved_by_step_a.\nQed.\n\n(* Preservation related stuff, probably move to other file*)\n\nDefinition smachine := Sym.symbolic_cfi_machine stable.\nDefinition cmachine := Conc.concrete_cfi_machine mi stable masks.\n\nContext {mcc : monitor_code_bwd_correctness mi stable}. (*should this go to the top?*)\n\nDefinition check st st' := in_user st && in_user st'.\n\nProgram Instance cfi_refinementSC :\n (machine_refinement smachine cmachine) := {\n refine_state st st' := refine_state st st';\n\n check st st' := check st st'\n}.\nNext Obligation.\nProof.\n unfold refine_state in REF.\n destruct REF as [REF INV].\n destruct REF as [UREF | KREF].\n - (*starting from a user state*)\n split.\n { (*Visible step starting from a user state*)\n intro VIS.\n unfold check in VIS.\n move/andP in VIS.\n destruct VIS as [VIS VIS'].\n assert (HIT: hit_step cst cst')\n by (constructor; auto).\n destruct (cache_hit_simulation UREF HIT) as [ast' SSTEP REF'].\n unfold refine_state, refine_state_weak.\n eexists; split. eauto.\n split;\n eauto using Sym.invariants_preserved_by_step.\n }\n { (*invisible step starting a from user state*)\n intro INVIS.\n case/nandP: INVIS=> [CONTRA | NUSER].\n - eapply @refine_state_in_user in UREF.\n rewrite UREF in CONTRA.\n by discriminate.\n - (*user to not user step*)\n left.\n unfold refine_state. split.\n + right. exists cst; exists cst'.\n repeat (split; auto).\n unfold monitor_exec.\n move: (user_into_monitor UREF STEP NUSER) => ?.\n by eapply re_refl; eauto.\n + eauto using Sym.invariants_preserved_by_step.\n }\n - (*starting from a monitor state*)\n split.\n { (*and taking a visible step*)\n intro VIS.\n unfold check in VIS.\n move/andP in VIS.\n destruct VIS as [VIS VIS'].\n destruct KREF as [ust [kst [UREF [UKSTEP KEXEC]]]].\n unfold monitor_exec in KEXEC.\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in VIS.\n by rewrite KEXEC in VIS.\n }\n { (*and taking an invisible step*)\n intro VIS.\n assert (REFW : @refine_state_weak mt ops sp _ mi stable ast cst)\n by (right; auto).\n destruct (backwards_simulation REFW STEP) as [REFW' | [ast' STEP' REF']].\n - left. split; auto.\n - right. eexists; split; eauto.\n unfold refine_state.\n split.\n + left. assumption.\n + eauto using Sym.invariants_preserved_by_step.\n }\nQed.\nNext Obligation.\n apply (backwards_simulation_attacker REF STEPA).\nQed.\n\n(*This is a helper lemma to instantiate CFI refinement between\n symbolic and concrete*)\nLemma attacker_no_v : forall si sj,\n Sym.invariants stable si ->\n ~~ Sym.ssucc stable si sj ->\n Symbolic.step stable si sj ->\n ~ Sym.step_a si sj.\nProof.\n move=> si sj INV /negbTE SUCC STEP STEPA.\n destruct INV as [ITG [VTG ETG]].\n inversion STEPA. subst.\n inversion STEP;\n repeat (\n match goal with\n | [H: Symbolic.next_state_pc _ _ _ = _ |- _] =>\n unfold Symbolic.next_state_pc in H\n | [H: Symbolic.next_state_reg _ _ _ _ = _ |- _] =>\n unfold Symbolic.next_state_reg in H\n | [H: Symbolic.next_state_reg_and_pc _ _ _ _ _ = _ |- _] =>\n unfold Symbolic.next_state_reg_and_pc in H\n | [H: Symbolic.next_state _ _ = Some _ |- _] =>\n unfold Symbolic.next_state in H; simpl in H; match_inv\n end); subst;\n unfold Sym.ssucc in SUCC; simpl in SUCC;\n inversion ST; try subst;\n try match goal with\n | [H: (?Pc + 1)%w = ?Pc |- _] =>\n rewrite H in SUCC; try subst mem' reg' int; try subst mem reg\n end;\n try rewrite PC in SUCC; try rewrite INST in SUCC;\n try match goal with\n | [H: Some _ = Some _ |- _] => simpl in H; inversion H\n end;\n try match goal with\n | [H: match ?Expr with _ => _ end = _ |- _] =>\n destruct Expr eqn:?\n end;\n try match goal with\n | [H: (?Pc + 1)%w = ?Pc |- _] =>\n rewrite H in SUCC; rewrite eqxx in SUCC; discriminate\n end;\n try match goal with\n | H : context[?pc == ?pc] |- _ => rewrite eqxx in H => //\n end.\n (*jump case*)\n unfold Sym.instructions_tagged in ITG.\n specialize (ITG _ _ _ PC). simpl in ITG. subst.\n congruence.\n (*bnz case*)\n destruct (w == 0%w).\n - subst mem' reg'. simpl in *.\n destruct a as [v [|]].\n + rewrite H2 in Heqo0. rewrite PC in Heqo0. inversion Heqo0. subst o i.\n rewrite INST in SUCC.\n destruct o0;\n apply Bool.orb_false_iff in SUCC; destruct SUCC;\n rewrite {2}H2 in H; rewrite eqxx in H; by discriminate.\n + rewrite H2 in Heqo0. rewrite Heqo0 in PC. by inversion PC.\n - subst mem' reg'. simpl in *.\n destruct a as [v [|]].\n + rewrite H2 in Heqo0. rewrite PC in Heqo0. inversion Heqo0. subst o i.\n rewrite INST in SUCC.\n destruct o0;\n apply Bool.orb_false_iff in SUCC; destruct SUCC;\n rewrite {2}H2 in H0; rewrite eqxx in H0; by discriminate.\n + rewrite H2 in Heqo0. rewrite Heqo0 in PC. by inversion PC.\n subst mem' reg' int.\n rewrite H2 in Heqo0.\n rewrite Heqo0 in PC. by discriminate.\n (*jal case*)\n unfold Sym.instructions_tagged in ITG.\n specialize (ITG _ _ _ PC). simpl in ITG. subst.\n congruence.\n (*syscall case*)\n by discriminate.\n rewrite GETCALL in Heqo.\n by discriminate.\nQed.\n\nLemma refine_traces_kexec axs cxs cst cst' :\n refine_traces cfi_refinementSC axs (cst :: cxs) ->\n in_monitor cst ->\n cst' \\in cxs ->\n in_monitor cst' \\/ exists cst'',\n in_user cst'' /\\\n exec (Concrete.step ops masks) cst cst''.\nProof.\n elim: cxs axs cst => [|a cxs IHcxs] axs cst RTRACE MONITOR IN; first by [].\n inversion RTRACE\n as [? ? REF' | ? ? ? ? ? STEP CHECK REF REF' RTRACE'\n | ? ? ? ? ? ? STEP ASTEP REF REF' RTRACE'\n | ? ? ? ? ? ? NSTEP STEPA CSTEPA REF REF' RTRACE'];\n subst; simpl in *.\n { (*non-visible step*)\n rewrite !inE in IN; case/orP: IN => [/eqP ? | IN]; try subst a.\n + have [USER|USER] := boolP (in_user cst').\n * right. exists cst'. split; auto.\n by econstructor; eauto.\n * destruct REF as [WREF INV]; clear INV.\n destruct WREF as [CONTRA | KREF].\n { apply @refine_state_in_user in CONTRA.\n apply @in_user_in_monitor in CONTRA.\n by rewrite MONITOR in CONTRA.\n }\n { destruct KREF as [cst0 [kst [KREF [CSTEP KEXEC]]]].\n assert (MONITOR' := monitor_step KREF CSTEP KEXEC STEP MONITOR USER).\n left. assumption.\n }\n + have [USER|USER] := boolP (in_user a).\n * right. exists a; split; auto.\n by econstructor; eauto.\n * destruct REF as [WREF INV]; clear INV.\n destruct WREF as [CONTRA | KREF].\n { apply @refine_state_in_user in CONTRA.\n apply @in_user_in_monitor in CONTRA.\n by rewrite MONITOR in CONTRA.\n }\n { destruct KREF as [cst0 [kst [KREF [CSTEP KEXEC]]]].\n assert (MONITOR' := monitor_step KREF CSTEP KEXEC STEP MONITOR USER).\n destruct (IHcxs (ast :: axs0) a RTRACE' MONITOR' IN)\n as [MONITOR'' | [cst'' [USER'' EXEC]]].\n - left; assumption.\n - right. exists cst''.\n split; auto.\n by econstructor; eauto.\n }\n }\n { (*visible step*)\n rewrite !inE in IN; case/orP: IN=> [/eqP ?|IN]; try subst a.\n + have [USER|USER] := boolP (in_user cst').\n * right. exists cst'. split; auto.\n by econstructor; eauto.\n * destruct REF as [WREF INV]; clear INV.\n destruct WREF as [CONTRA | KREF].\n { apply @refine_state_in_user in CONTRA.\n apply @in_user_in_monitor in CONTRA.\n by rewrite MONITOR in CONTRA.\n }\n { destruct KREF as [cst0 [kst [KREF [CSTEP KEXEC]]]].\n assert (MONITOR' := monitor_step KREF CSTEP KEXEC STEP MONITOR USER).\n left. assumption.\n }\n + have [USER|USER] := boolP (in_user a).\n * right. exists a; split; auto.\n by econstructor; eauto.\n * destruct REF as [WREF INV]; clear INV.\n destruct WREF as [CONTRA | KREF].\n { apply @refine_state_in_user in CONTRA.\n apply @in_user_in_monitor in CONTRA.\n by rewrite MONITOR in CONTRA.\n }\n { destruct KREF as [cst0 [kst [KREF [CSTEP KEXEC]]]].\n assert (MONITOR' := monitor_step KREF CSTEP KEXEC STEP MONITOR USER).\n destruct (IHcxs (ast' :: axs0) a RTRACE' MONITOR' IN)\n as [MONITOR'' | [cst'' [USER'' EXEC]]].\n - left; assumption.\n - right. exists cst''.\n split; auto.\n by econstructor; eauto.\n }\n }\n { (*attacker step - attacker not allowed in monitor mode*)\n inversion STEPA; subst.\n clear IHcxs RTRACE' RTRACE NSTEP CSTEPA MEQUIV REQUIV IN.\n move/eqP: MONITOR INUSER.\n rewrite /Concrete.pct /= => ->.\n by rewrite rules.fdecode_monitor_tag.\n }\nQed.\n\nLemma attacker_up_to ast ast' cst cst' axs cxs :\n Sym.all_attacker (ast :: ast' :: axs) ->\n Sym.all_stuck stable (ast :: ast' :: axs) ->\n Conc.step_a cst cst' /\\ ~ Concrete.step ops masks cst cst' ->\n refine_traces cfi_refinementSC (ast :: ast' :: axs) (cst :: cst' :: cxs) ->\n Conc.all_attacker masks (cst :: cst' :: cxs) \\/\n exists hd tl csi csj,\n cst :: cst' :: cxs = hd ++ csi :: csj :: tl /\\\n Conc.all_attacker masks (hd ++ [:: csi]) /\\\n Concrete.step _ masks csi csj /\\ ~~ check csi csj /\\\n ((exists asi, refine_traces cfi_refinementSC [:: asi] (csi :: csj :: tl)\n /\\ exec (@Sym.step_a mt ids cfg) ast asi)\n \\/ (exists asi asj atl,\n refine_traces cfi_refinementSC (asi :: asj :: atl) (csj :: tl) /\\\n Sym.all_stuck stable (asi :: asj :: atl) /\\\n exec (@Sym.step_a mt ids cfg) ast asi /\\\n refine_state asi csi)).\nProof.\n intros ALLA ALLS CSTEP RTRACE.\n move: axs cst cst' ast ast' ALLA ALLS CSTEP RTRACE.\n induction cxs as [|cst'' cxs]; simpl in *; intros.\n - inversion RTRACE\n as [? ? REF' | ? ? ? ? ? STEP CHECK REF REF' RTRACE'\n | ? ? ? ? ? ? STEP ASTEP REF REF' RTRACE'\n | ? ? ? ? ? ? NSTEP STEPA CSTEPA REF REF' RTRACE']; subst.\n + left.\n intros ? ? IN2;\n destruct IN2 as [[? ?] | CONTRA];\n [subst | destruct CONTRA].\n auto.\n + exfalso. simpl in *.\n have IN: ast \\in (ast :: ast' :: axs) by rewrite inE eqxx.\n specialize (ALLS ast IN).\n eauto.\n + left. intros ? ? IN2.\n destruct IN2 as [[? ?] | CONTRA];\n [subst | destruct CONTRA].\n * simpl in *. auto.\n - inversion RTRACE\n as [? ? REF' | ? ? ? ? ? STEP CHECK REF REF' RTRACE'\n | ? ? ? ? ? ? STEP ASTEP REF REF' RTRACE'\n | ? ? ? ? ? ? NSTEP STEPA CSTEPA REF REF' RTRACE']; subst.\n + exfalso. simpl in STEP.\n destruct CSTEP as [? CONTRA].\n destruct (CONTRA STEP).\n + exfalso. simpl in *.\n have IN: ast \\in (ast :: ast' :: axs) by rewrite inE eqxx.\n specialize (ALLS ast IN).\n eauto.\n + destruct axs as [|ast'' axs].\n * inversion RTRACE'\n as [? ? REF''| | | ]; subst.\n { simpl in *.\n right.\n exists [:: cst]; exists cxs; exists cst'; exists cst''.\n split; auto.\n split. intros ? ? IN2.\n destruct IN2 as [[? ?] | CONTRA];\n [subst | destruct CONTRA].\n split; auto.\n split; auto.\n split; auto.\n left.\n exists ast'. split; auto.\n by econstructor; eauto.\n }\n * inversion RTRACE'; subst.\n { right.\n exists [:: cst]; exists cxs; exists cst'; exists cst''.\n split; auto.\n split.\n intros ? ? IN2;\n destruct IN2 as [[? ?] | CONTRA]; [subst | destruct CONTRA].\n auto.\n split. assumption.\n split. assumption.\n right.\n eexists; eexists; eexists; split; eauto.\n split.\n apply Sym.all_stuck_red in ALLS.\n by auto.\n by econstructor; eauto.\n }\n { have IN: ast' \\in (ast :: ast' :: ast'' :: axs) by rewrite !inE eqxx orbT.\n specialize (ALLS ast' IN).\n simpl in H6.\n exfalso.\n eauto.\n }\n {\n apply Sym.all_attacker_red in ALLA.\n apply Sym.all_stuck_red in ALLS.\n assert (STEP: Conc.step_a cst' cst'' /\\ ~ Concrete.step ops masks cst' cst'')\n by auto.\n specialize (IHcxs axs cst' cst'' ast' ast'' ALLA ALLS STEP RTRACE').\n destruct IHcxs as [ALLA' | IH].\n - (*all attacker*)\n left.\n intros csi csj IN2.\n destruct IN2 as [[? ?] | IN2]; subst.\n + simpl in *. auto.\n + auto.\n - destruct IH\n as [chd [ctl [csi [csj [CLST [ALLA' [UCSTEP [CHECK IH]]]]]]]].\n destruct IH as [IH | IH].\n { destruct IH as [asi [RTRACE'' EXEC]].\n right.\n rewrite CLST.\n exists (cst :: chd); exists ctl; exists csi; exists csj.\n split; auto.\n split.\n { intros ? ? IN2.\n destruct chd.\n - destruct IN2 as [[? ?] | CONTRA];\n [subst | destruct CONTRA].\n inv CLST.\n assumption.\n - inv CLST.\n destruct IN2 as [[? ?] | IN2]; subst.\n + auto.\n + apply ALLA' in IN2.\n assumption.\n }\n { split. assumption.\n split; [assumption | idtac].\n left. exists asi. split; auto.\n by econstructor; eauto.\n }\n }\n { destruct IH as [asi [asj [atl [RTRACE'' [STUCK'' [EXEC'' REF'']]]]]].\n right.\n rewrite CLST.\n exists (cst :: chd); exists ctl; exists csi; exists csj.\n split; auto.\n split.\n { intros ? ? IN2.\n destruct chd.\n - destruct IN2 as [[? ?] | CONTRA];\n [subst | destruct CONTRA].\n inv CLST.\n assumption.\n - inv CLST.\n destruct IN2 as [[? ?] | IN2]; subst.\n + auto.\n + apply ALLA' in IN2.\n assumption.\n }\n { split. assumption.\n split; [assumption | idtac].\n right. eexists; eexists; eexists; split; eauto.\n }\n }\n }\nQed.\n\nLemma all_attacker_implies_all_user cst cst' cxs :\n Conc.all_attacker masks (cst :: cst' :: cxs) ->\n all in_user (cst :: cst' :: cxs).\nProof.\n intro ALLA.\n apply/allP=> x IN.\n elim: cxs cst cst' ALLA IN => [|a cxs IH]; intros.\n - have IN2 : In2 cst cst' [:: cst;cst'] by simpl; auto.\n apply ALLA in IN2.\n destruct IN2 as [STEPA ?].\n by rewrite !inE in IN; case/orP: IN=> /eqP ?; subst; inv STEPA; auto.\n - rewrite inE in IN; case/orP: IN=> [/eqP ? | IN]; subst.\n + assert (IN2: In2 cst cst' (cst :: cst' :: a :: cxs))\n by (simpl; auto).\n destruct (ALLA _ _ IN2) as [STEPA ?].\n by inv STEPA; auto.\n + by apply Conc.all_attacker_red in ALLA; eauto.\nQed.\n\nLemma all_attacker_implies_all_user' cst cst' cxs :\n Conc.all_attacker masks (cst :: cxs ++ [:: cst']) ->\n all in_user (cst :: cxs ++ [:: cst']).\nProof.\n intro ALLA.\n apply/allP=> x IN.\n elim: cxs cst cst' ALLA IN=> [|a cxs IH] /=; intros.\n - rewrite !inE in IN; case/orP: IN=> /eqP ?; subst.\n + have IN2 : In2 cst cst' [:: cst;cst'] by (simpl; auto).\n apply ALLA in IN2.\n destruct IN2 as [STEPA ?].\n by inv STEPA; auto.\n + assert (IN2 : In2 cst cst' [:: cst;cst']) by (simpl; auto).\n destruct (ALLA _ _ IN2) as [STEPA ?].\n inv STEPA; auto.\n - rewrite inE in IN; case/orP: IN=> [/eqP ?|IN]; subst.\n + assert (IN2: In2 cst a (cst :: a :: cxs ++ [:: cst']))\n by (simpl; auto).\n simpl in ALLA.\n apply ALLA in IN2.\n destruct IN2 as [STEPA ?].\n by inv STEPA; auto.\n + simpl in ALLA.\n apply Conc.all_attacker_red in ALLA.\n specialize (IH _ _ ALLA IN).\n assumption.\nQed.\n\nLemma user_into_monitor_wrapped sst cst cst' :\n in_user cst ->\n refine_state sst cst ->\n Concrete.step ops masks cst cst' ->\n ~~ in_user cst' -> in_monitor cst'.\nProof.\n intros USER REF STEP NUSER.\n destruct REF as [REF ?].\n destruct REF as [WREF | CONTRA].\n - by eauto using user_into_monitor.\n - destruct CONTRA as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in USER.\n by rewrite KEXEC in USER.\nQed.\n\n(* MOVE to refinement_common. *)\nLemma transfer_none_lookup_none cmvec ivec cmem cache :\n refinement_common.cache_correct cache cmem ->\n rules.decode_ivec (rules.encodable_of_fencodable e) cmem cmvec = Some ivec ->\n Symbolic.transfer ivec = None ->\n Concrete.cache_lookup cache masks cmvec = None.\nProof.\n move=> CACHE DEC TRANS.\n case LOOKUP: (Concrete.cache_lookup cache masks cmvec) => [crvec|] //=.\n have [t E] : exists t, rules.decode Symbolic.P cmem (Concrete.ctpc cmvec) = Some t.\n have := rules.decode_ivec_inv DEC.\n by case: ivec {DEC TRANS} => [[?|] ? ? ?] => [[?]|[]]; eauto.\n have := CACHE _ _ LOOKUP.\n rewrite {}E => /(_ erefl) [ivec' [ovec [DEC' _ TRANS']]].\n rewrite DEC in DEC'. case: DEC' TRANS => ->.\n by rewrite TRANS'.\nQed.\n\nLemma violation_implies_kexec sst cst cst' umvec sxs cxs :\n Sym.violation stable sst ->\n build_ivec stable sst = Some umvec ->\n in_user cst ->\n ~~ check cst cst' ->\n Concrete.step ops masks cst cst' ->\n refine_state sst cst ->\n refine_traces cfi_refinementSC (sst :: sxs) (cst' :: cxs) ->\n all in_monitor (cst' :: cxs).\nProof.\n move=> VIOLATION UMVEC USER NUSER' STEP REF RTRACE.\n rewrite /check USER /= in NUSER'.\n assert (UHANDLER := Sym.is_violation_implies_stop VIOLATION UMVEC).\n assert (MONITOR := user_into_monitor_wrapped USER REF STEP NUSER').\n rewrite /= MONITOR /=.\n apply/allP=> kst /(refine_traces_kexec RTRACE MONITOR)\n [? //|[cst'' [USER'' EXEC]]].\n (*the case where one user step was in the trace contradicts*)\n destruct REF as [[REF | CONTRA] ?].\n - have [//= cmvec CMVEC DEC] := refine_ivec REF UMVEC.\n destruct REF.\n apply @in_user_in_monitor in USER''.\n destruct cst as [cmemt cregt cachet [cpct ctpct] epct].\n destruct sst as [smemt sregt [spct tpct] intt].\n rewrite /Concrete.pcv /= in rs_pc. subst cpct.\n simpl in DEC.\n have := @handler_correct_disallowed_case mt ops sp _ mi\n stable mcc _\n cmvec _\n _ spct@ctpct _ cst''\n rs_minv _ USER''.\n rewrite DEC UHANDLER => /(_ erefl).\n have LOOKUP := transfer_none_lookup_none rs_cache DEC UHANDLER.\n have /= <- := initial_handler_state CMVEC LOOKUP STEP.\n by move=> /(_ EXEC).\n - (*refinement contradictory case*)\n destruct CONTRA as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in USER.\n by rewrite KEXEC in USER.\nQed.\n\nLemma no_umvec_implies_kexec sst cst cst' sxs cxs :\n Sym.violation stable sst ->\n build_ivec stable sst = None ->\n in_user cst ->\n ~~ check cst cst' ->\n Concrete.step ops masks cst cst' ->\n refine_state sst cst ->\n refine_traces cfi_refinementSC (sst :: sxs) (cst' :: cxs) ->\n all in_monitor (cst' :: cxs).\nProof.\n move=> VIOLATION UMVEC USER NUSER' STEP REF RTRACE.\n rewrite /check USER /= in NUSER'.\n (*assert (UHANDLER := Sym.is_violation_implies_stop stable sst VIOLATION UMVEC).*)\n assert (MONITOR := user_into_monitor_wrapped USER REF STEP NUSER').\n rewrite /= MONITOR /=.\n apply/allP=> kst /(refine_traces_kexec RTRACE MONITOR)\n [? //|[cst'' [USER'' EXEC]]].\n (*the case where one user step was in the trace contradicts*)\n destruct REF as [[REF | CONTRA] ?].\n - have [cmvec CMVEC] := step_build_cmvec STEP.\n case DEC: (rules.decode_ivec _ (Concrete.mem cst) cmvec) => [ivec|].\n by rewrite (refine_ivec_inv REF CMVEC DEC) in UMVEC.\n destruct REF. subst.\n have := @handler_correct_disallowed_case mt ops sp _ mi\n stable mcc _\n cmvec _ _ (Concrete.pc cst) _ cst''\n rs_minv _ (in_user_in_monitor USER'').\n rewrite DEC => /(_ erefl).\n case LOOKUP: (Concrete.cache_lookup (Concrete.cache cst) masks cmvec) => [crvec|].\n rewrite /in_user /= in USER.\n have := rs_cache _ _ LOOKUP.\n rewrite (build_cmvec_ctpc CMVEC) /= => /(_ USER) [ivec [ovec [DEC' _ _ _]]].\n by rewrite DEC' in DEC.\n by rewrite -(initial_handler_state CMVEC LOOKUP STEP) => /(_ EXEC).\n - (*refinement contradictory case*)\n destruct CONTRA as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in USER.\n by rewrite KEXEC in USER.\nQed.\n\nTheorem cfg_true_equiv ssi ssj csi csj :\n refine_state ssi csi ->\n refine_state ssj csj ->\n Symbolic.step stable ssi ssj ->\n Sym.ssucc stable ssi ssj ->\n Concrete.step ops masks csi csj ->\n Conc.csucc cfg csi csj.\nProof.\n intros.\n destruct H as [REF INV].\n destruct REF as [UREFI | KREFI].\n - destruct H0 as [REF' INV'].\n destruct REF' as [UREFJ | KREFJ].\n + move: (refine_state_in_user UREFI) (refine_state_in_user UREFJ) => USERI USERJ.\n assert (NMONITOR : in_monitor csi || in_monitor csj = false).\n { apply/norP.\n by rewrite (in_user_in_monitor USERI) (in_user_in_monitor USERJ). }\n destruct ssi as [smemi sregi [pci tpci] inti].\n destruct csi as [cmemi cregi cachei [pci' ctpci] epci].\n destruct UREFI as [PCI DEC REFM REFR CACHE MVE WF MI].\n rewrite /Concrete.pcv /= in PCI. subst pci'.\n destruct ssj as [smemj sregj [pcj tpcj] intj].\n destruct csj as [cmemj cregj cachej [pcj' ctpcj] epcj].\n destruct UREFJ as [PCJ DEC' REFM' REFR' C3 C5 C6 C7].\n rewrite /Concrete.pcv /= in PCJ. subst pcj'.\n unfold Conc.csucc.\n rewrite NMONITOR /=.\n unfold Sym.ssucc in H2.\n rewrite /= in H2.\n destruct (getm smemi pci) as [[v tg]|] eqn:GET.\n * rewrite GET in H2.\n have [ctg /= DECctg CGET] := proj2 REFM pci v tg GET.\n rewrite CGET DECctg /=.\n destruct tg as [[src|]|].\n { simpl in GET.\n destruct (decode_instr v) eqn:INST.\n - destruct i eqn:OP; try assumption. (*TODO: fix jmp/jal copy paste*)\n { (*jmp*)\n destruct (getm smemi pcj) as [[v' tg]|] eqn:GET'.\n - have [ctg' /= DECctg' CGET'] := proj2 REFM pcj v' tg GET'.\n rewrite GET' in H2.\n by rewrite CGET' DECctg'.\n - rewrite GET' in H2.\n destruct (stable pcj) eqn:GETCALL.\n + rewrite GETCALL in H2.\n unfold wf_entry_points in WF.\n specialize (WF pcj (Symbolic.entry_tag s)).\n assert (ECALL : exists2 sc : Symbolic.syscall mt,\n stable pcj = Some sc &\n Symbolic.entry_tag sc = Symbolic.entry_tag s)\n by (eexists; eauto).\n apply WF in ECALL.\n case: (getm cmemi pcj) ECALL => [[v' tg]|] ECALL //.\n move/andP in ECALL.\n case: ECALL => [ISNOP /= /eqP ETAG].\n rewrite ETAG.\n destruct (Symbolic.entry_tag s) as [[?|]|] eqn:ETAG';\n rewrite ETAG' in H2; try discriminate.\n apply/andP.\n by auto.\n + rewrite GETCALL in H2. by discriminate.\n }\n { (*jal*)\n destruct (getm smemi pcj) as [[v' tg]|] eqn:GET'.\n - have [ctg' /= DECctg' CGET'] := proj2 REFM pcj v' tg GET'.\n rewrite GET' in H2.\n by rewrite CGET' DECctg'.\n - rewrite GET' in H2.\n destruct (stable pcj) eqn:GETCALL.\n + rewrite GETCALL in H2.\n unfold wf_entry_points in WF.\n specialize (WF pcj (Symbolic.entry_tag s)).\n assert (ECALL : exists2 sc : Symbolic.syscall mt,\n stable pcj = Some sc &\n Symbolic.entry_tag sc = Symbolic.entry_tag s)\n by (eexists; eauto).\n apply WF in ECALL.\n case: (getm cmemi pcj) ECALL => [[v' tg]|] ECALL //.\n case/andP: ECALL => [ISNOP ETAG].\n simpl.\n move/eqP:ETAG => /= ETAG.\n rewrite ETAG.\n destruct (Symbolic.entry_tag s) as [[?|]|] eqn:ETAG';\n rewrite ETAG' in H2; try discriminate.\n apply/andP.\n by auto.\n + rewrite GETCALL in H2. by discriminate.\n }\n - by discriminate.\n }\n { by trivial. }\n { by discriminate. }\n { rewrite GET in H2.\n case GETSC: (stable _) H2 => [sc|] //= _.\n remember (Symbolic.entry_tag sc) as sct eqn:ETAG. symmetry in ETAG.\n have /WF: exists2 sc, stable pci = Some sc &\n Symbolic.entry_tag sc = sct by eexists; eauto.\n case GET': (getm cmemi pci) => [[v ctg]|] //=.\n assert (CONTRA := fun CACHE GET' =>\n valid_initial_user_instr_tags (v := v) (ti := ctg) CACHE USERI USERJ H3 GET').\n move: (CONTRA CACHE GET') => {CONTRA} /=.\n case: (rules.fdecode _ ctg) => [[t | ]|] //= _.\n by rewrite andbF. }\n + destruct KREFJ as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n unfold Conc.csucc. rewrite KEXEC.\n simpl. rewrite orbT. reflexivity.\n - destruct KREFI as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n unfold Conc.csucc. rewrite KEXEC.\n by reflexivity.\nQed.\n\nTheorem cfg_false_equiv ssi ssj csi csj :\n refine_state ssi csi ->\n refine_state ssj csj ->\n ~~ Sym.ssucc stable ssi ssj ->\n check csi csj ->\n Concrete.step ops masks csi csj ->\n ~~ Conc.csucc cfg csi csj.\nProof.\n intros.\n destruct H as [REF INV], H0 as [REF' INV']. clear INV'.\n unfold check in H2.\n move/andP in H2.\n destruct H2 as [USER USER'].\n destruct REF as [REF | CONTRA].\n - destruct REF' as [REF' | CONTRA'].\n + apply @in_user_in_monitor in USER.\n apply @in_user_in_monitor in USER'.\n unfold Conc.csucc. rewrite (negbTE USER) (negbTE USER').\n simpl.\n move: (refine_state_in_user REF) (refine_state_in_user REF') => USERT USERT'.\n destruct ssi as [smem sreg [pc tpc] int],\n csi as [cmem creg cache [pc2 ctpc] epc],\n ssj as [smem' sreg' [pc' tpc'] int'],\n csj as [cmem' creg' cache' [pc2' ctpc'] epc'],\n REF as [PC DEC REFM REFR CACHE MVEC WF MI],\n REF' as [PC' DEC' REFM' REFR' C3 C5 C6 C7].\n simpl. rewrite /Concrete.pcv /= in PC PC'. subst pc2 pc2'.\n unfold Sym.ssucc in H1.\n simpl in H1.\n destruct (getm smem pc) eqn:GET.\n { destruct a as [v utg].\n destruct utg.\n - rewrite GET in H1.\n move/(proj2 REFM): GET => //= [ctg DECctg GET].\n rewrite GET DECctg.\n simpl.\n destruct (decode_instr v).\n + (*is instruction*)\n destruct i eqn:OP; destruct o; try trivial.\n destruct (getm smem pc') as [[v' [[dst|]|]]|] eqn:SGET'.\n * rewrite SGET' in H1.\n move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * rewrite SGET' in H1.\n rewrite /Symbolic.pcv /=.\n destruct (getm cmem pc') as [[cv' ctg']|] eqn:GET'.\n { simpl.\n case DEC'': (rules.fdecode _ ctg') => [[ut|ut]|] //=.\n - by rewrite (proj1 REFM _ _ _ _ DEC'' GET') in SGET'.\n - unfold wf_entry_points in WF.\n destruct (stable pc') eqn:GETCALL.\n + rewrite GETCALL in H1.\n specialize (WF pc' (Symbolic.entry_tag s0)).\n assert (ECALL: (exists2 sc : Symbolic.syscall mt,\n stable pc' = Some sc &\n Symbolic.entry_tag sc = Symbolic.entry_tag s0))\n by (eexists; eauto).\n apply WF in ECALL.\n rewrite GET' in ECALL.\n move/andP in ECALL. destruct ECALL as [ISNOP CTG].\n move/eqP:CTG => CTG.\n rewrite /= DEC'' in CTG. case: CTG => CGT. subst ut.\n destruct (Symbolic.entry_tag s0) as [[?|]|] eqn:ETAG; rewrite ETAG in H1;\n auto.\n by rewrite (negbTE H1) andbF.\n + clear H1.\n case: ut DEC'' => [[ut|]|] //= DEC''.\n apply/negP=> /andP [ISNOP _].\n move: (wf_entry_points_only_if WF GET' DEC'' ISNOP) => [? ? ?].\n congruence.\n }\n { by reflexivity. }\n (*copy paste from above, TODO: fix*)\n destruct (getm smem pc') as [[v' [[dst|]|]]|] eqn:SGET'.\n * rewrite SGET' in H1.\n move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * move/(proj2 REFM): SGET' => [/= ctg' DECctg' SGET'].\n by rewrite SGET' DECctg'.\n * rewrite SGET' in H1.\n rewrite /Symbolic.pcv /=.\n destruct (getm cmem pc') as [[cv' ctg']|] eqn:GET'.\n { simpl.\n case DEC'': (rules.fdecode _ ctg') => [[ut|ut]|] //=.\n - by rewrite (proj1 REFM _ _ _ _ DEC'' GET') in SGET'.\n - unfold wf_entry_points in WF.\n destruct (stable pc') eqn:GETCALL.\n + rewrite GETCALL in H1.\n specialize (WF pc' (Symbolic.entry_tag s0)).\n assert (ECALL: (exists2 sc : Symbolic.syscall mt,\n stable pc' = Some sc &\n Symbolic.entry_tag sc = Symbolic.entry_tag s0))\n by (eexists; eauto).\n apply WF in ECALL.\n rewrite GET' in ECALL.\n case/andP: ECALL=> [ISNOP CTG].\n move/eqP:CTG => CTG.\n rewrite /= DEC'' in CTG. case: CTG => CGT. subst ut.\n destruct (Symbolic.entry_tag s0) as [[?|]|] eqn:ETAG; rewrite ETAG in H1;\n auto.\n by rewrite (negbTE H1) andbF.\n + clear H1.\n case: ut DEC'' => [[ut|]|] //= DEC''.\n apply/negP=> /andP [ISNOP _].\n move: (wf_entry_points_only_if WF GET' DEC'' ISNOP) => [? ? ?].\n congruence.\n }\n { by reflexivity. }\n + by assumption.\n - apply REFM in GET.\n case: GET=> ctg /= DEC'' GET.\n by rewrite /= GET DEC''.\n }\n { rewrite /Symbolic.pcv /=.\n destruct (getm cmem pc) as [[v ctg]|] eqn:GET'; trivial. simpl.\n case DECTG: (rules.fdecode _ _)=> [[t| ]| ] //=.\n by rewrite (proj1 REFM _ _ _ _ DECTG GET') in GET. }\n + destruct CONTRA' as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in USER'. rewrite KEXEC in USER'.\n discriminate.\n - destruct CONTRA as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n apply @in_user_in_monitor in USER. rewrite KEXEC in USER.\n discriminate.\nQed.\n\nProgram Instance cfi_refinementAS_specs :\n machine_refinement_specs cfi_refinementSC.\nNext Obligation. (*step or no step*)\n by case: (stepP' masks cst cst') => [H | H]; auto.\nQed.\nNext Obligation. (*initial states*)\n unfold Conc.cinitial in H.\n destruct H as [ast [INIT REF]].\n eexists; split; [eassumption | split].\n - left; assumption.\n - destruct INIT as [? INV]; by assumption.\nQed.\nNext Obligation.\n case/nandP: H1=> [CONTRA | NUSER].\n - destruct H as [REF INV].\n move: REF => [/(@refine_state_in_user _) INUSER | REF].\n + rewrite INUSER in CONTRA.\n by discriminate.\n + destruct REF as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n unfold Conc.csucc. rewrite KEXEC.\n by reflexivity.\n - destruct H as [REF INV].\n destruct REF as [REF | REF].\n + assert (MONITOR' := user_into_monitor REF H0 NUSER).\n unfold Conc.csucc. rewrite MONITOR'.\n rewrite orbT. reflexivity.\n + destruct REF as [? [? [? [? KEXEC]]]].\n apply restricted_exec_snd in KEXEC.\n unfold Conc.csucc. rewrite KEXEC.\n by reflexivity.\nQed.\nNext Obligation. (*symbolic-concrete cfg relation*)\n apply (introTF idP).\n have [SUCC|SUCC] := boolP (Sym.ssucc stable asi asj).\n - by eauto using cfg_true_equiv.\n - apply/negP. by eauto using cfg_false_equiv.\nQed.\nNext Obligation. (*symbolic no attacker on violation*)\n destruct H as [? INV].\n by eapply attacker_no_v; eauto.\nQed.\nNext Obligation. (*symbolic stopping implies concrete stopping*)\nProof.\n rename H into CHECK.\n rename H0 into SUCC.\n rename H1 into SSTEP.\n rename H2 into REFI.\n rename H3 into RTRACES.\n rename H4 into SSTOP.\n unfold Sym.stopping in SSTOP.\n unfold Conc.stopping.\n unfold check in CHECK.\n case/andP: CHECK => [USERI USERJ].\n destruct REFI as [WREFI INVI].\n inversion RTRACES\n as [? ? REF' | ? ? ? ? ? STEP CHECK REFJ REF' RTRACE'\n | ? ? ? ? ? ? STEP ASTEP REFJ REF' RTRACE'\n | ? ? ? ? ? ? NSTEP STEPA SSTEPA REF REF' RTRACE'];\n subst; simpl in *.\n - (*case trace is a singleton*)\n left.\n split; [intros ? ? IN2; destruct IN2 | idtac].\n by apply/andP; auto.\n - (*case an invisible step is taken*)\n destruct (Sym.succ_false_implies_violation INVI SUCC SSTEP)\n as [CONTRA | VIOLATION]; first done.\n right.\n exists [:: csj]; exists (cst' :: cxs0).\n split; auto.\n split.\n intros ? ? CONTRA; destruct CONTRA.\n split; first by apply/allP=> x; rewrite inE => /eqP -> {x}; auto.\n destruct (build_ivec stable asj) as [umvec|] eqn:UMVEC.\n + (*case the umvec for asj exists*)\n by eauto using violation_implies_kexec.\n + (*case where the umvec for asj does not exist*)\n by eauto using no_umvec_implies_kexec.\n - (*case of normal steps*)\n exfalso.\n destruct SSTOP as [? ALLS].\n have IN: asj \\in (asj :: ast' :: axs0) by rewrite inE eqxx.\n apply ALLS in IN.\n by eauto.\n - (*case of attacker steps*)\n destruct (Sym.succ_false_implies_violation INVI SUCC SSTEP)\n as [CONTRA | VIOLATION]; first done.\n destruct SSTOP as [ALLA ALLS].\n assert (STEPA' : Conc.step_a csj cst' /\\ ~ Concrete.step ops masks csj cst')\n by auto.\n clear STEPA NSTEP.\n destruct (attacker_up_to ALLA ALLS STEPA' RTRACES) as [ALLA' | IH].\n + left. split. by assumption.\n apply all_attacker_implies_all_user in ALLA'. by assumption.\n + (*inductive cases*)\n destruct IH\n as [chd [ctl [csi' [csj' [CLST [ALLA' [CSTEP [CHECK IH']]]]]]]].\n clear RTRACES RTRACE'.\n destruct IH' as [[asj' [RTRACE AEXEC]]| [asi' [asj' [atl RTRACE]]]].\n { (*non-contradictory case, we took some attacker steps at first*)\n assert (VIOLATION' := Sym.violation_preserved_by_exec_a VIOLATION AEXEC).\n clear VIOLATION.\n right.\n rewrite CLST.\n exists (chd++[:: csi']); exists (csj'::ctl).\n split. rewrite -catA. by reflexivity.\n split. by assumption.\n split.\n { apply/allP.\n destruct chd.\n - move=> x /=; rewrite inE; move=> /eqP {x}->.\n by inv CLST; auto.\n - move=> x IN.\n apply all_attacker_implies_all_user' in ALLA'.\n assert (ALLU: forall x, x \\in ((s :: chd) ++ [:: csi']) -> in_user x)\n by (apply/allP; auto).\n specialize (ALLU _ IN). by auto.\n }\n { inversion RTRACE as [| ? ? ? ? ? STEP' CHECK' REFI' REFJ' RTRACE' | |];\n subst.\n assert (USERI' : in_user csi').\n { destruct chd.\n - inv CLST.\n by assumption.\n - apply all_attacker_implies_all_user' in ALLA'.\n have IN: csi' \\in (s :: chd ++ [:: csi'])\n by rewrite !(inE, mem_cat) /= eqxx !orbT; eauto.\n assert (ALLU: forall x, x \\in ((s :: chd) ++ [:: csi']) -> in_user x)\n by (apply/allP; auto).\n specialize (ALLU _ IN). by auto.\n }\n destruct (build_ivec stable asj') as [umvec|] eqn:UMVEC.\n - (*case the umvec exists*)\n eauto using violation_implies_kexec.\n - (*case the umvec does not exist*)\n eauto using no_umvec_implies_kexec.\n }\n }\n { (*contradictory case, mixed attacker steps and unchecked ones*)\n exfalso.\n destruct RTRACE as [RTRACE [ALLS' [AEXEC REFN]]].\n destruct (refine_traces_astep RTRACE)\n as [csn [csn' [IN2 [SSTEPN | [SSTEPAN STEPAN]]]]].\n * assert (IN: asi' \\in (asi' :: asj' :: atl))\n by (rewrite !inE eqxx; auto).\n apply ALLS' in IN. by eauto.\n assert (VIOLATION' := Sym.violation_preserved_by_exec_a VIOLATION AEXEC).\n clear VIOLATION.\n assert (USERI' : in_user csi').\n { destruct chd.\n - inv CLST.\n by auto.\n - apply all_attacker_implies_all_user' in ALLA'.\n assert (ALLU : forall x, x \\in (s :: chd ++ [:: csi']) ->\n in_user x)\n by (apply/allP; auto).\n have IN: csi' \\in (s :: chd ++ [:: csi'])\n by rewrite !(inE, mem_cat) eqxx !orbT /=; auto.\n by auto.\n }\n assert (USERN: in_user csn)\n by (inv STEPAN; auto).\n destruct ctl; [by inversion RTRACE |idtac].\n destruct (build_ivec stable asi') as [umvec|] eqn:UMVEC.\n - (*case the umvec exists*)\n assert (MONITOR := violation_implies_kexec VIOLATION' UMVEC USERI'\n CHECK CSTEP REFN RTRACE).\n apply In2_implies_In in IN2.\n assert (MONITOR' : forall x, x \\in (csj' :: s :: ctl) -> in_monitor x)\n by (apply/allP; auto).\n apply MONITOR' in IN2.\n apply @in_user_in_monitor in USERN.\n rewrite IN2 in USERN.\n by discriminate.\n - (*case the umvec does not exist*)\n assert (MONITOR := no_umvec_implies_kexec VIOLATION' UMVEC USERI'\n CHECK CSTEP REFN RTRACE).\n apply In2_implies_In in IN2.\n assert (MONITOR' : forall x, x \\in (csj' :: s :: ctl) -> in_monitor x)\n by (apply/allP; auto).\n apply MONITOR' in IN2.\n apply @in_user_in_monitor in USERN.\n rewrite IN2 in USERN.\n by discriminate.\n }\nQed.\n\nEnd Refinement.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/cfi/refinementSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.22541662624228417, "lm_q1q2_score": 0.12411605472310602}} {"text": "(*\n * © 2020 XXX.\n * \n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n List.\n\nFrom SPICY Require Import\n MyPrelude\n Maps\n ChMaps\n Messages\n Keys\n Automation\n Tactics\n Simulation\n AdversaryUniverse\n\n ModelCheck.ModelCheck\n ModelCheck.UniverseEqAutomation\n ModelCheck.ProtocolAutomation\n ModelCheck.SafeProtocol\n ModelCheck.ProtocolFunctions\n ModelCheck.SilentStepElimination\n.\n\nFrom protocols Require Import\n PGP.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n RealWorld.RealWorldNotations\n SimulationAutomation.\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nModule PGPProtocolSecure <: AutomatedSafeProtocolSS.\n\n Import PGPProtocol.\n\n Definition t__hon := Nat.\n Definition t__adv := Unit.\n Definition b := tt.\n Definition iu0 := ideal_univ_start.\n Definition ru0 := real_univ_start.\n\n Import Gen Tacs SetLemmas.\n\n #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core.\n\n Lemma next_key_natmap_exists :\n forall {V} (m : NatMap.t V),\n exists k, m $? k = None.\n Proof.\n intros.\n exists (next_key m); eauto using Maps.next_key_not_in.\n Qed.\n\n Lemma next_key_chmap_exists :\n forall {V} (m : ChMap.t V),\n exists k, m #? (# k) = None.\n Proof.\n intros.\n exists (next_key_nat m); eauto using next_key_not_in.\n Qed.\n\n Lemma safe_invariant :\n invariantFor\n {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv |}\n (fun st => safety st /\\ alignment st /\\ returns_align st).\n Proof.\n eapply invariant_weaken.\n\n - eapply multiStepClosure_ok; simpl.\n autounfold in *.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n gen1.\n \n - intros.\n simpl in *.\n\n sets_invert; split_ex\n ; simpl in *; autounfold with core\n ; subst; simpl\n ; unfold safety, alignment, returns_align\n ; ( repeat simple apply conj\n ; [ solve_honest_actions_safe; clean_map_lookups; eauto 8\n | trivial\n | unfold labels_align; intros; rstep; subst; solve_labels_align\n | try solve [ intros; find_step_or_solve ] \n ]).\n\n Unshelve.\n all: exact 0 || auto.\n\n Qed.\n \n Lemma U_good : @universe_starts_sane _ Unit b ru0.\n Proof.\n autounfold;\n unfold universe_starts_sane; simpl.\n repeat (apply conj); intros; eauto.\n - solve_perm_merges; eauto.\n - econstructor.\n - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros.\n unfold mkrUsr; simpl.\n rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto.\n - unfold lameAdv; simpl; eauto.\n Qed.\n\n Lemma universe_starts_safe : universe_ok ru0.\n Proof.\n pose proof (adversary_is_lame_adv_univ_ok_clauses U_good).\n \n unfold universe_ok\n ; autounfold\n ; simpl\n ; intuition eauto\n .\n\n - econstructor; eauto.\n - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto.\n solve_simple_maps; eauto.\n\n rewrite Forall_natmap_forall; intros.\n\n solve_simple_maps; simpl\n ; unfold permission_heap_good; intros;\n solve_simple_maps; solve_concrete_maps; eauto.\n\n - unfold user_cipher_queues_ok.\n rewrite Forall_natmap_forall; intros.\n focus_user\n ; simpl in *; econstructor; eauto.\n\n - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok\n ; repeat simple apply conj\n ; intros\n ; clean_map_lookups\n ; intros\n ; focus_user\n ; try contradiction; try discriminate; simpl;\n repeat (apply conj); intros; clean_map_lookups; eauto.\n\n - unfold honest_users_only_honest_keys; intros.\n focus_user;\n subst;\n simpl in *;\n clean_map_lookups;\n unfold mkrUsr; simpl; \n rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty;\n eauto;\n simpl in *;\n solve_perm_merges;\n solve_concrete_maps;\n solve_simple_maps;\n eauto.\n Qed.\n\nEnd PGPProtocolSecure.\n", "meta": {"author": "usenix21-paper58", "repo": "paper58", "sha": "e5117b0cb1d749df1768c9098aee7112ae16d8e9", "save_path": "github-repos/coq/usenix21-paper58-paper58", "path": "github-repos/coq/usenix21-paper58-paper58/paper58-e5117b0cb1d749df1768c9098aee7112ae16d8e9/protocols/PGPSS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.24508500761839525, "lm_q1q2_score": 0.12349984764307606}} {"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import Eqdep_dec.\nRequire Import Classes.SetoidTactics.\nRequire Import Pred PredCrash.\nRequire Import Prog.\nRequire Import Hoare.\nRequire Import SepAuto.\nRequire Import BasicProg.\nRequire Import Omega.\nRequire Import Word.\nRequire Import Rec.\nRequire Import Array.\nRequire Import WordAuto.\nRequire Import Cache.\nRequire Import FSLayout.\nRequire Import Rounding.\nRequire Import List ListUtils.\nRequire Import Psatz.\nRequire Import AsyncDisk.\nRequire Import RecArrayUtils.\nRequire Import AsyncRecArray.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n\nModule PaddedLog.\n\n Module DescSig <: RASig.\n\n Definition xparams := log_xparams.\n Definition RAStart := LogDescriptor.\n Definition RALen := LogDescLen.\n Definition xparams_ok (xp : xparams) := goodSize addrlen ((RAStart xp) + (RALen xp)).\n\n Definition itemtype := Rec.WordF addrlen.\n Definition items_per_val := valulen / addrlen.\n\n Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n Proof.\n unfold items_per_val; simpl.\n rewrite valulen_is.\n cbv; auto.\n Qed.\n\n End DescSig.\n\n\n Module DataSig <: RASig.\n\n Definition xparams := log_xparams.\n Definition RAStart := LogData.\n Definition RALen := LogLen.\n Definition xparams_ok (xp : xparams) := goodSize addrlen ((RAStart xp) + (RALen xp)).\n\n Definition itemtype := Rec.WordF valulen.\n Definition items_per_val := 1.\n\n Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n Proof.\n unfold items_per_val; simpl.\n rewrite valulen_is.\n cbv; auto.\n Qed.\n\n End DataSig.\n\n Module Desc := AsyncRecArray DescSig.\n Module Data := AsyncRecArray DataSig.\n Module DescDefs := Desc.Defs.\n Module DataDefs := Data.Defs.\n\n\n (************* Log header *)\n Module Hdr.\n Definition header_type := Rec.RecF ([(\"ndesc\", Rec.WordF addrlen);\n (\"ndata\", Rec.WordF addrlen)]).\n Definition header := Rec.data header_type.\n Definition hdr := (nat * nat)%type.\n Definition mk_header (len : hdr) : header := ($ (fst len), ($ (snd len), tt)).\n\n Theorem hdrsz_ok : Rec.len header_type <= valulen.\n Proof.\n rewrite valulen_is. apply leb_complete. compute. trivial.\n Qed.\n Local Hint Resolve hdrsz_ok.\n\n Lemma plus_minus_header : Rec.len header_type + (valulen - Rec.len header_type) = valulen.\n Proof.\n apply le_plus_minus_r; auto.\n Qed.\n\n Definition hdr2val (h : header) : valu.\n set (zext (Rec.to_word h) (valulen - Rec.len header_type)) as r.\n rewrite plus_minus_header in r.\n refine r.\n Defined.\n\n Definition val2hdr (v : valu) : header.\n apply Rec.of_word.\n rewrite <- plus_minus_header in v.\n refine (split1 _ _ v).\n Defined.\n\n Arguments hdr2val: simpl never.\n\n Lemma val2hdr2val : forall h,\n val2hdr (hdr2val h) = h.\n Proof.\n unfold val2hdr, hdr2val.\n unfold eq_rec_r, eq_rec.\n intros.\n rewrite <- plus_minus_header.\n unfold zext.\n autorewrite with core; auto.\n simpl; destruct h; tauto.\n Qed.\n\n Arguments val2hdr: simpl never.\n Opaque val2hdr. (* for some reason \"simpl never\" doesn't work *)\n\n\n Definition xparams := log_xparams.\n Definition LAHdr := LogHeader.\n\n Inductive state : Type :=\n | Synced : hdr -> state\n | Unsync : hdr -> hdr -> state\n .\n\n Definition state_goodSize st :=\n match st with\n | Synced n => goodSize addrlen (fst n) /\\ goodSize addrlen (snd n)\n | Unsync n o => goodSize addrlen (fst n) /\\ goodSize addrlen (snd n) /\\\n goodSize addrlen (fst o) /\\ goodSize addrlen (snd o)\n end.\n\n Definition rep xp state : @rawpred :=\n ([[ state_goodSize state ]] *\n match state with\n | Synced n =>\n (LAHdr xp) |-> (hdr2val (mk_header n), nil)\n | Unsync n o =>\n (LAHdr xp) |-> (hdr2val (mk_header n), [hdr2val (mk_header o)]%list)\n end)%pred.\n\n Definition xform_rep_synced : forall xp n,\n crash_xform (rep xp (Synced n)) =p=> rep xp (Synced n).\n Proof.\n unfold rep; intros; simpl.\n xform; auto.\n Qed.\n\n Definition xform_rep_unsync : forall xp n o,\n crash_xform (rep xp (Unsync n o)) =p=> rep xp (Synced n) \\/ rep xp (Synced o).\n Proof.\n unfold rep; intros; simpl.\n xform; cancel.\n or_l; cancel.\n or_r; cancel.\n Qed.\n\n Definition read T xp cs rx : prog T := Eval compute_rec in\n let^ (cs, v) <- BUFCACHE.read (LAHdr xp) cs;\n rx ^(cs, (# ((val2hdr v) :-> \"ndesc\"), # ((val2hdr v) :-> \"ndata\"))).\n\n Definition write T xp n cs rx : prog T :=\n cs <- BUFCACHE.write (LAHdr xp) (hdr2val (mk_header n)) cs;\n rx cs.\n\n Definition sync T xp cs rx : prog T :=\n cs <- BUFCACHE.sync (LAHdr xp) cs;\n rx cs.\n\n Local Hint Unfold rep state_goodSize : hoare_unfold.\n\n Theorem write_ok : forall xp n cs,\n {< F d old,\n PRE BUFCACHE.rep cs d *\n [[ goodSize addrlen (fst n) /\\ goodSize addrlen (snd n) ]] *\n [[ (F * rep xp (Synced old))%pred d ]]\n POST RET: cs\n exists d', BUFCACHE.rep cs d' *\n [[ (F * rep xp (Unsync n old))%pred d' ]]\n XCRASH exists cs' d', BUFCACHE.rep cs' d' * [[ (F * rep xp (Unsync n old))%pred d' ]]\n >} write xp n cs.\n Proof.\n unfold write.\n hoare.\n xcrash.\n Qed.\n\n Theorem read_ok : forall xp cs,\n {< F d n,\n PRE BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced n))%pred d ]]\n POST RET: ^(cs, r)\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced n))%pred d ]] *\n [[ r = n ]]\n CRASH exists cs', BUFCACHE.rep cs' d\n >} read xp cs.\n Proof.\n unfold read.\n hoare.\n subst; rewrite val2hdr2val; simpl.\n unfold mk_header, Rec.recget'; simpl.\n repeat rewrite wordToNat_natToWord_idempotent'; auto.\n destruct n; auto.\n Qed.\n\n Theorem sync_ok : forall xp cs,\n {< F d n old,\n PRE BUFCACHE.rep cs d *\n [[ (F * rep xp (Unsync n old))%pred d ]]\n POST RET: cs\n exists d', BUFCACHE.rep cs d' *\n [[ (F * rep xp (Synced n))%pred d' ]]\n XCRASH exists cs' d', BUFCACHE.rep cs' d' *\n [[ (F * rep xp (Unsync n old))%pred d' ]]\n >} sync xp cs.\n Proof.\n unfold sync.\n hoare.\n xcrash.\n Qed.\n\n Hint Extern 1 ({{_}} progseq (write _ _ _) _) => apply write_ok : prog.\n Hint Extern 1 ({{_}} progseq (read _ _) _) => apply read_ok : prog.\n Hint Extern 1 ({{_}} progseq (sync _ _) _) => apply sync_ok : prog.\n\n End Hdr.\n\n\n (****************** Log contents and states *)\n\n Definition entry := (addr * valu)%type.\n Definition contents := list entry.\n\n Inductive state :=\n (* The log is synced on disk *)\n | Synced (l: contents)\n (* The log has been truncated; but the length (0) is unsynced *)\n | Truncated (old: contents)\n (* The log is being extended; only the content has been updated (unsynced) *)\n | ExtendedUnsync (old: contents)\n (* The log has been extended; the new contents are synced but the length is unsynced *)\n | Extended (old: contents) (new: contents).\n\n Definition ent_addr (e : entry) := addr2w (fst e).\n Definition ent_valu (e : entry) := snd e.\n\n Definition ndesc_log (log : contents) := (divup (length log) DescSig.items_per_val).\n\n Fixpoint log_nonzero (log : contents) : list entry :=\n match log with\n | (0, _) :: rest => log_nonzero rest\n | e :: rest => e :: log_nonzero rest\n | nil => nil\n end.\n\n Definition vals_nonzero (log : contents) := map ent_valu (log_nonzero log).\n\n Fixpoint nonzero_addrs (al : list addr) : nat :=\n match al with\n | 0 :: rest => nonzero_addrs rest\n | e :: rest => S (nonzero_addrs rest)\n | nil => 0\n end.\n\n Fixpoint combine_nonzero (al : list addr) (vl : list valu) : contents :=\n match al, vl with\n | 0 :: al', v :: vl' => combine_nonzero al' vl\n | a :: al', v :: vl' => (a, v) :: (combine_nonzero al' vl')\n | _, _ => nil\n end.\n\n Definition ndata_log (log : contents) := nonzero_addrs (map fst log) .\n\n Definition addr_valid (e : entry) := goodSize addrlen (fst e).\n\n Definition entry_valid (ent : entry) := fst ent <> 0 /\\ addr_valid ent.\n\n Definition rep_contents xp (log : contents) : rawpred :=\n ( [[ Forall addr_valid log ]] *\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr log)) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero log)) *\n Desc.avail_rep xp (ndesc_log log) (LogDescLen xp - (ndesc_log log)) *\n Data.avail_rep xp (ndata_log log) (LogLen xp - (ndata_log log))\n )%pred.\n\n Definition padded_addr (al : list addr) :=\n setlen al (roundup (length al) DescSig.items_per_val) 0.\n\n Definition padded_log (log : contents) :=\n setlen log (roundup (length log) DescSig.items_per_val) (0, $0).\n\n Definition rep_inner xp (st : state) : rawpred :=\n (match st with\n | Synced l =>\n Hdr.rep xp (Hdr.Synced (ndesc_log l, ndata_log l)) *\n rep_contents xp l\n\n | Truncated old =>\n Hdr.rep xp (Hdr.Unsync (0, 0) (ndesc_log old, ndata_log old)) *\n rep_contents xp old\n\n | ExtendedUnsync old =>\n Hdr.rep xp (Hdr.Synced (ndesc_log old, ndata_log old)) *\n rep_contents xp old\n\n | Extended old new =>\n Hdr.rep xp (Hdr.Unsync (ndesc_log old + ndesc_log new, ndata_log old + ndata_log new)\n (ndesc_log old, ndata_log old)) *\n rep_contents xp ((padded_log old) ++ new) *\n [[ Forall entry_valid new ]]\n end)%pred.\n\n Definition xparams_ok xp := \n DescSig.xparams_ok xp /\\ DataSig.xparams_ok xp /\\\n (LogLen xp) = DescSig.items_per_val * (LogDescLen xp).\n\n Definition rep xp st (hm : hashmap) :=\n ([[ xparams_ok xp ]] * rep_inner xp st)%pred.\n\n Local Hint Unfold rep rep_inner rep_contents xparams_ok: hoare_unfold.\n\n Definition avail T xp cs rx : prog T :=\n let^ (cs, nr) <- Hdr.read xp cs;\n let '(ndesc, ndata) := nr in\n rx ^(cs, ((LogLen xp) - ndesc * DescSig.items_per_val)).\n\n Definition read T xp cs rx : prog T :=\n let^ (cs, nr) <- Hdr.read xp cs;\n let '(ndesc, ndata) := nr in\n let^ (cs, wal) <- Desc.read_all xp ndesc cs;\n let al := map (@wordToNat addrlen) wal in\n let^ (cs, vl) <- Data.read_all xp ndata cs;\n rx ^(cs, combine_nonzero al vl).\n\n (* this is an evil hint *)\n Remove Hints Forall_nil.\n\n Lemma Forall_True : forall A (l : list A),\n Forall (fun _ : A => True) l.\n Proof.\n intros; rewrite Forall_forall; auto.\n Qed.\n Hint Resolve Forall_True.\n\n Lemma combine_nonzero_ok : forall l,\n combine_nonzero (map fst l) (vals_nonzero l) = log_nonzero l.\n Proof.\n unfold vals_nonzero.\n induction l; intros; simpl; auto.\n destruct a, n; simpl.\n case_eq (map ent_valu (log_nonzero l)); intros; simpl.\n apply map_eq_nil in H; auto.\n rewrite <- H; auto.\n rewrite IHl; auto.\n Qed.\n\n Lemma combine_nonzero_nil : forall a,\n combine_nonzero a nil = nil.\n Proof.\n induction a; intros; simpl; auto.\n destruct a; simpl; auto.\n Qed.\n Local Hint Resolve combine_nonzero_nil.\n\n Lemma combine_nonzero_app_zero : forall a b,\n combine_nonzero (a ++ [0]) b = combine_nonzero a b.\n Proof.\n induction a; intros; simpl; auto.\n destruct b; auto.\n destruct a, b; simpl; auto.\n rewrite IHa; auto.\n Qed.\n\n Lemma combine_nonzero_app_zeros : forall n a b,\n combine_nonzero (a ++ repeat 0 n) b = combine_nonzero a b.\n Proof.\n induction n; intros; simpl.\n rewrite app_nil_r; auto.\n rewrite <- cons_nil_app.\n rewrite IHn.\n apply combine_nonzero_app_zero.\n Qed.\n\n Local Hint Resolve roundup_ge DescDefs.items_per_val_gt_0.\n\n Lemma combine_nonzero_padded_addr : forall a b,\n combine_nonzero (padded_addr a) b = combine_nonzero a b.\n Proof.\n unfold padded_addr, vals_nonzero.\n induction a; intros; simpl; auto.\n unfold setlen, roundup; simpl.\n rewrite divup_0; simpl; auto.\n\n unfold setlen, roundup; simpl.\n destruct a, b; simpl; auto;\n rewrite firstn_oob; simpl; auto;\n rewrite combine_nonzero_app_zeros; auto.\n Qed.\n\n Lemma map_fst_repeat : forall A B n (a : A) (b : B),\n map fst (repeat (a, b) n) = repeat a n.\n Proof.\n induction n; intros; simpl; auto.\n rewrite IHn; auto.\n Qed.\n\n Lemma map_entaddr_repeat_0 : forall n b,\n map ent_addr (repeat (0, b) n) = repeat $0 n.\n Proof.\n induction n; intros; simpl; auto.\n rewrite IHn; auto.\n Qed.\n\n Lemma combine_nonzero_padded_log : forall l b,\n combine_nonzero (map fst (padded_log l)) b = combine_nonzero (map fst l) b.\n Proof.\n unfold padded_log, setlen, roundup; intros.\n induction l; simpl.\n rewrite divup_0; simpl; auto.\n \n rewrite <- IHl.\n destruct a, b, n; simpl; auto;\n repeat rewrite firstn_oob; simpl; auto;\n repeat rewrite map_app;\n setoid_rewrite map_fst_repeat;\n repeat rewrite combine_nonzero_app_zeros; auto.\n Qed.\n\n Lemma addr_valid_padded : forall l,\n Forall addr_valid l -> Forall addr_valid (padded_log l).\n Proof.\n unfold padded_log, setlen, roundup; intros.\n rewrite firstn_oob; simpl; auto.\n apply Forall_append; auto.\n rewrite Forall_forall; intros.\n apply repeat_spec in H0; subst.\n unfold addr_valid; simpl.\n apply zero_lt_pow2.\n Qed.\n\n Lemma padded_addr_valid : forall l,\n Forall addr_valid (padded_log l) ->\n Forall addr_valid l.\n Proof.\n unfold padded_log, setlen; intros.\n rewrite firstn_oob in H; auto.\n eapply forall_app_r; eauto.\n Qed.\n\n Local Hint Resolve addr_valid_padded padded_addr_valid.\n\n Lemma map_wordToNat_ent_addr : forall l,\n Forall addr_valid l ->\n (map (@wordToNat _) (map ent_addr l)) = map fst l.\n Proof.\n unfold ent_addr, addr2w.\n induction l; intros; simpl; auto.\n rewrite IHl; f_equal.\n rewrite wordToNat_natToWord_idempotent'; auto.\n apply Forall_inv in H; unfold addr_valid in H; auto.\n eapply Forall_cons2; eauto.\n Qed.\n\n Lemma combine_nonzero_padded_wordToNat : forall l,\n Forall addr_valid l ->\n combine_nonzero (map (@wordToNat _) (map ent_addr (padded_log l))) (vals_nonzero l) = log_nonzero l.\n Proof.\n intros; unfold ent_addr, addr2w.\n rewrite <- combine_nonzero_ok.\n rewrite <- combine_nonzero_padded_log.\n f_equal.\n rewrite map_wordToNat_ent_addr; auto.\n Qed.\n\n Lemma vals_nonzero_addrs : forall l,\n length (vals_nonzero l) = nonzero_addrs (map fst l).\n Proof.\n induction l; intros; simpl; auto.\n destruct a, n; simpl; auto.\n Qed.\n\n Lemma log_nonzero_addrs : forall l,\n length (log_nonzero l) = nonzero_addrs (map fst l).\n Proof.\n induction l; intros; simpl; auto.\n destruct a, n; simpl; auto.\n Qed.\n\n Lemma desc_ipack_padded : forall l,\n DescDefs.ipack (map ent_addr l) = DescDefs.ipack (map ent_addr (padded_log l)).\n Proof.\n unfold padded_log, setlen; intros.\n rewrite firstn_oob, map_app, map_entaddr_repeat_0 by auto.\n rewrite DescDefs.ipack_app_item0; auto.\n rewrite map_length; auto.\n Qed.\n\n Local Hint Resolve combine_nonzero_padded_wordToNat.\n\n Lemma desc_padding_synced_piff : forall xp a l,\n Desc.array_rep xp a (Desc.Synced (map ent_addr (padded_log l)))\n <=p=> Desc.array_rep xp a (Desc.Synced (map ent_addr l)).\n Proof.\n unfold Desc.array_rep, Desc.synced_array, Desc.rep_common; intros.\n split; cancel; subst.\n unfold padded_log, setlen, roundup in H0.\n rewrite firstn_oob, map_app in H0 by auto.\n apply Desc.items_valid_app in H0; intuition.\n apply eq_sym; apply desc_ipack_padded.\n unfold padded_log, setlen, roundup.\n rewrite firstn_oob, map_app by auto.\n apply Desc.items_valid_app2; auto.\n autorewrite with lists; auto.\n apply desc_ipack_padded.\n Qed.\n\n Lemma desc_padding_unsync_piff : forall xp a l,\n Desc.array_rep xp a (Desc.Unsync (map ent_addr (padded_log l)))\n <=p=> Desc.array_rep xp a (Desc.Unsync (map ent_addr l)).\n Proof.\n unfold Desc.array_rep, Desc.unsync_array, Desc.rep_common; intros.\n split; cancel; subst.\n unfold padded_log, setlen, roundup in H.\n rewrite firstn_oob, map_app in H by auto.\n apply Desc.items_valid_app in H; intuition.\n apply eq_sym; apply desc_ipack_padded.\n unfold padded_log, setlen, roundup.\n rewrite firstn_oob, map_app by auto.\n apply Desc.items_valid_app2; auto.\n autorewrite with lists; auto.\n apply desc_ipack_padded.\n Qed.\n\n Lemma goodSize_ndesc : forall l,\n goodSize addrlen (length l) -> goodSize addrlen (ndesc_log l).\n Proof.\n intros; unfold ndesc_log.\n eapply goodSize_trans; [ apply divup_le | eauto ].\n destruct (mult_O_le (length l) DescSig.items_per_val); auto.\n contradict H0; apply DescDefs.items_per_val_not_0.\n Qed.\n Local Hint Resolve goodSize_ndesc.\n\n Lemma padded_log_length: forall l,\n length (padded_log l) = roundup (length l) DescSig.items_per_val.\n Proof.\n unfold padded_log, roundup; intros.\n rewrite setlen_length; auto.\n Qed.\n\n Lemma nonzero_addrs_app_zero : forall a,\n nonzero_addrs (a ++ [0]) = nonzero_addrs a.\n Proof.\n induction a; intros; simpl; auto.\n destruct a; simpl; auto.\n Qed.\n\n Lemma nonzero_addrs_app_zeros : forall n a,\n nonzero_addrs (a ++ repeat 0 n) = nonzero_addrs a.\n Proof.\n induction n; intros; simpl.\n rewrite app_nil_r; auto.\n rewrite <- cons_nil_app.\n rewrite IHn.\n apply nonzero_addrs_app_zero.\n Qed.\n\n Lemma nonzero_addrs_padded_log : forall l,\n nonzero_addrs (map fst (padded_log l)) = nonzero_addrs (map fst l).\n Proof.\n unfold padded_log; induction l; simpl; auto.\n rewrite setlen_nil, repeat_is_nil; simpl; auto.\n unfold roundup; rewrite divup_0; omega.\n \n destruct a, n; simpl;\n rewrite <- IHl;\n unfold setlen, roundup;\n repeat rewrite firstn_oob, map_app by auto;\n setoid_rewrite map_fst_repeat;\n repeat rewrite nonzero_addrs_app_zeros; simpl; auto.\n Qed.\n\n Lemma vals_nonzero_length : forall l,\n length (vals_nonzero l) <= length l.\n Proof.\n unfold vals_nonzero; induction l; intros; simpl; auto.\n destruct a, n; simpl; auto.\n autorewrite with lists in *; omega.\n Qed.\n\n Lemma ndata_log_goodSize : forall l,\n goodSize addrlen (length l) -> goodSize addrlen (ndata_log l).\n Proof.\n unfold ndata_log; intros.\n rewrite <- vals_nonzero_addrs.\n eapply goodSize_trans.\n apply vals_nonzero_length; auto.\n auto.\n Qed.\n Local Hint Resolve ndata_log_goodSize.\n\n\n Arguments Desc.array_rep : simpl never.\n Arguments Data.array_rep : simpl never.\n Arguments Desc.avail_rep : simpl never.\n Arguments Data.avail_rep : simpl never.\n Arguments divup : simpl never.\n Hint Extern 0 (okToUnify (Hdr.rep _ _) (Hdr.rep _ _)) => constructor : okToUnify.\n Hint Extern 0 (okToUnify (Desc.array_rep _ _ _) (Desc.array_rep _ _ _)) => constructor : okToUnify.\n Hint Extern 0 (okToUnify (Data.array_rep _ _ _) (Data.array_rep _ _ _)) => constructor : okToUnify.\n Hint Extern 0 (okToUnify (Desc.avail_rep _ _ _) (Desc.avail_rep _ _ _)) => constructor : okToUnify.\n Hint Extern 0 (okToUnify (Data.avail_rep _ _ _) (Data.avail_rep _ _ _)) => constructor : okToUnify.\n\n\n Definition avail_ok : forall xp cs,\n {< F l d,\n PRE:hm\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced l) hm)%pred d ]]\n POST:hm' RET: ^(cs, r)\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced l) hm')%pred d ]] *\n [[ r = (LogLen xp) - roundup (length l) DescSig.items_per_val ]]\n CRASH:hm' exists cs',\n BUFCACHE.rep cs' d *\n [[ (F * rep xp (Synced l) hm')%pred d ]]\n >} avail xp cs.\n Proof.\n unfold avail.\n safestep.\n safestep.\n cancel.\n Qed.\n\n Definition read_ok : forall xp cs,\n {< F l d,\n PRE:hm\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced l) hm)%pred d ]]\n POST:hm' RET: ^(cs, r)\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced l) hm')%pred d ]] *\n [[ r = log_nonzero l ]]\n CRASH:hm' exists cs',\n BUFCACHE.rep cs' d *\n [[ (F * rep xp (Synced l) hm')%pred d ]]\n >} read xp cs.\n Proof.\n unfold read.\n safestep.\n prestep. norm. cancel. intuition simpl.\n eassign (map ent_addr (padded_log l)).\n rewrite map_length, padded_log_length.\n auto. auto.\n pred_apply.\n rewrite desc_padding_synced_piff; cancel.\n\n safestep.\n setoid_rewrite vals_nonzero_addrs; unfold ndata_log.\n replace DataSig.items_per_val with 1 by (cbv; auto); omega.\n\n safestep.\n rewrite desc_padding_synced_piff; cancel.\n replace (map ent_valu (log_nonzero l)) with (vals_nonzero l); auto.\n\n all: cancel.\n rewrite desc_padding_synced_piff; cancel.\n Qed.\n\n\n Lemma goodSize_0 : forall sz, goodSize sz 0.\n Proof.\n unfold goodSize; intros.\n apply zero_lt_pow2.\n Qed.\n\n Lemma ndesc_log_nil : ndesc_log nil = 0.\n Proof.\n unfold ndesc_log; simpl.\n rewrite divup_0; auto.\n Qed.\n\n Lemma ndata_log_nil : ndata_log nil = 0.\n Proof.\n unfold ndata_log; simpl; auto.\n Qed.\n\n Local Hint Resolve goodSize_0.\n\n\n Definition trunc T xp cs rx : prog T :=\n cs <- Hdr.write xp (0, 0) cs;\n cs <- Hdr.sync xp cs;\n rx cs.\n\n Local Hint Resolve Forall_nil.\n\n Lemma helper_sep_star_reorder : forall (a b c d : rawpred),\n a * b * c * d =p=> (a * c) * (b * d).\n Proof.\n intros; cancel.\n Qed.\n\n Lemma helper_add_sub_0 : forall a b,\n a <= b -> a + (b - a) + 0 = b.\n Proof.\n intros; omega.\n Qed.\n\n Lemma helper_trunc_ok : forall xp l,\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr l)) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero l)) *\n Desc.avail_rep xp (ndesc_log l) (LogDescLen xp - ndesc_log l) *\n Data.avail_rep xp (ndata_log l) (LogLen xp - ndata_log l) *\n Hdr.rep xp (Hdr.Synced (0, 0))\n =p=>\n Hdr.rep xp (Hdr.Synced (ndesc_log [], ndata_log [])) *\n Desc.array_rep xp 0 (Desc.Synced []) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero [])) *\n Desc.avail_rep xp (ndesc_log []) (LogDescLen xp - ndesc_log []) *\n Data.avail_rep xp (ndata_log []) (LogLen xp - ndata_log []).\n Proof.\n intros.\n unfold ndesc_log, vals_nonzero; simpl; rewrite divup_0.\n rewrite Desc.array_rep_sync_nil_sep_star, Data.array_rep_sync_nil_sep_star; auto.\n cancel.\n unfold ndata_log; simpl; repeat rewrite Nat.sub_0_r.\n rewrite <- log_nonzero_addrs.\n rewrite Data.array_rep_size_ok_pimpl, Desc.array_rep_size_ok_pimpl.\n rewrite Data.array_rep_avail, Desc.array_rep_avail.\n simpl; rewrite divup_1; autorewrite with lists.\n cancel.\n rewrite helper_sep_star_reorder.\n rewrite Desc.avail_rep_merge by auto.\n rewrite Data.avail_rep_merge by auto.\n repeat rewrite helper_add_sub_0 by auto.\n cancel.\n Qed.\n\n Definition trunc_ok : forall xp cs,\n {< F l d,\n PRE:hm\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced l) hm)%pred d ]]\n POST:hm' RET: cs exists d',\n BUFCACHE.rep cs d' *\n [[ (F * rep xp (Synced nil) hm')%pred d' ]]\n XCRASH:hm' exists cs' d',\n BUFCACHE.rep cs' d' * [[ (F * (rep xp (Truncated l) hm'))%pred d' ]]\n >} trunc xp cs.\n Proof.\n unfold trunc.\n step.\n step.\n step.\n cancel_by helper_trunc_ok.\n\n (* crash conditions *)\n xcrash.\n xcrash.\n Qed.\n\n Definition loglen_valid xp ndesc ndata :=\n ndesc <= LogDescLen xp /\\ ndata <= LogLen xp.\n\n Definition loglen_invalid xp ndesc ndata :=\n ndesc > LogDescLen xp \\/ ndata > LogLen xp.\n\n Definition loglen_valid_dec xp ndesc ndata :\n {loglen_valid xp ndesc ndata} + {loglen_invalid xp ndesc ndata }.\n Proof.\n unfold loglen_valid, loglen_invalid.\n destruct (lt_dec (LogDescLen xp) ndesc);\n destruct (lt_dec (LogLen xp) ndata); simpl; auto.\n left; intuition.\n Defined.\n\n Remove Hints goodSize_0.\n\n Definition entry_valid_ndata : forall l,\n Forall entry_valid l -> ndata_log l = length l.\n Proof.\n unfold ndata_log; induction l; rewrite Forall_forall; intuition.\n destruct a, n; simpl.\n exfalso; intuition.\n apply (H (0, w)); simpl; auto.\n rewrite IHl; auto.\n rewrite Forall_forall; intros.\n apply H; simpl; intuition.\n Qed.\n\n Lemma loglen_valid_desc_valid : forall xp old new,\n DescSig.xparams_ok xp ->\n loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n Desc.items_valid xp (ndesc_log old) (map ent_addr new).\n Proof.\n unfold Desc.items_valid, loglen_valid.\n intuition.\n unfold DescSig.RALen; omega.\n autorewrite with lists; unfold DescSig.RALen.\n apply divup_ge; auto.\n unfold ndesc_log in *; omega.\n Qed.\n Local Hint Resolve loglen_valid_desc_valid.\n\n\n Lemma loglen_valid_data_valid : forall xp old new,\n DataSig.xparams_ok xp ->\n Forall entry_valid new ->\n loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n Data.items_valid xp (ndata_log old) (map ent_valu new).\n Proof.\n unfold Data.items_valid, loglen_valid.\n intuition.\n unfold DataSig.RALen; omega.\n autorewrite with lists; unfold DataSig.RALen.\n apply divup_ge; auto.\n rewrite divup_1; rewrite <- entry_valid_ndata by auto.\n unfold ndata_log in *; omega.\n Qed.\n Local Hint Resolve loglen_valid_data_valid.\n\n Lemma helper_loglen_desc_valid_extend : forall xp new old,\n loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n ndesc_log new + (LogDescLen xp - ndesc_log old - ndesc_log new) \n = LogDescLen xp - ndesc_log old.\n Proof.\n unfold loglen_valid, ndesc_log; intros.\n omega.\n Qed.\n\n Lemma helper_loglen_data_valid_extend : forall xp new old,\n loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n ndata_log new + (LogLen xp - ndata_log old - ndata_log new) \n = LogLen xp - ndata_log old.\n Proof.\n unfold loglen_valid, ndata_log; intros.\n omega.\n Qed.\n\n Lemma helper_loglen_data_valid_extend_entry_valid : forall xp new old,\n Forall entry_valid new ->\n loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n length new + (LogLen xp - ndata_log old - ndata_log new) \n = LogLen xp - ndata_log old.\n Proof.\n intros.\n rewrite <- entry_valid_ndata by auto.\n apply helper_loglen_data_valid_extend; auto.\n Qed.\n\n Lemma padded_desc_valid : forall xp st l,\n Desc.items_valid xp st (map ent_addr l)\n -> Desc.items_valid xp st (map ent_addr (padded_log l)).\n Proof.\n unfold Desc.items_valid; intuition.\n autorewrite with lists in *.\n rewrite padded_log_length; unfold roundup.\n apply Nat.mul_le_mono_pos_r.\n apply DescDefs.items_per_val_gt_0.\n apply divup_le; lia.\n Qed.\n\n Lemma mul_le_mono_helper : forall a b,\n b > 0 -> a <= a * b.\n Proof.\n intros; rewrite Nat.mul_comm.\n destruct (mult_O_le a b); auto; omega.\n Qed.\n\n Lemma loglen_valid_goodSize_l : forall xp a b,\n loglen_valid xp a b -> DescSig.xparams_ok xp -> DataSig.xparams_ok xp ->\n goodSize addrlen a.\n Proof.\n unfold loglen_valid, DescSig.xparams_ok, DataSig.xparams_ok; intuition.\n eapply goodSize_trans.\n eapply le_trans. eauto.\n apply le_plus_r. eauto.\n Qed.\n\n Lemma loglen_valid_goodSize_r : forall xp a b,\n loglen_valid xp a b -> DescSig.xparams_ok xp -> DataSig.xparams_ok xp ->\n goodSize addrlen b.\n Proof.\n unfold loglen_valid, DescSig.xparams_ok, DataSig.xparams_ok; intuition.\n eapply goodSize_trans.\n eapply le_trans. eauto.\n apply le_plus_r. eauto.\n Qed.\n\n Lemma ent_valid_addr_valid : forall l,\n Forall entry_valid l -> Forall addr_valid l.\n Proof.\n intros; rewrite Forall_forall in *; intros.\n apply H; auto.\n Qed.\n Local Hint Resolve ent_valid_addr_valid.\n Local Hint Resolve Forall_append DescDefs.items_per_val_not_0.\n\n Lemma helper_add_sub : forall a b,\n a <= b -> a + (b - a) = b.\n Proof.\n intros; omega.\n Qed.\n\n\n Lemma nonzero_addrs_app : forall a b,\n nonzero_addrs (a ++ b) = nonzero_addrs a + nonzero_addrs b.\n Proof.\n induction a; intros; simpl; auto.\n destruct a; auto.\n rewrite IHa; omega.\n Qed.\n\n Lemma ndata_log_app : forall a b,\n ndata_log (a ++ b) = ndata_log a + ndata_log b.\n Proof.\n unfold ndata_log; intros.\n repeat rewrite map_app.\n rewrite nonzero_addrs_app; auto.\n Qed.\n\n Lemma ndesc_log_padded_log : forall l,\n ndesc_log (padded_log l) = ndesc_log l.\n Proof.\n unfold ndesc_log; intros.\n rewrite padded_log_length.\n unfold roundup; rewrite divup_divup; auto.\n Qed.\n\n Lemma ndesc_log_app : forall a b,\n length a = roundup (length a) DescSig.items_per_val ->\n ndesc_log (a ++ b) = ndesc_log a + ndesc_log b.\n Proof.\n unfold ndesc_log; intros.\n rewrite app_length, H at 1.\n unfold roundup.\n rewrite Nat.add_comm, Nat.mul_comm.\n rewrite divup_add by auto.\n omega.\n Qed.\n\n Lemma ndesc_log_padded_app : forall a b,\n ndesc_log (padded_log a ++ b) = ndesc_log a + ndesc_log b.\n Proof.\n intros.\n rewrite ndesc_log_app.\n rewrite ndesc_log_padded_log; auto.\n rewrite padded_log_length.\n rewrite roundup_roundup; auto.\n Qed.\n\n Lemma ndata_log_padded_log : forall a,\n ndata_log (padded_log a) = ndata_log a.\n Proof.\n unfold ndata_log, padded_log, setlen, roundup; intros.\n rewrite firstn_oob by auto.\n repeat rewrite map_app.\n rewrite repeat_map; simpl.\n rewrite nonzero_addrs_app.\n setoid_rewrite <- app_nil_l at 3.\n rewrite nonzero_addrs_app_zeros; auto.\n Qed.\n\n\n Lemma ndata_log_padded_app : forall a b,\n ndata_log (padded_log a ++ b) = ndata_log a + ndata_log b.\n Proof.\n intros.\n rewrite ndata_log_app.\n rewrite ndata_log_padded_log; auto.\n Qed.\n\n Lemma vals_nonzero_app : forall a b,\n vals_nonzero (a ++ b) = vals_nonzero a ++ vals_nonzero b.\n Proof.\n unfold vals_nonzero; induction a; intros; simpl; auto.\n destruct a, n; simpl; auto.\n rewrite IHa; auto.\n Qed.\n\n Lemma log_nonzero_repeat_0 : forall n,\n log_nonzero (repeat (0, $0) n) = nil.\n Proof.\n induction n; simpl; auto.\n Qed.\n\n Lemma log_nonzero_app : forall a b,\n log_nonzero (a ++ b) = log_nonzero a ++ log_nonzero b.\n Proof.\n induction a; simpl; intros; auto.\n destruct a, n; simpl; auto.\n rewrite IHa; auto.\n Qed.\n\n Lemma vals_nonzero_padded_log : forall l,\n vals_nonzero (padded_log l) = vals_nonzero l.\n Proof.\n unfold vals_nonzero, padded_log, setlen, roundup; simpl.\n induction l; intros; simpl; auto.\n rewrite firstn_oob; simpl; auto.\n rewrite log_nonzero_repeat_0; auto.\n\n destruct a, n.\n rewrite <- IHl.\n repeat rewrite firstn_oob; simpl; auto.\n repeat rewrite log_nonzero_app, map_app.\n repeat rewrite log_nonzero_repeat_0; auto.\n\n repeat rewrite firstn_oob; simpl; auto.\n f_equal.\n repeat rewrite log_nonzero_app, map_app.\n repeat rewrite log_nonzero_repeat_0; auto.\n simpl; rewrite app_nil_r; auto.\n Qed.\n\n Lemma entry_valid_vals_nonzero : forall l,\n Forall entry_valid l ->\n log_nonzero l = l.\n Proof.\n unfold entry_valid; induction l; simpl; auto.\n destruct a, n; simpl; auto; intros.\n exfalso.\n rewrite Forall_forall in H; intuition.\n apply (H (0, w)); simpl; auto.\n rewrite IHl; auto.\n eapply Forall_cons2; eauto.\n Qed.\n\n Lemma nonzero_addrs_entry_valid : forall l,\n Forall entry_valid l ->\n nonzero_addrs (map fst l) = length l.\n Proof.\n induction l; simpl; intros; auto.\n destruct a, n; simpl.\n exfalso.\n rewrite Forall_forall in H.\n apply (H (0, w)); simpl; auto.\n rewrite IHl; auto.\n eapply Forall_cons2; eauto.\n Qed.\n\n Lemma extend_ok_helper : forall F xp old new,\n Forall entry_valid new ->\n Data.array_rep xp (ndata_log old) (Data.Synced (map ent_valu new)) *\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr old)) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero old)) *\n Desc.avail_rep xp (ndesc_log old + divup (length (map ent_addr new)) DescSig.items_per_val)\n (LogDescLen xp - ndesc_log old - ndesc_log new) *\n Data.avail_rep xp (ndata_log old + divup (length (map ent_valu new)) DataSig.items_per_val)\n (LogLen xp - ndata_log old - ndata_log new) *\n Desc.array_rep xp (ndesc_log old) (Desc.Synced (map ent_addr (padded_log new))) * F\n =p=>\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old ++ new))) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero (padded_log old ++ new))) *\n Desc.avail_rep xp (ndesc_log (padded_log old ++ new)) \n (LogDescLen xp - ndesc_log (padded_log old ++ new)) *\n Data.avail_rep xp (ndata_log (padded_log old ++ new))\n (LogLen xp - ndata_log (padded_log old ++ new)) * F.\n Proof.\n intros.\n repeat rewrite ndesc_log_padded_app, ndata_log_padded_app.\n setoid_rewrite Nat.sub_add_distr.\n unfold ndesc_log.\n rewrite divup_1.\n rewrite entry_valid_ndata with (l := new); auto.\n repeat rewrite map_length.\n rewrite map_app, vals_nonzero_app.\n rewrite <- Desc.array_rep_synced_app.\n rewrite <- Data.array_rep_synced_app.\n repeat rewrite Nat.add_0_l.\n repeat rewrite desc_padding_synced_piff.\n repeat rewrite map_length.\n repeat rewrite vals_nonzero_padded_log.\n rewrite divup_1, padded_log_length.\n unfold roundup; rewrite divup_mul; auto.\n unfold ndata_log; rewrite vals_nonzero_addrs.\n unfold vals_nonzero; rewrite entry_valid_vals_nonzero with (l := new); auto.\n cancel.\n\n rewrite Nat.mul_1_r; auto.\n rewrite map_length, padded_log_length.\n unfold roundup; auto.\n Qed.\n\n Lemma nonzero_addrs_bound : forall l,\n nonzero_addrs l <= length l.\n Proof.\n induction l; simpl; auto.\n destruct a; omega.\n Qed.\n\n Lemma extend_ok_synced_hdr_helper : forall xp old new,\n Hdr.rep xp (Hdr.Synced (ndesc_log old + ndesc_log new, ndata_log old + ndata_log new))\n =p=>\n Hdr.rep xp (Hdr.Synced (ndesc_log (padded_log old ++ new),\n ndata_log (padded_log old ++ new))).\n Proof.\n intros.\n rewrite ndesc_log_padded_app, ndata_log_padded_app; auto.\n Qed.\n\n Local Hint Resolve extend_ok_synced_hdr_helper.\n\n Lemma nonzero_addrs_roundup : forall B (l : list (addr * B)) n,\n n > 0 ->\n nonzero_addrs (map fst l) <= (divup (length l) n) * n.\n Proof.\n intros.\n eapply le_trans.\n apply nonzero_addrs_bound.\n rewrite map_length.\n apply roundup_ge; auto.\n Qed.\n\n Lemma loglen_invalid_overflow : forall xp old new,\n LogLen xp = DescSig.items_per_val * LogDescLen xp ->\n loglen_invalid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n length (padded_log old ++ new) > LogLen xp.\n Proof.\n unfold loglen_invalid, ndesc_log, ndata_log; intros.\n rewrite app_length; repeat rewrite padded_log_length.\n unfold roundup; intuition.\n rewrite H.\n setoid_rewrite <- Nat.mul_comm at 2.\n apply divup_add_gt; auto.\n\n eapply lt_le_trans; eauto.\n apply Nat.add_le_mono.\n apply nonzero_addrs_roundup; auto.\n erewrite <- map_length.\n apply nonzero_addrs_bound.\n Qed.\n\n Hint Rewrite Desc.array_rep_avail Data.array_rep_avail\n padded_log_length divup_mul divup_1 map_length\n ndesc_log_padded_log nonzero_addrs_padded_log using auto: extend_crash.\n Hint Unfold roundup ndata_log : extend_crash.\n\n Ltac extend_crash :=\n repeat (autorewrite with extend_crash; autounfold with extend_crash; simpl);\n setoid_rewrite <- Desc.avail_rep_merge at 3;\n [ setoid_rewrite <- Data.avail_rep_merge at 3 | ];\n [ cancel\n | apply helper_loglen_data_valid_extend_entry_valid; auto\n | apply helper_loglen_desc_valid_extend; auto ].\n\n\n Definition extend T xp log cs rx : prog T :=\n let^ (cs, nr) <- Hdr.read xp cs;\n let '(ndesc, ndata) := nr in\n let '(nndesc, nndata) := ((ndesc_log log), (ndata_log log)) in\n If (loglen_valid_dec xp (ndesc + nndesc) (ndata + nndata)) {\n (* synced *)\n cs <- Desc.write_aligned xp ndesc (map ent_addr log) cs;\n (* extended unsync *)\n cs <- Data.write_aligned xp ndata (map ent_valu log) cs;\n cs <- Desc.sync_aligned xp ndesc nndesc cs;\n cs <- Data.sync_aligned xp ndata nndata cs;\n cs <- Hdr.write xp (ndesc + nndesc, ndata + nndata) cs;\n cs <- Hdr.sync xp cs;\n (* synced*)\n rx ^(cs, true)\n } else {\n rx ^(cs, false)\n }.\n\n\n Definition extend_ok : forall xp new cs,\n {< F old d,\n PRE:hm\n BUFCACHE.rep cs d *\n [[ Forall entry_valid new ]] *\n [[ (F * rep xp (Synced old) hm)%pred d ]]\n POST:hm' RET: ^(cs, r) exists d',\n BUFCACHE.rep cs d' * (\n [[ r = true /\\\n (F * rep xp (Synced ((padded_log old) ++ new)) hm')%pred d' ]] \\/\n [[ r = false /\\ length ((padded_log old) ++ new) > LogLen xp /\\\n (F * rep xp (Synced old) hm')%pred d' ]])\n XCRASH:hm' exists cs' d',\n BUFCACHE.rep cs' d' * (\n [[ (F * rep xp (Synced old) hm')%pred d' ]] \\/\n [[ (F * rep xp (Extended old new) hm')%pred d' ]])\n >} extend xp new cs.\n Proof.\n unfold extend.\n step.\n step.\n\n (* true case *)\n - (* write content *)\n safestep.\n rewrite Desc.avail_rep_split. cancel.\n autorewrite with lists; apply helper_loglen_desc_valid_extend; auto.\n\n safestep.\n unfold loglen_valid in *; unfold Data.items_valid; intuition.\n unfold DataSig.RALen; omega.\n autorewrite with lists.\n rewrite <- entry_valid_ndata by auto.\n replace DataSig.items_per_val with 1 by (cbv; auto).\n unfold DataSig.RALen; omega.\n rewrite Data.avail_rep_split. cancel.\n autorewrite with lists.\n rewrite divup_1; rewrite <- entry_valid_ndata by auto.\n apply helper_loglen_data_valid_extend; auto.\n\n (* sync content *)\n prestep. norm. cancel. intuition simpl.\n instantiate ( 1 := map ent_addr (padded_log new) ).\n rewrite map_length, padded_log_length; auto.\n apply padded_desc_valid.\n apply loglen_valid_desc_valid; auto.\n rewrite desc_padding_unsync_piff.\n pred_apply; cancel.\n\n safestep.\n autorewrite with lists.\n rewrite entry_valid_ndata, Nat.mul_1_r; auto.\n unfold loglen_valid in *; unfold Data.items_valid; intuition.\n unfold DataSig.RALen; omega.\n autorewrite with lists.\n rewrite <- entry_valid_ndata by auto.\n replace DataSig.items_per_val with 1 by (cbv; auto).\n unfold DataSig.RALen; omega.\n\n (* write header *)\n safestep.\n eapply loglen_valid_goodSize_l; eauto.\n eapply loglen_valid_goodSize_r; eauto.\n\n (* sync header *)\n safestep.\n\n (* post condition *)\n safestep.\n or_l; cancel.\n cancel_by extend_ok_helper; auto.\n\n (* crashes *)\n (* after header write : Extended *)\n rewrite ndesc_log_app, ndata_log_app.\n rewrite ndesc_log_padded_log, ndata_log_padded_log.\n eauto.\n rewrite padded_log_length, roundup_roundup; auto.\n xcrash.\n or_r; cancel.\n cancel_by extend_ok_helper; auto.\n\n (* after header sync : Synced new *)\n xcrash.\n or_r; cancel.\n cancel_by extend_ok_helper; auto.\n\n (* before header write : ExtendedUnsync *)\n xcrash.\n or_l; cancel.\n extend_crash.\n\n xcrash.\n or_l; cancel.\n extend_crash.\n\n xcrash.\n or_l; cancel.\n extend_crash.\n\n (* before write desc : Synced old *)\n xcrash.\n or_l; cancel.\n rewrite Desc.avail_rep_merge. cancel.\n rewrite map_length.\n apply helper_loglen_desc_valid_extend; auto.\n\n (* false case *)\n - step.\n or_r; cancel.\n apply loglen_invalid_overflow; auto.\n\n (* crash for the false case *)\n - cancel.\n xcrash.\n or_l; cancel.\n Qed.\n\n\n Hint Extern 1 ({{_}} progseq (avail _ _) _) => apply avail_ok : prog.\n Hint Extern 1 ({{_}} progseq (read _ _) _) => apply read_ok : prog.\n Hint Extern 1 ({{_}} progseq (trunc _ _) _) => apply trunc_ok : prog.\n Hint Extern 1 ({{_}} progseq (extend _ _ _) _) => apply extend_ok : prog.\n\n Lemma log_nonzero_padded_log : forall l,\n log_nonzero (padded_log l) = log_nonzero l.\n Proof.\n unfold padded_log, setlen, roundup; intros.\n rewrite firstn_oob by auto.\n rewrite log_nonzero_app.\n rewrite log_nonzero_repeat_0, app_nil_r; auto.\n Qed.\n\n Lemma log_nonzero_padded_app : forall l new,\n Forall entry_valid new ->\n log_nonzero l ++ new = log_nonzero (padded_log l ++ padded_log new).\n Proof.\n intros.\n rewrite log_nonzero_app.\n repeat rewrite log_nonzero_padded_log.\n f_equal.\n rewrite entry_valid_vals_nonzero; auto.\n Qed.\n\n Lemma log_nonzero_app_padded : forall l new,\n Forall entry_valid new ->\n log_nonzero l ++ new = log_nonzero (l ++ padded_log new).\n Proof.\n intros.\n rewrite log_nonzero_app, log_nonzero_padded_log.\n f_equal.\n rewrite entry_valid_vals_nonzero; auto.\n Qed.\n\n Theorem rep_synced_length_ok : forall F xp l d hm,\n (F * rep xp (Synced l) hm)%pred d -> length l <= LogLen xp.\n Proof.\n unfold rep, rep_inner, rep_contents, xparams_ok.\n unfold Desc.array_rep, Desc.synced_array, Desc.rep_common, Desc.items_valid.\n intros; destruct_lifts.\n rewrite map_length, Nat.sub_0_r in *.\n rewrite H5, Nat.mul_comm; auto.\n Qed.\n\n Lemma xform_rep_synced : forall xp l hm,\n crash_xform (rep xp (Synced l) hm) =p=> rep xp (Synced l) hm.\n Proof.\n unfold rep; simpl; unfold rep_contents; intros.\n xform; cancel.\n rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n rewrite Hdr.xform_rep_synced.\n cancel.\n Qed.\n\n Lemma xform_rep_truncated : forall xp l hm,\n crash_xform (rep xp (Truncated l) hm) =p=>\n rep xp (Synced l) hm \\/ rep xp (Synced nil) hm.\n Proof.\n unfold rep; simpl; unfold rep_contents; intros.\n xform; cancel.\n rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n rewrite Hdr.xform_rep_unsync.\n norm; auto.\n\n or_r; cancel.\n cancel_by helper_trunc_ok.\n or_l; cancel.\n Qed.\n\n Lemma xform_rep_extended_unsync : forall xp l hm,\n crash_xform (rep xp (ExtendedUnsync l) hm) =p=> rep xp (Synced l) hm.\n Proof.\n unfold rep; simpl; unfold rep_contents; intros.\n xform; cancel.\n\n rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n rewrite Hdr.xform_rep_synced.\n cancel.\n Qed.\n\n\n Theorem rep_extended_facts' : forall xp d old new hm,\n (rep xp (Extended old new) hm)%pred d ->\n Forall entry_valid new /\\\n LogLen xp >= ndata_log old + ndata_log new /\\ LogDescLen xp >= ndesc_log old + ndesc_log new.\n Proof.\n unfold rep, rep_inner, rep_contents, xparams_ok.\n unfold Desc.array_rep, Desc.synced_array, Desc.rep_common, Desc.items_valid.\n intros; destruct_lifts.\n rewrite map_length, Nat.sub_0_r in *.\n unfold ndata_log, ndesc_log; split; auto; split.\n\n rewrite H4, Nat.mul_comm.\n eapply le_trans; [ | eauto ].\n rewrite app_length, nonzero_addrs_entry_valid with (l := new) by auto.\n apply plus_le_compat_r.\n eapply le_trans.\n apply nonzero_addrs_bound.\n rewrite padded_log_length, map_length.\n apply roundup_ge; auto.\n\n eapply Nat.mul_le_mono_pos_r with (p := DescSig.items_per_val).\n apply DescDefs.items_per_val_gt_0.\n rewrite app_length, padded_log_length in H16.\n apply roundup_le in H16.\n rewrite roundup_roundup_add in H16 by auto.\n rewrite Nat.mul_add_distr_r.\n eapply le_trans; eauto.\n Qed.\n\n Theorem rep_extended_facts : forall xp old new hm,\n rep xp (Extended old new) hm =p=>\n (rep xp (Extended old new) hm *\n [[ LogLen xp >= ndata_log old + ndata_log new ]] *\n [[ LogDescLen xp >= ndesc_log old + ndesc_log new ]] *\n [[ Forall entry_valid new ]] )%pred.\n Proof.\n unfold pimpl; intros.\n pose proof rep_extended_facts' H.\n pred_apply; cancel.\n Qed.\n\n Lemma helper_sep_star_distr: forall AT AEQ V (a b c d : @pred AT AEQ V),\n a * b * c * d =p=> (c * a) * (d * b).\n Proof.\n intros; cancel.\n Qed.\n\n Lemma helper_add_sub_add : forall a b c,\n b >= c + a -> a + (b - (c + a)) = b - c.\n Proof.\n intros; omega.\n Qed.\n\n Lemma xform_rep_extended_helper : forall xp old new,\n Forall entry_valid new ->\n LogLen xp >= ndata_log old + ndata_log new ->\n LogDescLen xp >= ndesc_log old + ndesc_log new ->\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old ++ new))) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero (padded_log old ++ new))) *\n Desc.avail_rep xp (ndesc_log (padded_log old ++ new)) (LogDescLen xp - ndesc_log (padded_log old ++ new)) *\n Data.avail_rep xp (ndata_log (padded_log old ++ new)) (LogLen xp - ndata_log (padded_log old ++ new))\n =p=>\n Desc.array_rep xp 0 (Desc.Synced (map ent_addr old)) *\n Data.array_rep xp 0 (Data.Synced (vals_nonzero old)) *\n Desc.avail_rep xp (ndesc_log old) (LogDescLen xp - ndesc_log old) *\n Data.avail_rep xp (ndata_log old) (LogLen xp - ndata_log old).\n Proof.\n intros.\n rewrite map_app, vals_nonzero_app.\n rewrite ndesc_log_padded_app, ndata_log_padded_app.\n rewrite Desc.array_rep_synced_app_rev, Data.array_rep_synced_app_rev.\n repeat rewrite Nat.add_0_l.\n rewrite map_length, vals_nonzero_padded_log, padded_log_length.\n setoid_rewrite desc_padding_synced_piff.\n cancel.\n\n rewrite Data.array_rep_avail, Desc.array_rep_avail; simpl.\n unfold roundup; rewrite divup_divup by auto.\n setoid_rewrite vals_nonzero_addrs.\n setoid_rewrite divup_1.\n setoid_rewrite map_length.\n unfold ndata_log, ndesc_log.\n rewrite helper_sep_star_distr.\n rewrite Desc.avail_rep_merge, Data.avail_rep_merge.\n cancel.\n apply helper_add_sub_add; auto.\n apply helper_add_sub_add; auto.\n\n rewrite Nat.mul_1_r; auto.\n rewrite map_length, padded_log_length.\n unfold roundup; auto.\n Qed.\n\n Lemma xform_rep_extended : forall xp old new hm,\n crash_xform (rep xp (Extended old new) hm) =p=>\n rep xp (Synced old) hm \\/\n rep xp (Synced ((padded_log old) ++ new)) hm.\n Proof.\n intros; rewrite rep_extended_facts.\n unfold rep; simpl; unfold rep_contents; intros.\n xform; cancel.\n\n rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n rewrite Hdr.xform_rep_unsync.\n norm; auto.\n\n or_r; cancel.\n rewrite extend_ok_synced_hdr_helper; auto.\n\n or_l; cancel.\n apply xform_rep_extended_helper; auto.\n\n apply padded_addr_valid.\n eapply forall_app_r; eauto.\n Qed.\n\n Lemma rep_synced_app_pimpl : forall xp old new hm,\n rep xp (Synced (padded_log old ++ new)) hm =p=>\n rep xp (Synced (padded_log old ++ padded_log new)) hm.\n Proof.\n unfold rep; simpl; intros; unfold rep_contents; cancel.\n setoid_rewrite ndesc_log_padded_app.\n setoid_rewrite ndata_log_padded_app.\n rewrite ndesc_log_padded_log, ndata_log_padded_log.\n setoid_rewrite map_app.\n setoid_rewrite vals_nonzero_app.\n setoid_rewrite vals_nonzero_padded_log.\n cancel.\n\n rewrite Desc.array_rep_synced_app_rev.\n setoid_rewrite <- desc_padding_synced_piff at 2.\n eapply pimpl_trans2.\n eapply Desc.array_rep_synced_app.\n rewrite map_length, padded_log_length; unfold roundup; eauto.\n cancel.\n rewrite map_length, padded_log_length; unfold roundup; eauto.\n apply Forall_append.\n eapply forall_app_r; eauto.\n eapply forall_app_l in H2.\n apply addr_valid_padded; auto.\n Qed.\n\nEnd PaddedLog.\n\n\nModule DLog.\n\n Definition entry := (addr * valu)%type.\n Definition contents := list entry.\n\n Inductive state :=\n (* The log is synced on disk *)\n | Synced (navail : nat) (l: contents)\n (* The log has been truncated; but the length (0) is unsynced *)\n | Truncated (old: contents)\n (* The log is being extended; only the content has been updated (unsynced) *)\n | ExtendedUnsync (old: contents)\n (* The log has been extended; the new contents are synced but the length is unsynced *)\n | Extended (old: contents) (new: contents).\n\n Definition rep_common l padded : rawpred :=\n ([[ l = PaddedLog.log_nonzero padded /\\\n length padded = roundup (length padded) PaddedLog.DescSig.items_per_val ]])%pred.\n\n Definition rep xp st hm :=\n (match st with\n | Synced navail l =>\n exists padded, rep_common l padded *\n [[ navail = (LogLen xp) - (length padded) ]] *\n PaddedLog.rep xp (PaddedLog.Synced padded) hm\n | Truncated l =>\n exists padded, rep_common l padded *\n PaddedLog.rep xp (PaddedLog.Truncated padded) hm\n | ExtendedUnsync l =>\n exists padded, rep_common l padded *\n PaddedLog.rep xp (PaddedLog.ExtendedUnsync padded) hm\n | Extended l new =>\n exists padded, rep_common l padded *\n PaddedLog.rep xp (PaddedLog.Extended padded new) hm\n end)%pred.\n\n Local Hint Unfold rep rep_common : hoare_unfold.\n\n Section UnifyProof.\n Hint Extern 0 (okToUnify (PaddedLog.rep _ _ _) (PaddedLog.rep _ _ _)) => constructor : okToUnify.\n\n Definition read T xp cs rx : prog T :=\n r <- PaddedLog.read xp cs;\n rx r.\n\n Definition read_ok : forall xp cs,\n {< F l d nr,\n PRE:hm BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced nr l) hm)%pred d ]]\n POST:hm' RET: ^(cs, r)\n BUFCACHE.rep cs d *\n [[ r = l /\\ (F * rep xp (Synced nr l) hm')%pred d ]]\n CRASH:hm' exists cs',\n BUFCACHE.rep cs' d *\n [[ (F * rep xp (Synced nr l) hm')%pred d ]]\n >} read xp cs.\n Proof.\n unfold read.\n hoare.\n Qed.\n\n Definition trunc T xp cs rx : prog T :=\n cs <- PaddedLog.trunc xp cs;\n rx cs.\n\n Definition trunc_ok : forall xp cs,\n {< F l d nr,\n PRE:hm BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced nr l) hm)%pred d ]]\n POST:hm' RET: cs exists d',\n BUFCACHE.rep cs d' *\n [[ (F * rep xp (Synced (LogLen xp) nil) hm')%pred d' ]]\n XCRASH:hm' exists cs d',\n BUFCACHE.rep cs d' *\n [[ (F * rep xp (Truncated l) hm')%pred d' ]]\n >} trunc xp cs.\n Proof.\n unfold trunc.\n hoare.\n unfold roundup; rewrite divup_0; omega.\n\n (* crashes *)\n xcrash.\n Qed.\n\n\n Definition avail T xp cs rx : prog T :=\n r <- PaddedLog.avail xp cs;\n rx r.\n\n Definition avail_ok : forall xp cs,\n {< F l d nr,\n PRE:hm\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced nr l) hm)%pred d ]]\n POST:hm' RET: ^(cs, r)\n BUFCACHE.rep cs d *\n [[ (F * rep xp (Synced nr l) hm')%pred d ]] *\n [[ r = nr ]]\n CRASH:hm' exists cs',\n BUFCACHE.rep cs' d *\n [[ (F * rep xp (Synced nr l) hm')%pred d ]]\n >} avail xp cs.\n Proof.\n unfold avail.\n step.\n step.\n Qed.\n\n End UnifyProof.\n\n Local Hint Resolve PaddedLog.DescDefs.items_per_val_gt_0.\n\n Lemma extend_length_ok' : forall l new,\n length l = roundup (length l) PaddedLog.DescSig.items_per_val ->\n length (l ++ PaddedLog.padded_log new)\n = roundup (length (l ++ PaddedLog.padded_log new)) PaddedLog.DescSig.items_per_val.\n Proof.\n intros.\n repeat rewrite app_length.\n repeat rewrite PaddedLog.padded_log_length.\n rewrite H.\n rewrite roundup_roundup_add, roundup_roundup; auto.\n Qed.\n\n Lemma extend_length_ok : forall l new,\n length l = roundup (length l) PaddedLog.DescSig.items_per_val ->\n length (PaddedLog.padded_log l ++ PaddedLog.padded_log new)\n = roundup (length (PaddedLog.padded_log l ++ PaddedLog.padded_log new)) PaddedLog.DescSig.items_per_val.\n Proof.\n intros.\n apply extend_length_ok'.\n rewrite PaddedLog.padded_log_length.\n rewrite roundup_roundup; auto.\n Qed.\n\n Lemma helper_extend_length_ok : forall xp padded new F d hm,\n length padded = roundup (length padded) PaddedLog.DescSig.items_per_val\n -> length (PaddedLog.padded_log padded ++ new) > LogLen xp\n -> (F * PaddedLog.rep xp (PaddedLog.Synced padded) hm)%pred d\n -> length new > LogLen xp - length padded.\n Proof.\n intros.\n rewrite app_length in H0.\n pose proof (PaddedLog.rep_synced_length_ok H1).\n generalize H2.\n rewrite H.\n rewrite <- PaddedLog.padded_log_length.\n intro; omega.\n Qed.\n\n Local Hint Resolve extend_length_ok helper_extend_length_ok PaddedLog.log_nonzero_padded_app.\n\n Definition extend T xp new cs rx : prog T :=\n r <- PaddedLog.extend xp new cs;\n rx r.\n\n Definition rounded n := roundup n PaddedLog.DescSig.items_per_val.\n\n Definition entries_valid l := Forall PaddedLog.entry_valid l.\n\n Lemma extend_navail_ok : forall xp padded new, \n length padded = roundup (length padded) PaddedLog.DescSig.items_per_val ->\n LogLen xp - length padded - rounded (length new)\n = LogLen xp - length (PaddedLog.padded_log padded ++ PaddedLog.padded_log new).\n Proof.\n unfold rounded; intros.\n rewrite extend_length_ok by auto.\n rewrite app_length.\n rewrite H.\n repeat rewrite PaddedLog.padded_log_length.\n rewrite roundup_roundup_add by auto.\n rewrite roundup_roundup by auto.\n omega.\n Qed.\n\n Local Hint Resolve extend_navail_ok PaddedLog.rep_synced_app_pimpl.\n\n Definition extend_ok : forall xp new cs,\n {< F old d nr,\n PRE:hm\n BUFCACHE.rep cs d * [[ entries_valid new ]] *\n [[ (F * rep xp (Synced nr old) hm)%pred d ]]\n POST:hm' RET: ^(cs, r) exists d',\n BUFCACHE.rep cs d' * (\n [[ r = true /\\\n (F * rep xp (Synced (nr - (rounded (length new))) (old ++ new)) hm')%pred d' ]] \\/\n [[ r = false /\\ length new > nr /\\\n (F * rep xp (Synced nr old) hm')%pred d' ]])\n XCRASH:hm' exists cs' d',\n BUFCACHE.rep cs' d' * (\n [[ (F * rep xp (Synced nr old) hm')%pred d' ]] \\/\n [[ (F * rep xp (Extended old new) hm')%pred d' ]])\n >} extend xp new cs.\n Proof.\n unfold extend.\n\n safestep.\n eassign dummy; cancel.\n safestep.\n\n or_l; norm; [ cancel | intuition; pred_apply; norm ].\n eassign (PaddedLog.padded_log dummy ++ PaddedLog.padded_log new).\n cancel; auto.\n intuition.\n or_r; cancel; eauto.\n\n xcrash.\n or_l; cancel.\n or_r; cancel.\n Qed.\n\n Hint Extern 1 ({{_}} progseq (avail _ _) _) => apply avail_ok : prog.\n Hint Extern 1 ({{_}} progseq (read _ _) _) => apply read_ok : prog.\n Hint Extern 1 ({{_}} progseq (trunc _ _) _) => apply trunc_ok : prog.\n Hint Extern 1 ({{_}} progseq (extend _ _ _) _) => apply extend_ok : prog.\n\n\n (* ExtendedUnsync is actually a redundent state, it is equivalent to Synced *)\n Lemma extend_unsynced_synced : forall xp l hm,\n rep xp (ExtendedUnsync l) hm =p=> exists na, rep xp (Synced na l) hm.\n Proof.\n unfold rep, rep_common; cancel; eauto.\n Qed.\n\n Lemma synced_extend_unsynced : forall xp l na hm,\n rep xp (Synced na l) hm =p=> rep xp (ExtendedUnsync l) hm.\n Proof.\n unfold rep, rep_common; cancel; eauto.\n Qed.\n\n\n Lemma xform_rep_synced : forall xp na l hm,\n crash_xform (rep xp (Synced na l) hm) =p=> rep xp (Synced na l) hm.\n Proof.\n unfold rep, rep_common; intros.\n xform; cancel.\n apply PaddedLog.xform_rep_synced.\n all: auto.\n Qed.\n\n Lemma xform_rep_truncated : forall xp l hm,\n crash_xform (rep xp (Truncated l) hm) =p=> exists na,\n rep xp (Synced na l) hm \\/ rep xp (Synced (LogLen xp) nil) hm.\n Proof.\n unfold rep, rep_common; intros.\n xform; cancel.\n rewrite PaddedLog.xform_rep_truncated.\n cancel.\n or_r; cancel.\n rewrite roundup_0; auto.\n Qed.\n\n Lemma xform_rep_extended_unsync : forall xp l hm,\n crash_xform (rep xp (ExtendedUnsync l) hm) =p=> exists na, rep xp (Synced na l) hm.\n Proof.\n unfold rep, rep_common; intros.\n xform; cancel.\n apply PaddedLog.xform_rep_extended_unsync.\n all: auto.\n Qed.\n\n Lemma xform_rep_extended : forall xp old new hm,\n crash_xform (rep xp (Extended old new) hm) =p=>\n (exists na, rep xp (Synced na old) hm) \\/\n (exists na, rep xp (Synced na (old ++ new)) hm).\n Proof.\n unfold rep, rep_common; intros.\n xform.\n rewrite PaddedLog.rep_extended_facts.\n xform; cancel.\n rewrite PaddedLog.xform_rep_extended.\n cancel.\n or_r; norm.\n instantiate (1 := (PaddedLog.padded_log x ++ PaddedLog.padded_log new)).\n cancel; auto.\n intuition.\n Qed.\n\nEnd DLog.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/DiskLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2254166210386804, "lm_q1q2_score": 0.12237040697871046}} {"text": "Require Import FunInd.\nRequire Import CoqlibC Maps Errors IntegersC.\nRequire Import ASTC LinkingC.\nRequire Import ValuesC MemoryC EventsC GlobalenvsC Smallstep.\nRequire Import Ctypes Cop Csyntax Csem CstrategyC ClightC.\nRequire Import SimplExpr SimplExprspec.\n(** newly added **)\nRequire Export SimplExprproof.\nRequire Import Simulation.\nRequire Import Skeleton Mod ModSem SimMod SimModSemSR SimSymb SimMem MatchSimModSemSR.\nRequire Import ModSemProps.\nRequire Import CtypesC.\nRequire Import CtypingC.\nRequire SimMemId.\nRequire SoundTop.\nRequire Import sflib.\n\nSet Implicit Arguments.\n\nSection SIMMODSEM.\n\nVariable skenv_link: SkEnv.t.\nVariable sm_link: SimMem.t.\nVariable prog: Csyntax.program.\nVariable tprog: Clight.program.\nLet md_src: Mod.t := (CstrategyC.module prog).\nLet md_tgt: Mod.t := (ClightC.module1 tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\nHypothesis TRANSL: match_prog prog tprog.\nLet ge: Csem.genv := Csem.Build_genv (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog) prog.(prog_comp_env).\nLet tge: genv := Build_genv (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog) tprog.(prog_comp_env).\nDefinition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.\n\nInductive match_states\n (idx: nat) (st_src0: Csem.state) (st_tgt0: Clight.state) (sm0: SimMem.t): Prop :=\n| match_states_intro\n (MATCHST: SimplExprproof.match_states tge st_src0 st_tgt0)\n (MWF: SimMem.wf sm0)\n (MEASURE: measure st_src0 = idx).\n\nTheorem make_match_genvs :\n SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n Genv.match_genvs (match_globdef (fun (ctx : AST.program Csyntax.fundef type) f tf => tr_fundef f tf) eq prog) ge tge /\\ prog_comp_env prog = prog_comp_env tprog.\nProof.\n subst_locals. ss. rr in TRANSL. destruct TRANSL. r in H. esplits.\n - eapply SimSymbId.sim_skenv_revive; eauto.\n - hexploit (prog_comp_env_eq prog); eauto. i.\n hexploit (prog_comp_env_eq tprog); eauto. i.\n ss. congruence.\nQed.\n\nTheorem sim_modsem: ModSemPair.simSR msp.\nProof.\n eapply match_states_sim with (match_states := match_states) (match_states_at := top4) (sound_state := SoundTop.sound_state);\n eauto; ii; ss.\n - instantiate (1:= Nat.lt). apply lt_wf.\n - eapply SoundTop.sound_state_local_preservation.\n - (* init bsim *)\n destruct sm_arg; ss. clarify.\n inv SIMARGS; ss. clarify. inv INITTGT.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n eexists. eexists (SimMemId.mk _ _). esplits; eauto.\n + econs; eauto; ss.\n * inv TYP. rpapply match_callstates; eauto.\n { econs; eauto. }\n inv SAFESRC. folder. inv TYP.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. intro TFPTR; des. ss.\n f_equal; ss. inv TFPTR0; ss. inv H0; ss. unfold Csyntax.type_of_function. unfold type_of_function.\n f_equal; try congruence.\n + des. inv SAFESRC. ss.\n - (* init progress *)\n des. inv SAFESRC. inv SIMARGS; ss.\n exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. clarify. folder.\n inv TYP. inv H0. esplits; eauto. econs; eauto.\n folder. inv H3. ss. econs; try rewrite H5; eauto.\n - (* call wf *)\n inv MATCH; ss.\n - (* call fsim *)\n inv MATCH; ss. destruct sm0; ss. clarify. inv CALLSRC. inv MATCHST; ss.\n folder. esplits; eauto.\n + econs; eauto.\n * ss. folder. des. destruct TRANSL as [TRANSL0 _].\n exploit (SimSymbId.sim_skenv_revive TRANSL0); eauto.\n { apply SIMSKENV. }\n intro GE; des. apply (fsim_external_funct_id GE); ss.\n + econs; ss; eauto.\n * instantiate (1:= SimMemId.mk _ _). ss.\n * ss.\n + ss.\n - (* after fsim *)\n inv AFTERSRC. inv SIMRET; cycle 1.\n { inv CSTYLE. }\n ss. exists sm_ret. destruct sm_ret; ss. clarify.\n inv MATCH; ss. inv MATCHST; ss. esplits; eauto; econs; ss; eauto.\n clarify. econs; eauto.\n - (* final fsim *)\n inv MATCH. inv FINALSRC; inv MATCHST; ss. inv H3. destruct sm0; ss. clarify.\n eexists (SimMemId.mk _ _). esplits; ss; eauto. econs; ss; eauto.\n - left; i. esplits; eauto.\n { apply modsem_strongly_receptive; et. }\n inv MATCH. ii. hexploit (@simulation prog skenv_link skenv_link); eauto.\n { inv SIMSKENV. ss. }\n { exploit make_match_genvs; eauto. { eapply SIMSKENV. } intro T; des. esplits; eauto. }\n i. des_safe. esplits; eauto.\n + des.\n * left. eapply spread_dplus; eauto.\n { eapply modsem1_determinate; eauto. }\n * right. esplits; eauto. eapply spread_dstar; eauto.\n { eapply modsem1_determinate; eauto. }\n + econs; eauto.\nUnshelve.\n all: ss; try (by econs); try eapply Mem.empty.\nQed.\n\nEnd SIMMODSEM.\n\n\n\n\nSection SIMMOD.\n\nVariable prog: Csyntax.program.\nVariable tprog: Clight.program.\nHypothesis TRANSL: match_prog prog tprog.\nDefinition mp: ModPair.t := SimSymbId.mk_mp (Mod.Atomic.trans (CstrategyC.module prog)) (ClightC.module1 tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n econs; ss.\n - r. inv TRANSL. eapply CSk.match_program_eq; et.\n ii. destruct f1; ss.\n + clarify. right. inv MATCH. esplits; eauto. inv H2.\n unfold CsemC.signature_of_function, signature_of_function. f_equal; congruence.\n + clarify. left. inv MATCH. esplits; eauto.\n - ii. inv SIMSKENVLINK. eapply factor_simmodsem_source; eauto.\n { ii. ss. hexploit (@modsem_strongly_receptive skenv_link_tgt prog s); eauto. intro SR.\n inv SR. exploit ssr_traces_at; eauto.\n }\n { ii. ss. eapply modsem1_receptive; ss; eauto. }\n ss. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/cfrontend/SimplExprproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.24220562872535942, "lm_q1q2_score": 0.12204891085158415}} {"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.common.Memtype.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.logic.LayerData.\nRequire Export liblayers.compcertx.CompcertStructures.\nRequire Import liblayers.compcertx.ErrorMonad.\nRequire Import liblayers.compcertx.AbstractData.\nRequire Import liblayers.compcertx.AbstractData.\nRequire Import liblayers.compat.CompatData.\nOpen Scope positive_scope.\n\n\n(** * High-level step relations *)\n\nDefinition sextcall_sem `{mem_ops: Mem.MemoryModelOps} :=\n list val -> mem -> val -> mem -> Prop.\n\nSection WITH_MEMORY_MODEL.\n Context `{mem_ops: Mem.MemoryModelOps}.\n\n (** ** Extra information *)\n\n (** In addition to the step relation, those specify the primitive's\n signature (in term of C types) as well as the requirements on\n the stencil used. *)\n\n Record sextcall_info :=\n {\n sextcall_step :> list val -> mem -> val -> mem -> Prop;\n sextcall_csig: csignature\n }.\n\n Global Instance: Measure sextcall_step.\n\n Definition sextcall_args (sem: sextcall_info): Ctypes.typelist :=\n csig_args (sextcall_csig sem).\n\n Definition sextcall_res (sem: sextcall_info): Ctypes.type :=\n csig_res (sextcall_csig sem).\n\n Definition sextcall_cc (sem: sextcall_info): AST.calling_convention :=\n csig_cc (sextcall_csig sem).\n\n Definition sextcall_sig (sem: sextcall_info): signature :=\n csig_sig (sextcall_csig sem).\n\n (** ** Order *)\n\n Record sextcall_info_le (sem1 sem2: sextcall_info): Prop :=\n {\n sextcall_info_le_sem:\n (- ==> - ==> - ==> - ==> impl) sem1 sem2;\n sextcall_info_le_sig:\n sextcall_csig sem1 = sextcall_csig sem2\n }.\n\n Global Instance sextcall_info_le_preorder:\n PreOrder sextcall_info_le.\n Proof.\n split.\n * intros sem.\n split; eauto; reflexivity.\n * intros sem1 sem2 sem3 [] [].\n split; eauto; etransitivity; eauto.\n Qed.\nEnd WITH_MEMORY_MODEL.\n\n\n(** * Optional properties *)\n\nSection OPTIONAL_PROPERTIES.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n (** FIXME: nomenclature? m1 m2 m1' m2' *)\n Class ExtcallProperties {D: compatdata} (sem: sextcall_info (mem := mwd D)) :=\n {\n external_call_well_typed vargs m1 vres m2:\n sem vargs m1 vres m2 ->\n Val.has_type vres (typ_of_type (sextcall_res sem));\n\n external_call_valid_block vargs m1 vres m2 b:\n sem vargs m1 vres m2 ->\n Mem.valid_block m1 b ->\n Mem.valid_block m2 b;\n\n external_call_max_perm vargs m1 vres m2 b ofs p:\n sem vargs m1 vres m2 ->\n Mem.valid_block m1 b ->\n Mem.perm m2 b ofs Max p ->\n Mem.perm m1 b ofs Max p;\n\n external_call_readonly vargs m1 vres m2:\n sem vargs m1 vres m2 ->\n Mem.unchanged_on (loc_not_writable m1) m1 m2;\n\n external_call_mem_extends vargs m1 vres m2 m1' vargs':\n sem vargs m1 vres m2 ->\n Mem.extends m1 m1' ->\n Val.lessdef_list vargs vargs' ->\n exists vres' m2',\n sem vargs' m1' vres' m2' /\\\n Val.lessdef vres vres' /\\\n Mem.extends m2 m2' /\\\n Mem.unchanged_on (loc_out_of_bounds m1) m1' m2';\n\n external_call_mem_inject vargs m1 vres m2 f m1' vargs':\n inject_incr (Mem.flat_inj glob_threshold) f ->\n sem vargs m1 vres m2 ->\n Mem.inject f m1 m1' ->\n val_list_inject f vargs vargs' ->\n exists f' vres' m2',\n sem vargs' m1' vres' m2' /\\\n val_inject f' vres vres' /\\\n Mem.inject f' m2 m2' /\\\n Mem.unchanged_on (loc_unmapped f) m1 m2 /\\\n Mem.unchanged_on (loc_out_of_reach f m1) m1' m2' /\\\n inject_incr f f' /\\\n inject_separated f f' m1 m1';\n\n external_call_determ vargs m vres1 m1 vres2 m2:\n sem vargs m vres1 m1 ->\n sem vargs m vres2 m2 ->\n vres1 = vres2 /\\ m1 = m2\n\n }.\n\n Class ExtcallInvariants {D: compatdata} (sem: sextcall_info (mem := mwd D)) :=\n {\n external_call_low_level_invariant vargs m d vres m' d':\n sem vargs (m, d) vres (m', d') ->\n forall VALID_GENV_NEXT: glob_threshold <= Mem.nextblock m,\n low_level_invariant (Mem.nextblock m) d ->\n low_level_invariant (Mem.nextblock m') d';\n\n external_call_high_level_invariant vargs m d vres m' d':\n sem vargs (m, d) vres (m', d') ->\n high_level_invariant d ->\n high_level_invariant d';\n\n external_call_kernel_mode vargs m d vres m' d':\n sem vargs (m, d) vres (m', d') ->\n kernel_mode d ->\n kernel_mode d';\n\n external_call_inv_nextblock vargs m d vres m' d':\n sem vargs (m, d) vres (m', d') ->\n Mem.nextblock m <= Mem.nextblock m';\n\n external_call_inject_neutral vargs m d vres m' d':\n sem vargs (m, d) vres (m', d') ->\n (* XXXX: is [low_level_invariant (Mem.nextblock m) d] necessary here?\n If so, then this property will have to be moved to [ExtcallInvariants] *)\n val_list_inject (Mem.flat_inj (Mem.nextblock m)) vargs vargs ->\n Mem.inject_neutral (Mem.nextblock m) m ->\n forall NEXT_LE: Ple glob_threshold (Mem.nextblock m),\n (val_inject (Mem.flat_inj (Mem.nextblock m')) vres vres /\\\n Mem.inject_neutral (Mem.nextblock m') m');\n\n external_call_inv_well_typed vargs m1 vres m2:\n sem vargs m1 vres m2 ->\n Val.has_type vres (typ_of_type (sextcall_res sem))\n\n }.\n\n Record sextcall_primsem (D: compatdata) :=\n {\n sextcall_primsem_step :> sextcall_info (mem := mwd D);\n sextcall_props: res (ExtcallProperties sextcall_primsem_step);\n sextcall_invs: res (ExtcallInvariants sextcall_primsem_step)\n }.\n\n Global Instance: forall D, Measure (sextcall_primsem_step D).\n\n (** ** Order *)\n\n Definition sextcall_primsem_le {D} :=\n (sextcall_info_le @@ sextcall_primsem_step D)%signature.\n\n Local Instance RelCompFun_preorder {A B} (R: relation B) (π: A -> B):\n Measure π ->\n PreOrder R ->\n PreOrder (R @@ π)%signature.\n Proof.\n intros Hπ HR.\n split; typeclasses eauto.\n Qed.\n\n Global Instance sextcall_primsem_le_preorder D:\n PreOrder (sextcall_primsem_le (D:=D)).\n Proof.\n typeclasses eauto.\n Qed.\n\n Lemma sextcall_primsem_le_invs {D} (sem1 sem2: sextcall_primsem D):\n sextcall_primsem_le sem1 sem2 ->\n ExtcallInvariants sem2 ->\n ExtcallInvariants sem1.\n Proof.\n intros Hsem H.\n destruct sem1 as [sem1 props1 invs1].\n destruct sem2 as [sem2 props2 invs2].\n destruct Hsem as [Hstep12 Hsig12].\n destruct H as [Hstep Hcsig Hvalid Hinvs Hinj Hwt]; subst.\n simpl in *.\n unfold arrow_pointwise_rel, impl in *.\n split; eauto.\n + unfold sextcall_res.\n rewrite Hsig12.\n eauto.\n Qed.\nEnd OPTIONAL_PROPERTIES.\n\n\n(** * Simulation diagrams *)\n\nSection SIM.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n\n Class MatchExtcallStates {D1 D2} (R: compatrel D1 D2)\n f m1 d1 m2 d2:=\n {\n match_inject:\n Mem.inject f m1 m2;\n match_related:\n relate_AbData f d1 d2;\n match_match:\n match_AbData d1 m2 f;\n match_inject_flat:\n inject_incr (Mem.flat_inj glob_threshold) f;\n match_inject_forward:\n forall b1 b2 delta, f b1 = Some (b2, delta) -> delta = 0%Z /\\ b1 <= b2;\n match_nextblock_forward:\n Mem.nextblock m1 <= Mem.nextblock m2;\n match_newglob_noperm i b ofs k p:\n In i new_glbl ->\n find_symbol i = Some b ->\n ~ Mem.perm m1 b ofs k p;\n match_newglob_nextblock i b:\n In i new_glbl ->\n find_symbol i = Some b ->\n b < Mem.nextblock m1;\n match_inject_inject b1 b2 b delta1 delta2:\n f b1 = Some (b, delta1) ->\n f b2 = Some (b, delta2) ->\n b1 = b2\n }.\n\n Record sextcall_sim {D1 D2: compatdata} (R: compatrel D1 D2)\n (sem1: sextcall_primsem D1) (sem2: sextcall_primsem D2): Prop :=\n {\n sextcall_sim_step:\n forall f vargs1 m1 d1 vres1 m1' d1' vargs2 m2 d2,\n forall (LOW_LEVEL_INVARIANT: low_level_invariant (Mem.nextblock m2) d2),\n forall (L_HIGH_LEVEL_INVARIANT: high_level_invariant d2),\n forall (H_HIGH_LEVEL_INVARIANT: high_level_invariant d1),\n sem1 vargs1 (m1, d1) vres1 (m1', d1') ->\n val_list_inject f vargs1 vargs2 ->\n MatchExtcallStates R f m1 d1 m2 d2 ->\n exists f' vres2 m2' d2',\n sem2 vargs2 (m2, d2) vres2 (m2', d2') /\\\n val_inject f vres1 vres2 /\\\n MatchExtcallStates R f' m1' d1' m2' d2' /\\\n inject_incr f f';\n sextcall_sim_sig:\n sextcall_csig sem1 = sextcall_csig sem2;\n sextcall_sim_invs:\n ExtcallInvariants sem1\n }.\n\n Global Instance sextcall_sim_le {D1 D2} (R: compatrel D1 D2):\n Proper\n (sextcall_primsem_le --> sextcall_primsem_le ++> impl)\n (sextcall_sim R).\n Proof.\n intros sem1' sem1 Hsem1 sem2 sem2' Hsem2 H.\n destruct sem1 as [sem1 props1 invs1].\n destruct sem2 as [sem2 props2 invs2].\n destruct sem1' as [sem1' props1' invs1'].\n destruct sem2' as [sem2' props2' invs2'].\n destruct Hsem1 as [Hstep1 Hsig1].\n destruct Hsem2 as [Hstep2 Hsig2].\n destruct H as [Hstep Hcsig Hinvs]; subst.\n simpl in *.\n constructor; simpl; eauto; try congruence.\n - intros.\n exploit Hstep; try rel_auto.\n intros [f' [vres2 [m2' [d2' [Hstep2' [Hinj12 Hmatch]]]]]].\n exists f', vres2, m2', d2'; rel_auto.\n - edestruct Hinvs as [Hll2 Hhl2 Hkm2 Hnb2 Hin2 Hwt2]; eauto.\n unfold arrow_pointwise_rel, impl in *.\n split; eauto.\n + unfold sextcall_res.\n rewrite Hsig1.\n eauto.\n Qed.\nEnd SIM.\n", "meta": {"author": "VeriGu", "repo": "E6998-Formal-Verification", "sha": "83c0bdd12b723f81c08886be1dedca0ca8aff0eb", "save_path": "github-repos/coq/VeriGu-E6998-Formal-Verification", "path": "github-repos/coq/VeriGu-E6998-Formal-Verification/E6998-Formal-Verification-83c0bdd12b723f81c08886be1dedca0ca8aff0eb/certikos/liblayers/compat/CompatCPrimitives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.24220562325537975, "lm_q1q2_score": 0.12204890809522762}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Proof of functional correctness *)\n(* for the C functions implemented in the VVMXInit layer *)\n(* *)\n(* Xiongnan (Newman) Wu *)\n(* *)\n(* Yale University *)\n(* *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import TrapArgGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CLemmas.\nRequire Import XOmega.\nRequire Import PProcCSource.\nRequire Import AbstractDataType.\nRequire Import ObjThread.\nRequire Import ObjProc.\nRequire Import ObjArg.\n\n\nModule PPROCCODE.\n\n Section WithPrimitives.\n\n Context `{real_params: RealParams}.\n Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n Context `{Hmwd: UseMemWithData memb}.\n\n Let mem := mwd (cdata RData).\n\n Context `{Hstencil: Stencil}.\n Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n(*\n Section LA2PARESV.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem (fun d => get_curid_spec d)\n ⊕ pt_read ↦ gensem (fun a b d => ptRead_spec d a b)\n ⊕ pt_resv ↦ gensem (fun a b c d => ptResv_spec d a b c).\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section La2paResvBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** pt_resv *)\n\n Variable bpt_resv: block.\n\n Hypothesis hpt_resv1 : Genv.find_symbol ge pt_resv = Some bpt_resv. \n \n Hypothesis hpt_resv2 : Genv.find_funct_ptr ge bpt_resv = Some (External (EF_external pt_resv (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) tvoid cc_default).\n\n (** pt_read *)\n\n Variable bpt_read: block.\n\n Hypothesis hpt_read : Genv.find_symbol ge pt_read = Some bpt_read. \n \n Hypothesis hpt_read2 : Genv.find_funct_ptr ge bpt_read = Some (External (EF_external pt_read (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma la2pa_resv_body_correct: forall m d d' env le va pa,\n env = PTree.empty _ ->\n PTree.get tva le = Some (Vint va) ->\n la2pa_resv_spec d (Int.unsigned va) = Some (d', Int.unsigned pa) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) la2pa_resv_body E0 le' (m, d') (Out_return (Some (Vint pa, tint))).\n Proof. \n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n subst.\n unfold la2pa_resv_body.\n functional inversion H1; subst.\n\n generalize H4; intro tmpinv;\n unfold ptRead_spec in tmpinv;\n case_eq (ikern d); intro ikern; rewrite ikern in tmpinv; try discriminate tmpinv;\n case_eq (ihost d); intro ihost; rewrite ihost in tmpinv; try discriminate tmpinv;\n clear tmpinv.\n rewrite <- Int.unsigned_repr with (cid d) in H4.\n esplit.\n repeat vcgenfull.\n unfold get_curid_spec.\n rewrite ikern, ihost, H5.\n rewrite <- Int.unsigned_repr with (cid d).\n reflexivity.\n omega.\n rewrite H4.\n change 0 with (Int.unsigned Int.zero).\n reflexivity.\n discharge_cmp.\n repeat vcgenfull.\n instantiate (1:= (Int.repr padr')).\n rewrite Int.unsigned_repr; try omega.\n reflexivity.\n repeat vcgen.\n reflexivity.\n repeat vcgen.\n repeat vcgen.\n repeat vcgen.\n repeat vcgen.\n unfold Int.modu.\n rewrite Int.unsigned_repr; try omega.\n simpl.\n assert(Int.repr (padr' / 4096 * 4096 + Int.unsigned va mod 4096) = pa).\n erewrite <- unsigned_inj.\n reflexivity.\n rewrite Int.unsigned_repr.\n assumption.\n xomega.\n rewrite <- H.\n simpl.\n unfold sem_add.\n simpl.\n unfold sem_binarith.\n simpl.\n repeat vcgenfull.\n xomega.\n xomega.\n xomega.\n xomega.\n omega.\n\n generalize H4; intro tmpinv;\n unfold ptRead_spec in tmpinv;\n case_eq (ikern d'); intro ikern; rewrite ikern in tmpinv; try discriminate tmpinv;\n case_eq (ihost d'); intro ihost; rewrite ihost in tmpinv; try discriminate tmpinv;\n clear tmpinv.\n rewrite <- Int.unsigned_repr with (cid d') in H4.\n esplit.\n repeat vcgenfull.\n unfold get_curid_spec.\n rewrite ikern, ihost, H5.\n rewrite <- Int.unsigned_repr with (cid d').\n reflexivity.\n omega.\n rewrite H4.\n instantiate (1:= (Int.repr padr)).\n rewrite Int.unsigned_repr; try omega.\n reflexivity.\n discharge_cmp.\n repeat vcgenfull.\n repeat vcgen.\n reflexivity.\n repeat vcgen.\n repeat vcgen.\n repeat vcgen.\n repeat vcgen.\n unfold Int.modu.\n rewrite Int.unsigned_repr; try omega.\n simpl.\n assert(Int.repr (padr / 4096 * 4096 + Int.unsigned va mod 4096) = pa).\n erewrite <- unsigned_inj.\n reflexivity.\n rewrite Int.unsigned_repr.\n assumption.\n xomega.\n rewrite <- H.\n unfold sem_add.\n simpl.\n unfold sem_binarith.\n simpl.\n repeat vcgenfull.\n xomega.\n xomega.\n xomega.\n xomega.\n omega.\n Qed.\n\n End La2paResvBody.\n\n Theorem la2pa_resv_code_correct:\n spec_le (la2pa_resv ↦ la2pa_resv_spec_low) (〚la2pa_resv ↦ f_la2pa_resv 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (la2pa_resv_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp b2 Hb2fs Hb2fp b3 Hb3fs Hb3fp b4 Hb4fs Hb4fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_la2pa_resv)\n (Vint va::nil)\n (create_undef_temps (fn_temps f_la2pa_resv)))) H0. \n Qed.\n\n End LA2PARESV.\n*)\n\n Section UCTXARG1.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg1Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg1_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg1_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg1_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof. \n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg1_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n unfold uctx_get_spec. \n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n repeat zdestruct. \n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n omega.\n Qed.\n\n End UctxArg1Body.\n\n Theorem uctx_arg1_code_correct:\n spec_le (uctx_arg1 ↦ uctx_arg1_spec_low) (〚uctx_arg1 ↦ f_uctx_arg1 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg1_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg1)\n nil\n (create_undef_temps (fn_temps f_uctx_arg1)))) H0. \n Qed.\n\n End UCTXARG1.\n\n\n Section UCTXARG2.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg2Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg2_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg2_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg2_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg2_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n unfold uctx_get_spec. \n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n repeat zdestruct. \n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n omega.\n Qed.\n\n End UctxArg2Body.\n\n Theorem uctx_arg2_code_correct:\n spec_le (uctx_arg2 ↦ uctx_arg2_spec_low) (〚uctx_arg2 ↦ f_uctx_arg2 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg2_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg2)\n nil\n (create_undef_temps (fn_temps f_uctx_arg2)))) H0. \n Qed.\n\n End UCTXARG2.\n\n\n Section UCTXARG3.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg3Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg3_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg3_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg3_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg3_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n unfold uctx_get_spec. \n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n repeat zdestruct. \n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n omega.\n Qed.\n\n End UctxArg3Body.\n\n Theorem uctx_arg3_code_correct:\n spec_le (uctx_arg3 ↦ uctx_arg3_spec_low) (〚uctx_arg3 ↦ f_uctx_arg3 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg3_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg3)\n nil\n (create_undef_temps (fn_temps f_uctx_arg3)))) H0. \n Qed.\n\n End UCTXARG3.\n\n\n Section UCTXARG4.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg4Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg4_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg4_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg4_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg4_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n unfold uctx_get_spec. \n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n repeat zdestruct. \n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n omega.\n Qed.\n\n End UctxArg4Body.\n\n Theorem uctx_arg4_code_correct:\n spec_le (uctx_arg4 ↦ uctx_arg4_spec_low) (〚uctx_arg4 ↦ f_uctx_arg4 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg4_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg4)\n nil\n (create_undef_temps (fn_temps f_uctx_arg4)))) H0. \n Qed.\n\n End UCTXARG4.\n\n\n Section UCTXARG5.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg5Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg5_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg5_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg5_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg5_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n unfold uctx_get_spec. \n rewrite Int.unsigned_repr.\n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n repeat zdestruct. \n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n Qed.\n\n End UctxArg5Body.\n\n Theorem uctx_arg5_code_correct:\n spec_le (uctx_arg5 ↦ uctx_arg5_spec_low) (〚uctx_arg5 ↦ f_uctx_arg5 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg5_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg5)\n nil\n (create_undef_temps (fn_temps f_uctx_arg5)))) H0. \n Qed.\n\n End UCTXARG5.\n\n Section UCTXARG6.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_get ↦ gensem uctx_get_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxArg6Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_get *)\n\n Variable buctx_get: block.\n\n Hypothesis huctx_get1 : Genv.find_symbol ge uctx_get = Some buctx_get. \n \n Hypothesis huctx_get2 : Genv.find_funct_ptr ge buctx_get = Some (External (EF_external uctx_get (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n Lemma uctx_arg6_body_correct: forall m d env le arg,\n env = PTree.empty _ ->\n uctx_arg6_spec d = Some (Int.unsigned arg) ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_arg6_body E0 le' (m, d) (Out_return (Some (Vint arg, tint))).\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H1; assumption).\n unfold uctx_arg6_body.\n functional inversion H0; subst.\n assert(ipt: ipt d = true).\n destruct H1. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec. \n rewrite H3, H4, H5.\n rewrite Int.unsigned_repr.\n reflexivity. \n omega.\n rewrite Int.unsigned_repr.\n unfold uctx_get_spec. \n rewrite H3, H4, H5, ipt, H6.\n unfold is_UCTXT_ptr.\n rewrite H2.\n rewrite zle_lt_true.\n reflexivity.\n omega. \n omega.\n Qed.\n\n End UctxArg6Body.\n\n Theorem uctx_arg6_code_correct:\n spec_le (uctx_arg6 ↦ uctx_arg6_spec_low) (〚uctx_arg6 ↦ f_uctx_arg6 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_arg6_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_arg6)\n nil\n (create_undef_temps (fn_temps f_uctx_arg6)))) H0. \n Qed.\n\n End UCTXARG6.\n\n Section UCTXSETERRNO.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_set ↦ gensem uctx_set_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxSetErronoBody.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_set *)\n\n Variable buctx_set: block.\n\n Hypothesis huctx_set1 : Genv.find_symbol ge uctx_set = Some buctx_set. \n \n Hypothesis huctx_set2 : Genv.find_funct_ptr ge buctx_set = Some (External (EF_external uctx_set (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n Lemma uctx_set_errno_body_correct: forall m d d' env le errno,\n env = PTree.empty _ ->\n PTree.get terrno le = Some (Vint errno) ->\n uctx_set_errno_spec (Int.unsigned errno) d = Some d' ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_set_errno_body E0 le' (m, d') Out_normal.\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n unfold uctx_set_errno_body.\n functional inversion H1; subst.\n assert(ipt: ipt d = true).\n destruct H2. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec.\n rewrite H4, H5, H6.\n rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n unfold uctx_set_spec.\n rewrite H4, H5, H6, ipt.\n unfold is_UCTXT_ptr.\n rewrite zle_lt_true.\n reflexivity.\n omega.\n omega.\n omega.\n Qed.\n\n End UctxSetErronoBody.\n\n Theorem uctx_set_errno_code_correct:\n spec_le (uctx_set_errno ↦ uctx_set_errno_spec_low) (〚uctx_set_errno ↦ f_uctx_set_errno 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_set_errno_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_set_errno)\n (Vint arg::nil)\n (create_undef_temps (fn_temps f_uctx_set_errno)))) H0. \n Qed.\n\n End UCTXSETERRNO.\n\n\n Section UCTXSETRETVAL1.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_set ↦ gensem uctx_set_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxSetRetval1Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_set *)\n\n Variable buctx_set: block.\n\n Hypothesis huctx_set1 : Genv.find_symbol ge uctx_set = Some buctx_set. \n \n Hypothesis huctx_set2 : Genv.find_funct_ptr ge buctx_set = Some (External (EF_external uctx_set (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n Lemma uctx_set_retval1_body_correct: forall m d d' env le retval,\n env = PTree.empty _ ->\n PTree.get tretval le = Some (Vint retval) ->\n uctx_set_retval1_spec (Int.unsigned retval) d = Some d' ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_set_retval1_body E0 le' (m, d') Out_normal.\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n unfold uctx_set_retval1_body.\n functional inversion H1; subst.\n assert(ipt: ipt d = true).\n destruct H2. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec.\n rewrite H4, H5, H6.\n rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n unfold uctx_set_spec.\n rewrite H4, H5, H6, ipt.\n unfold is_UCTXT_ptr.\n rewrite zle_lt_true.\n reflexivity.\n omega.\n omega.\n omega.\n Qed.\n\n End UctxSetRetval1Body.\n\n Theorem uctx_set_retval1_code_correct:\n spec_le (uctx_set_retval1 ↦ uctx_set_retval1_spec_low) (〚uctx_set_retval1 ↦ f_uctx_set_retval1 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_set_retval1_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_set_retval1)\n (Vint arg::nil)\n (create_undef_temps (fn_temps f_uctx_set_retval1)))) H0. \n Qed.\n\n End UCTXSETRETVAL1.\n\n Section UCTXSETRETVAL2.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_set ↦ gensem uctx_set_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxSetRetval2Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_set *)\n\n Variable buctx_set: block.\n\n Hypothesis huctx_set1 : Genv.find_symbol ge uctx_set = Some buctx_set. \n \n Hypothesis huctx_set2 : Genv.find_funct_ptr ge buctx_set = Some (External (EF_external uctx_set (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n Lemma uctx_set_retval2_body_correct: forall m d d' env le retval,\n env = PTree.empty _ ->\n PTree.get tretval le = Some (Vint retval) ->\n uctx_set_retval2_spec (Int.unsigned retval) d = Some d' ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_set_retval2_body E0 le' (m, d') Out_normal.\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n unfold uctx_set_retval2_body.\n functional inversion H1; subst.\n assert(ipt: ipt d = true).\n destruct H2. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec.\n rewrite H4, H5, H6.\n rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n unfold uctx_set_spec.\n rewrite H4, H5, H6, ipt.\n unfold is_UCTXT_ptr.\n rewrite zle_lt_true.\n reflexivity.\n omega.\n omega.\n omega.\n Qed.\n\n End UctxSetRetval2Body.\n\n Theorem uctx_set_retval2_code_correct:\n spec_le (uctx_set_retval2 ↦ uctx_set_retval2_spec_low) (〚uctx_set_retval2 ↦ f_uctx_set_retval2 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_set_retval2_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_set_retval1)\n (Vint arg::nil)\n (create_undef_temps (fn_temps f_uctx_set_retval2)))) H0. \n Qed.\n\n End UCTXSETRETVAL2.\n\n Section UCTXSETRETVAL3.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_set ↦ gensem uctx_set_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxSetRetval3Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_set *)\n\n Variable buctx_set: block.\n\n Hypothesis huctx_set1 : Genv.find_symbol ge uctx_set = Some buctx_set. \n \n Hypothesis huctx_set2 : Genv.find_funct_ptr ge buctx_set = Some (External (EF_external uctx_set (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n Lemma uctx_set_retval3_body_correct: forall m d d' env le retval,\n env = PTree.empty _ ->\n PTree.get tretval le = Some (Vint retval) ->\n uctx_set_retval3_spec (Int.unsigned retval) d = Some d' ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_set_retval3_body E0 le' (m, d') Out_normal.\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n unfold uctx_set_retval3_body.\n functional inversion H1; subst.\n assert(ipt: ipt d = true).\n destruct H2. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec.\n rewrite H4, H5, H6.\n rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n unfold uctx_set_spec.\n rewrite H4, H5, H6, ipt.\n unfold is_UCTXT_ptr.\n rewrite zle_lt_true.\n reflexivity.\n omega.\n omega.\n omega.\n Qed.\n\n End UctxSetRetval3Body.\n\n Theorem uctx_set_retval3_code_correct:\n spec_le (uctx_set_retval3 ↦ uctx_set_retval3_spec_low) (〚uctx_set_retval3 ↦ f_uctx_set_retval3 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_set_retval3_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_set_retval1)\n (Vint arg::nil)\n (create_undef_temps (fn_temps f_uctx_set_retval3)))) H0. \n Qed.\n\n End UCTXSETRETVAL3.\n\n Section UCTXSETRETVAL4.\n\n Let L: compatlayer (cdata RData) := get_curid ↦ gensem get_curid_spec\n ⊕ uctx_set ↦ gensem uctx_set_spec.\n\n Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n Section UctxSetRetval4Body.\n\n Context `{Hwb: WritableBlockOps}.\n\n Variable (sc: stencil).\n\n Variables (ge: genv)\n (STENCIL_MATCHES: stencil_matches sc ge).\n\n (** get_curid *)\n\n Variable bget_curid: block.\n\n Hypothesis hget_curid1 : Genv.find_symbol ge get_curid = Some bget_curid. \n \n Hypothesis hget_curid2 : Genv.find_funct_ptr ge bget_curid = Some (External (EF_external get_curid (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n (** uctx_set *)\n\n Variable buctx_set: block.\n\n Hypothesis huctx_set1 : Genv.find_symbol ge uctx_set = Some buctx_set. \n \n Hypothesis huctx_set2 : Genv.find_funct_ptr ge buctx_set = Some (External (EF_external uctx_set (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n Lemma uctx_set_retval4_body_correct: forall m d d' env le retval,\n env = PTree.empty _ ->\n PTree.get tretval le = Some (Vint retval) ->\n uctx_set_retval4_spec (Int.unsigned retval) d = Some d' ->\n high_level_invariant d ->\n exists le',\n exec_stmt ge env le ((m, d): mem) uctx_set_retval4_body E0 le' (m, d') Out_normal.\n Proof.\n generalize max_unsigned_val; intro muval.\n intros.\n assert(cid_range: 0 <= cid d < 64) by (destruct H2; assumption).\n unfold uctx_set_retval4_body.\n functional inversion H1; subst.\n assert(ipt: ipt d = true).\n destruct H2. \n rewrite <- valid_ikern_ipt.\n assumption.\n esplit.\n repeat vcgen.\n unfold get_curid_spec.\n rewrite H4, H5, H6.\n rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n unfold uctx_set_spec.\n rewrite H4, H5, H6, ipt.\n unfold is_UCTXT_ptr.\n rewrite zle_lt_true.\n unfold uctx'.\n unfold uctx.\n repeat rewrite Int.unsigned_repr.\n reflexivity.\n omega.\n rewrite Int.unsigned_repr.\n omega.\n omega.\n Qed.\n\n End UctxSetRetval4Body.\n\n Theorem uctx_set_retval4_code_correct:\n spec_le (uctx_set_retval4 ↦ uctx_set_retval4_spec_low) (〚uctx_set_retval4 ↦ f_uctx_set_retval4 〛L).\n Proof.\n set (L' := L) in *. unfold L in *.\n fbigstep_pre L'.\n fbigstep (uctx_set_retval4_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n (bind_parameter_temps' (fn_params f_uctx_set_retval1)\n (Vint arg::nil)\n (create_undef_temps (fn_temps f_uctx_set_retval4)))) H0. \n Qed.\n\n End UCTXSETRETVAL4.\n\n\n End WithPrimitives.\n\nEnd PPROCCODE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/trap/PProcCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.23934933647101644, "lm_q1q2_score": 0.12154443276733744}} {"text": "Require Import Coq.Program.Equality.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.FSets.FMapAVL. \nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Ascii String.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Mult.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\n\nAdd LoadPath \".\" as Top0.\nRequire Import Top0.Keys.\nRequire Import Top0.Heap.\nRequire Import Top0.Tactics.\nRequire Import Top0.Environment.\nRequire Import Top0.Definitions.\nRequire Import Top0.CorrectnessLemmas.\nRequire Import Top0.AdditionalLemmas.\nRequire Import Top0.Determinism.\nRequire Import Top0.TypeSystem.\nRequire Import Top0.EffectSystem.\nRequire Import Top0.Axioms.\n\nImport EffectSoundness.\nImport TypeSoundness.\n\nLemma DeterminismReadOnlyCond:\n forall h env rho e b1 b2 h' cheap cacts,\n (h, env, rho, e) ⇓ (h', Bit b1, Phi_Nil) ->\n (h, env, rho, e) ⇓ (cheap, Bit b2, cacts) ->\n H.Equal h' cheap /\\ Bit b1 = Bit b2 /\\ Phi_Nil = cacts.\nProof.\n intros.\n generalize dependent cacts.\n generalize dependent cheap.\n generalize dependent b2.\n dependent induction H; intros; \n inversion H0; subst; intuition.\n rewrite H in H2. inversion H2; subst. auto.\nQed.\n\nAxiom RewritePhiR:\n forall acts, Phi_Seq Phi_Nil acts = acts.\n\nLemma EvalTrueIsTrue:\n forall h h' h'' env rho e efft efff eff tacts,\n (h, env, rho, Cond e efft efff) ⇓ (h'', Eff eff, tacts) ->\n (h, env, rho, e) ⇓ (h', Bit true, Phi_Nil) ->\n (h', env, rho, efft) ⇓ (h'', Eff eff, tacts).\nProof.\n intros.\n inversion H; subst. \n - assert ( Hbit : H.Equal h' cheap /\\ Bit true = Bit true /\\ Phi_Nil = cacts )\n by (eapply DeterminismReadOnlyCond; eauto).\n assert ( HD :h = h') by (eapply EmptyTracePreservesHeap_1; eauto).\n destruct Hbit as [? [H_ ?]]; inversion H_; subst.\n assert ( HD :h' = cheap) by (eapply EmptyTracePreservesHeap_1; eauto). \n assert (Phi_Seq Phi_Nil tacts0 = tacts0) by (rewrite RewritePhiR; auto). rewrite H2.\n rewrite HD.\n assumption.\n - assert ( Hbit : H.Equal h' cheap /\\ Bit true = Bit false /\\ Phi_Nil = cacts )\n by (eapply DeterminismReadOnlyCond; eauto; \n assert ( HD :h = h') by (eapply EmptyTracePreservesHeap_1; eauto); \n apply HMapP.Equal_refl).\n destruct Hbit as [? [H_ ?]]; inversion H_; subst.\nQed.\n\n\nLemma EvalFalseIsFalse:\nforall h h' h'' env rho e efft efff eff tacts,\n (h, env, rho, Cond e efft efff) ⇓ (h'', Eff eff, tacts) ->\n (h, env, rho, e) ⇓ (h', Bit false, Phi_Nil) ->\n (h', env, rho, efff) ⇓ (h'', Eff eff, tacts).\nintros.\n inversion H; subst. \n - assert ( Hbit : H.Equal h' cheap /\\ Bit false = Bit true /\\ Phi_Nil = cacts )\n by (eapply DeterminismReadOnlyCond; eauto; \n assert ( HD :h = h') by (eapply EmptyTracePreservesHeap_1; eauto); \n apply HMapP.Equal_refl).\n destruct Hbit as [? [H_ ?]]; inversion H_; subst.\n - assert ( Hbit : H.Equal h' cheap /\\ Bit false = Bit false /\\ Phi_Nil = cacts )\n by (eapply DeterminismReadOnlyCond; eauto).\n assert ( HD :h = h') by (eapply EmptyTracePreservesHeap_1; eauto).\n destruct Hbit as [? [H_ ?]]; inversion H_; subst.\n assert ( HD :h' = cheap) by (eapply EmptyTracePreservesHeap_1; eauto). \n assert (Phi_Seq Phi_Nil facts = facts) by (rewrite RewritePhiR; auto). rewrite H2.\n rewrite HD.\n assumption.\nQed.\n\nLemma DeterminismReadOnlyRefs :\n forall h env rho ea0 h'' h' r1 l0 r l aacts,\n (h, env, rho, ea0) ⇓ (h'', Loc (Rgn2_Const true false r1) l0, Phi_Nil) -> \n (h, env, rho, ea0) ⇓ (h', Loc (Rgn2_Const true false r) l, aacts) ->\n H.Equal h'' h' /\\ Loc (Rgn2_Const true false r1) l0 = Loc (Rgn2_Const true false r) l /\\ Phi_Nil = aacts.\nProof.\n intros. \n generalize dependent aacts.\n generalize dependent r.\n generalize dependent l.\n generalize dependent h'.\n dependent induction H.\n intros. inversion H0; subst. rewrite H2 in H. inversion H; subst. intuition.\nQed.\n\n\nTheorem Correctness_soundness_ext :\n forall h h' h'' env rho p p' v eff stty ctxt rgns ea ee,\n (h, env, rho, ea) ⇓ (h', v, p) ->\n forall h_ h'_ v_ p_,\n H.Equal h h_ ->\n (h_, env, rho, ea) ⇓ (h'_, v_, p_) ->\n (h, env, rho, ee) ⇓ (h'', Eff eff, p') ->\n BackTriangle (ctxt, rgns, rho, ea, ee) ->\n forall static ty, \n ReadOnlyPhi p' ->\n TcHeap (h, stty) ->\n TcRho (rho, rgns) ->\n TcEnv (stty, rho, env, ctxt) -> \n TcExp (ctxt, rgns, ea, ty, static) ->\n p ⊑ eff.\nProof.\n intros h h' h'' env rho p p' v eff stty ctxt rgns ea ee BS1. \n generalize dependent p'. \n generalize dependent ee.\n generalize dependent stty.\n generalize dependent ctxt.\n generalize dependent rgns.\n generalize dependent eff.\n generalize dependent h''.\n dynamic_cases (dependent induction BS1) Case;\n intros h'' eff rgns ctxt stty ee_exp p'; \n intros h_ h'_ v_ p_ HEqual BS2;\n intros HEff HBt static ty HRonly HHeap HRho HEnv HExp;\n try (solve [assert (Phi_Nil ⊑ eff) by (constructor); inversion BS2; subst; intuition]).\n Case \"mu_app\". \n inversion HExp as [ | | | | | \n ? ? ? ? ? ? ? ? ? ? ? HExp_ef HExp_ea \n | | | | | | | | | | | | | | | | | | | ]; subst.\n assert (clsTcVal : exists stty', \n (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n /\\ TcHeap (fheap, stty')\n /\\ TcVal (stty', \n Cls (env', rho', Mu f x ec' ee'), \n subst_rho rho (Ty2_Arrow tya effc ty effe Ty2_Effect))) \n by (eapply ty_sound; eauto).\n destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n \n assert (argTcVal : exists stty',\n (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n /\\ TcHeap (aheap, stty')\n /\\ TcVal (stty', v0, subst_rho rho tya))\n by (eapply ty_sound; eauto using update_env, ext_stores__env).\n destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n \n inversion TcVal_cls as [ | | | \n ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs [A B C D HSubst] \n | | |]; subst. \n inversion TcExp_abs as [ | | | \n ? ? ? ? ? ? ? ? ? ? ? HBt_ec_ee TcExp_ec' TcExp_ee' \n | | | | | | | | | | | | | | | | | | | | |]; subst.\n rewrite <- HSubst in TcVal_cls.\n do 2 rewrite subst_rho_arrow in HSubst. \n inversion HSubst as [[H_tyx_tya A C D E]]; clear A C D E.\n rewrite <- H_tyx_tya in TcVal_v'.\n \n (* goal *)\n assert (HSOUND : Phi_Seq (Phi_Seq facts aacts) bacts ⊑ eff).\n \n { apply PTS_Seq. \n SCase \"Phi_Seq facts aacts ⊑ eff\".\n apply PTS_Seq.\n SSCase \"facts ⊑ eff\".\n assert (H_ : facts ⊑ eff). \n {\n inversion HBt as [ | | | | \n | ? ? ? ? ? ? ? ? ? ? TcExp_ef TcExp_ea HBt_ef HBt_ea HR_ef HR_ea \n | | | | | | | | | | | | | ]; subst.\n SSSCase \"Mu_App ef ea0 << (efff0 ⊕ (effa0 ⊕ Eff_App ef ea0))\". \n inversion HEff; subst. \n assert (facts ⊑ eff).\n { eapply IHBS1_1 with (h_:=h'') (p_:=facts); eauto. \n - apply HFacts.Equal_refl. } \n assumption.\n SSSCase \"Mu_App ef ea0 << (⊤)\". \n inversion HEff; subst.\n apply PhiInThetaTop.\n }\n exact H_. \n SSCase \" aacts ⊑ eff\". \n inversion HBt as [ | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TcExp_ef TcExp_ea HBt_ef HBt_ea HR_ef HR_ea \n | | | | | | | | | | | | | ]; subst.\n SSSCase \"Mu_App ef ea0 << Eff_App ef ea0\". \n assert (H_ : aacts ⊑ eff).\n { eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=facts) in HR_ef. \n - apply ReadOnlyTracePreservesHeap_1 in BS1_1. \n + symmetry in BS1_1.\n inversion HEff; subst. \n assert (aacts ⊑ eff).\n eapply IHBS1_2 with (h_:=h'') (p_:=aacts); eauto.\n * apply HFacts.Equal_refl. \n * assumption.\n + assumption. \n - assert (facts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_ef, facts)) by\n (eapply eff_sound; eauto). \n eassumption. }\n exact H_. \n SSSCase \"Mu_App ef ea0 << (⊤)\". \n assert (H_ : aacts ⊑ eff).\n { induction eff; inversion HEff; subst. \n apply PhiInThetaTop. }\n exact H_. \n SCase \"bacts ⊑ eff\". \n inversion HEff; subst; \n inversion HBt as [ | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TcExp_ef TcExp_ea HBt_ef HBt_ea HR_ef HR_ea \n | | | | | | | | | | | | | ]; subst. \n SSSCase \"Mu_App ef ea0 << Eff_App ef ea0\".\n assert (HD3 : bacts ⊑ eff). \n { eapply IHBS1_3\n with (stty:=sttya) (p':=bacts0); eauto using HFacts.Equal_refl.\n - eapply EvaluationEffectFromEffApp; eauto.\n - inversion HRonly as [ | | ? ? A B | ]. exact B.\n - { apply update_env; simpl. \n - eapply ext_stores__env; eauto. \n apply update_env. \n + eassumption.\n + eapply ext_stores__val with (stty:=sttyb); eauto.\n - eapply ext_stores__val with (stty:=sttya); eauto. }\n }\n exact HD3.\n SSSCase \"Mu_App ef ea0 << (⊤)\".\n assert (H_ : bacts ⊑ None).\n { eapply IHBS1_3 \n with (stty:=sttya) (ee:=⊤); eauto. \n SSSSCase \"Equal Heaps\".\n apply HFacts.Equal_refl. \n SSSSCase \"Effect Evaluation\".\n econstructor.\n SSSSCase \"Back Triangle\". \n econstructor.\n SSSSCase \"Extended TcEnv\".\n { apply update_env; simpl. \n - eapply ext_stores__env; eauto. \n apply update_env. \n + eassumption.\n + eapply ext_stores__val with (stty:=sttyb); eauto.\n - eapply ext_stores__val with (stty:=sttya); eauto. }\n }\n exact H_. }\n exact HSOUND.\n Case \"rgn_app\". \n inversion HExp as [ | | | | | \n | ? ? ? ? ? ? ? HTcExp_er HTcRgn_w \n | | | | | | | | | | | | | | | | | |]; subst.\n assert (clsTcVal : exists stty', \n (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n /\\ TcHeap (fheap, stty')\n /\\ TcVal (stty', Cls (env', rho', Lambda x eb), \n subst_rho rho (Ty2_ForallRgn effr tyr))). \n eapply ty_sound;eauto. \n destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n \n inversion TcVal_cls as [ | | | \n ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs [A B C D HSubst] \n | | |]; subst. \n inversion TcExp_abs as [ | | | |\n ? ? ? ? ? ? HNo HLc1 HLc2 HBt_eb HTExp_eb\n | | | | | | | | | | | | | | | | | | | |]; subst.\n rewrite <- HSubst in TcVal_cls.\n do 2 rewrite subst_rho_forallrgn in HSubst.\n inversion HSubst as [[H_fold A]]; clear A.\n \n (* goal *)\n assert (HSOUND : Phi_Seq facts bacts ⊑ eff). \n {apply PTS_Seq.\n SCase \"facts ⊑ eff\".\n eapply IHBS1_1 with (h_:=h); eauto. apply HFacts.Equal_refl. \n inversion HBt; subst; eauto.\n econstructor; eauto.\n SCase \" bacts ⊑ eff\".\n inversion HBt; subst.\n SSCase \"Rgn_App er w << (∅)\". \n { eapply IHBS1_2 with (ee:=∅); eauto. \n - inversion HEff; subst. econstructor.\n - inversion HEff; subst. econstructor. \n - apply update_rho; auto.\n - eapply extended_rho; eauto. }\n SSCase \"Rgn_App er w << (⊤)\". \n { eapply IHBS1_2 with (ee:=⊤); eauto using update_rho, extended_rho; \n induction eff; \n try (solve [ apply HFacts.Equal_refl | constructor ]); inversion HEff.\n subst. econstructor.\n }\n }\n exact HSOUND.\n Case \"eff_app\".\n inversion HExp as [ | | | | | | | \n ? ? ? ? ? ? ? ? ? ? HExp_ef HExp_ea \n | | | | | | | | | | | | | | | | | ]; subst.\n assert (clsTcVal : exists stty', \n (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n /\\ TcHeap (h', stty')\n /\\ TcVal (stty', \n Cls (env', rho', Mu f x ec' ee'), \n subst_rho rho (Ty2_Arrow tya effc tyc effe Ty2_Effect))) \n by (eapply ty_sound; eauto).\n destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n \n assert (argTcVal : exists stty',\n (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n /\\ TcHeap (h', stty')\n /\\ TcVal (stty', v', subst_rho rho tya))\n by (eapply ty_sound; eauto using update_env, ext_stores__env).\n destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n \n inversion TcVal_cls as [ | | | \n ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs [A B C D HSubst] \n | | |]; subst. \n inversion TcExp_abs as [ | | | \n ? ? ? ? ? ? ? ? ? ? HBt_ec_ee TcExp_ec' TcExp_ee' \n | | | | | | | | | | | | | | | | | | | | |]; subst.\n rewrite <- HSubst in TcVal_cls.\n do 2 rewrite subst_rho_arrow in HSubst. \n inversion HSubst as [[H_tyx_tya A C D E]]; clear A C D E.\n rewrite <- H_tyx_tya in TcVal_v'.\n \n (* goal *)\n assert (HSOUND : Phi_Seq (Phi_Seq facts aacts) bacts ⊑ eff).\n \n { inversion HBt; subst. \n apply PTS_Seq.\n - apply PTS_Seq. \n + inversion HEff; subst.\n apply PhiInThetaTop.\n + inversion HEff; subst.\n apply PhiInThetaTop.\n - inversion HEff; subst.\n apply PhiInThetaTop. } \n exact HSOUND.\n Case \"par_pair\".\n inversion HBt as [ | | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? A B C D HBt_a HBt_b HBt_c HBt_d \n | | | | | | | | | | | |]; subst; \n inversion HEff; subst; [ | apply PhiInThetaTop]. \n inversion HExp as [ | | | | | ? ? ? ? ? ? ? ? ? ? HExp_ef HExp_ea \n | | | \n ? ? ? ? ? ? ? ? ? ? ? ? HBt_1 HBt_2 HExp_mu1 HExp_mu2 HExp_eff1 HExp_eff2 \n | | | | | | | | | | | | | | | | ]; subst. \n inversion HEff; subst. inversion H4; subst. inversion H12; subst.\n\n assert (H' : acts_eff1 ⊑ effa1).\n { eapply IHBS1_1 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption. }\n assert (H'' : acts_eff2 ⊑ effb1).\n { eapply IHBS1_2 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption. }\n assert (H''' : acts_mu1 ⊑ effa0).\n { eapply IHBS1_3 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption. }\n assert (H'''' : acts_mu2 ⊑ effb2).\n { eapply IHBS1_4 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption. }\n \n assert (H_ : (Phi_Par acts_eff1 acts_eff2) ⊑ (Union_Theta effa1 effb1)). \n apply PTS_Par; [ apply Theta_introl | apply Theta_intror ]; eauto.\n\n assert (H__ : (Phi_Par acts_mu1 acts_mu2) ⊑ (Union_Theta effa0 effb2)). \n apply PTS_Par; [ apply Theta_introl | apply Theta_intror ]; eauto.\n\n assert (_H__ : ReadOnlyPhi acts_eff1).\n { eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:= acts_eff1) in B; auto.\n assert (facts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_ee_1, acts_eff1)) by\n (eapply eff_sound; eauto). \n assumption. }\n \n assert (_H_ : acts_mu1 ⊑ theta1). \n { induction theta1; [| apply PhiInThetaTop].\n eapply IHBS1_3 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HExp_mu1; subst. auto.\n } \n \n assert (_H____ : ReadOnlyPhi acts_eff2).\n { eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:= acts_eff2) in D; auto.\n assert (facts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_ee_2, acts_eff2)) by\n (eapply eff_sound; eauto). \n assumption. }\n\n assert (_H___ : acts_mu2 ⊑ theta2).\n { induction theta2; [| apply PhiInThetaTop].\n eapply IHBS1_4 with (h_:=h''); eauto using HFacts.Equal_refl.\n inversion HExp_mu2; subst. auto.\n } \n apply PTS_Seq. \n apply Theta_introl. assumption.\n apply Theta_intror. assumption.\n Case \"cond_true\".\n (* goal *)\n assert (HSOUND : Phi_Seq cacts tacts ⊑ eff).\n { inversion HBt as [ | | | | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? \n TcExp_e TcExp_et TcExp_ef HBt_e HBt_et HBt_ef\n | | | | | | | | | | ]; subst. \n - assert (H' : cacts ⊑ Some empty_set).\n { eapply IHBS1_1 with (h_:=h) (p':=Phi_Nil); eauto. \n - apply HFacts.Equal_refl. \n - constructor.\n - constructor. } \n \n apply EmptyUnionIsIdentity.\n apply EmptyIsNil in H'. subst. \n apply PTS_Seq; [apply PTS_Nil |].\n\n assert (HEq_1 : cheap = h).\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n assumption.\n constructor. }\n rewrite UnionEmptyWithEffIsEff.\n \n { eapply IHBS1_2 with (ee:=efft) (h_:=h) ; eauto.\n - apply Equal_heap_equal. auto.\n - subst. eassumption.\n - eapply EvalTrueIsTrue; eauto. \n - subst. assumption. }\n - inversion HEff; subst.\n apply PhiInThetaTop. \n }\n exact HSOUND.\n Case \"cond_false\".\n (* goal *)\n assert (HSOUND : Phi_Seq cacts facts ⊑ eff).\n { inversion HBt as [ | | | | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? \n TcExp_e TcExp_et TcExp_ef HBt_e HBt_et HBt_ef\n | | | | | | | | | |]; subst. \n - assert (H' : cacts ⊑ Some empty_set).\n { eapply IHBS1_1 with (h_:=h) (p':=Phi_Nil); eauto. \n - apply HFacts.Equal_refl. \n - constructor.\n - constructor. } \n \n apply EmptyUnionIsIdentity.\n apply EmptyIsNil in H'. subst. \n apply PTS_Seq; [apply PTS_Nil |].\n\n assert (HEq_1 : cheap = h).\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n assumption.\n constructor. }\n rewrite UnionEmptyWithEffIsEff.\n \n { eapply IHBS1_2 with (ee:=efff) (h_:=h) ; eauto.\n - apply Equal_heap_equal. auto.\n - subst. eassumption.\n - eapply EvalFalseIsFalse; eauto. \n - subst. assumption. }\n - inversion HEff; subst.\n apply PhiInThetaTop. \n }\n exact HSOUND.\n Case \"new_ref e\".\n (* goal *)\n assert (HSOUND : Phi_Seq vacts (Phi_Elem (DA_Alloc r (allocate_H heap' r) v0)) ⊑ eff).\n { inversion HEff; subst; \n inversion HBt as [ | | | | | | \n | | | ? ? ? ? ? ? ? ? TcExp_e HBt_e\n | | | | | | | | | ]; subst.\n apply EnsembleUnionComp. \n SCase \"Ref w e << (a ⊕ AllocAbs w)\". \n eapply IHBS1 with (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly; assumption.\n inversion H8; subst.\n apply PTS_Elem. apply DAT_Alloc_Abs.\n rewrite H in H1. inversion H1.\n apply In_singleton.\n SCase \"Ref w e << (⊤)\". \n apply PhiInThetaTop. \n }\n exact HSOUND.\n Case \"get_ref e\". \n (* goal *)\n assert (HSOUND : Phi_Seq aacts (Phi_Elem (DA_Read r l v)) ⊑ eff ).\n { inversion HBt as [ | | | | | | | \n | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TcExp_e TcExp_et TcExp_ef HBt_e HBt_et HBt_ef | \n | ? ? ? ? ? ? ? ? TcExp_ea0 HBt_ea0 | \n | | | | | | | ]; subst. \n - inversion HEff; subst. \n apply EnsembleUnionComp.\n + eapply IHBS1 with (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly; subst. assumption.\n + apply PTS_Elem. inversion H10; subst.\n rewrite H in H2; inversion H2.\n apply DAT_Read_Abs. apply In_singleton. \n - inversion HEff; subst.\n assert (aacts ⊑ Some empty_set). \n eapply IHBS1 with (h_:=h); eauto using HFacts.Equal_refl; constructor.\n apply PTS_Seq.\n + apply EmptyInAnyTheta. assumption.\n + apply PTS_Elem.\n simpl in H; inversion H; subst. \n apply DAT_Read_Conc. \n assert (HD: H.Equal h'' h' /\\ \n Loc (Rgn2_Const true false r1) l0 = Loc (Rgn2_Const true false r) l /\\ \n Phi_Nil = aacts). \n eapply DeterminismReadOnlyRefs; eauto.\n destruct HD as [? [H_ ?]]; inversion H_; subst.\n apply In_singleton.\n - econstructor; inversion HEff; subst; apply PhiInThetaTop.\n }\n exact HSOUND.\n Case \"set_ref e1 e2\".\n (* goal *)\n assert (HSOUND : Phi_Seq (Phi_Seq aacts vacts) (Phi_Elem (DA_Write r l v0)) ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | | | | | ]; subst. \n SCase \"Assign w ea0 ev << (eff1 ⊕ (eff2 ⊕ WriteAbs w))\".\n inversion HEff; subst.\n apply PTS_Seq. \n SSCase \"Phi_Seq aacts vacts ⊑ Union_Theta effa effb\".\n apply EnsembleUnionComp.\n SSSCase \"aacts ⊑ effa\".\n inversion HExp; subst.\n eapply IHBS1_1 with (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly; subst. assumption.\n SSSCase \"vacts ⊑ effb\". \n inversion HEff; subst. \n inversion H9; subst.\n inversion HExp; subst.\n \n assert (facts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, aacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : heap' = h''). \n eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=aacts) in HR.\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n - assumption. \n - assumption. } \n exact facts_Eff. \n \n assert (vacts ⊑ effa1). \n { eapply IHBS1_2 with (p':= phia0); eauto using HFacts.Equal_refl. \n - rewrite HEq_1. eassumption.\n - inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption.\n - rewrite HEq_1. assumption. }\n apply Theta_introl. assumption.\n SSCase \"Phi_Elem (DA_Write r l v0) ⊑ Union_Theta effa effb\". \n inversion H9; subst. \n assert (Phi_Elem (DA_Write r l v0) ⊑ effb0).\n apply PTS_Elem. inversion H10; subst.\n rewrite H in H1. inversion H1; subst.\n apply DAT_Write_Abs; apply In_singleton.\n apply Theta_intror. apply Theta_intror. \n assumption.\n SCase \" Assign (Rgn2_Const true false r0) ea0 ev << (eff1 ⊕ (eff2 ⊕ WriteConc ea0))\".\n inversion HEff; subst. \n apply PTS_Seq.\n SSCase \"Phi_Seq aacts vacts ⊑ Union_Theta effa effb\".\n apply EnsembleUnionComp.\n SSSCase \"aacts ⊑ effa\".\n inversion HExp; subst.\n eapply IHBS1_1 with (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly; subst. \n assumption.\n SSSCase \"vacts ⊑ effb\". \n inversion HExp; subst. \n inversion H9; subst.\n\n assert (facts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, aacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : heap' = h''). \n { eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=aacts) in HR.\n - apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n assumption. assumption. \n - eassumption. }\n \n assert (vacts ⊑ effa0). \n { eapply IHBS1_2 with (p':= phia0); eauto using HFacts.Equal_refl. \n - rewrite HEq_1. eassumption.\n - inversion HRonly as [ | | ? ? X Y | ]; inversion X; inversion Y; assumption.\n - rewrite HEq_1. assumption. }\n apply Theta_introl. assumption. \n SSCase \"Phi_Elem (DA_Write r l v0) ⊑ Union_Theta effa effb\".\n inversion H9; subst. \n assert (Phi_Elem (DA_Write r l v0) ⊑ effb0).\n apply PTS_Elem. inversion H10; subst. \n assert (HD: H.Equal h'' heap' /\\ Loc (Rgn2_Const true false r1) l0 = \n Loc (Rgn2_Const true false r0) l /\\ Phi_Nil = aacts).\n eapply DeterminismReadOnlyRefs; eauto.\n destruct HD as [? [H_ ?]]; inversion H_; subst.\n inversion H; subst.\n apply DAT_Write_Conc; apply In_singleton.\n apply Theta_intror. apply Theta_intror. assumption.\n SCase \"Assign w ea0 ev << (⊤)\".\n inversion HEff; subst. \n apply PhiInThetaTop.\n }\n exact HSOUND.\n Case \"nat_plus x y\". \n (* goal *)\n assert (HSOUND : Phi_Seq lacts racts ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? ? HTcExp_a HTcExp_b HR HBt_a HBt_b \n | | | | ]; subst;\n inversion HEff; subst;\n [apply EnsembleUnionComp | ]. \n \n - eapply IHBS1_1 with (ee:=eff1) (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly as [ | | ? ? X Y | ]; assumption.\n - assert (lacts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, lacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : lheap = h''). \n eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=lacts) in HR.\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n - assumption. \n - assumption. } \n exact lacts_Eff. \n \n eapply IHBS1_2 with (ee:=eff2) (h_:=h'') (p':=phib); eauto using HFacts.Equal_refl.\n + apply Equal_heap_equal; auto.\n + rewrite <- HEq_1. eassumption. \n + rewrite HEq_1. eassumption. \n + inversion HRonly as [ | | ? ? X Y | ]; assumption.\n + rewrite HEq_1. assumption.\n - apply PhiInThetaTop.\n } \n exact HSOUND.\n Case \"nat_minus x y\". \n (* goal *)\n assert (HSOUND : Phi_Seq lacts racts ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | \n | ? ? ? ? ? ? ? ? ? ? ? HTcExp_a HTcExp_b HR HBt_a HBt_b\n | | | ]; subst;\n inversion HEff; subst;\n [apply EnsembleUnionComp | ]. \n \n - eapply IHBS1_1 with (ee:=eff1) (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly as [ | | ? ? X Y | ]; assumption.\n - assert (lacts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, lacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : lheap = h''). \n eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=lacts) in HR.\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n - assumption. \n - assumption. } \n exact lacts_Eff. \n \n eapply IHBS1_2 with (ee:=eff2) (h_:=h'') (p':=phib); eauto using HFacts.Equal_refl.\n + apply Equal_heap_equal; auto.\n + rewrite <- HEq_1. eassumption. \n + rewrite HEq_1. eassumption. \n + inversion HRonly as [ | | ? ? X Y | ]; assumption.\n + rewrite HEq_1. assumption.\n - apply PhiInThetaTop.\n } \n exact HSOUND.\n Case \"nat_times x y\".\n (* goal *)\n assert (HSOUND : Phi_Seq lacts racts ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | | \n | ? ? ? ? ? ? ? ? ? ? ? HTcExp_a HTcExp_b HR HBt_a HBt_b \n | | ]; subst;\n inversion HEff; subst;\n [apply EnsembleUnionComp | ]. \n \n - eapply IHBS1_1 with (ee:=eff1) (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly as [ | | ? ? X Y | ]; assumption.\n - assert (lacts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, lacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : lheap = h''). \n eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=lacts) in HR.\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n - assumption. \n - assumption. } \n exact lacts_Eff. \n \n eapply IHBS1_2 with (ee:=eff2) (h_:=h'') (p':=phib); eauto using HFacts.Equal_refl.\n + apply Equal_heap_equal; auto.\n + rewrite <- HEq_1. eassumption. \n + rewrite HEq_1. eassumption. \n + inversion HRonly as [ | | ? ? X Y | ]; assumption.\n + rewrite HEq_1. assumption.\n - apply PhiInThetaTop.\n } \n exact HSOUND.\n Case \"bool_eq x y\".\n (* goal *)\n assert (HSOUND : Phi_Seq lacts racts ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | | | \n | ? ? ? ? ? ? ? ? ? ? ? HTcExp_a HTcExp_b HR HBt_a HBt_b \n | ]; subst;\n inversion HEff; subst;\n [apply EnsembleUnionComp | ]. \n \n - eapply IHBS1_1 with (ee:=eff1) (h_:=h''); eauto using HFacts.Equal_refl. \n inversion HRonly as [ | | ? ? X Y | ]; assumption.\n - assert (lacts_Eff : Epsilon_Phi_Soundness (fold_subst_eps rho static_e1, lacts)) by\n (eapply eff_sound; eauto). \n assert (HEq_1 : lheap = h''). \n eapply ReadOnlyStaticImpliesReadOnlyPhi with (phi:=lacts) in HR.\n { apply ReadOnlyTracePreservesHeap_1 in BS1_1. symmetry in BS1_1. \n - assumption. \n - assumption. } \n exact lacts_Eff. \n \n eapply IHBS1_2 with (ee:=eff2) (h_:=h'') (p':=phib); eauto using HFacts.Equal_refl.\n + apply Equal_heap_equal; auto.\n + rewrite <- HEq_1. eassumption. \n + rewrite HEq_1. eassumption. \n + inversion HRonly as [ | | ? ? X Y | ]; assumption.\n + rewrite HEq_1. assumption.\n - apply PhiInThetaTop.\n } \n exact HSOUND.\n Case \"eff_concat\".\n (* goal *)\n assert (HSOUND : Phi_Seq phia phib ⊑ eff ).\n { inversion HBt as [| | | | | | | | | | |\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | ? ? ? ? ? ? ? ? ? ? HBt_ea0 HBt_ev TcExp_ea0 HR\n | | | \n | ? ? ? ? ? ? ? ? ? ? ? HTcExp_a HTcExp_b HR HBt_a HBt_b \n | ]; subst;\n inversion HEff; subst.\n apply PhiInThetaTop.\n }\n exact HSOUND.\nQed.", "meta": {"author": "esmifro", "repo": "SurfaceEffects", "sha": "3450e4b771de4062ab73ee20947adf3f9de579ba", "save_path": "github-repos/coq/esmifro-SurfaceEffects", "path": "github-repos/coq/esmifro-SurfaceEffects/SurfaceEffects-3450e4b771de4062ab73ee20947adf3f9de579ba/Correctness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.23370636225126956, "lm_q1q2_score": 0.12141543826539429}} {"text": "(**************************************************************************)\n(* This file is part of CertrBPF, *)\n(* a formally verified rBPF verifier + interpreter + JIT in Coq. *)\n(* *)\n(* Copyright (C) 2022 Inria *)\n(* *)\n(* This program is free software; you can redistribute it and/or modify *)\n(* it under the terms of the GNU General Public License as published by *)\n(* the Free Software Foundation; either version 2 of the License, or *)\n(* (at your option) any later version. *)\n(* *)\n(* This program is distributed in the hope that it will be useful, *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)\n(* GNU General Public License for more details. *)\n(* *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import MemRegion State Monad.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom dx.Type Require Import Bool.\nFrom dx Require Import IR.\nFrom Coq Require Import List ZArith.\nFrom compcert Require Import Integers Values Clight Memory AST.\nFrom compcert Require Import Coqlib.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import clight_exec Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import correct_is_well_chunk_bool correct_eval_mrs_num correct_eval_mrs_regions correct_check_mem_aux correct_cmp_ptr32_nullM.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n(**\nCheck check_mem.\ncheck_mem\n : permission -> memory_chunk -> val -> M val\n*)\n\nSection Check_mem.\n Context {S:special_blocks}.\n (** The program contains our function of interest [fn] *)\n Definition p : Clight.program := prog.\n\n (* [Args,Res] provides the mapping between the Coq and the C types *)\n (* Definition Args : list CompilableType := [stateCompilableType].*)\n Definition args : list Type := [(permission:Type); (memory_chunk:Type); (val:Type)].\n Definition res : Type := (val:Type).\n\n (* [f] is a Coq Monadic function with the right type *)\n Definition f : arrow_type args (M State.state res) := check_mem.\n\n\n (* [fn] is the Cligth function which has the same behaviour as [f] *)\n Definition fn: Clight.function := f_check_mem.\n\n\n (* [match_arg] relates the Coq arguments and the C arguments *)\n Definition match_arg_list : DList.t (fun x => x -> Inv _) ((unit:Type) ::args) :=\n dcons (fun _ => StateLess _ is_state_handle)\n (dcons (stateless perm_correct)\n (dcons (stateless match_chunk)\n (dcons (stateless val32_correct)\n (DList.DNil _)))).\n\n (* [match_res] relates the Coq result and the C result *)\n Definition match_res : res -> Inv State.state:= stateless eq.\n\n Instance correct_function_check_mem : forall a, correct_function _ p args res f fn ModNothing false match_state match_arg_list match_res a.\n Proof.\n correct_function_from_body args.\n correct_body.\n (** how to use correct_* *)\n unfold INV.\n unfold f, cl_app.\n unfold check_mem.\n correct_forward.\n\n get_invariant _chunk.\n exists (v::nil).\n split.\n unfold map_opt, exec_expr. rewrite p0.\n reflexivity.\n intros; simpl.\n intuition eauto.\n\n intros.\n correct_forward.\n 2:{ (**r if-else branch *)\n correct_forward.\n\n eexists ; split_and.\n - reflexivity.\n - reflexivity.\n - reflexivity.\n - simpl ; auto.\n intro. constructor. reflexivity.\n }\n (**r if-then branch *)\n\n correct_forward.\n\n get_invariant _st.\n unfold eval_inv in *.\n exists (v::nil).\n split_and.\n unfold map_opt,exec_expr.\n rewrite p0; reflexivity.\n simpl; intros.\n tauto.\n -\n intros.\n correct_forward.\n\n get_invariant _st.\n unfold eval_inv,stateless, is_state_handle in *.\n subst.\n exists (Vptr st_blk Ptrofs.zero::nil).\n split.\n unfold map_opt, exec_expr.\n rewrite p0; reflexivity.\n simpl;intros.\n unfold is_state_handle. split ; auto.\n intros.\n correct_forward.\n\n get_invariant _st.\n get_invariant _mem_reg_num.\n get_invariant _perm.\n get_invariant _chunk.\n get_invariant _addr.\n get_invariant _mrs.\n exists (v :: v0 :: v1 :: v2 :: v3 :: v4 :: nil).\n split.\n unfold map_opt, exec_expr.\n rewrite p0, p1, p2, p3, p4, p5; reflexivity.\n simpl;intros.\n unfold correct_eval_mrs_num.match_res in c3.\n destruct c3 as (Hc_eq & _).\n unfold correct_eval_mrs_regions.match_res in c7.\n intuition eauto.\n\n intros.\n correct_forward.\n\n get_invariant _check_mem__1.\n exists (v::nil).\n split.\n unfold map_opt, exec_expr.\n rewrite p0; reflexivity.\n simpl;intros.\n unfold eval_inv,correct_check_mem_aux.match_res,stateless in c2.\n tauto.\n intros.\n\n correct_forward.\n 2:{\n correct_forward.\n\n get_invariant _check_mem__1.\n exists v.\n split_and;auto.\n simpl.\n apply Cop.cast_val_casted;auto.\n }\n\n correct_forward.\n eexists.\n split_and.\n reflexivity.\n reflexivity.\n reflexivity.\n simpl.\n intro ; constructor; reflexivity.\n\n get_invariant _is_null.\n unfold exec_expr.\n unfold eval_inv,correct_cmp_ptr32_nullM.match_res, match_bool,stateless in c2.\n rewrite p0.\n rewrite c2.\n unfold Val.of_bool.\n destruct x3; reflexivity.\n - get_invariant _well_chunk.\n unfold exec_expr.\n rewrite p0.\n unfold eval_inv, stateless, match_bool in c2.\n unfold Val.of_bool.\n rewrite c2.\n destruct x; reflexivity.\n Qed.\n\nEnd Check_mem.\n\nExisting Instance correct_function_check_mem.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_check_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.22815649691270323, "lm_q1q2_score": 0.12119886975614842}} {"text": "Require Import Smallstep.\nRequire Import Machregs.\nRequire Import Asm.\nRequire Import Integers.\nRequire Import List.\nRequire Import ZArith.\nRequire Import Memtype.\nRequire Import Memory.\nRequire Import Archi.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Values.\nRequire Import Conventions1.\nRequire Import AsmFacts.\nRequire Import SSAsm RealAsm RealAsmgen.\nRequire Import AsmRegs.\nRequire Import Errors.\nRequire Import Linking.\n\n Section PRESERVATION.\n\n Variable prog: Asm.program.\n Let ge := Genv.globalenv prog.\n\n Definition pc_at (s: state): option ((function * instruction) + external_function) :=\n let '(State rs m) := s in\n match rs PC with\n | Vptr b o =>\n match Genv.find_funct_ptr ge b with\n | Some (Internal f) =>\n match find_instr (Ptrofs.unsigned o) (fn_code f) with\n | Some i => Some (inl (f,i))\n | None => None\n end\n | Some (External ef) => Some (inr ef)\n | None => None\n end\n | _ => None\n end.\n\n Inductive seq: state -> state -> Prop :=\n | seq_intro rs1 rs2 m (REQ: forall r, r <> RA -> rs1 r = rs2 r): seq (State rs1 m) (State rs2 m).\n\n Inductive match_states: state -> state -> Prop :=\n | match_states_call_alloc\n (rs1 rs2: regset) m1 m2\n (REQ: forall r : preg, r <> RSP -> r <> RA -> rs1 r = rs2 r)\n (RRSP: rs1 RSP = Val.offset_ptr (rs2 RSP) (Ptrofs.repr (size_chunk Mptr)))\n (MEQ: Mem.storev Mptr m1 (rs2 RSP) (rs1 RA) = Some m2)\n f ialloc\n (PC1: pc_at (State rs1 m1) = Some (inl (f,ialloc)))\n (ALLOC: is_alloc ialloc):\n match_states (State rs1 m1) (State rs2 m2)\n | match_states_call_external\n (rs1 rs2: regset) m1 m2\n (REQ: forall r : preg, r <> RSP -> r <> RA -> rs1 r = rs2 r)\n (RRSP: rs1 RSP = Val.offset_ptr (rs2 RSP) (Ptrofs.repr (size_chunk Mptr)))\n (MEQ: Mem.storev Mptr m1 (rs2 RSP) (rs1 RA) = Some m2)\n ef\n (PC1: pc_at (State rs1 m1) = Some (inr ef)):\n match_states (State rs1 m1) (State rs2 m2)\n | match_states_free_ret\n (rs1 rs2: regset) m\n (REQ: forall r : preg, r <> RSP -> r <> RA -> rs1 r = rs2 r)\n (RRSP: rs1 RSP = Val.offset_ptr (rs2 RSP) ((Ptrofs.repr (size_chunk Mptr))))\n (LOADRA: loadvv Mptr m (rs2 RSP) = Some (rs1 RA))\n f\n (PC1: pc_at (State rs1 m) = Some (inl (f,Pret))):\n match_states (State rs1 m) (State rs2 m)\n | match_states_free_jmp\n (rs1 rs2: regset) m\n (REQ: forall r: preg, r <> RSP -> r <> RA -> rs1 r = rs2 r)\n (RRSP: rs1 RSP = Val.offset_ptr (rs2 RSP) ((Ptrofs.repr (size_chunk Mptr))))\n (MEQ: loadvv Mptr m (rs2 RSP) = Some (rs1 RA))\n (RANU: rs1 RA <> Vundef)\n f ijmp\n (PC1: pc_at (State rs1 m) = Some (inl (f,ijmp)))\n (JMP: is_jmp ijmp):\n match_states (State rs1 m) (State rs2 m)\n | match_states_normal s1 s2\n (SEQ: seq s1 s2)\n (PC1: match pc_at s2 with\n | Some (inl (f,i)) => ~ intermediate_instruction i\n | Some (inr ef) => False\n | None => True\n end\n ):\n match_states s1 s2\n | match_states_stuck s1 s2\n (PCnone: pc_at s1 = None)\n (PCeq: rs_state s1 PC = rs_state s2 PC)\n (RAXeq: rs_state s1 RAX = rs_state s2 RAX)\n : match_states s1 s2.\n\n Lemma max_stacksize_range':\n size_chunk Mptr <= max_stacksize <= Ptrofs.max_unsigned.\n Proof.\n split. unfold max_stacksize.\n destruct Mptr; simpl; lia.\n vm_compute. congruence.\n Qed.\n\n Hypothesis WF: wf_asm_prog ge.\n\n Lemma max_stacksize_aligned : (8 | max_stacksize).\n Proof. unfold max_stacksize. exists 512. lia. Qed.\n\n Lemma max_stacksize_range : 0 <= max_stacksize <= Ptrofs.max_unsigned.\n Proof. unfold max_stacksize. vm_compute. split; congruence. Qed.\n\n Lemma max_stacksize'_range : 0 <= max_stacksize + align (size_chunk Mptr) 8 <= Ptrofs.max_unsigned.\n Proof. unfold max_stacksize. vm_compute. split; congruence. Qed.\n\n\n Lemma initial_states_match :\n forall s1 s2,\n SSAsm.initial_state prog s1 ->\n initial_state prog s2 ->\n exists s1', SSAsm.initial_state prog s1' /\\ match_states s1' s2.\n Proof.\n simpl; intros s1 s2 IS1 IS2.\n exists s1; split; auto. inv IS1; inv IS2.\n unfold ge, ge0, ge1, rs0, rs1 in *. rewrite_hyps.\n apply Genv.init_mem_stack in H as STK.\n apply Genv.init_mem_sid in H as SID.\n apply Mem.alloc_result in H0 as X. unfold Mem.nextblock in X. unfold fresh_block in X. rewrite STK in X.\n simpl in X. subst.\n destruct (Genv.find_funct_ptr ge bmain0) eqn:Fmain.\n - destruct f.\n + eapply match_states_call_alloc.\n * intros. simpl_regs. rewrite (Pregmap.gso _ _ H2). rewrite (Pregmap.gso _ _ H3). reflexivity.\n * simpl_regs. Opaque max_stacksize. simpl. f_equal.\n * simpl_regs.\n simpl. rewrite <- Ptrofs.sub_add_opp.\n unfold Ptrofs.sub.\n rewrite (Ptrofs.unsigned_repr (size_chunk Mptr)).\n rewrite (Ptrofs.unsigned_repr (max_stacksize + align (size_chunk Mptr) 8)).\n 3: vm_compute; intuition congruence. unfold stkblock.\n simpl in H4. congruence.\n generalize max_stacksize'_range. lia.\n * simpl. simpl_regs. rewrite Fmain.\n erewrite wf_asm_alloc_at_beginning; eauto.\n * apply make_palloc_is_alloc.\n + eapply match_states_call_external.\n * intros. simpl_regs. rewrite (Pregmap.gso _ _ H2). rewrite (Pregmap.gso _ _ H3). auto.\n * simpl_regs. simpl. f_equal.\n * simpl_regs.\n simpl. rewrite <- Ptrofs.sub_add_opp.\n unfold Ptrofs.sub.\n rewrite (Ptrofs.unsigned_repr (size_chunk Mptr)).\n rewrite (Ptrofs.unsigned_repr (max_stacksize + align (size_chunk Mptr) 8)).\n 3: vm_compute; intuition congruence. unfold stkblock.\n simpl in H4. congruence.\n generalize max_stacksize'_range. lia.\n * simpl. simpl_regs. rewrite Fmain. eauto.\n - eapply match_states_stuck. simpl. rewrite Fmain. auto.\n simpl. simpl_regs. auto.\n simpl. simpl_regs. auto.\n Qed.\n\n Lemma match_states_PC:\n forall s1 s2,\n match_states s1 s2 ->\n rs_state s1 PC = rs_state s2 PC.\n Proof.\n intros s1 s2 MS; inv MS; try rewrite REQ by congruence; try reflexivity.\n inv SEQ. simpl; auto. apply REQ. congruence. auto.\n Qed.\n\n Inductive is_builtin: instruction -> Prop :=\n | is_builtin_intro ef args res: is_builtin (Pbuiltin ef args res).\n\n Lemma is_builtin_dec i: is_builtin i \\/ ~ is_builtin i.\n Proof.\n destruct i; first [right; now inversion 1|now econstructor].\n Qed.\n\n Lemma step_internal:\n forall s t s'\n (STEP: SSAsm.step ge s t s')\n f i\n (PCAT: pc_at s = Some (inl (f,i)))\n (NB: ~ is_builtin i),\n SSAsm.exec_instr ge f i (rs_state s) (m_state s) = Next (rs_state s') (m_state s') /\\ t = E0.\n Proof.\n unfold pc_at; intros s t s' STEP; inv STEP.\n - rewrite H, H0, H1. inversion 1; subst. simpl. eauto.\n - rewrite H, H0, H1. intros f0 i A; inv A. intro NIB; exfalso; apply NIB. constructor.\n - rewrite H, H0. inversion 1.\n Qed.\n\n Lemma step_external_store:\n forall s t s'\n (STEP: SSAsm.step ge s t s')\n ef\n (PCAT: pc_at s = Some (inr ef)),\n exists m2,\n Mem.storev Mptr (m_state s) (Val.offset_ptr (rs_state s RSP) (Ptrofs.neg (Ptrofs.repr (size_chunk Mptr))))\n (rs_state s RA) = Some m2.\n Proof.\n unfold pc_at; intros s t s' STEP; inv STEP; rewrite H, H0; try now destr.\n inversion 1; simpl; eauto.\n Qed.\n\n Lemma internal_step:\n forall rs1 rs2 m1 m2 f i\n (PCAT: pc_at (State rs1 m1) = Some (inl (f,i)))\n (EI: SSAsm.exec_instr ge f i rs1 m1 = Next rs2 m2),\n SSAsm.step ge (State rs1 m1) E0 (State rs2 m2).\n Proof.\n intros.\n simpl in PCAT. repeat destr_in PCAT.\n eapply SSAsm.exec_step_internal; eauto.\n Qed.\n\n Lemma offset_ptr_neg_sub a b ptr:\n (Val.offset_ptr (Val.offset_ptr ptr (Ptrofs.neg a)) (Ptrofs.sub a b)) = Val.offset_ptr ptr (Ptrofs.neg b).\n Proof.\n rewrite Val.offset_ptr_assoc. f_equal.\n rewrite Ptrofs.sub_add_opp. rewrite <- Ptrofs.add_assoc.\n rewrite (Ptrofs.add_commut (Ptrofs.neg _)). rewrite Ptrofs.add_neg_zero. apply Ptrofs.add_zero_l.\n Qed.\n\n Lemma offset_ptr_neg_sub' : forall sp sz,\n Val.offset_ptr (Val.offset_ptr sp (Ptrofs.repr (size_chunk Mptr))) (Ptrofs.neg sz) =\n Val.offset_ptr sp (Ptrofs.neg (Ptrofs.sub sz (Ptrofs.repr (size_chunk Mptr)))).\n Proof.\n intros. destruct sp; simpl; auto.\n f_equal.\n rewrite <- Ptrofs.sub_add_opp.\n rewrite <- Ptrofs.sub_add_opp.\n rewrite (Ptrofs.sub_add_opp sz _).\n rewrite Ptrofs.sub_add_r.\n rewrite Ptrofs.sub_add_opp.\n rewrite (Ptrofs.sub_add_opp i _).\n reflexivity.\n Qed.\n\n Lemma offset_ptr_cancel:\n forall ptr a,\n (exists b o, ptr = Vptr b o) ->\n Val.offset_ptr (Val.offset_ptr ptr a) (Ptrofs.neg a) = ptr.\n Proof.\n intros ptr a (b & o & EQ); subst. simpl.\n rewrite <- Ptrofs.sub_add_opp.\n rewrite Ptrofs.add_commut.\n rewrite Ptrofs.sub_add_l.\n rewrite Ptrofs.sub_idem. rewrite Ptrofs.add_zero_l. auto.\n Qed.\n\n Lemma eval_addrmode64_seq:\n forall (rs rs' : regset) (REQ: forall r, r <> RA -> rs r = rs' r) a,\n eval_addrmode64 ge a rs = eval_addrmode64 ge a rs'.\n Proof.\n intros.\n unfold eval_addrmode64.\n destr. f_equal. destr. apply REQ. congruence.\n f_equal. destr. destr. rewrite REQ by congruence. auto.\n Qed.\n\n Lemma eval_addrmode32_seq:\n forall (rs rs' : regset) (REQ: forall r, r <> RA -> rs r = rs' r) a,\n eval_addrmode32 ge a rs = eval_addrmode32 ge a rs'.\n Proof.\n intros.\n unfold eval_addrmode32.\n destr. f_equal. destr. apply REQ. congruence.\n f_equal. destr. destr. rewrite REQ by congruence. auto.\n Qed.\n\n Lemma eval_addrmode_seq:\n forall (rs rs' : regset) (REQ: forall r, r <> RA -> rs r = rs' r) a,\n eval_addrmode ge a rs = eval_addrmode ge a rs'.\n Proof.\n unfold eval_addrmode. intros.\n destr; eauto using eval_addrmode32_seq, eval_addrmode64_seq.\n Qed.\n\n Lemma eval_testcond_seq:\n forall (rs rs' : regset) (REQ: forall r, r <> RA -> rs r = rs' r) t,\n eval_testcond t rs = eval_testcond t rs'.\n Proof.\n unfold eval_testcond. intros.\n repeat rewrite REQ by congruence. repeat destr.\n Qed.\n\n Lemma exec_load_seq:\n forall chunk m a r r' rd r0 m0,\n seq (State r m) (State r' m) ->\n exec_load ge chunk m a r rd = Next r0 m0 ->\n exists r1 m1,\n exec_load ge chunk m a r' rd = Next r1 m1.\n Proof.\n unfold exec_load; intros chunk m a r r' rd r0 m0 SEQ EL; repeat destr_in EL.\n erewrite eval_addrmode_seq in Heqo. rewrite Heqo. eauto. inv SEQ; auto.\n Qed.\n\n Lemma exec_store_seq:\n forall chunk m a r r' rd lrd r0 m0,\n seq (State r m) (State r' m) ->\n exec_store ge chunk m a r rd lrd= Next r0 m0 ->\n rd <> RA ->\n exists r1 m1,\n exec_store ge chunk m a r' rd lrd = Next r1 m1.\n Proof.\n unfold exec_store; intros chunk m a r r' rd lrd r0 m0 SEQ EL NRA; repeat destr_in EL.\n inv SEQ.\n erewrite eval_addrmode_seq in Heqo. rewrite <- REQ. rewrite Heqo. eauto. auto. auto.\n Qed.\n\n Lemma goto_label_seq:\n forall f l rs1 rs2 m rs' m'\n (GL : goto_label ge f l rs1 m = Next rs' m')\n (SEQ: rs1 PC = rs2 PC),\n exists (rs2' : regset) (m2' : mem), goto_label ge f l rs2 m = Next rs2' m2'.\n Proof.\n unfold goto_label. intros. destr. rewrite <- SEQ. destr. destr. eauto.\n Qed.\n\n Ltac force_rewrite_match H :=\n match goal with\n H: ?b = _ |- context [ match ?a with _ => _ end ] =>\n cut (b = a);[ let A := fresh in intro A; rewrite <- A, H | ]\n end.\n\n Lemma eval_builtin_arg_eq_rs:\n forall (rs1 rs2: regset) (REQ: forall r, r <> RA -> rs1 r = rs2 r) sp m args vargs\n (NIN: ~ in_builtin_arg args RA),\n eval_builtin_arg ge rs1 sp m args vargs ->\n eval_builtin_arg ge rs2 sp m args vargs.\n Proof.\n induction 3; rewrite ? REQ; try econstructor; eauto.\n intro; subst. now simpl in NIN.\n simpl in NIN. apply IHeval_builtin_arg1. intuition.\n simpl in NIN. apply IHeval_builtin_arg2. intuition.\n simpl in NIN. apply IHeval_builtin_arg1. intuition.\n simpl in NIN. apply IHeval_builtin_arg2. intuition.\n Qed.\n\n Lemma eval_builtin_args_eq_rs:\n forall (rs1 rs2: regset) (REQ: forall r, r <> RA -> rs1 r = rs2 r) sp m args vargs\n (NIN: Forall (fun arg => ~ in_builtin_arg arg RA) args),\n eval_builtin_args ge rs1 sp m args vargs ->\n eval_builtin_args ge rs2 sp m args vargs.\n Proof.\n induction 3; constructor; eauto.\n eapply eval_builtin_arg_eq_rs. 3: apply H. auto. inv NIN; auto.\n inv NIN. apply IHlist_forall2. auto.\n Qed.\n\n Lemma preg_of_not_RA:\n forall r,\n preg_of r <> RA.\n Proof.\n unfold preg_of. intros.\n destr.\n Qed.\n\n Lemma extcall_arg_eq_rs:\n forall (rs1 rs2: regset)\n (REQ : forall r : preg, r <> RA -> rs1 r = rs2 r)\n m1 l arg\n (ARGS : extcall_arg rs1 m1 l arg),\n extcall_arg rs2 m1 l arg.\n Proof.\n intros rs1 rs2 REQ m1 l arg ARGS; inv ARGS.\n - rewrite REQ.\n econstructor. apply preg_of_not_RA.\n - econstructor; eauto. rewrite <- REQ; eauto. congruence.\n Qed.\n\n Lemma extcall_arg_pair_eq_rs:\n forall (rs1 rs2: regset)\n (REQ : forall r : preg, r <> RA -> rs1 r = rs2 r)\n m1 l arg\n (ARGS : extcall_arg_pair rs1 m1 l arg),\n extcall_arg_pair rs2 m1 l arg.\n Proof.\n intros; inv ARGS; econstructor; eauto using extcall_arg_eq_rs.\n Qed.\n\n Lemma extcall_arguments_eq_rs:\n forall (rs1 rs2: regset)\n (REQ : forall r : preg, r <> RA -> rs1 r = rs2 r)\n m1 sg args\n (ARGS : extcall_arguments rs1 m1 sg args),\n extcall_arguments rs2 m1 sg args.\n Proof.\n intros rs1 rs2 REQ m1. unfold extcall_arguments.\n induction 1; econstructor; eauto using extcall_arg_pair_eq_rs.\n Qed.\n\n Lemma extcall_progress:\n forall (rs1 rs2: regset)\n (REQ : forall r : preg, r <> RSP -> r <> RA -> rs1 r = rs2 r)\n (RRSP : rs1 RSP = Val.offset_ptr (rs2 RSP) (Ptrofs.repr (size_chunk Mptr)))\n m2\n b ef\n (FFP : Genv.find_funct_ptr ge b = Some (External ef))\n (PC1 : rs1 PC = Vptr b Ptrofs.zero)\n args res\n (ARGS : extcall_arguments rs1 m2 (ef_sig ef) args)\n ra (LOADRA: Mem.loadv Mptr m2 (rs2 RSP) = Some ra)\n (SP_TYPE : Val.has_type (rs1 RSP) Tptr)\n (SP_NOT_VUNDEF : rs1 RSP <> Vundef)\n (RA_NOT_VUNDEF : ra <> Vundef)\n m' t\n (EXTCALL : external_call ef ge args m2 t res m'),\n exists s2', step ge (State rs2 m2) t s2'.\n Proof.\n intros.\n eexists.\n eapply exec_step_external. rewrite <- REQ by congruence. eauto. eauto.\n eapply extcall_arguments_eq_rs. 2: eauto. intros. simpl_regs.\n setoid_rewrite Pregmap.gsspec. rewrite <- RRSP.\n destr. apply REQ. eauto. eauto.\n rewrite RRSP in SP_NOT_VUNDEF. unfold Val.offset_ptr in SP_NOT_VUNDEF. destr_in SP_NOT_VUNDEF. apply Val.Vptr_has_type.\n eauto.\n rewrite RRSP in SP_NOT_VUNDEF. unfold Val.offset_ptr in SP_NOT_VUNDEF. destr_in SP_NOT_VUNDEF.\n auto. eauto. eauto.\n Qed.\n\n Lemma real_asm_progress:\n forall s1 s2,\n match_states s1 s2 ->\n safe (SSAsm.semantics prog) s1 ->\n real_asm_inv s2 ->\n (exists r : int, final_state s2 r) \\/ (exists (t : trace) (s2' : state), step (Genv.globalenv prog) s2 t s2').\n Proof.\n intros s1 s2 MS SAFE SPAL.\n destruct (SAFE _ (star_refl _ _ _)) as [(r & FS)|(t & s2' & STEP)].\n {\n simpl in FS. inv FS.\n assert (pc_at (State rs m) = None).\n - simpl. rewrite H. unfold Vnullptr. destruct ptr64; auto.\n - inv MS; try congruence. inv SEQ.\n left. eexists; constructor; rewrite <- REQ; eauto. congruence. congruence.\n destruct s2. left. eexists; simpl in *; econstructor. congruence. rewrite <- RAXeq; eauto.\n }\n simpl in *. fold ge in STEP |- *.\n inv MS.\n - exploit step_internal. apply STEP. eauto. intro IB; inv IB; inv ALLOC. intros (EI & T0).\n simpl in *. subst.\n inv ALLOC; simpl in EI. repeat destr_in EI.\n repeat destr_in PC1.\n exploit wf_asm_wf_allocframe; eauto. intro A; inv A.\n rewrite offset_ptr_neg_sub in Heqo.\n rewrite RRSP in Heqo.\n rewrite offset_ptr_cancel in Heqo.\n assert (m = m2) by congruence. subst.\n rewrite RRSP in Heqo0.\n rewrite offset_ptr_neg_sub' in Heqo0.\n right; do 2 eexists.\n eapply exec_step_internal.\n rewrite <- REQ by congruence. eauto. eauto. eauto.\n simpl. rewrite Heqo0. eauto.\n unfold Mem.storev in MEQ. destr_in MEQ. eauto.\n - simpl in PC1. repeat destr_in PC1.\n inv STEP; rewrite_hyps.\n right. exists t.\n assert (m2 = m0).\n {\n rewrite RRSP in H3.\n rewrite offset_ptr_cancel in H3. congruence.\n unfold Mem.storev in MEQ. destr_in MEQ. eauto.\n } subst.\n eapply extcall_progress; eauto.\n assert (exists b o, rs2 RSP = Vptr b o).\n {\n unfold Mem.storev, Mem.loadv in MEQ.\n destruct (rs2 RSP); simpl in *; try congruence. eauto.\n }\n unfold Mem.storev in H3.\n rewrite RRSP in H3. rewrite offset_ptr_cancel in H3; eauto.\n destr_in H3.\n simpl. erewrite Mem.load_store_same; eauto.\n change Mptr with (chunk_of_type Tptr).\n erewrite Val.load_result_same. auto. auto.\n - exploit step_internal. apply STEP. eauto. intro IB; inv IB. intros (EI & T0).\n simpl in EI. repeat destr_in EI.\n simpl in *.\n repeat destr_in PC1. unfold loadvv in LOADRA.\n unfold Mem.loadv in LOADRA. destr_in LOADRA. destr_in Heqo1.\n assert (v = rs1 RA). destr_in LOADRA. subst.\n inv SPAL. red in RSPPTR. simpl in RSPPTR. rewrite Heqv0 in RSPPTR.\n destruct RSPPTR as (o & EQRSP & AL);inv EQRSP; eauto.\n right; do 2 eexists.\n eapply exec_step_internal.\n rewrite <- REQ by congruence. eauto. eauto. eauto.\n simpl. rewrite Heqv0. unfold loadvv.\n simpl. rewrite Heqo1. rewrite LOADRA. eauto.\n - exploit step_internal. apply STEP. eauto. intro IB; inv IB; inv JMP. intros (EI & T0).\n simpl in *.\n repeat destr_in PC1.\n inv JMP.\n + (*Pjmp_s*)\n right; do 2 eexists.\n eapply exec_step_internal.\n rewrite <- REQ by congruence. eauto. eauto. eauto.\n simpl. simpl in EI; simpl; repeat destr_in EI.\n + (*Pjmp_r*)\n right; do 2 eexists.\n eapply exec_step_internal.\n rewrite <- REQ by congruence. eauto. eauto. eauto.\n simpl. simpl in EI; simpl; repeat destr_in EI. eauto.\n rewrite <- REQ. eauto. rewrite Heqo1. eauto.\n intro. subst. eapply wf_asm_jmp_no_rsp; eauto. auto.\n congruence. congruence.\n - inversion SEQ; subst.\n simpl in *. rewrite <- REQ in PC1 by congruence.\n repeat destr_in PC1; subst.\n repeat destr_in Heqo.\n + inversion STEP; subst; rewrite_hyps.\n destruct (is_call_dec i1).\n {\n destruct (SAFE _ (star_one _ _ _ _ _ STEP)) as [(r & FS)|(t & s2' & STEP2)].\n - inv FS.\n inv i; simpl in H6; repeat destr_in H6.\n +\n simpl_regs_in H1. unfold Genv.symbol_address in H1. destr_in H1.\n inversion H1. inversion H1.\n +\n simpl_regs_in H1. unfold Genv.symbol_address in H1. destr_in H1.\n unfold Genv.find_funct in Heqo. destr_in Heqo. inversion H0.\n - (* match_state *)\n assert (exists b f', Genv.find_funct_ptr ge b = Some f' /\\\n rs' PC = Vptr b Ptrofs.zero).\n {\n rename H6 into EI.\n inv i; simpl in EI; repeat destr_in EI.\n simpl_regs. unfold Genv.find_funct in Heqo; repeat destr_in Heqo. eauto.\n simpl_regs. unfold Genv.find_funct in Heqo; repeat destr_in Heqo. eauto.\n }\n destruct H as (b & f' & FFP & PC').\n destruct f'.\n + inv i.\n *\n exploit step_internal. apply STEP2. simpl. rewrite PC'. rewrite FFP.\n erewrite wf_asm_alloc_at_beginning; eauto. inversion 1. intros (EI & T0). subst.\n simpl in EI. repeat destr_in EI.\n right; do 2 eexists. eapply exec_step_internal. rewrite <- REQ; eauto. congruence. eauto. eauto.\n simpl in H6. destr_in H6. inv H6. simpl. force_rewrite_match Heqo. eauto.\n simpl_regs. rewrite <- ! REQ.\n f_equal.\n apply offset_ptr_neg_sub. congruence. congruence.\n\n *\n exploit step_internal. apply STEP2. simpl. rewrite PC'. rewrite FFP.\n erewrite wf_asm_alloc_at_beginning; eauto. inversion 1. intros (EI & T0). subst.\n simpl in EI. repeat destr_in EI.\n right; do 2 eexists. eapply exec_step_internal. rewrite <- REQ; eauto. congruence. eauto. eauto.\n simpl in H6. destr_in H6. inv H6. simpl. force_rewrite_match Heqo. eauto.\n simpl_regs. rewrite <- ! REQ.\n f_equal.\n apply offset_ptr_neg_sub. congruence. congruence.\n + generalize (step_external_store _ _ _ STEP2 e). simpl; rewrite PC' , FFP.\n intro STORE; trim STORE. auto. destruct STORE as (m2' & STORE).\n inv i.\n *\n simpl in H6. destr_in H6. inv H6. revert STORE. simpl_regs. intros.\n right; do 2 eexists. eapply exec_step_internal. rewrite <- REQ; eauto. congruence. eauto. eauto.\n simpl. rewrite <- ! REQ. rewrite STORE. eauto. congruence. congruence.\n *\n simpl in H6. destr_in H6. inv H6. revert STORE. simpl_regs. intros.\n right; do 2 eexists. eapply exec_step_internal. rewrite <- REQ; eauto. congruence. eauto. eauto.\n simpl. rewrite <- ! REQ. rewrite STORE. eauto. congruence. congruence. congruence.\n }\n\n cut (exists rs2' m2', exec_instr ge f0 i1 rs2 m = Next rs2' m2').\n intros (rs2' & m2' & EI'). right; exists E0, (State rs2' m2').\n eapply exec_step_internal. rewrite <- REQ by congruence; eauto. eauto. eauto. eauto.\n destruct i1; simpl in H6; simpl; eauto using exec_load_seq, exec_store_seq.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n repeat rewrite <- REQ by congruence. repeat destr_in H6. eauto.\n repeat rewrite <- REQ by congruence. repeat destr_in H6. eauto.\n repeat rewrite <- REQ by congruence. repeat destr_in H6. eauto.\n repeat rewrite <- REQ by congruence. repeat destr_in H6. eauto.\n repeat destr; eauto.\n eapply goto_label_seq; eauto. apply REQ; congruence.\n destr_in H6. inv H6. eauto. destr_in H6. do 2 eexists. rewrite <- REQ. rewrite Heqo.\n eauto. congruence.\n erewrite <- eval_testcond_seq by eauto. repeat destr_in H6; eauto. eapply goto_label_seq; eauto. apply REQ; congruence.\n erewrite <- eval_testcond_seq by eauto. destr_in H6.\n erewrite <- eval_testcond_seq by eauto. repeat destr_in H6; eauto. eapply goto_label_seq; eauto. apply REQ; congruence.\n rewrite <- REQ by congruence. destr. destr. eapply goto_label_seq. eauto. simpl_regs. apply REQ; congruence.\n exfalso; apply n; econstructor.\n exfalso; apply n; econstructor.\n exfalso; apply PC1. constructor 2. auto.\n eapply exec_store_seq; eauto. congruence.\n eapply exec_store_seq; eauto. congruence.\n exfalso; apply PC1. constructor 1. constructor.\n eapply eval_builtin_args_eq_rs in H4. rewrite REQ in H4.\n right; do 2 eexists. eapply exec_step_builtin. rewrite <- REQ; eauto. congruence. all: eauto. congruence.\n eapply wf_asm_builtin_not_PC; eauto.\n + inv STEP; repeat destr_in Heqo.\n - inv STEP; simpl in *; repeat destr_in PCnone.\n Qed.\n\n Lemma ptrofs_cancel i f s:\n i =\n Ptrofs.add\n (Ptrofs.add (Ptrofs.add i s) (Ptrofs.neg f))\n (Ptrofs.sub f s).\n Proof.\n rewrite ! Ptrofs.add_assoc.\n transitivity (Ptrofs.add i Ptrofs.zero). rewrite Ptrofs.add_zero. auto.\n f_equal.\n rewrite Ptrofs.sub_add_opp.\n rewrite (Ptrofs.add_commut f). rewrite <- (Ptrofs.add_assoc _ (Ptrofs.neg s)).\n rewrite (Ptrofs.add_commut _ (Ptrofs.neg s)). rewrite (Ptrofs.add_assoc (Ptrofs.neg s)).\n rewrite <- (Ptrofs.add_assoc _ (Ptrofs.neg s)).\n rewrite Ptrofs.add_neg_zero. rewrite Ptrofs.add_zero_l.\n rewrite Ptrofs.add_commut. rewrite Ptrofs.add_neg_zero. auto.\n Qed.\n\n Lemma offset_ptr_has_type:\n forall ptr o,\n Val.has_type (Val.offset_ptr ptr o) Tptr.\n Proof.\n intros. destruct ptr; now (simpl; auto).\n Qed.\n\n\n Lemma goto_label_match:\n forall f l rs2 m2 rs2' m2' rs1,\n (forall r: preg, r<>RA -> rs1 r = rs2 r) ->\n goto_label ge f l rs2 m2 = Next rs2' m2' ->\n exists rs1' m1', goto_label ge f l rs1 m2 = Next rs1' m1' /\\ seq (State rs1' m1') (State rs2' m2').\n Proof.\n intros f l rs2 m2 rs2' m2' rs1 REQ GL2.\n edestruct goto_label_seq as (rs1' & m1' & GL). eauto. symmetry; apply REQ. congruence. rewrite GL.\n do 2 eexists; split; eauto.\n unfold goto_label in GL2, GL. destr_in GL. rewrite REQ in GL by congruence.\n repeat destr_in GL. inv GL2.\n constructor. intros. regs_eq.\n Qed.\n\n Lemma find_instr_same : forall c i1 i2 ofs1 ofs2,\n find_instr ofs1 c = i1 ->\n find_instr ofs2 c = i2 ->\n ofs1 = ofs2 ->\n i1 = i2.\n Proof.\n intros. congruence. Qed.\n\n Lemma goto_label_PC:\n forall f l r m r0 m0\n (GL: goto_label ge f l r m = Next r0 m0)\n b i\n (PCbef: r PC = Vptr b i)\n (FFP: Genv.find_funct_ptr ge b = Some (Internal f)) ,\n (forall f0 i2,\n pc_at (State r0 m0) = Some (inl (f0,i2)) ->\n ~ intermediate_instruction i2)\n /\\ (forall ef,\n pc_at (State r0 m0) = Some (inr ef) ->\n False ).\n Proof.\n intros.\n simpl.\n unfold goto_label in GL.\n rewrite PCbef, FFP in GL. destr_in GL. inv GL. simpl_regs. rewrite FFP.\n destr. split. 2: inversion 1. intros f0 i2 EQ; inv EQ.\n assert (EQz: Ptrofs.unsigned (Ptrofs.repr z) = z).\n {\n replace z with (z-0) by lia.\n eapply label_pos_repr. rewrite Z.add_0_r. eapply wf_asm_code_bounded. eauto. lia. eauto.\n } rewrite EQz in *.\n generalize (label_pos_spec l (fn_code f0) 0 z). intro LPS; trim LPS.\n rewrite Z.add_0_r. eapply wf_asm_code_bounded; eauto. trim LPS. lia. trim LPS; auto.\n generalize (find_instr_ofs_pos _ _ _ LPS).\n intros POS II; inv II.\n {\n inv H. exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo0.\n generalize (instr_size_positive (Plabel l)); lia.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe. eauto. 2: apply H.\n rewrite EQz. eauto.\n intros (o' & ifree & FI & IFREE & RNG).\n generalize (find_instr_same _ _ _ _ _ LPS FI). intro. exploit H0.\n unfold instr_size. lia. intro. inv IFREE. congruence.\n }\n Qed.\n\n Lemma exec_instr_normal:\n forall rs1 rs2 m1 m2 b ofs f i rs2' m2',\n seq (State rs1 m1) (State rs2 m2) ->\n rs2 PC = Vptr b ofs ->\n Genv.find_funct_ptr ge b = Some (Internal f) ->\n find_instr (Ptrofs.unsigned ofs) (fn_code f) = Some i ->\n exec_instr ge f i rs2 m2 = Next rs2' m2' ->\n ~ intermediate_instruction i ->\n ~ is_call i ->\n ~ is_free i ->\n (exists rs1' m1',\n SSAsm.exec_instr ge f i rs1 m1 = Next rs1' m1' /\\\n seq (State rs1' m1') (State rs2' m2')) /\\\n match pc_at (State rs2' m2') with\n | Some (inl (_, i)) => ~ intermediate_instruction i\n | Some (inr ef) => False\n | None => True\n end.\n Proof.\n intros rs1 rs2 m1 m2 b ofs f i rs2' m2' SEQ PC2 FFP FI EI NII NIC NIF.\n simpl.\n inv SEQ.\n assert (SSAsm.exec_instr ge f i rs2 m2 = Next rs2' m2').\n {\n rewrite <- EI.\n destruct i; auto.\n contradict NIC; constructor.\n contradict NIC; constructor.\n contradict NII. constructor 2. auto.\n contradict NII. constructor. constructor.\n contradict NIF. constructor.\n } clear EI; rename H into EI.\n split.\n {\n destruct i; simpl in *; unfold exec_load, exec_store in *;\n erewrite ? eval_addrmode_seq by eauto;\n repeat erewrite ? eval_testcond_seq by eauto;\n erewrite ? REQ by congruence;\n repeat destr_in EI;\n try (do 2 eexists; split; [eauto|constructor; intros; simpl; regs_eq;\n try eapply eval_addrmode64_seq ;\n try eapply eval_addrmode32_seq; now eauto\n ]; fail).\n do 2 eexists; split; [eauto|constructor; intros; simpl; regs_eq; repeat destr; simpl; regs_eq].\n do 2 eexists; split; [eauto|constructor; intros; simpl; regs_eq; repeat destr; simpl; regs_eq].\n eapply goto_label_match; eauto.\n eapply goto_label_match; eauto.\n\n erewrite eval_testcond_seq by eauto. rewrite Heqo0. eapply goto_label_match; eauto.\n erewrite eval_testcond_seq by eauto. rewrite Heqo0.\n do 2 eexists; split; [eauto|constructor; intros; simpl; regs_eq; repeat destr; simpl; regs_eq].\n erewrite eval_testcond_seq by eauto. rewrite Heqo0.\n do 2 eexists; split; [eauto|constructor; intros; simpl; regs_eq; repeat destr; simpl; regs_eq].\n eapply goto_label_match. 2: eauto. intros; regs_eq.\n contradict NII. constructor 2; auto.\n contradict NII. constructor. constructor.\n }\n destruct (Val.eq (rs2' PC) (Val.offset_ptr (rs2 PC) (Ptrofs.repr (instr_size i)))).\n {\n rewrite e, PC2. simpl. rewrite FFP.\n destr. repeat destr_in Heqo. rename Heqo0 into FI'.\n intro A.\n inv A.\n {\n inv H. exploit wf_asm_alloc_only_at_beginning. eauto. apply FI'.\n erewrite wf_asm_pc_repr; eauto.\n generalize (Ptrofs.unsigned_range ofs) (instr_size_positive i); lia.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe; eauto.\n intros (o' & ifree & FI2 & IFREE & RNG).\n erewrite wf_asm_pc_repr in RNG; eauto.\n unfold instr_size in *.\n replace (Ptrofs.unsigned o') with (Ptrofs.unsigned ofs) in FI2 by lia.\n rewrite FI in FI2. inv FI2. inv IFREE. contradiction NIF. constructor.\n }\n }\n destruct i; simpl in *; unfold exec_load, exec_store in EI; repeat destr_in EI;\n unfold compare_ints, compare_longs, compare_floats, compare_floats32 in n;\n repeat destr_in n;\n simpl_regs_in n; unfold instr_size in n; unfold Ptrofs.one in n; try congruence.\n generalize (goto_label_PC _ _ _ _ _ _ H0 _ _ PC2 FFP). simpl. intros (A & B); repeat destr; eauto.\n contradict NII. econstructor 2. right. econstructor.\n contradict NII. econstructor 2. right. econstructor.\n generalize (goto_label_PC _ _ _ _ _ _ H0 _ _ PC2 FFP). simpl. intros (A & B); repeat destr; eauto.\n generalize (goto_label_PC _ _ _ _ _ _ H0 _ _ PC2 FFP). simpl. intros (A & B); repeat destr; eauto.\n generalize (goto_label_PC _ _ _ _ _ _ H0 _ _ PC2 FFP). simpl. intros (A & B); repeat destr; eauto.\n contradict NIC. constructor.\n contradict NIC. constructor.\n contradict NII. constructor 2. auto.\n Qed.\n\n Lemma offsets_after_call_correct:\n forall c pos o,\n 0 <= pos ->\n In o (offsets_after_call c pos) ->\n exists oc icall, find_instr oc c = Some icall /\\ is_call icall /\\ oc + instr_size icall = o - pos.\n Proof.\n induction c; simpl; intros; eauto.\n easy.\n destr_in H0.\n - destruct H0.\n + subst.\n exists 0, a. rewrite zeq_true. split; auto. split; auto. lia.\n + destruct (fun pos => IHc _ _ pos H0) as (oc & icall & INSTR & ICALL & EQ).\n generalize (instr_size_positive a). lia.\n exists (oc + instr_size a).\n rewrite pred_dec_false.\n unfold instr_size in *.\n replace (oc + 1 - 1) with oc by lia. rewrite INSTR.\n eexists; split; eauto. split; auto. lia.\n generalize (instr_size_positive a) (find_instr_ofs_pos _ _ _ INSTR). lia.\n - destruct (fun pos => IHc _ _ pos H0) as (oc & icall & INSTR & ICALL & EQ).\n generalize (instr_size_positive a). lia.\n exists (oc + instr_size a).\n rewrite pred_dec_false.\n unfold instr_size in *.\n replace (oc + 1 - 1) with oc by lia. rewrite INSTR.\n eexists; split; eauto. split; auto. lia.\n generalize (instr_size_positive a) (find_instr_ofs_pos _ _ _ INSTR). lia.\n Qed.\n\n Lemma loadvv_bastck_storev:\n forall rs m v ,\n rsp_ptr (State rs m) -> bstack_perm (State rs m) ->\n loadvv Mptr m (rs RSP) = Some v ->\n Mem.storev Mptr m (rs RSP) v = Some m.\n Proof.\n intros. destruct H as (ofs & SP & ALIGN).\n simpl in SP. rewrite SP in *. unfold loadvv in H1. destr_in H1.\n assert (v0 = v). destr_in H1. subst.\n eapply Mem.loadv_val_storev; eauto. destr_in H1.\n Qed.\n\n Lemma real_asm_step:\n forall s2 t s2',\n step (Genv.globalenv prog) s2 t s2' ->\n forall s1 : state,\n match_states s1 s2 ->\n real_asm_inv s2 ->\n safe (SSAsm.semantics prog) s1 ->\n exists s1', SSAsm.step (Genv.globalenv prog) s1 t s1' /\\ match_states s1' s2'.\n Proof.\n intros s2 t s2' STEP s1 MS INV SAFE. inv INV.\n fold ge in STEP.\n inv MS.\n - (*Pallocframe*)\n simpl in PC1. repeat destr_in PC1.\n rewrite REQ in Heqv by congruence.\n inv STEP; rewrite_hyps. 2: inv ALLOC.\n inv ALLOC. simpl in H6. destr_in H6. inv H6.\n eexists; split. eapply SSAsm.exec_step_internal. rewrite REQ by congruence; eauto.\n eauto. eauto.\n simpl. (* force_rewrite_match MEQ.*)\n cut (Mem.storev Mptr m1 (rs2 RSP) (rs1 RA) = Mem.storev Mptr m1 (Val.offset_ptr (Val.offset_ptr (rs1 RSP) (Ptrofs.neg (Ptrofs.repr (align sz 8)))) ora) (rs1 RA)); [let A := fresh in intro A; rewrite <- A,H|]. rewrite <- H. rewrite MEQ.\n rewrite <- offset_ptr_neg_sub' in Heqo1. rewrite <- RRSP in Heqo1. rewrite Heqo1.\n eauto. f_equal.\n rewrite RRSP.\n eapply wf_asm_wf_allocframe in Heqo0; eauto. inv Heqo0.\n unfold Mem.storev, Mem.loadv in MEQ.\n destruct (rs2 RSP); simpl in *; try congruence.\n f_equal. apply ptrofs_cancel.\n eapply match_states_normal.\n constructor. intros. apply nextinstr_eq.\n intros; apply set_reg_eq. intros. apply set_reg_eq. eauto.\n auto.\n rewrite RRSP. rewrite Val.offset_ptr_assoc. f_equal.\n rewrite Ptrofs.sub_add_opp. rewrite Ptrofs.neg_add_distr. rewrite Ptrofs.add_commut.\n rewrite Ptrofs.neg_involutive. auto.\n simpl. simpl_regs. rewrite Heqv. simpl. rewrite Heqo.\n destr. destr_in Heqo2. inv Heqo2.\n intro A.\n inv A.\n {\n inv H. exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo0. intro I0.\n exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo3.\n rewrite Ptrofs.add_unsigned. rewrite I0.\n rewrite Ptrofs.unsigned_repr. simpl. unfold Ptrofs.one. rewrite Ptrofs.unsigned_repr. lia. vm_compute. split; congruence.\n unfold Ptrofs.one. rewrite Ptrofs.unsigned_repr.\n vm_compute. split; congruence.\n vm_compute. split; congruence.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe; eauto.\n intros (o' & ifree & FI & IFREE & RNG).\n exploit wf_asm_alloc_only_at_beginning; eauto.\n unfold Ptrofs.one in RNG.\n replace 1 with (instr_size (Pallocframe sz ora olink)) in RNG by reflexivity.\n erewrite wf_asm_pc_repr in RNG; eauto.\n assert (Ptrofs.unsigned o' = Ptrofs.unsigned ofs). lia.\n rewrite H0 in FI. rewrite FI in Heqo0. inv IFREE. inv Heqo0.\n }\n - (* external call *)\n simpl in PC1. repeat destr_in PC1.\n rewrite REQ in Heqv by congruence.\n inv STEP; rewrite_hyps.\n assert (RAC : ra_after_call ge (rs1 RA)).\n {\n destruct (SAFE _ (star_refl _ _ _)) as [(rr & FS)|(tt & s' & STEP)].\n simpl in FS. inv FS. contradict H1. rewrite REQ by congruence. rewrite Heqv. inversion 1.\n simpl in STEP.\n rewrite <- REQ in Heqv by congruence.\n fold ge in STEP.\n inv STEP; rewrite_hyps; auto.\n }\n unfold Mem.storev in MEQ; destr_in MEQ.\n assert (rs1 RA = ra /\\ ra <> Vundef /\\ Val.has_type ra Tptr).\n {\n simpl in *. split.\n erewrite Mem.load_store_same in LOADRA; eauto. inv LOADRA.\n change Mptr with (chunk_of_type Tptr).\n symmetry. apply Val.load_result_same.\n revert RA_NOT_VUNDEF. unfold Val.load_result, Mptr, Tptr.\n destruct ptr64 eqn:PTR.\n destruct (rs1 RA); simpl; try congruence; auto.\n destruct (rs1 RA); simpl; try congruence; auto.\n eapply Mem.load_type in LOADRA.\n change Tptr with (type_of_chunk Mptr). auto.\n } destruct H as (RA1 & RA1U & RATYP); subst.\n eexists; split. eapply SSAsm.exec_step_external. rewrite REQ by congruence; eauto.\n eauto.\n rewrite <- MEQ.\n rewrite RRSP. rewrite offset_ptr_cancel. reflexivity. eauto.\n eapply extcall_arguments_eq_rs. 2: apply H3.\n intros. setoid_rewrite Pregmap.gsspec. rewrite <- RRSP.\n destr. symmetry; apply REQ. auto. auto.\n rewrite RRSP. apply offset_ptr_has_type.\n auto.\n rewrite RRSP. simpl; congruence.\n auto.\n eauto. eauto. reflexivity.\n eapply match_states_normal.\n constructor. intros.\n destruct (preg_eq r RSP). subst. simpl_regs.\n rewrite set_pair_no_rsp.\n unfold undef_caller_save_regs. simpl.\n auto.\n apply no_rsp_loc_external_result.\n rewrite (Pregmap.gso _ _ n).\n intros; apply set_reg_eq.\n intros. apply set_reg_eq.\n intros. apply set_pair_eq.\n intros.\n unfold undef_caller_save_regs. destr; auto.\n auto. auto.\n simpl. simpl_regs.\n destr. destr_in Heqo0. destr_in Heqo0.\n destruct RAC as (RAU & RAC).\n specialize (RAC _ _ eq_refl _ Heqo1). red in RAC. destr_in RAC. destr_in Heqo0. inv Heqo0.\n destruct (offsets_after_call_correct _ _ _ (Z.le_refl _) RAC) as (oc & icall & ICALL & ISCALL & EQofs).\n intro II; inv II.\n {\n inv H. exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo2.\n generalize (find_instr_ofs_pos _ _ _ ICALL) (instr_size_positive icall). lia.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe; eauto.\n intros (o' & ifree & FI & IFREE & RNG).\n generalize (find_instr_same _ _ _ _ _ FI ICALL). intro. exploit H0.\n unfold instr_size in *. simpl in *. lia.\n inv IFREE. inv ISCALL; congruence.\n }\n - (*Pret*)\n simpl in PC1. repeat destr_in PC1.\n rewrite REQ in Heqv by congruence. inv STEP; rewrite_hyps.\n assert ( RAC : ra_after_call ge (rs1 RA)).\n {\n destruct (SAFE _ (star_refl _ _ _)) as [(rr & FS)|(tt & s' & STEP)].\n simpl in FS. inv FS. contradict H1. rewrite REQ by congruence. rewrite Heqv. inversion 1.\n simpl in STEP.\n rewrite <- REQ in Heqv by congruence.\n fold ge in STEP.\n inv STEP; rewrite_hyps; auto.\n simpl in H7. destr_in H7.\n }\n simpl in H6. destr_in H6. inv H6.\n assert (RAV: rs1 RA = v).\n {\n unfold loadvv in Heqo1. destr_in Heqo1.\n }\n eexists; split. eapply SSAsm.exec_step_internal. rewrite REQ by congruence; eauto. eauto. eauto.\n simpl. rewrite pred_dec_true. eauto. eauto.\n apply match_states_normal.\n + constructor. intros. rewrite ! (Pregmap.gso _ _ H). apply set_reg_eq; auto.\n intros.\n setoid_rewrite Pregmap.gsspec. destr. apply REQ. auto. auto.\n + simpl. simpl_regs.\n destr. destr_in Heqo2. destr_in Heqo2.\n destruct RAC as (RAU & RAC).\n specialize (RAC _ _ RAV _ Heqo3). red in RAC. destr_in RAC. destr_in Heqo2. inv Heqo2.\n destruct (offsets_after_call_correct _ _ _ (Z.le_refl _) RAC) as (oc & icall & ICALL & ISCALL & EQofs).\n intro II; inv II.\n {\n inv H. exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo4.\n generalize (find_instr_ofs_pos _ _ _ ICALL) (instr_size_positive icall). lia.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe; eauto.\n intros (o' & ifree & FI & IFREE & RNG).\n generalize (find_instr_same _ _ _ _ _ FI ICALL). intro. exploit H0.\n unfold instr_size in *. simpl in *. lia.\n inv IFREE. inv ISCALL; congruence.\n }\n - (* Pjmp *)\n simpl in PC1. repeat destr_in PC1.\n rewrite REQ in Heqv by congruence. inv STEP; rewrite_hyps. 2: now (inv JMP).\n inv JMP.\n + (* Pjmp_s *)\n simpl in H6. inv H6.\n eexists; split. eapply SSAsm.exec_step_internal. rewrite REQ by congruence; eauto. eauto. eauto.\n simpl. eauto.\n fold ge.\n destr_in H0.\n destr_in H0. inv H0.\n destruct f.\n * (*jmp to the begin of an internal function*)\n eapply match_states_call_alloc.\n intros. apply set_reg_eq; auto.\n simpl_regs. auto.\n simpl_regs.\n eapply loadvv_bastck_storev; eauto.\n simpl. simpl_regs.\n unfold Genv.find_funct in Heqo1. destr.\n unfold Genv.symbol_address in Heqv0. destr_in Heqv0. inv Heqv0.\n rewrite pred_dec_true in Heqo1 by auto. rewrite Heqo1.\n erewrite wf_asm_alloc_at_beginning; eauto. constructor.\n *(*jmp to an external function*)\n eapply match_states_call_external.\n intros. apply set_reg_eq; auto. simpl_regs. auto.\n simpl_regs. eapply loadvv_bastck_storev; eauto.\n simpl. simpl_regs. unfold Genv.find_funct in Heqo1. destr.\n unfold Genv.symbol_address in Heqv0. destr_in Heqv0. inv Heqv0.\n rewrite pred_dec_true in Heqo1 by auto. rewrite Heqo1. eauto.\n + (*Pjmp_r*)\n simpl in H6. inv H6.\n eexists; split. eapply SSAsm.exec_step_internal. rewrite REQ by congruence; eauto. eauto. eauto.\n simpl. eauto.\n fold ge. rewrite REQ.\n destr_in H0. intro. subst. eapply wf_asm_jmp_no_rsp; eauto. congruence. congruence.\n destr_in H0. inv H0.\n destruct f.\n * (*jmp to the begin of an internal function*)\n eapply match_states_call_alloc.\n intros. apply set_reg_eq; auto.\n simpl_regs. auto.\n simpl_regs.\n unfold Mem.loadv in MEQ.\n eapply loadvv_bastck_storev; eauto.\n simpl. simpl_regs.\n unfold Genv.find_funct in Heqo1. destr.\n unfold Genv.symbol_address in Heqv0. destr_in Heqo1. subst.\n rewrite Heqo1.\n erewrite wf_asm_alloc_at_beginning; eauto. constructor.\n * (*jmp to an external function*)\n eapply match_states_call_external.\n intros. apply set_reg_eq; auto. simpl_regs. auto.\n simpl_regs.\n eapply loadvv_bastck_storev; eauto.\n simpl. simpl_regs. unfold Genv.find_funct in Heqo1. destr. destr_in Heqo1.\n subst. rewrite Heqo1. eauto.\n - (*common case*)\n inv STEP; simpl in *; rewrite H, H0, ? H1 in PC1.\n + destruct (is_call_dec i).\n {\n inv i0.\n +(* Pcall_s *)\n simpl in H2.\n destruct (SAFE _ (star_refl _ _ _)) as [(rr & FS)|(t & s' & STEP)].\n simpl in FS. inv FS. contradict H3. inv SEQ. rewrite REQ by congruence. rewrite H. inversion 1.\n simpl in STEP. fold ge in STEP.\n assert (t = E0).\n {\n inv SEQ. rewrite <- REQ in H by congruence.\n inv STEP; rewrite_hyps; auto.\n } subst.\n eexists; split. eauto.\n edestruct step_internal; eauto. inv SEQ. simpl. rewrite REQ, H, H0, H1. eauto. congruence. inversion 1.\n simpl in H3. destr_in H3. inv H3.\n unfold Genv.find_funct in Heqo. repeat destr_in Heqo.\n inv SEQ. simpl in *. subst. destruct s'. simpl in *. subst.\n destr_in H2. inv H2.\n destruct f0.\n eapply match_states_call_alloc.\n intros. rewrite (Pregmap.gso _ _ H2). apply set_reg_eq; auto. intros; apply set_reg_eq. auto.\n rewrite REQ by congruence; auto.\n simpl_regs. rewrite REQ by congruence.\n symmetry; apply offset_ptr_cancel.\n unfold Mem.storev, Mem.loadv in Heqo. destruct (rs RSP); simpl in *; try congruence; eauto.\n rewrite <- Heqo.\n f_equal. simpl_regs.\n rewrite REQ by congruence; auto.\n simpl. rewrite H5.\n erewrite wf_asm_alloc_at_beginning; eauto. constructor.\n eapply match_states_call_external.\n intros. rewrite (Pregmap.gso _ _ H2). apply set_reg_eq; auto. intros; apply set_reg_eq. auto.\n rewrite REQ by congruence; auto.\n simpl_regs. rewrite REQ by congruence.\n symmetry; apply offset_ptr_cancel.\n unfold Mem.storev, Mem.loadv in Heqo. destruct (rs RSP); simpl in *; try congruence; eauto.\n rewrite <- Heqo.\n rewrite REQ by congruence; auto.\n simpl. rewrite H5. eauto.\n + (*Pcall_r*)\n simpl in H2.\n destruct (SAFE _ (star_refl _ _ _)) as [(rr & FS)|(t & s' & STEP)].\n simpl in FS. inv FS. contradict H3. inv SEQ. rewrite REQ by congruence. rewrite H. inversion 1.\n simpl in STEP. fold ge in STEP.\n assert (t = E0).\n {\n inv SEQ. rewrite <- REQ in H by congruence.\n inv STEP; rewrite_hyps; auto.\n } subst.\n eexists; split. eauto.\n edestruct step_internal; eauto. inv SEQ. simpl. rewrite REQ, H, H0, H1. eauto. congruence. inversion 1.\n simpl in H3. destr_in H3. inv H3.\n unfold Genv.find_funct in Heqo. repeat destr_in Heqo.\n inv SEQ. simpl in *. subst. destruct s'. simpl in *. subst.\n destr_in H2. inv H2.\n destruct f0.\n eapply match_states_call_alloc.\n intros. rewrite (Pregmap.gso _ _ H2). apply set_reg_eq; auto. intros; apply set_reg_eq. auto.\n rewrite REQ by congruence; auto. rewrite <- REQ. auto. congruence.\n simpl_regs. rewrite REQ by congruence.\n symmetry; apply offset_ptr_cancel.\n unfold Mem.storev, Mem.loadv in Heqo. destruct (rs RSP); simpl in *; try congruence; eauto.\n rewrite <- Heqo.\n f_equal. simpl_regs.\n rewrite REQ by congruence; auto.\n simpl. rewrite H5.\n erewrite wf_asm_alloc_at_beginning; eauto. constructor.\n eapply match_states_call_external.\n intros. rewrite (Pregmap.gso _ _ H2). apply set_reg_eq; auto. intros; apply set_reg_eq. auto.\n rewrite REQ by congruence; auto. rewrite <- REQ. auto. congruence.\n simpl_regs. rewrite REQ by congruence.\n symmetry; apply offset_ptr_cancel.\n unfold Mem.storev, Mem.loadv in Heqo. destruct (rs RSP); simpl in *; try congruence; eauto.\n rewrite <- Heqo.\n rewrite REQ by congruence; auto.\n simpl. rewrite H5. eauto.\n }\n destruct (is_free_dec i).\n {\n inv i0.\n (*Pfreeframe*)\n simpl in H2.\n destruct (SAFE _ (star_refl _ _ _)) as [(rr & FS)|(t & s' & STEP)].\n simpl in FS. inv FS. contradict H3. inv SEQ. rewrite REQ by congruence. rewrite H. inversion 1.\n simpl in STEP. fold ge in STEP.\n assert (t = E0).\n {\n inv SEQ. rewrite <- REQ in H by congruence.\n inv STEP; rewrite_hyps; auto.\n } subst.\n eexists; split. eauto.\n edestruct step_internal; eauto. inv SEQ. simpl. rewrite REQ, H, H0, H1 by congruence. eauto. inversion 1.\n simpl in H3. destr_in H3. inv H3.\n inv SEQ. simpl in *. subst. destruct s'. simpl in *. subst.\n inv H2.\n edestruct wf_asm_after_freeframe as (i' & FI & RJ); eauto. constructor.\n destruct RJ as [RET|JMP].\n - (*Pfree -> Pret*)\n eapply match_states_free_ret.\n intros.\n apply nextinstr_eq.\n rewrite (Pregmap.gso _ _ H3). simpl_regs. auto.\n rewrite REQ by congruence; auto.\n simpl_regs.\n rewrite Val.offset_ptr_assoc. f_equal.\n generalize (Ptrofs.repr (align sz 8)).\n generalize (Ptrofs.repr (size_chunk Mptr)).\n intros. rewrite <- Ptrofs.sub_add_l.\n rewrite Ptrofs.sub_add_opp.\n rewrite Ptrofs.add_assoc. rewrite Ptrofs.add_neg_zero. rewrite Ptrofs.add_zero; auto.\n simpl_regs.\n rewrite <- Heqo. f_equal.\n rewrite <- REQ by congruence; auto.\n eapply wf_asm_free_spec in H1; eauto. f_equal. destruct H1 as (SZ & ORA); subst. auto.\n simpl. simpl_regs. rewrite REQ, H by congruence. simpl. rewrite H0. rewrite FI. subst; eauto.\n - (*Pfree -> jmp *)\n eapply match_states_free_jmp.\n intros.\n apply nextinstr_eq.\n rewrite (Pregmap.gso _ _ H3). simpl_regs. auto.\n rewrite REQ by congruence; auto.\n simpl_regs.\n rewrite Val.offset_ptr_assoc. f_equal.\n generalize (Ptrofs.repr (align sz 8)).\n generalize (Ptrofs.repr (size_chunk Mptr)).\n intros. rewrite <- Ptrofs.sub_add_l.\n rewrite Ptrofs.sub_add_opp.\n rewrite Ptrofs.add_assoc. rewrite Ptrofs.add_neg_zero. rewrite Ptrofs.add_zero; auto.\n simpl_regs.\n rewrite <- Heqo. f_equal.\n rewrite <- REQ by congruence; auto.\n eapply wf_asm_free_spec in H1; eauto. f_equal. destruct H1 as (SZ & ORA); subst. auto.\n simpl_regs.\n unfold loadvv in Heqo. destr_in Heqo. destr_in Heqo.\n simpl. simpl_regs. rewrite REQ, H by congruence. simpl. rewrite H0. rewrite FI. subst; eauto.\n auto.\n }\n destruct s1. simpl in *. fold ge.\n edestruct exec_instr_normal as ((rs1' & m1' & EI & SEQ') & NEXT); eauto.\n eexists; split.\n inv SEQ.\n eapply SSAsm.exec_step_internal; eauto.\n rewrite REQ by congruence; eauto.\n apply match_states_normal. auto. auto.\n + inv SEQ. eexists; split. eapply SSAsm.exec_step_builtin; eauto.\n rewrite REQ by congruence; eauto.\n eapply eval_builtin_args_eq_rs. 3: rewrite REQ by congruence; apply H2. intros; symmetry; apply REQ; auto.\n eapply wf_asm_builtin_not_PC; eauto.\n apply match_states_normal.\n constructor. intros. apply nextinstr_nf_eq.\n apply set_res_eq. apply undef_regs_eq. intros; auto.\n simpl. simpl_regs. rewrite set_res_other.\n rewrite Asmgenproof0.undef_regs_other_2. rewrite H; simpl. rewrite H0.\n 2: apply pc_not_destroyed_builtin.\n 2: eapply wf_asm_builtin_not_PC; eauto.\n destr. destr_in Heqo. inv Heqo.\n intro II; inv II.\n {\n inv H4. exploit wf_asm_alloc_only_at_beginning. eauto. apply Heqo0.\n unfold Ptrofs.one. replace 1 with (instr_size (Pbuiltin ef args res)) by reflexivity.\n erewrite wf_asm_pc_repr; eauto.\n apply not_eq_sym. apply Z.lt_neq.\n generalize (Ptrofs.unsigned_range ofs) (instr_size_positive (Pbuiltin ef args res)). lia.\n }\n {\n exploit wf_asm_ret_jmp_comes_after_freeframe; eauto.\n intros (o' & ifree & FI & IFREE & RNG).\n unfold Ptrofs.one in *.\n replace 1 with (instr_size (Pbuiltin ef args res)) in RNG by reflexivity.\n erewrite wf_asm_pc_repr in RNG; eauto.\n generalize (find_instr_same _ _ _ _ _ FI H1). intro. exploit H5.\n lia. intro. inv IFREE. congruence.\n }\n + easy.\n - destruct s1. simpl in *. rewrite PCeq in PCnone.\n inv STEP; simpl in *; repeat destr_in PCnone.\n Qed.\n\n Hypothesis prog_no_rsp: asm_prog_no_rsp ge.\n\n Theorem real_asm_correct:\n backward_simulation (SSAsm.semantics prog) (RealAsm.semantics prog).\n Proof.\n eapply backward_simulation_plus\n with (match_states := fun s1 s2 => match_states s1 s2 /\\ real_asm_inv s2).\n - reflexivity.\n - simpl; intros s1 IS1. inv IS1.\n apply Genv.init_mem_stack in H as STK. apply Mem.alloc_result in H0 as STK'.\n apply Genv.init_mem_sid in H as SID.\n unfold Mem.nextblock in STK'. unfold fresh_block in STK'. rewrite STK in STK'.\n simpl in STK'. subst.\n edestruct (Mem.valid_access_store m1 Mptr stkblock (max_stacksize + align (size_chunk Mptr) 8 - size_chunk Mptr) Vnullptr).\n split.\n red; intros. exploit Mem.perm_alloc_2; eauto. instantiate (1:= ofs).\n split.\n cut (size_chunk Mptr <= max_stacksize).\n intro.\n assert (0 <= align (size_chunk Mptr) 8). unfold Mptr. destr.\n lia. unfold Mptr. destr; vm_compute; congruence.\n lia. intro. rewrite SID in H3. eapply Mem.perm_implies; eauto. apply perm_F_any.\n apply Z.divide_sub_r.\n apply Z.divide_add_r.\n apply align_Mptr_stack_limit.\n apply align_Mptr_align8.\n apply align_size_chunk_divides.\n eexists; econstructor. eauto. eauto.\n simpl. rewrite SID in *.\n rewrite Ptrofs.unsigned_repr. eauto.\n generalize max_stacksize_range. generalize max_stacksize'_range. generalize (size_chunk_pos Mptr).\n generalize (align_le (size_chunk Mptr) 8).\n lia. eauto.\n - simpl; intros s1 s2 IS1 IS2.\n edestruct initial_states_match as (s1' & IS1' & MS); eauto.\n eexists; split; eauto. split; auto. eapply real_initial_inv; eauto.\n - simpl; intros s1 s2 r (MS & INV) FS; inv FS.\n assert (pc_at s1 = None).\n {\n generalize (match_states_PC _ _ MS). intros PCeq.\n unfold pc_at. destr. simpl in *. rewrite PCeq.\n rewrite H. unfold Vnullptr. destruct ptr64; simpl; auto.\n }\n inv MS; try congruence.\n inv SEQ. simpl in *.\n constructor. rewrite REQ by congruence. auto. rewrite REQ; auto. congruence.\n destruct s1; simpl in *. constructor. congruence. congruence.\n - simpl. intros s1 s2 (MS & INV) SAFE; eapply real_asm_progress; eauto.\n - simpl. intros s2 t s2' STEP s1 (MS & INV) SAFE.\n edestruct real_asm_step as (s1' & STEP' & MS'); eauto.\n exists s1'; split; eauto. apply plus_one; auto. split; auto.\n eapply real_asm_inv_inv; eauto.\nQed.\n\n End PRESERVATION.\n(*\nDefinition transf_program (p: Asm.program) : Asm.program := p.\n\nDefinition match_prog (p :Asm.program) (tp:Asm.program):=\n p = tp.\n\nLemma transf_program_match:\n forall p, match_prog p (transf_program p).\nProof.\n intros. reflexivity.\nQed.\n\n Lemma match_prog_inv: forall t tp,\n match_prog t tp -> t = tp.\n Proof.\n intros t tp MT. red in MT. auto.\n Qed.\n\n Definition match_prog (p: Asm.program) (tp: Asm.program) :=\n match_program (fun _ f tf => transf_fundef f = OK tf) eq p tp.\n*)\n Definition match_prog (p: Asm.program) (tp: Asm.program) :=\n match_program (fun _ f tf => transf_fundef f = OK tf) eq p tp.\n\n Lemma transf_program_match:\n forall p tp, transf_program p = OK tp -> match_prog p tp.\n Proof.\n intros. eapply match_transform_partial_program; eauto.\n Qed.\n\n Lemma match_prog_inv: forall t tp,\n match_prog t tp -> t = tp.\n Proof.\n intros t tp MT. red in MT. red in MT. red in MT.\n destruct MT as (MT & EQ1 & EQ2).\n set (P :=\n (match_ident_globdef (fun (_ : program Asm.fundef unit) (f tf : Asm.fundef) => transf_fundef f = OK tf)\n (@eq unit) t)) in *.\n destruct t, tp. simpl in *. subst.\n apply list_forall2_ind with (P:=P) (l:= prog_defs) (l0:= prog_defs0).\n - auto.\n - intros a1 al b1 bl Pab LP EQ1. inv EQ1.\n f_equal.\n f_equal. red in Pab. red in Pab. destruct Pab as [Pab1 Pab2].\n destruct a1, b1. simpl in *. subst. f_equal.\n destruct g. inv Pab2.\n destruct f. inv H0.\n monadInv H1. unfold transf_function in EQ.\n destr_in EQ; inv EQ.\n simpl in *. inv H1. auto. inv Pab2. inv H0. auto.\n - auto.\nQed.\n\n Section PRESERVATION2.\n\n Variable prog: Asm.program.\n Variable tprog: Asm.program.\n Hypothesis TRANSF: match_prog prog tprog.\n Let ge := Genv.globalenv prog.\n\n(* Hypothesis WF: wf_asm_prog ge. *)\n Hypothesis prog_no_rsp: asm_prog_no_rsp ge.\n\n Theorem real_asm_correct':\n backward_simulation (SSAsm.semantics prog) (RealAsm.semantics tprog).\n Proof.\n red in TRANSF.\n unfold transf_program in TRANSF.\n exploit match_prog_inv; eauto. intro EQ. subst tprog.\n apply real_asm_correct; auto.\n intros. red. intros. exploit (Genv.find_funct_ptr_transf_partial TRANSF); eauto.\n intros (tf & FFP & TF).\n simpl in TF; monadInv TF. unfold transf_function in EQ. destr_in EQ.\n eapply wf_asm_function_check_correct; eauto.\n Qed.\n\n\n End PRESERVATION2.\n\n", "meta": {"author": "SJTU-PLV", "repo": "nominal-compcert-popl22-artifact", "sha": "b2d2ee12497ac86c59034d042ef142cc3a123752", "save_path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact", "path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact/nominal-compcert-popl22-artifact-b2d2ee12497ac86c59034d042ef142cc3a123752/Multi-Stack-CompCert/x86/RealAsmproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.12113752677422057}} {"text": "(**************************************************************************)\n(* This file is part of CertrBPF, *)\n(* a formally verified rBPF verifier + interpreter + JIT in Coq. *)\n(* *)\n(* Copyright (C) 2022 Inria *)\n(* *)\n(* This program is free software; you can redistribute it and/or modify *)\n(* it under the terms of the GNU General Public License as published by *)\n(* the Free Software Foundation; either version 2 of the License, or *)\n(* (at your option) any later version. *)\n(* *)\n(* This program is distributed in the hope that it will be useful, *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)\n(* GNU General Public License for more details. *)\n(* *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import Flag MemRegion State Monad rBPFMonadOp.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\n\nFrom Coq Require Import List ZArith.\nFrom compcert Require Import Integers Values Clight Memory AST.\nFrom compcert Require Import Coqlib.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import clight_exec Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import correct_eval_mrs_regions correct_get_mem_region correct_upd_reg correct_bpf_interpreter_aux correct_eval_flag correct_eval_reg.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nCheck bpf_interpreter.\nbpf_interpreter\n : nat -> M val\n*)\n\nSection Bpf_interpreter.\n Context {S: special_blocks}.\n\n (** The program contains our function of interest [fn] *)\n Definition p : Clight.program := prog.\n\n (* [Args,Res] provides the mapping between the Coq and the C types *)\n (* Definition Args : list CompilableType := [stateCompilableType].*)\n Definition args : list Type := [(nat:Type)].\n Definition res : Type := (val:Type).\n\n (* [f] is a Coq Monadic function with the right type *)\n Definition f : arrow_type args (M State.state res) := bpf_interpreter.\n\n (* [fn] is the Cligth function which has the same behaviour as [f] *)\n Definition fn: Clight.function := f_bpf_interpreter.\n\n (* [match_arg] relates the Coq arguments and the C arguments *)\n Definition match_arg_list :DList.t (fun x => x -> Inv _) ((unit:Type) ::args) :=\n (dcons (fun _ => StateLess _ is_state_handle)\n (dcons (stateless nat_correct)\n (DList.DNil _))).\n\n (* [match_res] relates the Coq result and the C result *)\n Definition match_res : res -> Inv State.state := fun x => StateLess _ (val64_correct x).\n\n Instance correct_function_bpf_interpreter : forall a, correct_function _ p args res f fn ModSomething false match_state match_arg_list match_res a.\n Proof.\n correct_function_from_body args.\n correct_body.\n (** how to use correct_* *)\n unfold INV.\n unfold f, app.\n unfold bpf_interpreter.\n correct_forward.\n\n get_invariant _st.\n get_invariant _fuel.\n exists (v::v0::nil).\n split.\n unfold map_opt, exec_expr. rewrite p0,p1; reflexivity.\n intros; simpl.\n intuition eauto.\n intros.\n\n correct_forward.\n\n get_invariant _st.\n exists (v::nil).\n split.\n unfold map_opt, exec_expr. rewrite p0; reflexivity.\n intros; simpl.\n intuition eauto.\n intros.\n\n correct_forward.\n {\n correct_forward.\n\n get_invariant _st.\n exists (v:: (Vint (Int.repr 0))::nil).\n split.\n unfold map_opt, exec_expr. rewrite p0; reflexivity.\n intros; simpl.\n unfold stateless, reg_correct.\n intuition eauto.\n intros.\n\n correct_forward.\n\n get_invariant _res.\n unfold eval_inv, correct_eval_reg.match_res, val64_correct in c0.\n destruct c0 as (c0 & vl & Hvl_eq); subst.\n exists (Vlong vl).\n split.\n unfold exec_expr. rewrite p0. reflexivity.\n\n split.\n unfold eval_inv, match_res, val64_correct.\n intuition eauto.\n split.\n reflexivity.\n intros.\n constructor.\n }\n\n correct_forward; eauto.\n eexists.\n split.\n unfold exec_expr; simpl.\n reflexivity.\n split.\n unfold match_res, val64_correct, Int64.zero; simpl.\n intuition eauto.\n split.\n reflexivity.\n intros.\n constructor.\n\n get_invariant _f.\n unfold exec_expr.\n rewrite p0.\n unfold eval_inv, correct_eval_flag.match_res, flag_correct in c0.\n rewrite c0.\n unfold Cop.sem_binary_operation, Val.of_bool, int_of_flag, Z_of_flag; simpl.\n destruct x0; reflexivity.\nQed.\n\nEnd Bpf_interpreter.\n\nExisting Instance correct_function_bpf_interpreter.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_bpf_interpreter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.23651624182730094, "lm_q1q2_score": 0.12102928822525573}} {"text": "Require Import FunInd.\nRequire Import CoqlibC Maps Integers Floats Lattice Kildall.\nRequire Import Compopts AST Linking.\nRequire Import ValuesC MemoryC Globalenvs Events.\nRequire Import Registers Op RTLC.\nRequire Import ValueDomainC ValueAOp Liveness.\nRequire Import sflib.\n(** copied && added C **)\nRequire Import Skeleton.\nRequire Export ValueAnalysis.\nRequire Import Preservation.\nRequire Import UnreachC.\nRequire Import Sound.\nRequire Import ModSem.\n\n\n\nSection PRSV.\n\n Variable skenv_link: SkEnv.t.\n Variable p: program.\n\n Hypothesis INCL: SkEnv.includes skenv_link (Sk.of_program fn_sig p).\n\n Let modsem := RTLC.modsem skenv_link p.\n\n Local Existing Instance Unreach.\n\n Theorem sound_state_preservation:\n local_preservation_strong modsem get_mem le' (sound_state p modsem.(globalenv)).\n Proof.\n econs; eauto.\n { ss. eapply UnreachC.liftspec; et. }\n - i. inv INIT. ss. esplits; eauto; cycle 1.\n { destruct args; ss. refl. }\n econs; eauto. i.\n set (ge := (SkEnv.revive (SkEnv.project skenv_link (Sk.of_program fn_sig p)) p)) in *.\n set (f := fun b =>\n if plt b (Genv.genv_next ge) then\n match Genv.invert_symbol ge b with None => BCglob None | Some id => BCglob (Some id) end\n else\n if (plt b (Args.m args).(Mem.nextblock)) && (negb (su_init b))\n then BCother else BCinvalid).\n assert(IMG: exists bc, bc.(bc_img) = f).\n { unshelve eexists (BC _ _ _); s; eauto.\n - ii. subst f. ss. des_ifs.\n - ii. subst f. ss. des_ifs. apply_all_once Genv.invert_find_symbol. clarify.\n }\n subst f. des.\n assert(T: <> /\\ <> /\\ <> /\\ <>).\n { r in SUARG. des_ifs. }\n clear SUARG. des. ss. unfold Sound.vals in *. rewrite Forall_forall in *.\n assert(FP: forall blk, su_init blk -> Ple ge.(Genv.genv_next) blk).\n { inv SKENV. ss. i. inv MEM. rewrite <- PUB. apply NNPP. ii. inv WF. exploit WFHI; eauto. }\n assert(NB: Ple ge.(Genv.genv_next) (Args.m args).(Mem.nextblock)).\n { inv SKENV. ss. destruct args; ss. }\n assert(GE: genv_match bc ge).\n { r. esplits; eauto.\n * ii. rewrite IMG in *. split; i.\n { exploit Genv.genv_symb_range; eauto. i.\n apply_all_once Genv.find_invert_symbol.\n unfold fundef in *. des_ifs.\n }\n des_ifs. apply Genv.invert_find_symbol; eauto.\n * rewrite IMG. ii.\n assert(Plt b (Mem.nextblock (Args.m args))).\n { eapply Plt_Ple_trans; eauto. }\n des_ifs; eauto.\n * rewrite IMG. ii. des_ifs.\n }\n eapply sound_call_state with (bc:= bc); eauto.\n + econs; eauto; cycle 1.\n { inv MEM; ss. rewrite NB0. xomega. }\n + ii. repeat spc VALS. destruct v; econs; eauto. econs; eauto. rewrite IMG. inv TYP. ss.\n apply in_zip_iff in H0. des. unfold typify in *. des_ifs.\n hexploit1 VALS.\n { eapply nth_error_In; eauto. }\n repeat spc VALS. specialize (VALS eq_refl). (* TODO: fix spc ... *) des.\n des_ifs; ss. bsimpl. des; ss. des_sumbool. inv MEM. congruence.\n + inv SKENV. ss. clear - IMG ROMATCH H INCL CSTYLE.\n ii. exploit (ROMATCH b id ab); eauto.\n { rewrite IMG in *. des_ifs. ss. des_ifs.\n - clear - Heq Heq0. eapply Genv.invert_find_symbol in Heq. subst ge. unfold SkEnv.revive in *.\n rewrite Genv_map_defs_symb in Heq. eapply Genv.find_invert_symbol in Heq. clarify.\n - clear - Heq Heq0. eapply Genv.invert_find_symbol in Heq. subst ge. unfold SkEnv.revive in *.\n rewrite Genv_map_defs_symb in Heq. eapply Genv.find_invert_symbol in Heq. clarify.\n }\n { hexploit (romem_for_consistent_2 _ _ H); eauto. intro LO.\n exploit LO; eauto. intro LOA; des. clarify.\n rewrite IMG in *. des_ifs. apply Genv.invert_find_symbol in Heq.\n eapply romem_for_ske_complete; et.\n clear - LOA LOA0 LOA1 LOA2 Heq INCL.\n exploit SkEnv.project_impl_spec; et. intro PROJ.\n exploit SkEnv.project_revive_precise; et. intro PRECISE. inv PRECISE.\n exploit P2GE; et. i; des. ss. unfold fundef in *. folder. clarify.\n assert(INTSID: internals (Sk.of_program fn_sig p) id).\n { rewrite Sk.of_program_internals. unfold internals. des_ifs. }\n assert(DEFSID: defs (Sk.of_program fn_sig p) id).\n { eapply internals_defs; et. }\n assert(BIG: Genv.find_def skenv_link b = Some (Gvar v)).\n { generalize (Sk.of_program_prog_defmap p fn_sig id). intro REL.\n inv REL; try congruence. rewrite LOA in *. clarify.\n assert(y = Gvar v).\n { inv H1. inv H2. ss. destruct i1, i2; ss. }\n clarify. inv INCL. exploit DEFS; et. i; des.\n assert(blk = b).\n { inv PROJ. exploit (SYMBKEEP id); et.\n i; des. rewrite SYMB0 in *. clear - H SYMB. subst ge. unfold SkEnv.revive in *.\n rewrite Genv_map_defs_symb in *. clarify.\n }\n clarify. rewrite DEF0. clear - MATCH LOA2.\n (*** TODO: make lemma!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ***)\n inv MATCH. inv H0. destruct info1, info2; ss.\n inv H1; ss.\n }\n assert(SMALL: Genv.find_def (SkEnv.project skenv_link (Sk.of_program fn_sig p)) b = Some (Gvar v)).\n { inv PROJ.\n exploit DEFKEEP; et.\n { apply Genv.find_invert_symbol; et. rewrite <- SYMBKEEP; et. }\n i; des.\n assert(gd_small = (Gvar v)).\n { (* TODO: make lemma!!!!!!!!!!!!!!!!! *)\n clear - PROG LOA. generalize (Sk.of_program_prog_defmap p fn_sig id). intro REL.\n inv REL; try congruence.\n rewrite LOA in *. rewrite PROG in *. clarify.\n inv H1. inv H0. repeat f_equal. destruct i1, i2; ss.\n }\n clarify.\n }\n unfold Genv.find_var_info. des_ifs.\n }\n rewrite Args.get_m_m in *; ss.\n intro RO; des. esplits; et. eapply bmatch_incr; et.\n ii. ss. rewrite IMG. des_ifs.\n * clear - Heq Heq0. eapply Genv.invert_find_symbol in Heq. subst ge. unfold SkEnv.revive in *.\n rewrite Genv_map_defs_symb in Heq. eapply Genv.find_invert_symbol in Heq. clarify.\n * clear - Heq Heq0. eapply Genv.invert_find_symbol in Heq. subst ge. unfold SkEnv.revive in *.\n rewrite Genv_map_defs_symb in Heq. eapply Genv.find_invert_symbol in Heq. clarify.\n * clear - Heq0 Heq H0.\n apply_all_once Genv.invert_find_symbol.\n assert(Genv.find_symbol ge i = Some b0).\n { subst ge. unfold SkEnv.revive. rewrite Genv_map_defs_symb. ss. }\n apply Genv.find_invert_symbol in H. clarify.\n + assert(BCSU: forall b, bc b <> BCinvalid -> ~ su_init b).\n { intros ? BC. rewrite IMG in BC.\n destruct (plt b (Genv.genv_next skenv_link)).\n - inv SKENV. ss. inv WF. ii. hexploit WFLO; eauto. i. Unreach.nb_tac. xomega.\n - des_ifs. bsimpl. des. ii. congruence.\n }\n assert(SUBC: forall b (VALID: Plt b (Mem.nextblock (Args.m args))), ~ su_init b -> bc b <> BCinvalid).\n { intros ? ? SU. rewrite IMG. des_ifs. bsimpl. des; ss. des_sumbool.\n inv SKENV. ss.\n }\n assert(SUMEM: forall b : block, bc b <> BCinvalid -> smatch bc (Args.m args) b Ptop).\n { i. rr. rename H0 into SU.\n hexploit BCSU; eauto. intro SU0. split; i.\n - hexploit mem'_load_val'; eauto. intro SUV.\n { destruct v; econs; et. econs; et. exploit SUV; et. i; des. ii.\n exploit BCSU; et.\n exploit SUBC; try apply H1; et.\n { inv MEM. Unreach.nb_tac. ss. }\n ss.\n }\n - hexploit mem'_loadbytes_val'; eauto. intro SUV.\n { econs; et. exploit SUV; et. i; des. ii.\n exploit BCSU; et.\n exploit SUBC; try apply H1; et.\n { inv MEM. Unreach.nb_tac. ss. }\n ss.\n }\n }\n econs; s; eauto.\n * rewrite IMG. ii. des_ifs; ss.\n * rewrite IMG. ii. des_ifs; ss. rewrite PTree.gempty in *. ss.\n * intros ? A. rewrite IMG in A. inv SKENV. ss. des_ifs; try xomega. bsimpl. des. des_sumbool. xomega.\n + r. rewrite IMG. i. des_ifs.\n + rr. ss. inv MEM. inv SKENV. ss. rewrite NB0. esplits; eauto.\n * i. des_ifs; try xomega. rewrite IMG. rewrite <- PUB. inv WF.\n destruct (su_init blk) eqn:T; des_sumbool.\n { hexploit WFLO; eauto. i. des_ifs; try xomega. bsimpl. ss. }\n des_ifs. bsimpl. exfalso. des_sumbool. xomega.\n * refl.\n - ii; ss. eapply sound_step with (se := skenv_link); eauto.\n eapply SkEnv.senv_genv_compat; eauto.\n - i; ss. inv SUST.\n assert(GR: exists su_gr, SemiLattice.greatest le'\n (* (fun su => su0.(UnreachC.ge_nb) = su.(UnreachC.ge_nb) /\\ args' su args) *)\n (fun su => le' su0 su /\\ args' su args)\n su_gr /\\ le' su0 su_gr).\n { specialize (H p (linkorder_refl _)).\n set (args0 := args).\n inv AT. inv H; ss. des.\n exploit sound_state_sound_args; eauto. i.\n hexploit (@UnreachC.greatest_ex (bc2su bc (Genv.genv_next skenv_link) (Mem.nextblock m0)) args0); eauto.\n { subst args0. r in H. des. esplits; eauto; cycle 1. { r. ss. esplits; eauto. } ss. refl. }\n i; des. ss. esplits; eauto.\n - exploit (@UnreachC.get_greatest_le); ss; eauto.\n { subst args0; ss. }\n + eapply UnreachC.hle_lift; eauto.\n - rr in GR. des. etrans; eauto. eapply UnreachC.hle_lift; eauto.\n }\n des. esplits; eauto.\n { inv AT; ss. refl. }\n { exploit H; eauto. { apply linkorder_refl. } intro T; des. inv T; ss. }\n { r in GR. inv AT. ss. des. r in PROP0. des. esplits; et. }\n { refl. }\n ii. r in RETV. des. esplits; eauto; cycle 1.\n { inv AT; inv AFTER; ss. rewrite Retv.get_m_m; ss. refl. }\n + econs; eauto. intros cunit LO. specialize (H cunit LO). inv AFTER; ss. inv H; ss.\n assert(BCARGS: (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock)).(Sound.args) args).\n { ss. inv AT; ss. s. des. rpapply sound_state_sound_args; eauto. }\n assert(BCLE0: le' su0 (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock))).\n { eapply UnreachC.hle_lift; eauto. }\n assert(BCLE1: le' (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock)) su_gr).\n { eapply GR; eauto. esplits; eauto. inv AT. ss. }\n set (f := fun b => if plt b (Mem.nextblock m_arg)\n then bc b\n else\n if plt b (Mem.nextblock (Retv.m retv))\n then\n if su_ret b\n then BCinvalid\n else BCother\n else BCinvalid).\n assert(exists bc', <>).\n { unshelve eexists (BC _ _ _); ss.\n - ii. subst f. ss. des_ifs. eapply bc_stack; eauto.\n - ii. subst f. ss. des_ifs. eapply bc_glob; eauto.\n } des.\n\n assert(HLEAFTER: Unreach.hle (bc2su bc (Genv.genv_next skenv_link) (Mem.nextblock m_arg))\n (bc2su bc' (Genv.genv_next skenv_link) (Mem.nextblock (Retv.m retv)))).\n { rr. ss. rewrite IMG. unfold f.\n assert(NB: Ple (Mem.nextblock m_arg) (Mem.nextblock (Retv.m retv))).\n { inv AT; ss. rewrite Retv.get_m_m in *; ss. inv MLE. inv RO0. ss. }\n esplits; ss.\n - i. des_ifs. xomega.\n }\n\n assert(GRARGS: Sound.args su_gr args).\n { rr in GR. des. inv AT; ss. }\n exploit Unreach.hle_hle_old; try apply LE; eauto.\n { rr in GRARGS. des. inv AT; ss. des; ss. }\n intro LEOLD.\n assert (VMTOP0: forall v, Sound.val su_gr v -> vmatch bc' v Vtop).\n { i. ss. r in H. destruct v; econs; eauto. econs; eauto.\n exploit H; eauto. i; des. rewrite IMG. subst f. s. des_ifs_safe.\n assert(NBC: ~ (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock)) b).\n { ii. ss. r in BCLE1. des. exploit PRIV; eauto. des_ifs. }\n ss. des. inv MEM. rr in GRARGS. inv AT; ss. des. inv MEM. ss.\n rewrite NB0 in *. des_ifs; try xomega.\n intro BC. unfold bc2su in *. ss. rewrite BC in *. ss.\n }\n assert (VMTOP: forall v, val' su_ret v -> vmatch bc' v Vtop).\n { i. r in H. destruct v; econs; eauto. econs; eauto.\n exploit H; eauto. i; des. rewrite IMG. subst f. s. des_ifs_safe.\n assert(NSU: ~su_gr b).\n { ii. r in LEOLD. des. exploit PRIV; eauto. i; ss. congruence. }\n assert(NBC: ~ (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock)) b).\n { ii. ss. r in BCLE1. des. exploit PRIV; eauto. des_ifs. }\n ss. des. inv MEM. rewrite NB in *. des_ifs.\n clear - NBC p0.\n ii. unfold bc2su in *. ss. rewrite H in *. ss.\n }\n assert (VMTOP1: forall v (BELOW: bc_below bc (Mem.nextblock m_arg)),\n vmatch bc v Vtop -> vmatch bc' v Vtop).\n { i. inv H; econs; eauto. inv H2; econs; eauto.\n exploit BELOW; eauto. i.\n rewrite IMG. unfold f.\n des_ifs.\n }\n assert (PMTOP: forall blk ofs, ~ su_ret blk -> Plt blk (Mem.nextblock (Retv.m retv)) -> pmatch bc' blk ofs Ptop).\n { i. r in H. econs; eauto.\n assert(NSU: ~su_gr blk).\n { ii. r in LEOLD. des. exploit PRIV; eauto. }\n assert(NBC: ~ (bc2su bc (Genv.genv_next skenv_link) m_arg.(Mem.nextblock)) blk).\n { ii. ss. r in BCLE1. des. exploit PRIV; eauto. des_ifs. }\n ss. rewrite IMG. unfold f. des_ifs.\n ii. rewrite H1 in *. ss.\n }\n assert (PMTOP1: forall blk ofs\n (BELOW: bc_below bc (Mem.nextblock m_arg)),\n pmatch bc blk ofs Ptop -> pmatch bc' blk ofs Ptop).\n { i. inv H; econs; eauto.\n exploit BELOW; eauto. i.\n ss. rewrite IMG. unfold f. des_ifs.\n }\n assert (SMTOP: forall b, bc' b <> BCinvalid -> smatch bc' (Retv.m retv) b Ptop).\n { intros; split; intros.\n - destruct (su_gr b) eqn:T.\n + assert(Plt b (Mem.nextblock m_arg)).\n { rr in GRARGS. inv AT; ss. des. inv MEM.\n inv WF0. exploit WFHI; try apply T. eauto. i. Unreach.nb_tac. ss.\n }\n rewrite IMG in *. subst f. ss. des_ifs.\n\n inv MM. exploit mmatch_top; eauto. intro SM. rr in SM. des.\n assert(LD: Mem.load chunk m_arg b ofs = Some v).\n { inv MLE. inv AT. ss. erewrite <- Mem.load_unchanged_on_1; try apply PRIV; eauto. }\n exploit SM; eauto.\n + assert(~ su_ret b).\n { rewrite IMG in *. subst f. ss. des_ifs.\n rr in LE. des. ss. erewrite <- OLD; eauto.\n { congruence. }\n rr in GRARGS. inv AT; ss. des. inv MEM0. Unreach.nb_tac. ss.\n }\n eapply VMTOP; eauto. eapply mem'_load_val'; eauto. inv AT; ss. des_ifs; des; ss.\n - destruct (su_gr b) eqn:T.\n + assert(Plt b (Mem.nextblock m_arg)).\n { rr in GRARGS. inv AT; ss. des. inv MEM.\n inv WF0. exploit WFHI; eauto. i.\n Unreach.nb_tac. ss.\n }\n rewrite IMG in *. subst f. ss. des_ifs.\n\n inv MM. exploit mmatch_top; eauto. intro SM. rr in SM. des.\n assert(LD: Mem.loadbytes m_arg b ofs 1 = Some [Fragment (Vptr b' ofs') q i]).\n { inv MLE. inv AT. ss. erewrite <- Mem.loadbytes_unchanged_on_1; try apply PRIV; eauto. }\n exploit SM0; eauto.\n + try (by econs; eauto).\n assert(~ su_ret b).\n { rewrite IMG in *. subst f. ss. des_ifs.\n rr in LE. des. ss. erewrite <- OLD; eauto; try congruence.\n rr in GRARGS. des. inv AT; ss. des. inv MEM0. Unreach.nb_tac. ss.\n }\n eapply PMTOP; eauto; cycle 1.\n { inv AT; ss. des_ifs; des. inv MEM1.\n Local Transparent Mem.loadbytes.\n unfold Mem.loadbytes in *. des_ifs.\n exploit (SOUND b ofs); eauto.\n { eapply r. xomega. }\n i; des. ss. Unreach.nb_tac. xomega.\n }\n eapply mem'_loadbytes_val'; eauto.\n des_ifs; des; ss.\n }\n\n rewrite Retv.get_m_m in *; ss.\n eapply sound_return_state with (bc := bc'); eauto.\n * apply sound_stack_new_bound with (Mem.nextblock m_arg); cycle 1.\n { inv HLEAFTER. des. ss. }\n apply sound_stack_exten with bc; auto; cycle 1.\n { i. rewrite IMG. unfold f. des_ifs. }\n apply sound_stack_inv with m_arg; auto.\n i. inv MLE. inv AT. ss.\n eapply Mem.loadbytes_unchanged_on_1; try apply PRIV; eauto.\n u. i. eapply BCLE1; et. ss. des_ifs. des_sumbool. ss.\n * eapply VMTOP; et. unfold typify. des_ifs. des; ss.\n * eapply romatch_exten; cycle 1.\n { instantiate (1 := bc). rewrite IMG. subst f. split; i; try by des_ifs.\n des_ifs_safe. exfalso. eapply n. eapply mmatch_below. eauto. congruence.\n }\n inv AT. ss. inv MLE. eapply romatch_ext; et; i.\n { assert(RANGE_PERM: Mem.range_perm (Retv.m retv) b ofs (ofs + n) Cur Readable).\n { eapply Mem.loadbytes_range_perm; et. }\n erewrite <- Mem.loadbytes_unchanged_on_1; try eapply RO0; et.\n - eapply mmatch_below; et. congruence.\n - i. inv SKENV. ss. rr in ROMATCH. des.\n exploit (romem_for_consistent cunit); eauto. intro X; des.\n\n inv GE. hexploit (H3 id b); eauto. intro Y. des.\n hexploit1 Y0; eauto.\n\n eapply (ROMATCH b id); eauto.\n + unfold ske2bc. s. rename b into blk. exploit Genv.genv_symb_range; et. intro BNB. des_ifs_safe.\n dup Y0. unfold SkEnv.revive in Y1. ss. rewrite Genv_map_defs_symb in Y1.\n exploit Genv.find_invert_symbol; et. intro INV. rewrite INV. ss.\n + eapply romem_for_ske_complete; et. clear - LO X INCL Y0 X2. inv INCL.\n exploit (prog_defmap_linkorder cunit); et. intro Z; des.\n hexploit (Sk.of_program_prog_defmap p fn_sig id); et. intro REL.\n unfold fundef in *. rewrite Z in REL. inv REL. symmetry in H0.\n exploit DEFS; et. intro W; des.\n assert(b = blk).\n { clear - Y0 SYMB. unfold SkEnv.revive, SkEnv.project in *. uge. ss.\n rewrite MapsC.PTree_filter_key_spec in *. des_ifs.\n (* TODO: make lemma *)\n } clarify.\n unfold SkEnv.project. ss. unfold Genv.find_var_info.\n erewrite Genv_map_defs_def_inv; et; cycle 1.\n exploit Genv.find_invert_symbol; et. intro INV.\n rewrite INV. unfold o_bind. s. rewrite H0. s. unfold internals. rewrite H0. s.\n inv Z0. inv H1. ss. inv H2. inv H3. inv MATCH. inv H3. inv H9. destruct info1, i3; ss. repeat f_equal; ss.\n\n (* TODO: make lemma *)\n clear - X2 H1. unfold ValueAnalysis.definitive_initializer in *. des_ifs; inv H1; ss.\n }\n { apply PERM; et. eapply mmatch_below; et. congruence. }\n * { constructor; simpl; intros.\n + apply ablock_init_sound. apply SMTOP. simpl; congruence.\n + rewrite PTree.gempty in H0; discriminate.\n + apply SMTOP; auto.\n + apply SMTOP; auto.\n + red; simpl; intros. destruct (plt b (Mem.nextblock m_arg)).\n * eapply Pos.lt_le_trans. eauto. { inv AT. apply MLE. }\n * rewrite IMG in *. subst f. ss. des_ifs.\n }\n * eapply genv_match_exten; eauto.\n { rewrite IMG. subst f. split; i; try by des_ifs.\n des_ifs_safe. exfalso. eapply n. eapply mmatch_below. eauto. congruence.\n }\n { i. rewrite IMG. unfold f. des_ifs_safe.\n exfalso. eapply n. eapply mmatch_below. eauto. congruence.\n }\n * red; simpl; intros. rewrite IMG. unfold f. des_ifs.\n eapply NOSTK; auto.\n * ss. etrans; eauto.\n - ii. inv FINAL. s.\n inv SUST. specialize (H p (linkorder_refl _)). inv H.\n exists (bc2su bc (Genv.genv_next skenv_link) m_ret.(Mem.nextblock)).\n exploit sound_state_sound_retv; try apply STK; eauto; ss; eauto. i; des.\n esplits; try refl; ss; eauto.\n Qed.\n\nEnd PRSV.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/backend/ValueAnalysisC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2365162418273009, "lm_q1q2_score": 0.12102928822525572}} {"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import ZSet.\nRequire Import ListLemma2.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import AuxStateDataType.\nRequire Import RealParams.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import LayerCalculusLemma.\nRequire Import TacticsForTesting.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import AbstractMachine.Spec.\nRequire Import PTWalk.Spec.\nRequire Import NPTWalk.Layer.\nRequire Import HypsecCommLib.\nRequire Import Constants.\nRequire Import NPTWalk.Spec.\nRequire Import PTWalk.Layer.\nRequire Import RData.\n\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nLtac destruct_case H :=\n match type of H with\n | ?a < ?x <= ?b =>\n let H' := fresh \"C\" in\n let H1 := fresh \"T\" in\n assert(H': a < x <= b - 1 \\/ x = b) by omega; clear H;\n simpl in H'; destruct H' as [H' | H1]; [try omega; destruct_case H'|]\n | ?a <= ?n < ?b =>\n let H' := fresh \"C\" in\n let H1 := fresh \"T\" in\n assert (H': n = a \\/ a + 1 <= n < b) by omega; clear H;\n simpl in H'; destruct H' as [H' | H1]; destruct_case H'\n end.\n\nLocal Hint Unfold\n phys_page\n pmd_page\n stage2_pgd_index\n pgd_index\n pud_index\n pmd_index\n pte_index.\n\n(* page table relation *)\n\nInductive relate_entry (vmid: Z) (hnpt: NPT) (lnpt: NPT): Z -> Z -> Z -> Z -> Prop :=\n| RELATE_ENTRY:\n forall addr pfn level pte\n (Hlevel: level = 0 \\/ level = 2 \\/ level = 3)\n (Hpte0: level = 0 <-> pte = 0)\n (Hpfn0: level = 0 -> pfn = 0)\n (Hpfn2: level = 2 -> pfn = phys_page pte / PAGE_SIZE +\n (addr / PAGE_SIZE - addr / PAGE_SIZE / PTRS_PER_PMD * PTRS_PER_PMD))\n (Hpfn3: level = 3 -> pfn = phys_page pte / PAGE_SIZE)\n (Hlevel0: level = 0 ->\n let vttbr_pa := pool_start vmid in\n let pgd_idx := pgd_index addr in\n let pgd_p := Z.lor vttbr_pa (pgd_idx * 8) in\n let pgd := ZMap.get pgd_p (pt_vttbr_pool lnpt) in\n let pgd_pa := phys_page pgd in\n (pgd = 0 \\/\n (pgd <> 0 /\\\n let pud_idx := pud_index addr in\n let pud_p := Z.lor pgd_pa (pud_idx * 8) in\n let pud := ZMap.get pud_p (pt_pgd_pool lnpt) in\n let pud_pa := phys_page pud in\n pud = 0 \\/\n (pud <> 0 /\\\n let pmd_idx := pmd_index addr in\n let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n let pmd := ZMap.get pmd_p (pt_pud_pool lnpt) in\n let pmd_pa := phys_page pmd in\n pmd = 0 \\/ (pmd <> 0 /\\ pmd_table pmd = PMD_TYPE_TABLE /\\\n let pte_idx := pte_index addr in\n let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n ZMap.get pte_p (pt_pmd_pool lnpt) = pte)))))\n (Hlevel2: level = 2 ->\n let vttbr_pa := pool_start vmid in\n let pgd_idx := pgd_index addr in\n let pgd_p := Z.lor vttbr_pa (pgd_idx * 8) in\n let pgd := ZMap.get pgd_p (pt_vttbr_pool lnpt) in\n let pgd_pa := phys_page pgd in\n pgd <> 0 /\\\n let pud_idx := pud_index addr in\n let pud_p := Z.lor pgd_pa (pud_idx * 8) in\n let pud := ZMap.get pud_p (pt_pgd_pool lnpt) in\n let pud_pa := phys_page pud in\n pud <> 0 /\\\n let pmd_idx := pmd_index addr in\n let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n ZMap.get pmd_p (pt_pud_pool lnpt) = pte /\\\n pmd_table pte <> PMD_TYPE_TABLE)\n (Hlevel3: level = 3 ->\n let vttbr_pa := pool_start vmid in\n let pgd_idx := pgd_index addr in\n let pgd_p := Z.lor vttbr_pa (pgd_idx * 8) in\n let pgd := ZMap.get pgd_p (pt_vttbr_pool lnpt) in\n let pgd_pa := phys_page pgd in\n pgd <> 0 /\\\n let pud_idx := pud_index addr in\n let pud_p := Z.lor pgd_pa (pud_idx * 8) in\n let pud := ZMap.get pud_p (pt_pgd_pool lnpt) in\n let pud_pa := phys_page pud in\n pud <> 0 /\\\n let pmd_idx := pmd_index addr in\n let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n let pmd := ZMap.get pmd_p (pt_pud_pool lnpt) in\n pmd <> 0 /\\\n pmd_table pmd = PMD_TYPE_TABLE /\\\n let pmd_pa := phys_page pmd in\n let pte_idx := pte_index addr in\n let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n ZMap.get pte_p (pt_pmd_pool lnpt) = pte),\n relate_entry vmid hnpt lnpt addr pfn level pte.\n\nInductive valid_lnpt (vmid: Z) (lnpt: NPT) : Prop :=\n| VALID_LNPT\n (Hvmid_valid: valid_vmid vmid)\n (Hvttbr_pool_range: forall p, is_int64 (p @ (pt_vttbr_pool lnpt)) = true)\n (Hpgd_pool_range: forall p, is_int64 (p @ (pt_pgd_pool lnpt)) = true)\n (Hpud_pool_range: forall p, is_int64 (p @ (pt_pud_pool lnpt)) = true)\n (Hpmd_pool_range: forall p, is_int64 (p @ (pt_pmd_pool lnpt)) = true)\n (Hpgd_next_range: pgd_start vmid <= pt_pgd_next lnpt <= pud_start vmid)\n (Hpud_next_range: pud_start vmid <= pt_pud_next lnpt <= pmd_start vmid)\n (Hpmd_next_range: pmd_start vmid <= pt_pmd_next lnpt <= pool_end vmid)\n (Hpgd_next_align: phys_page (pt_pgd_next lnpt) = (pt_pgd_next lnpt))\n (Hpud_next_align: phys_page (pt_pud_next lnpt) = (pt_pud_next lnpt))\n (Hpmd_next_align: phys_page (pt_pmd_next lnpt) = (pt_pmd_next lnpt))\n (Hpgd_next: forall addr, addr >= pt_pgd_next lnpt -> addr @ (pt_pgd_pool lnpt) = 0)\n (Hpud_next: forall addr, addr >= pt_pud_next lnpt -> addr @ (pt_pud_pool lnpt) = 0)\n (Hpmd_next: forall addr, addr >= pt_pmd_next lnpt -> addr @ (pt_pmd_pool lnpt) = 0)\n (Hvttbr_pool: forall addr, addr @ (pt_vttbr_pool lnpt) = 0 \\/\n (pgd_start vmid <= phys_page (addr @ (pt_vttbr_pool lnpt)) < pt_pgd_next lnpt /\\\n (phys_page (addr @ (pt_vttbr_pool lnpt))) @ (pt_pgd_par lnpt) = addr))\n (Hpgd_pool: forall addr, addr @ (pt_pgd_pool lnpt) = 0 \\/\n (pud_start vmid <= phys_page (addr @ (pt_pgd_pool lnpt)) < pt_pud_next lnpt /\\\n (phys_page (addr @ (pt_pgd_pool lnpt))) @ (pt_pud_par lnpt) = addr))\n (Hpud_pool: forall addr, addr @ (pt_pud_pool lnpt) = 0 \\/ pmd_table (addr @ (pt_pud_pool lnpt)) <> PMD_TYPE_TABLE \\/\n (pmd_table (addr @ (pt_pud_pool lnpt)) = PMD_TYPE_TABLE /\\\n pmd_start vmid <= phys_page (addr @ (pt_pud_pool lnpt)) < pt_pmd_next lnpt /\\\n (phys_page (addr @ (pt_pud_pool lnpt))) @ (pt_pmd_par lnpt) = addr)):\n valid_lnpt vmid lnpt.\n\nInductive relate_npt : Z -> NPT -> NPT -> Prop :=\n| RELATE_NPT:\n forall vmid hnpt lnpt\n (Hvalid: valid_lnpt vmid lnpt)\n (Hnext_pgd: pt_pgd_next hnpt = pt_pgd_next lnpt)\n (Hnext_pud: pt_pud_next hnpt = pt_pud_next lnpt)\n (Hnext_pmd: pt_pmd_next hnpt = pt_pmd_next lnpt)\n (Hlevel2: forall addr addr'\n (His_addr: valid_addr addr)\n (His_addr': valid_addr addr')\n (Hpgd_same: pgd_index addr = pgd_index addr')\n (Hpud_same: pud_index addr = pud_index addr')\n (Hpmd_same: pmd_index addr = pmd_index addr')\n pfn level pte\n (Hpte: (addr / PAGE_SIZE) @ (pt hnpt) = (pfn, level, pte))\n pfn' level' pte'\n (Hpte': (addr' / PAGE_SIZE) @ (pt hnpt) = (pfn', level', pte')),\n level = 2 -> level' = 2)\n (Hpgd_t: forall addr (ge0: 0 <= addr),\n let pgd_idx := pgd_index addr in\n pgd_idx @ (pgd_t hnpt) = true <->\n let vttbr_p := pool_start vmid in\n let pgd_p := Z.lor vttbr_p (pgd_idx * 8) in\n pgd_p @ (pt_vttbr_pool lnpt) <> 0)\n (Hpud_t: forall addr (ge0: 0 <= addr),\n let pgd_idx := pgd_index addr in\n let pud_idx := pud_index addr in\n pud_idx @ (pgd_idx @ (pud_t hnpt)) = true <->\n let vttbr_p := pool_start vmid in\n let pgd_p := Z.lor vttbr_p (pgd_idx * 8) in\n let pgd := pgd_p @ (pt_vttbr_pool lnpt) in\n pgd <> 0 /\\\n let pud_p := Z.lor (phys_page pgd) (pud_idx * 8) in\n let pud := pud_p @ (pt_pgd_pool lnpt) in\n pud <> 0)\n (Hpmd_t: forall addr (ge0: 0 <= addr),\n let pgd_idx := pgd_index addr in\n let pud_idx := pud_index addr in\n let pmd_idx := pmd_index addr in\n pmd_idx @ (pud_idx @ (pgd_idx @ (pmd_t hnpt))) = true <->\n let vttbr_p := pool_start vmid in\n let pgd_p := Z.lor vttbr_p (pgd_idx * 8) in\n let pgd := pgd_p @ (pt_vttbr_pool lnpt) in\n pgd <> 0 /\\\n let pud_p := Z.lor (phys_page pgd) (pud_idx * 8) in\n let pud := pud_p @ (pt_pgd_pool lnpt) in\n pud <> 0 /\\\n let pmd_p := Z.lor (phys_page pud) (pmd_idx * 8) in\n let pmd := pmd_p @ (pt_pud_pool lnpt) in\n pmd_table pmd = PMD_TYPE_TABLE /\\ pmd <> 0)\n (Hrelate: forall addr pfn level pte\n (Hvalid: valid_addr addr)\n (Hhpt: ZMap.get (addr / PAGE_SIZE) (pt hnpt) = (pfn, level, pte)),\n relate_entry vmid hnpt lnpt addr pfn level pte),\n relate_npt vmid hnpt lnpt.\n\n(* auxillary lemmas *)\n\nLemma zne_comm:\n forall (a b: Z), a <> b -> b <> a.\nProof.\n auto.\nQed.\n\nLemma and_or_same:\n forall n k, Z.land (Z.lor n k) k = k.\nProof.\n intros. Z.bitwise. rewrite andb_orb_distrib_l.\n now destruct (Z.testbit n m) eqn:H1; destruct (Z.testbit k m) eqn:H2.\nQed.\n\nLemma lor_ne0:\n forall a b, Z.lor a b <> 0 <-> a <> 0 \\/ b <> 0.\nProof.\n intros. pose proof (Z.lor_eq_0_iff a b).\n split; apply Decidable.contrapositive;\n unfold Decidable.decidable; tauto.\nQed.\n\nLemma testbit_false_eq0:\n forall a n, n >= 0 -> a = 0 -> Z.testbit a n = false.\nProof.\n intros. rewrite H0. induction n. easy. easy. contradict H. auto.\nQed.\n\nLemma testbit_true_ne0:\n forall a , (exists n, n >= 0 /\\ Z.testbit a n = true) -> a <> 0.\nProof.\n intro. pose proof (testbit_false_eq0 a).\n apply Decidable.contrapositive. unfold Decidable.decidable. tauto.\n intros. assert (a = 0) by tauto. destruct H1 as (? & ? & ?).\n apply H in H1. contradict H1. rewrite H3. easy. easy.\nQed.\n\nLemma testbit_ones n i (H : 0 <= n)\n : Z.testbit (Z.ones n) i = ((0 <=? i) && (i = 0 -> Z.testbit a n = negb (Z.testbit (Z.lnot a) n).\nProof.\n intros. induction a; induction n. easy. easy.\n assert (Z.neg p < 0) by easy. contradiction.\n induction p; easy.\n simpl. rewrite -> Pos.add_1_r. rewrite Pos.pred_N_succ. simpl. rewrite negb_involutive. auto.\n assert (Z.neg p < 0) by easy. contradiction.\n simpl. induction p. easy. simpl. induction p; easy.\n easy.\n induction p; simpl; try easy.\n induction p. assert (Z.neg p0 < 0) by easy. contradiction.\n assert (Z.neg p0 < 0) by easy. contradiction.\n assert (Z.neg p0 < 0) by easy. contradiction.\nQed.\n\nLemma phys_page_land:\n forall a, phys_page a = Z.land a 281474976706560.\nProof.\n intros. unfold phys_page. rewrite <- Z.land_assoc. simpl. reflexivity.\nQed.\n\nLemma phys_page_testbit_low:\n forall a n, n < 12 -> Z.testbit (phys_page a) n = false.\nProof.\n intros. rewrite phys_page_land. rewrite Z.land_spec.\n apply andb_false_iff. right.\n assert (n < 0 \\/ n = 0 \\/ n = 1 \\/ n = 2 \\/ n = 3 \\/ n = 4 \\/ n = 5 \\/ n = 6 \\/\n n = 7 \\/ n = 8 \\/ n = 9 \\/ n = 10 \\/ n = 11) by omega.\n destruct H0. induction n; auto with zarith. now assert (Z.pos p > 0).\n repeat (destruct H0; srewrite; auto with zarith).\nQed.\n\nLemma phys_page_testbit_mid:\n forall a n, 12 <= n < 48 -> Z.testbit (phys_page a) n = Z.testbit a n.\nProof.\n intros. rewrite phys_page_land. rewrite Z.land_spec.\n assert (forall n, 12 <= n < 48 -> Z.testbit 281474976706560 n = true).\n intros. assert (Z.testbit (Z.shiftr 281474976706560 12) (n0-12) = true).\n replace (Z.shiftr 281474976706560 12) with (Z.ones 36) by auto with zarith.\n assert (0 <= n0 - 12 < 36) by omega. rewrite testbit_ones.\n apply andb_true_iff. split; bool_rel; omega. auto with zarith.\n rewrite Z.shiftr_spec in H1. now replace (n0-12+12) with n0 in H1 by auto with zarith.\n omega.\n pose proof (H0 n H). rewrite H1. apply andb_true_r.\nQed.\n\nLemma phys_page_testbit_high:\n forall a n, 48 <= n -> Z.testbit (phys_page a) n = false.\nProof.\n intros. rewrite phys_page_land. rewrite Z.land_spec.\n assert (Z.testbit 281474976706560 n = false).\n apply Z.bits_above_log2; try omega. assert (Z.log2 281474976706560 = 47) by auto with zarith.\n omega. rewrite H0. apply andb_false_r.\nQed.\n\nLemma phys_page_upper_bound:\n forall a, phys_page a <= 281474976706560.\nProof.\n intros. rewrite phys_page_land.\n induction a. auto with zarith. apply land_upper_bound_r; auto with zarith.\n apply land_leN_if. assert (Z.neg p < 0). apply Zlt_neg_0. omega.\nQed.\n\nLemma mod_pow2_0_if:\n forall a n, (forall m, m < n -> Z.testbit a m = false) -> (n >=0) -> a mod 2^n = 0.\nProof.\n intros. apply Z.bits_inj'. intros. assert (0 <= n0 < n \\/ n <= n0) as Hn0 by omega.\n destruct Hn0 as [Hn0 | Hn0]. destruct Hn0. rewrite Z.bits_0.\n pose proof (H n0 H3). rewrite <- H4. now apply Z.mod_pow2_bits_low.\n rewrite Z.mod_pow2_bits_high; try omega. now rewrite Z.bits_0.\nQed.\n\nLemma div_gt_if:\n forall a b c, a mod c = 0 -> b mod c =0 -> c > 0 -> a > b -> a / c > b / c.\nProof.\n intros.\n replace (a) with (c*(a/c)) in H2. replace (b) with (c*(b/c)) in H2.\n apply (Zmult_gt_reg_r (a/c) (b/c) c H1).\n replace (a/c*c) with (c*(a/c)) by auto with zarith.\n replace (b/c*c) with (c*(b/c)) by auto with zarith.\n auto.\n symmetry. apply Z_div_exact_full_2; omega. symmetry. apply Z_div_exact_full_2; omega.\nQed.\n\nLemma div_le_if:\n forall a b c, a mod c = 0 -> b mod c = 0 -> c > 0 -> a < b -> a / c < b / c.\nProof.\n intros. apply Z.gt_lt. apply Z.lt_gt in H2. apply (div_gt_if b a c H0 H H1 H2).\nQed.\n\nLemma div_mult_cancel_if:\n forall a b, b > 0 -> a mod b = 0 -> a / b * b = a.\nProof.\n intros. assert (a mod b + a / b * b = a / b * b). rewrite H0. auto.\n rewrite <- H1. pose proof (Zmod_eq a b H). auto with zarith.\nQed.\n\nLemma Z_div_mult_ge0: forall a b:Z, a >= 0 -> b > 0 -> (a/b)*b >= 0.\nProof.\n intros. assert (a/b>=0) by now apply Z_div_ge0. apply Z.ge_le in H1. apply Z.le_ge.\n now apply Zmult_gt_0_le_0_compat.\nQed.\n\nLemma Z_div_mult_le: forall a b:Z, a >= 0 -> b > 0 -> (a/b)*b <= a.\nProof.\n intros. pose proof (Zdiv_mult_le a b b). rewrite Z.mul_comm in H1.\n replace (b * a) with (a * b) in H1 by apply Z.mul_comm.\n replace (a * b / b) with (a) in H1. apply H1; auto with zarith.\n symmetry. apply Z_div_mult; auto with zarith.\nQed.\n\nLemma bits_iff_ge:\n forall a (Ha: 0 < a) b (Hb: b <= a), exists m, (Z.testbit a m = true /\\ Z.log2 b <= m).\nProof.\n intros. exists (Z.log2 a). split. now apply Z.bit_log2. now apply Z.log2_le_mono.\nQed.\n\nLemma testbit_false_neg:\n forall a n (Hn: n < 0), Z.testbit a n = false.\nProof.\n intros. induction n; easy.\nQed.\n\nLemma Hshiftl3: (Z.shiftl 511 3 = 4088).\nProof.\n auto with zarith.\nQed.\n\nLemma Htest_f:\n (forall n (Hn: 12 <= n) m (Hm: 0 <= m), Z.testbit (Z.land (Z.shiftl m 3) (Z.shiftl 511 3)) n = false).\nProof.\n intros.\n assert (0 <= Z.shiftl m 3) as Ha_shiftl. rewrite Z.shiftl_nonneg. auto with zarith.\n assert (0 <= 4088) as Htmp by auto with zarith.\n pose proof (land_upper_bound_r (Z.shiftl m 3) 4088 Ha_shiftl Htmp).\n apply Z.log2_le_mono in H. simpl in H.\n apply Z.bits_above_log2. apply Z.land_nonneg. auto with zarith.\n rewrite Hshiftl3. auto with zarith.\nQed.\n\nLemma simpl_land_mult:\n forall a, Z.land a 511 * 8 = Z.land (Z.shiftl a 3) (Z.shiftl 511 3).\nProof.\n intros. replace 8 with (2^3) by auto with zarith.\n repeat rewrite <- Z.shiftl_mul_pow2 by auto with zarith.\n repeat rewrite Z.shiftl_land. reflexivity.\nQed.\n\nLemma Hhigh_or:\n forall n (Hn: 12 <= n) m (Hm: 0 <= m) b,\n b || Z.testbit (Z.land (Z.shiftl m 3) (Z.shiftl 511 3)) n = b.\nProof.\n intros. rewrite Htest_f. now rewrite orb_false_r. apply Hn. apply Hm.\nQed.\n\nLemma land_upper_bound_r':\n forall a b, (0 <= b) -> Z.land a b <= b.\nProof.\n intros. induction a. auto. apply land_upper_bound_r; auto with zarith.\n apply (land_leN_if (Z.neg p) b b). assert (Z.neg p < 0). easy.\n omega.\nQed.\n\nLemma pgd_index_upperbound:\n forall addr, pgd_index addr <= 511.\nProof.\n intros. unfold pgd_index. now apply land_upper_bound_r'.\nQed.\n\nLemma pud_index_upperbound:\n forall addr, pud_index addr <= 511.\nProof.\n intros. unfold pud_index. now apply land_upper_bound_r'.\nQed.\n\nLemma pmd_index_upperbound:\n forall addr, pmd_index addr <= 511.\nProof.\n intros. unfold pmd_index. now apply land_upper_bound_r'.\nQed.\n\nLemma or3nz:\n forall n, Z.lor n 3 <> 0.\nProof.\n intros. red. intros. induction n. Transparent Z.lor. now simpl in H.\n pose proof (Z.lor_nonneg (Z.pos p) 3). destruct H0.\n assert (0 <= Z.pos p /\\ 0 <= 3 ) by auto with zarith.\n now apply H1 in H2.\n pose proof (Z.lor_neg (Z.neg p) 3). destruct H0.\n assert (Z.neg p < 0 \\/ 3 < 0). now left.\n now apply H1 in H2.\n Opaque Z.lor.\nQed.\n\n(* page address lemmas *)\n\nLemma pt_addr_not_zero_or:\n forall addr n, is_pt_addr addr = true -> phys_page (Z.lor addr n) <> 0.\nProof.\n intros. Local Transparent Z.land Z.lor.\n unfold phys_page. unfold is_pt_addr in H. apply andb_true_iff in H.\n destruct H as [Haddr1 Haddr2].\n rewrite <- Z.land_assoc. simpl. rewrite Z.land_lor_distr_l.\n bool_rel.\n assert (addr mod 2 ^ 49 = addr). apply Z.mod_small.\n assert (PT_POOL_START + PT_POOL_SIZE < 2^49). autounfold. simpl.\n unfold Z.pow_pos. simpl. auto with zarith. bool_rel.\n split. autounfold in Haddr1. omega. autounfold in Haddr2, H. omega.\n assert (12 < Z.log2 addr < 48). autounfold in Haddr1. autounfold in Haddr2.\n assert (65536 + 256 * 33554432 = 8590000128) by easy.\n assert (addr <= 8590000128) by omega. pose proof (Z.log2_le_mono addr 8590000128).\n apply H2 in H1.\n assert (Z.log2 8590000128 < 48) by easy.\n pose proof (Z.log2_le_mono 65536 addr). assert (Z.log2 65536 = 16) by easy.\n apply H4 in Haddr1. omega.\n apply lor_ne0. assert (Z.land addr 281474976706560 <> 0).\n assert (Z.testbit (Z.land addr 281474976706560) (Z.log2 addr) = true).\n rewrite Z.land_spec. apply andb_true_iff. split.\n apply Z.bit_log2. autounfold in Haddr1. omega.\n assert (Z.testbit (Z.shiftr 281474976706560 12) ((Z.log2 addr)-12) = true).\n assert (Z.shiftr 281474976706560 12 = (Z.ones 36)) by easy.\n rewrite H1. rewrite testbit_ones. apply andb_true_iff. split; bool_rel; omega. easy.\n rewrite Z.shiftr_spec in H1. assert (Z.log2 addr-12+12 = Z.log2 addr). auto with zarith.\n rewrite H2 in H1. apply H1. omega.\n pose proof (testbit_true_ne0 (Z.land addr 281474976706560)).\n apply H2. eexists. assert (Z.log2 addr >= 0) by omega.\n split. apply H3. apply H1. auto.\n Local Opaque Z.land Z.lor.\nQed.\n\nLemma phys_page_or_not_change:\n forall addr n (Hn: 0 <= n < 4096), phys_page addr = addr -> phys_page (Z.lor addr n) = addr.\nProof.\n intros. Local Transparent Z.land Z.lor.\n unfold phys_page in *. rewrite <- Z.land_assoc in H. rewrite <- Z.land_assoc.\n simpl in *. rewrite Z.land_lor_distr_l. rewrite H.\n assert (Z.land n 281474976706560 = 0).\n apply Z.bits_inj'. intros. rewrite Z.testbit_0_l.\n rewrite Z.land_spec. apply andb_false_iff.\n assert (0 <= n0 < 12 \\/ 12 <= n0) by omega. destruct H1. right.\n assert (-1 < n0 <= 11) by omega. destruct_case H2; srewrite; simpl; reflexivity.\n left. apply Z.bits_above_log2; auto with zarith. assert (n <= 4095) by omega.\n apply Z.log2_le_mono in H2. simpl in H2. omega.\n rewrite H0. apply Z.lor_0_r.\n Local Opaque Z.land Z.lor.\nQed.\n\nLemma page_and_4096:\n forall n (Hn: 0 <= n), 0 <= (Z.land n 511) * 8 < 4096.\nProof.\n intros. split. pose proof (Z.land_nonneg n 511). omega.\n pose proof (land_upper_bound_r n 511). omega.\nQed.\n\nLemma phys_page_mod_4096:\n forall a, phys_page a mod 4096 = 0.\nProof.\n intros. replace 4096 with (2^12) by auto with zarith.\n pose proof (phys_page_testbit_low a).\n apply (mod_pow2_0_if (phys_page a) 12 H). auto with zarith.\nQed.\n\nLemma phys_page_lt_4096:\n forall n m (Hpn: phys_page n = n) (Hpm: phys_page m = m), n < m -> n + 4096 <= m.\nProof.\n intros. assert ((n + 4096) / 4096 = n / 4096 + 1).\n replace (n + 4096) with (n + 1 * 4096) by auto.\n now rewrite Z_div_plus_full by auto with zarith.\n assert (n mod 4096 = 0) as Hnmod. rewrite <- Hpn. apply phys_page_mod_4096.\n assert (m mod 4096 = 0) as Hmmod. rewrite <- Hpm. apply phys_page_mod_4096.\n assert (n / 4096 < m / 4096). apply div_le_if; omega.\n assert (n/4096 + 1 <= m / 4096). omega. rewrite <- H0 in H2.\n assert (4096 * ((n + 4096) / 4096) <= 4096 * (m / 4096)). auto with zarith.\n replace (4096 * ((n + 4096) / 4096)) with (n + 4096) in H3.\n replace (4096 * (m / 4096)) with m in H3. apply H3.\n apply Z_div_exact_2; auto with zarith.\n assert ((n + 4096) mod 4096 = 0).\n replace (n + 4096) with (n + 1 * 4096) by auto.\n rewrite Z_mod_plus; auto with zarith.\n apply Z_div_exact_2; auto with zarith.\nQed.\n\nLemma phys_page_fixed:\n forall addr, phys_page (phys_page addr) = phys_page addr.\nProof.\n intros. unfold phys_page.\n rewrite <- Z.land_assoc. simpl. rewrite <- Z.land_assoc. simpl.\n rewrite <- Z.land_assoc. simpl. rewrite <- Z.land_assoc. simpl.\n reflexivity.\nQed.\n\nHypothesis or_index_range:\n forall addr n (Haddr: 0 <= addr) (align: phys_page addr = addr) (Hn: 0 <= n),\n addr <= Z.lor addr ((Z.land n 511) * 8) < addr + 4096.\n\nLemma phys_page_a_page:\n forall addr, (phys_page addr = addr) -> addr < 281474976706560 ->\n phys_page (addr + 4096) = addr + 4096.\nProof.\n intros.\n assert (addr + 4096 = ((addr / 4096 + 1) * 2^12)).\n replace (2^12) with 4096 by auto with zarith. auto with zarith.\n assert ((addr + 4096) / 4096 = addr / 4096 + 1).\n replace (addr + 4096) with (addr + 1 * 4096) by auto.\n now rewrite Z_div_plus_full by auto with zarith.\n rewrite <- H1. symmetry. apply div_mult_cancel_if. auto with zarith.\n rewrite Zplus_mod. replace (4096 mod 4096) with 0 by auto with zarith.\n pose proof (phys_page_mod_4096 addr). rewrite H in H2.\n now rewrite H2.\n apply Z.bits_inj'. intros. assert (0 <= n < 12 \\/ 12 <= n < 48 \\/ 48 <= n) by omega.\n destruct H3.\n rewrite phys_page_testbit_low; try omega.\n rewrite H1. symmetry. apply Z.mul_pow2_bits_low. omega.\n destruct H3.\n rewrite phys_page_testbit_mid; try omega. reflexivity.\n pose proof (phys_page_upper_bound addr). rewrite H in H4.\n assert (0 < addr + 4096 <= 281474976710655).\n assert (0 <= addr). rewrite <- H. unfold phys_page. unfold PAGE_MASK.\n apply Z.land_nonneg. right. omega. omega.\n rewrite phys_page_testbit_high. symmetry.\n apply Z.bits_above_log2. omega. destruct H5.\n apply Z.log2_le_mono in H6.\n replace (Z.log2 281474976710655) with 47 in H6 by auto with zarith.\n omega. omega.\nQed.\n\nLemma div_mul_pmd_addr:\n forall addr, valid_addr addr ->\n valid_addr (addr / PAGE_SIZE / PTRS_PER_PMD * PTRS_PER_PMD * PAGE_SIZE).\nProof.\n intros. unfold valid_addr in *.\n assert (addr / PAGE_SIZE / PTRS_PER_PMD = addr / (PAGE_SIZE * PTRS_PER_PMD)) as Hdivmult.\n rewrite Zdiv_Zdiv. reflexivity. now unfold PAGE_SIZE. now unfold PTRS_PER_PMD.\n rewrite Hdivmult.\n assert (addr / (PAGE_SIZE * PTRS_PER_PMD) * PTRS_PER_PMD * PAGE_SIZE =\n addr / (PAGE_SIZE * PTRS_PER_PMD) * (PTRS_PER_PMD * PAGE_SIZE)) as Hmultassoc.\n auto with zarith.\n rewrite Hmultassoc.\n assert (addr / (PAGE_SIZE * PTRS_PER_PMD) * (PTRS_PER_PMD * PAGE_SIZE) <= addr) as Hle.\n assert (addr >= 0) by omega.\n now apply Z_div_mult_le.\n split. assert (addr / (PAGE_SIZE * PTRS_PER_PMD) >= 0) as Hge0. apply Z_div_ge0. easy. omega.\n apply Z.ge_le in Hge0.\n apply Zmult_gt_0_le_0_compat. easy. apply Hge0.\n omega.\nQed.\n\nLemma div_mul_page_addr:\n forall addr, valid_addr addr ->\n valid_addr (addr / PAGE_SIZE * PAGE_SIZE).\nProof.\n intros. unfold valid_addr in *. assert (addr >= 0) by omega.\n assert (addr / PAGE_SIZE * PAGE_SIZE <= addr) as Hle by now apply Z_div_mult_le.\n split. apply Z.ge_le. apply Z_div_mult_ge0. omega. easy. omega.\nQed.\n\nLemma pgd_pud_pmd_shift_eq:\n forall addr addr'\n (Hvalid: valid_addr addr)\n (Hvalid': valid_addr addr'),\n pgd_index addr = pgd_index addr' /\\\n pud_index addr = pud_index addr' /\\\n pmd_index addr = pmd_index addr' ->\n (Z.shiftr addr 39 = Z.shiftr addr' 39 /\\\n Z.shiftr addr 30 = Z.shiftr addr' 30 /\\\n Z.shiftr addr 21 = Z.shiftr addr' 21).\nProof.\n intros.\n unfold valid_addr in Hvalid, Hvalid'.\n assert (511 = Z.ones 9) as Hones by auto with zarith.\n unfold pgd_index, pud_index, pmd_index in H.\n destruct H as [Hpgd_idx [Hpud_idx Hpmd_idx]].\n rewrite Hones in *.\n repeat (rewrite Z.land_ones in Hpgd_idx, Hpud_idx, Hpmd_idx; try easy).\n unfold PGDIR_SHIFT in Hpgd_idx.\n unfold PUD_SHIFT in Hpud_idx.\n unfold PMD_SHIFT in Hpmd_idx.\n repeat (rewrite Z.shiftr_div_pow2 in Hpgd_idx, Hpud_idx, Hpmd_idx; try easy).\n (* Z.shiftr addr 39 = Z.shiftr addr' 39 *)\n assert (Z.shiftr addr 39 = Z.shiftr addr' 39) as Hpgd.\n assert (addr / 2 ^ 39 <= (KVM_ADDR_SPACE-1)/ 2 ^ 39) as Hdivle. apply Z_div_le. easy. omega.\n assert (addr' / 2 ^ 39 <= (KVM_ADDR_SPACE-1)/ 2 ^ 39) as Hdivle'. apply Z_div_le. easy. omega.\n assert ((KVM_ADDR_SPACE -1)/ 2 ^ 39 = 511) as Hkas by auto. rewrite Hkas in Hdivle.\n assert (addr / 2 ^ 39 < 512) as Hle_512 by omega.\n assert (addr' / 2 ^ 39 < 512) as Hle_512' by omega.\n assert (0 < 2 ^ 39). apply Z.pow_pos_nonneg; auto with zarith.\n destruct Hvalid as [Hvalid0 Hvalid1].\n assert ((addr/ 2 ^ 39) mod 2 ^ 9 = addr / 2 ^ 39) as Hdiv_mod. apply Z.mod_small.\n split. apply Z.ge_le. apply Z_div_ge0; auto with zarith. auto with zarith.\n assert ((addr'/ 2 ^ 39) mod 2 ^ 9 = addr' / 2 ^ 39) as Hdiv_mod'. apply Z.mod_small.\n split. apply Z.ge_le. apply Z_div_ge0; auto with zarith. auto with zarith.\n repeat (rewrite Z.shiftr_div_pow2; auto with zarith).\n (* Z.shiftr addr 30 = Z.shiftr addr' 30 *)\n assert (Z.shiftr addr 30 = Z.shiftr addr' 30) as Hpud.\n assert (forall n0, n0<9 -> Z.testbit (addr / 2 ^ 30) n0 = Z.testbit (addr' / 2 ^ 30) n0).\n intros.\n apply Z.bits_inj_iff in Hpud_idx. unfold Z.eqf in Hpud_idx.\n pose proof (Hpud_idx n0) as Hpud_idx'.\n rewrite Z.mod_pow2_bits_low in Hpud_idx'. rewrite Z.mod_pow2_bits_low in Hpud_idx'.\n apply Hpud_idx'. auto. auto.\n repeat (rewrite <- Z.shiftr_div_pow2 in H; try easy).\n apply Z.bits_inj_iff in Hpgd. unfold Z.eqf in Hpgd.\n assert (forall n0, 0<=n0->Z.testbit (Z.shiftr addr 30) n0 = Z.testbit (Z.shiftr addr' 30) n0).\n intros. assert (n0 < 9 \\/ n0 >= 9) as Hn0. omega. destruct Hn0 as [Hn0 | Hn0'].\n apply H in Hn0. apply Hn0.\n pose proof (Hpgd (n0-9)) as Hpgdn0.\n repeat rewrite Z.shiftr_spec; try omega.\n repeat (rewrite Z.shiftr_spec in Hpgdn0; try omega).\n replace (n0-9+39) with (n0+30) in Hpgdn0; try auto with zarith.\n apply Z.bits_inj'. apply H0.\n (* Z.shiftr addr 21 = Z.shiftr addr' 21 *)\n assert (Z.shiftr addr 21 = Z.shiftr addr' 21) as Hpmd.\n assert (forall n0, n0<9 -> Z.testbit (addr / 2 ^ 21) n0 = Z.testbit (addr' / 2 ^ 21) n0).\n intros.\n apply Z.bits_inj_iff in Hpmd_idx. unfold Z.eqf in Hpmd_idx.\n pose proof (Hpmd_idx n0) as Hpmd_idx'.\n rewrite Z.mod_pow2_bits_low in Hpmd_idx'. rewrite Z.mod_pow2_bits_low in Hpmd_idx'.\n apply Hpmd_idx'. auto. auto.\n repeat (rewrite <- Z.shiftr_div_pow2 in H; try easy).\n apply Z.bits_inj_iff in Hpgd. unfold Z.eqf in Hpgd.\n apply Z.bits_inj_iff in Hpud. unfold Z.eqf in Hpud.\n assert (forall n0, 0<=n0->Z.testbit (Z.shiftr addr 21) n0 = Z.testbit (Z.shiftr addr' 21) n0).\n intros. assert (n0 < 9 \\/ n0 >= 9) as Hn0. omega. destruct Hn0 as [Hn0 | Hn0'].\n apply H in Hn0. apply Hn0.\n pose proof (Hpud (n0-9)) as Hpudn0.\n repeat rewrite Z.shiftr_spec; try omega.\n repeat (rewrite Z.shiftr_spec in Hpudn0; try omega).\n replace (n0-9+30) with (n0+21) in Hpudn0; try auto with zarith.\n apply Z.bits_inj'. apply H0. auto.\nQed.\n\nLemma pte_shift_eq:\n forall addr addr'\n (Hvalid: valid_addr addr)\n (Hvalid': valid_addr addr'),\n pgd_index addr = pgd_index addr' /\\ pud_index addr = pud_index addr' /\\\n pmd_index addr = pmd_index addr' /\\ pte_index addr = pte_index addr' ->\n Z.shiftr addr 12 = Z.shiftr addr' 12.\nProof.\n intros. destruct H as [Hpgd_idx [Hpud_idx [Hpmd_idx Hpte_idx]]].\n pose proof (pgd_pud_pmd_shift_eq addr addr' Hvalid Hvalid') as Hshift_eq'.\n exploit Hshift_eq'. auto. intros Hshift_eq.\n destruct Hshift_eq as [Hpgd [Hpud Hpmd]].\n unfold valid_addr in Hvalid, Hvalid'.\n assert (511 = Z.ones 9) as Hones by auto with zarith.\n unfold pgd_index, pud_index, pmd_index, pte_index in *.\n rewrite Hones in *.\n repeat (rewrite Z.land_ones in Hpgd_idx, Hpud_idx, Hpmd_idx, Hpte_idx; try easy).\n unfold PGDIR_SHIFT in Hpgd_idx. unfold PUD_SHIFT in Hpud_idx.\n unfold PMD_SHIFT in Hpmd_idx. unfold PAGE_SHIFT in Hpte_idx.\n repeat (rewrite Z.shiftr_div_pow2 in Hpgd_idx, Hpud_idx, Hpmd_idx, Hpte_idx; try easy).\n assert (forall n0, n0<9 -> Z.testbit (addr / 2 ^ 12) n0 = Z.testbit (addr' / 2 ^ 12) n0).\n intros.\n apply Z.bits_inj_iff in Hpte_idx. unfold Z.eqf in Hpte_idx.\n pose proof (Hpte_idx n0) as Hpte_idx'.\n rewrite Z.mod_pow2_bits_low in Hpte_idx'. rewrite Z.mod_pow2_bits_low in Hpte_idx'.\n apply Hpte_idx'. auto. auto.\n repeat (rewrite <- Z.shiftr_div_pow2 in H; try easy).\n apply Z.bits_inj_iff in Hpgd. unfold Z.eqf in Hpgd.\n apply Z.bits_inj_iff in Hpud. unfold Z.eqf in Hpud.\n apply Z.bits_inj_iff in Hpmd. unfold Z.eqf in Hpmd.\n assert (forall n0, 0<=n0->Z.testbit (Z.shiftr addr 12) n0 = Z.testbit (Z.shiftr addr' 12) n0).\n intros. assert (n0 < 9 \\/ n0 >= 9) as Hn0. omega. destruct Hn0 as [Hn0 | Hn0'].\n apply H in Hn0. apply Hn0.\n pose proof (Hpmd (n0-9)) as Hpmdn0.\n repeat rewrite Z.shiftr_spec; try omega.\n repeat (rewrite Z.shiftr_spec in Hpmdn0; try omega).\n replace (n0-9+21) with (n0+12) in Hpmdn0; try auto with zarith.\n apply Z.bits_inj'. apply H0.\nQed.\n\nLemma pmd_same_cond:\n forall addr addr'\n (Hvalid: valid_addr addr)\n (Hvalid': valid_addr addr'),\n pgd_index addr = pgd_index addr' /\\ pud_index addr = pud_index addr' /\\\n pmd_index addr = pmd_index addr' <->\n addr / PAGE_SIZE / PTRS_PER_PMD = addr' / PAGE_SIZE / PTRS_PER_PMD.\nProof.\n intros.\n assert (PAGE_SIZE = 2 ^ 12) as Hpgsz by auto with zarith.\n assert (PTRS_PER_PMD = 2 ^ 9) as Hppm by auto with zarith.\n assert (511 = Z.ones 9) as Hones by auto with zarith.\n rewrite Hpgsz. rewrite Hppm.\n split; intros.\n (* -> *)\n pose proof (pgd_pud_pmd_shift_eq addr addr' Hvalid Hvalid' H) as Hshift_eq.\n destruct H as [Hpgd_idx [Hpud_idx Hpmd_idx]].\n unfold valid_addr in Hvalid, Hvalid'.\n unfold pgd_index, pud_index, pmd_index in *.\n repeat rewrite <- Z.shiftr_div_pow2; try easy.\n (* <- *)\n unfold valid_addr in Hvalid, Hvalid'.\n repeat (rewrite <- Z.shiftr_div_pow2 in H; try easy).\n repeat (rewrite Z.shiftr_shiftr in H; try easy).\n replace (12+9) with (21) in H by easy. autounfold.\n rewrite Hones. repeat rewrite Z.land_ones; try easy.\n apply Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall n0, n0>=21->Z.shiftr addr n0 = Z.shiftr addr' n0) as Haddrn0.\n intros. apply Z.bits_inj'. intros.\n pose proof (Z.shiftr_spec (Z.shiftr addr 21) (n0-21) n H1) as Hadd.\n rewrite Z.shiftr_shiftr in Hadd; auto with zarith.\n replace (21+(n0-21)) with n0 in Hadd; auto with zarith.\n rewrite Hadd.\n pose proof (Z.shiftr_spec (Z.shiftr addr' 21) (n0-21) n H1) as Hadd'.\n rewrite Z.shiftr_shiftr in Hadd'; auto with zarith.\n replace (21+(n0-21)) with n0 in Hadd'; auto with zarith.\n rewrite Hadd'. apply H.\n repeat split.\n assert (Z.shiftr addr 39 = Z.shiftr addr' 39). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\n assert (Z.shiftr addr 30 = Z.shiftr addr' 30). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\n assert (Z.shiftr addr 21 = Z.shiftr addr' 21). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\nQed.\n\nLemma pte_same_cond:\n forall addr addr'\n (Hvalid: valid_addr addr)\n (Hvalid': valid_addr addr'),\n pgd_index addr = pgd_index addr' /\\ pud_index addr = pud_index addr' /\\\n pmd_index addr = pmd_index addr' /\\ pte_index addr = pte_index addr' <->\n addr / PAGE_SIZE = addr' / PAGE_SIZE.\nProof.\n intros.\n assert (PAGE_SIZE = 2 ^ 12) as Hpgsz by auto with zarith.\n assert (511 = Z.ones 9) as Hones by auto with zarith.\n rewrite Hpgsz.\n split; intros.\n (* -> *)\n destruct H as [Hpgd_idx [Hpud_idx [Hpmd_idx Hpte_idx]]].\n pose proof (pgd_pud_pmd_shift_eq addr addr' Hvalid Hvalid') as Hshift_eq'.\n pose proof (pte_shift_eq addr addr' Hvalid Hvalid') as Hpte_shift_eq'.\n exploit Hshift_eq'. auto. intros Hshift_eq.\n exploit Hpte_shift_eq'. auto. intros Hpte_shift_eq.\n unfold valid_addr in Hvalid, Hvalid'.\n unfold pgd_index, pud_index, pmd_index in *.\n repeat rewrite <- Z.shiftr_div_pow2; try easy.\n (* <- *)\n unfold valid_addr in Hvalid, Hvalid'.\n repeat (rewrite <- Z.shiftr_div_pow2 in H; try easy).\n repeat (rewrite Z.shiftr_shiftr in H; try easy).\n autounfold.\n rewrite Hones. repeat rewrite Z.land_ones; try easy.\n apply Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall n0, n0>=12->Z.shiftr addr n0 = Z.shiftr addr' n0) as Haddrn0.\n intros. apply Z.bits_inj'. intros.\n pose proof (Z.shiftr_spec (Z.shiftr addr 12) (n0-12) n H1) as Hadd.\n rewrite Z.shiftr_shiftr in Hadd; auto with zarith.\n replace (12+(n0-12)) with n0 in Hadd; auto with zarith.\n rewrite Hadd.\n pose proof (Z.shiftr_spec (Z.shiftr addr' 12) (n0-12) n H1) as Hadd'.\n rewrite Z.shiftr_shiftr in Hadd'; auto with zarith.\n replace (12+(n0-12)) with n0 in Hadd'; auto with zarith.\n rewrite Hadd'. apply H.\n repeat split.\n assert (Z.shiftr addr 39 = Z.shiftr addr' 39). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\n assert (Z.shiftr addr 30 = Z.shiftr addr' 30). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\n assert (Z.shiftr addr 21 = Z.shiftr addr' 21). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\n assert (Z.shiftr addr 12 = Z.shiftr addr' 12). apply Haddrn0; auto with zarith.\n rewrite H0. reflexivity.\nQed.\n\nLemma or_index_ne_cond:\n forall n m a b (align_n: phys_page n = n) (align_m: phys_page m = m)\n (diff: n <> m \\/ (Z.land a 511) <> Z.land b 511),\n Z.lor n ((Z.land a 511) * 8) <> Z.lor m ((Z.land b 511) * 8).\nProof.\n intros. autounfold. intros.\n rewrite <- Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall a n, n >= 12 -> Z.testbit (Z.land a 511 * 8) n = false) as Habove_false.\n intros.\n apply (Z.bits_above_log2 (Z.land a0 511 * 8) n0).\n assert (0 <= Z.land a0 511). apply Z.land_nonneg. omega. omega.\n assert ((Z.land a0 511) * 8 <= 4095). assert (0 <= 4095) as Hle by easy.\n pose proof (land_upper_bound_r' a0 511 Hle). omega.\n apply Z.log2_le_mono in H1. simpl in H1. omega.\n assert (forall n0, 0 <= n0 -> Z.testbit m n0 = Z.testbit n n0 /\\\n Z.testbit (Z.land a 511 * 8) n0 =\n Z.testbit (Z.land b 511 * 8) n0).\n intros.\n pose proof (H n0) as Hfinal. repeat rewrite Z.lor_spec in Hfinal.\n assert (0 <= n0 < 12 \\/ n0 >= 12) as Hn0 by omega. destruct Hn0 as [Hn0 | Hn0].\n destruct Hn0 as [_ Hn0].\n pose proof (phys_page_testbit_low m n0 Hn0) as Hm_false. rewrite align_m in Hm_false.\n pose proof (phys_page_testbit_low n n0 Hn0) as Hn_false. rewrite align_n in Hn_false.\n rewrite Hm_false, Hn_false in *. repeat rewrite orb_false_l in Hfinal. auto.\n pose proof (Habove_false a n0 Hn0) as Ha_false.\n pose proof (Habove_false b n0 Hn0) as Hb_false.\n rewrite Ha_false, Hb_false in Hfinal. repeat rewrite orb_false_r in Hfinal.\n rewrite Ha_false, Hb_false. auto.\n assert (n = m /\\ Z.land a 511 * 8 = Z.land b 511 * 8) as Hfinal'.\n split; apply Z.bits_inj'; intros; pose proof (H0 n0 H1); easy.\n destruct Hfinal' as [Hfinal1 Hfinal2].\n assert (Z.land a 511 = Z.land b 511) by auto with zarith.\n destruct diff; auto.\nQed.\n\nLemma pgd_pool_next_zero:\n forall n vmid lnpt (Hvalid: valid_lnpt vmid lnpt) (Hvmid: 0 <= vmid) (Hn: 0 <= n),\n ((Z.lor (pt_pgd_next lnpt) (Z.land n 511 * 8)) @ (pt_pgd_pool lnpt)) = 0.\nProof.\n intros. destruct Hvalid.\n pose proof (Hpgd_next ((Z.lor (pt_pgd_next lnpt) (Z.land n 511 * 8)))).\n pose proof (lor_lower_bound_l (pt_pgd_next lnpt) (Z.land n 511 * 8)).\n apply H in H0. rewrite H0. unfold phys_page. auto.\n autounfold in Hpgd_next_range. omega.\n pose proof (Z.land_nonneg n 511) as Hnonneg.\n assert (0 <= n \\/ 0 <= 511) as Htrue by omega. apply Hnonneg in Htrue. auto with zarith.\nQed.\n\nLemma pud_pool_next_zero:\n forall n vmid lnpt (Hvalid: valid_lnpt vmid lnpt) (Hvmid: 0 <= vmid) (Hn: 0 <= n),\n ((Z.lor (pt_pud_next lnpt) (Z.land n 511 * 8)) @ (pt_pud_pool lnpt)) = 0.\nProof.\n intros. destruct Hvalid.\n pose proof (Hpud_next ((Z.lor (pt_pud_next lnpt) (Z.land n 511 * 8)))).\n pose proof (lor_lower_bound_l (pt_pud_next lnpt) (Z.land n 511 * 8)).\n apply H in H0. rewrite H0. unfold phys_page. auto.\n autounfold in Hpud_next_range. omega.\n pose proof (Z.land_nonneg n 511) as Hnonneg.\n assert (0 <= n \\/ 0 <= 511) as Htrue by omega. apply Hnonneg in Htrue. auto with zarith.\nQed.\n\nLemma pmd_pool_next_zero:\n forall n vmid lnpt (Hvalid: valid_lnpt vmid lnpt) (Hvmid: 0 <= vmid) (Hn: 0 <= n),\n ((Z.lor (pt_pmd_next lnpt) (Z.land n 511 * 8)) @ (pt_pmd_pool lnpt)) = 0.\nProof.\n intros. destruct Hvalid.\n pose proof (Hpmd_next ((Z.lor (pt_pmd_next lnpt) (Z.land n 511 * 8)))).\n pose proof (lor_lower_bound_l (pt_pmd_next lnpt) (Z.land n 511 * 8)).\n apply H in H0. rewrite H0. unfold phys_page. auto.\n autounfold in Hpmd_next_range. omega.\n pose proof (Z.land_nonneg n 511) as Hnonneg.\n assert (0 <= n \\/ 0 <= 511) as Htrue by omega. apply Hnonneg in Htrue. auto with zarith.\nQed.\n\nLemma vttbr_pool_ne_pgd_next:\n forall addr a b vmid lnpt (Hvalid: valid_lnpt vmid lnpt) (Ha: 0 <= a) (Hb: 0 <= b) (Hvmid: 0 <= vmid),\n Z.lor (phys_page (addr @ (pt_vttbr_pool lnpt))) (Z.land a 511 * 8) <>\n Z.lor (pt_pgd_next lnpt) (Z.land b 511 * 8).\nProof.\n intros.\n destruct Hvalid. autounfold in Hpgd_next_range.\n pose proof (Hvttbr_pool addr) as Hvttbr_pool'.\n repeat rewrite simpl_land_mult.\n destruct Hvttbr_pool' as [Hvttbr_pool' | Hvttbr_pool'].\n rewrite Hvttbr_pool'. simpl. autounfold in Hpgd_next_range. autounfold.\n intros.\n rewrite <- Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall n, ~(Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n)) as Hall_not_not.\n intros. autounfold. intros Hcond. apply Hcond. trivial.\n apply Logic.Classical_Pred_Type.all_not_not_ex in Hall_not_not.\n assert (exists n, Z.testbit (Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n = true /\\\n 16 <= n) as Hex.\n assert (Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) >= 69632) as Hlor_lower.\n assert (69632 <= pt_pgd_next lnpt) as Ha_lower by auto with zarith.\n assert (0 <= pt_pgd_next lnpt) as Ha_lower' by auto with zarith.\n assert (0 < pt_pgd_next lnpt) as Ha_lower'' by auto with zarith.\n assert (0 <= Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) as Hland_nonneg.\n apply Z.land_nonneg. rewrite Hshiftl3. auto with zarith.\n pose proof (lor_lower_bound_l (pt_pgd_next lnpt)\n (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) Ha_lower' Hland_nonneg) as Hlor_lower.\n auto with zarith. apply Z.ge_le in Hlor_lower.\n assert (0 < Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) as Hlor_lower'.\n auto with zarith.\n pose proof (bits_iff_ge (Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) Hlor_lower'\n 69632 Hlor_lower).\n destruct H0. exists x. simpl in H0. apply H0.\n assert (exists n , Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pgd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n) as Hcontra.\n destruct Hex as (x & Heex). destruct Heex as [Htest_t Hx]. assert (12 <= x) as Hx' by omega.\n pose proof (Htest_f x Hx') as Htest_f'.\n exists x. rewrite Htest_f'. rewrite Htest_t. easy. auto.\n contradict Hcontra. auto.\n\n destruct Hvttbr_pool' as [Hvttbr_pool' Hvttbr_pool''].\n autounfold. rewrite <- Z.bits_inj_iff. unfold Z.eqf. intros Hfalse.\n assert (forall n, (Z.testbit (phys_page addr @ (pt_vttbr_pool lnpt)) n) ||\n (Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n) =\n (Z.testbit (pt_pgd_next lnpt) n) || (Z.testbit (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) n))\n as Hfalse_spec.\n intros. repeat rewrite <- Z.lor_spec. apply Hfalse.\n\n assert (forall n, Z.testbit (phys_page addr @ (pt_vttbr_pool lnpt)) n =\n Z.testbit (pt_pgd_next lnpt) n) as Hhigh_or'.\n intros. assert (n < 12 \\/ 12 <= n) as Hn by omega. destruct Hn as [Hn | Hn].\n rewrite <- Hpgd_next_align. unfold phys_page. unfold PHYS_MASK, PAGE_MASK.\n repeat rewrite <- Z.land_assoc. simpl. repeat rewrite Z.land_spec.\n assert (n < 0 \\/ 0 <= n < 12) as Hn' by omega. destruct Hn' as [Hn' | Hn'].\n pose proof (testbit_false_neg 281474976710655 n Hn') as Htest_n. rewrite Htest_n.\n now repeat rewrite andb_false_r.\n assert (-1 < n <= 11) as Hn'' by omega.\n destruct_case Hn''; rewrite T; simpl; now repeat rewrite andb_false_r.\n pose proof (Hhigh_or n Hn a Ha (Z.testbit (phys_page addr @ (pt_vttbr_pool lnpt)) n)) as Hhigh_or'0.\n pose proof (Hhigh_or n Hn b Hb (Z.testbit (pt_pgd_next lnpt) n)) as Hhigh_or'1.\n pose proof (Hfalse_spec n) as Hfalse_spec'. rewrite Hhigh_or'0, Hhigh_or'1 in Hfalse_spec'. auto.\n assert (phys_page addr @ (pt_vttbr_pool lnpt) = pt_pgd_next lnpt) as Hfalse_eq.\n apply Z.bits_inj'. auto. omega.\nQed.\n\nLemma pgd_pool_ne_pud_next:\n forall addr a b vmid lnpt (Hvalid: valid_lnpt vmid lnpt) (Ha: 0 <= a) (Hb: 0 <= b) (Hvmid: 0 <= vmid),\n Z.lor (phys_page (addr @ (pt_pgd_pool lnpt))) (Z.land a 511 * 8) <>\n Z.lor (pt_pud_next lnpt) (Z.land b 511 * 8).\nProof.\n intros. Transparent Z.add. destruct Hvalid. autounfold in Hpud_next_range.\n pose proof (Hpgd_pool addr) as Hpgd_pool'.\n repeat rewrite simpl_land_mult.\n destruct Hpgd_pool' as [Hpgd_pool' | Hpgd_pool'].\n rewrite Hpgd_pool'. simpl. autounfold in Hpud_next_range. autounfold.\n intros.\n rewrite <- Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall n, ~(Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n)) as Hall_not_not.\n intros. autounfold. intros Hcond. apply Hcond. trivial.\n apply Logic.Classical_Pred_Type.all_not_not_ex in Hall_not_not.\n assert (exists n, Z.testbit (Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n = true /\\\n 16 <= n) as Hex.\n assert (Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) >= 69632) as Hlor_lower.\n assert (69632 <= pt_pud_next lnpt) as Ha_lower by auto with zarith.\n assert (0 <= pt_pud_next lnpt) as Ha_lower' by auto with zarith.\n assert (0 < pt_pud_next lnpt) as Ha_lower'' by auto with zarith.\n assert (0 <= Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) as Hland_nonneg.\n apply Z.land_nonneg. rewrite Hshiftl3. auto with zarith.\n pose proof (lor_lower_bound_l (pt_pud_next lnpt)\n (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) Ha_lower' Hland_nonneg) as Hlor_lower.\n auto with zarith. apply Z.ge_le in Hlor_lower.\n assert (0 < Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) as Hlor_lower'.\n auto with zarith.\n pose proof (bits_iff_ge (Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) Hlor_lower'\n 69632 Hlor_lower).\n destruct H0. exists x. simpl in H0. apply H0.\n assert (exists n , Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pud_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n) as Hcontra.\n destruct Hex as (x & Heex). destruct Heex as [Htest_t Hx]. assert (12 <= x) as Hx' by omega.\n pose proof (Htest_f x Hx') as Htest_f'.\n exists x. rewrite Htest_f'. rewrite Htest_t. easy. auto.\n contradict Hcontra. auto.\n\n destruct Hpgd_pool' as [Hpgd_pool' Hpgd_pool''].\n autounfold. rewrite <- Z.bits_inj_iff. unfold Z.eqf. intros Hfalse.\n assert (forall n, (Z.testbit (phys_page addr @ (pt_pgd_pool lnpt)) n) ||\n (Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n) =\n (Z.testbit (pt_pud_next lnpt) n) || (Z.testbit (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) n))\n as Hfalse_spec.\n intros. repeat rewrite <- Z.lor_spec. apply Hfalse.\n\n assert (forall n, Z.testbit (phys_page addr @ (pt_pgd_pool lnpt)) n =\n Z.testbit (pt_pud_next lnpt) n) as Hhigh_or'.\n intros. assert (n < 12 \\/ 12 <= n) as Hn by omega. destruct Hn as [Hn | Hn].\n rewrite <- Hpud_next_align. unfold phys_page. unfold PHYS_MASK, PAGE_MASK.\n repeat rewrite <- Z.land_assoc. simpl. repeat rewrite Z.land_spec.\n assert (n < 0 \\/ 0 <= n < 12) as Hn' by omega. destruct Hn' as [Hn' | Hn'].\n pose proof (testbit_false_neg 281474976710655 n Hn') as Htest_n. rewrite Htest_n.\n now repeat rewrite andb_false_r.\n assert (-1 < n <= 11) as Hn'' by omega.\n destruct_case Hn''; rewrite T; simpl; now repeat rewrite andb_false_r.\n pose proof (Hhigh_or n Hn a Ha (Z.testbit (phys_page addr @ (pt_pgd_pool lnpt)) n)) as Hhigh_or'0.\n pose proof (Hhigh_or n Hn b Hb (Z.testbit (pt_pud_next lnpt) n)) as Hhigh_or'1.\n pose proof (Hfalse_spec n) as Hfalse_spec'. rewrite Hhigh_or'0, Hhigh_or'1 in Hfalse_spec'. auto.\n assert (phys_page addr @ (pt_pgd_pool lnpt) = pt_pud_next lnpt) as Hfalse_eq.\n apply Z.bits_inj'. auto. omega.\nQed.\n\nLemma pud_pool_ne_pmd_next:\n forall addr a b vmid lnpt (Ha: 0 <= a) (Hb: 0 <= b) (Hvmid: 0 <= vmid)\n (Hvalid: valid_lnpt vmid lnpt)\n (Htable: pmd_table (addr @ (pt_pud_pool lnpt)) = PMD_TYPE_TABLE),\n Z.lor (phys_page (addr @ (pt_pud_pool lnpt))) (Z.land a 511 * 8) <>\n Z.lor (pt_pmd_next lnpt) (Z.land b 511 * 8).\nProof.\n intros. Transparent Z.add. destruct Hvalid. autounfold in Hpmd_next_range.\n pose proof (Hpud_pool addr) as Hpud_pool'.\n repeat rewrite simpl_land_mult.\n destruct Hpud_pool' as [Hpud_pool' | Hpud_pool'].\n rewrite Hpud_pool'. simpl. autounfold in Hpud_next_range. autounfold.\n intros.\n rewrite <- Z.bits_inj_iff in H. unfold Z.eqf in H.\n assert (forall n, ~(Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n)) as Hall_not_not.\n intros. autounfold. intros Hcond. apply Hcond. trivial.\n apply Logic.Classical_Pred_Type.all_not_not_ex in Hall_not_not.\n assert (exists n, Z.testbit (Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n = true /\\\n 16 <= n) as Hex.\n assert (Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) >= 69632) as Hlor_lower.\n assert (69632 <= pt_pmd_next lnpt) as Ha_lower by auto with zarith.\n assert (0 <= pt_pmd_next lnpt) as Ha_lower' by auto with zarith.\n assert (0 < pt_pmd_next lnpt) as Ha_lower'' by auto with zarith.\n assert (0 <= Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) as Hland_nonneg.\n apply Z.land_nonneg. rewrite Hshiftl3. auto with zarith.\n pose proof (lor_lower_bound_l (pt_pmd_next lnpt)\n (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) Ha_lower' Hland_nonneg) as Hlor_lower.\n auto with zarith. apply Z.ge_le in Hlor_lower.\n assert (0 < Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) as Hlor_lower'.\n auto with zarith.\n pose proof (bits_iff_ge (Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) Hlor_lower'\n 69632 Hlor_lower).\n destruct H0. exists x. simpl in H0. apply H0.\n assert (exists n , Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n <>\n Z.testbit (Z.lor (pt_pmd_next lnpt) (Z.land (Z.shiftl b 3) (Z.shiftl 511 3))) n) as Hcontra.\n destruct Hex as (x & Heex). destruct Heex as [Htest_t Hx]. assert (12 <= x) as Hx' by omega.\n pose proof (Htest_f x Hx') as Htest_f'.\n exists x. rewrite Htest_f'. rewrite Htest_t. easy. auto.\n contradict Hcontra. auto.\n\n destruct Hpud_pool' as [Hpud_pool' | [_ [Hpud_pool' Hpud_pool'']]]. auto.\n autounfold. rewrite <- Z.bits_inj_iff. unfold Z.eqf. intros Hfalse.\n assert (forall n, (Z.testbit (phys_page addr @ (pt_pud_pool lnpt)) n) ||\n (Z.testbit (Z.land (Z.shiftl a 3) (Z.shiftl 511 3)) n) =\n (Z.testbit (pt_pmd_next lnpt) n) || (Z.testbit (Z.land (Z.shiftl b 3) (Z.shiftl 511 3)) n))\n as Hfalse_spec.\n intros. repeat rewrite <- Z.lor_spec. apply Hfalse.\n\n assert (forall n, Z.testbit (phys_page addr @ (pt_pud_pool lnpt)) n =\n Z.testbit (pt_pmd_next lnpt) n) as Hhigh_or'.\n intros. assert (n < 12 \\/ 12 <= n) as Hn by omega. destruct Hn as [Hn | Hn].\n rewrite <- Hpmd_next_align. unfold phys_page. unfold PHYS_MASK, PAGE_MASK.\n repeat rewrite <- Z.land_assoc. simpl. repeat rewrite Z.land_spec.\n assert (n < 0 \\/ 0 <= n < 12) as Hn' by omega. destruct Hn' as [Hn' | Hn'].\n pose proof (testbit_false_neg 281474976710655 n Hn') as Htest_n. rewrite Htest_n.\n now repeat rewrite andb_false_r.\n assert (-1 < n <= 11) as Hn'' by omega.\n destruct_case Hn''; rewrite T; simpl; now repeat rewrite andb_false_r.\n pose proof (Hhigh_or n Hn a Ha (Z.testbit (phys_page addr @ (pt_pud_pool lnpt)) n)) as Hhigh_or'0.\n pose proof (Hhigh_or n Hn b Hb (Z.testbit (pt_pmd_next lnpt) n)) as Hhigh_or'1.\n pose proof (Hfalse_spec n) as Hfalse_spec'. rewrite Hhigh_or'0, Hhigh_or'1 in Hfalse_spec'. auto.\n assert (phys_page addr @ (pt_pud_pool lnpt) = pt_pmd_next lnpt) as Hfalse_eq.\n apply Z.bits_inj'. auto. omega.\nQed.\n\nLemma vttbr_align:\n forall vmid (Hvmid: valid_vmid vmid), phys_page (pool_start vmid) = pool_start vmid.\nProof.\n intros. repeat autounfold in Hvmid. unfold pool_start. unfold PT_POOL_START, PT_POOL_PER_VM.\n apply Z.bits_inj_iff'. intros.\n assert (0 <= n < 12 \\/ 12 <= n < 48 \\/ 48 <= n) as Hn by omega. destruct Hn as [Hn | [Hn | Hn]].\n rewrite phys_page_testbit_low by auto with zarith.\n replace (65536 + 33554432 * vmid) with (65536 * (1 + 512 * vmid)).\n replace (65536) with (2^16) by auto with zarith. rewrite Z.mul_comm.\n now rewrite Z.mul_pow2_bits_low by auto with zarith.\n rewrite Z.mul_add_distr_l. auto with zarith.\n apply phys_page_testbit_mid; auto with zarith.\n rewrite phys_page_testbit_high by auto with zarith.\n assert (65536 + 33554432 * vmid <= 536936458) by omega.\n apply Z.log2_le_mono in H0. replace (Z.log2 536936458) with (29) in H0 by auto with zarith.\n symmetry. apply Z.bits_above_log2; omega.\nQed.\n\nLemma vttbr_nz:\n forall vmid (Hvmid: valid_vmid vmid), pool_start vmid <> 0.\nProof.\n intros. autounfold in *. omega.\nQed.\n\nLemma pgd_index_diff_res_diff:\n forall addr addr0 vmid lnpt (Hvalid: valid_lnpt vmid lnpt),\n let pgd_idx := pgd_index addr in\n let pgd_idx0 := pgd_index addr0 in\n let vttbr := pool_start vmid in\n let pgd_p := Z.lor vttbr (pgd_idx * 8) in\n let pgd := pgd_p @ (pt_vttbr_pool lnpt) in\n let pgd_p0 := Z.lor vttbr (pgd_idx0 * 8) in\n let pgd0 := pgd_p0 @ (pt_vttbr_pool lnpt) in\n forall (Hpgd_nz: pgd <> 0) (Hpgd0_nz: pgd0 <> 0),\n pgd_idx <> pgd_idx0 -> phys_page pgd <> phys_page pgd0.\nProof.\n intros. unfold pgd_index in *.\n destruct Hvalid. assert (vttbr = pool_start vmid) as vttbr_val by reflexivity.\n assert (pgd_p <> pgd_p0). unfold pgd_p, pgd_p0. unfold pgd_idx, pgd_idx0 in *.\n apply (or_index_ne_cond vttbr vttbr (Z.shiftr addr PGDIR_SHIFT)\n (Z.shiftr addr0 PGDIR_SHIFT)); try apply vttbr_align; auto.\n pose proof (Hvttbr_pool pgd_p).\n pose proof (Hvttbr_pool pgd_p0).\n autounfold. unfold pgd, pgd0. intros.\n destruct H1, H2. unfold pgd0 in Hpgd0_nz. rewrite H2 in Hpgd0_nz. auto.\n destruct H2. unfold pgd in Hpgd_nz. rewrite H1 in Hpgd_nz. auto.\n unfold pgd0 in Hpgd0_nz. rewrite H2 in Hpgd0_nz. auto.\n destruct H1, H2. autounfold in H4, H5. srewrite. auto.\nQed.\n\nLemma pud_index_diff_res_diff:\n forall addr addr0 vmid lnpt (Hvalid: valid_lnpt vmid lnpt),\n let pgd_idx := pgd_index addr in\n let pud_idx := pud_index addr in\n let pgd_idx0 := pgd_index addr0 in\n let pud_idx0 := pud_index addr0 in\n let vttbr := pool_start vmid in\n let pgd_p := Z.lor vttbr (pgd_idx * 8) in\n let pgd := pgd_p @ (pt_vttbr_pool lnpt) in\n let pgd_p0 := Z.lor vttbr (pgd_idx0 * 8) in\n let pgd0 := pgd_p0 @ (pt_vttbr_pool lnpt) in\n let pud_p := Z.lor (phys_page pgd) (pud_idx * 8) in\n let pud := pud_p @ (pt_pgd_pool lnpt) in\n let pud_p0 := Z.lor (phys_page pgd0) (pud_idx0 * 8) in\n let pud0 := pud_p0 @ (pt_pgd_pool lnpt) in\n forall (Hpgd_nz: pgd <> 0) (Hpgd0_nz: pgd0 <> 0)\n (Hpud_nz: pud <> 0) (Hpud0_nz: pud0 <> 0),\n pgd_idx <> pgd_idx0 \\/ pud_idx <> pud_idx0 -> phys_page pud <> phys_page pud0.\nProof.\n intros. unfold pgd_index, pud_index in *.\n assert (pud_p <> pud_p0) as Hpudp_ne. unfold pud_p, pud_p0 in *. unfold pud_idx, pud_idx0 in *.\n apply (or_index_ne_cond (phys_page pgd) (phys_page pgd0) (Z.shiftr addr PUD_SHIFT)\n (Z.shiftr addr0 PUD_SHIFT)); auto using phys_page_fixed.\n destruct H.\n left.\n apply (pgd_index_diff_res_diff addr addr0 vmid lnpt Hvalid Hpgd_nz Hpgd0_nz H).\n auto.\n destruct Hvalid.\n pose proof (Hpgd_pool pud_p) as Hpgd_pool'.\n pose proof (Hpgd_pool pud_p0) as Hpgd0_pool'.\n autounfold. intros. unfold pud, pud0 in H0.\n destruct Hpgd_pool'. unfold pud in Hpud_nz. rewrite H1 in Hpud_nz. auto.\n destruct Hpgd0_pool'. unfold pud0 in Hpud0_nz. rewrite H2 in Hpud0_nz. auto.\n destruct H1, H2. autounfold in H3, H4. srewrite. auto.\nQed.\n\nLemma pmd_index_diff_res_diff:\n forall addr addr0 vmid lnpt (Hvalid: valid_lnpt vmid lnpt),\n let pgd_idx := pgd_index addr in\n let pud_idx := pud_index addr in\n let pmd_idx := pmd_index addr in\n let pgd_idx0 := pgd_index addr0 in\n let pud_idx0 := pud_index addr0 in\n let pmd_idx0 := pmd_index addr0 in\n let vttbr := pool_start vmid in\n let pgd_p := Z.lor vttbr (pgd_idx * 8) in\n let pgd := pgd_p @ (pt_vttbr_pool lnpt) in\n let pgd_p0 := Z.lor vttbr (pgd_idx0 * 8) in\n let pgd0 := pgd_p0 @ (pt_vttbr_pool lnpt) in\n let pud_p := Z.lor (phys_page pgd) (pud_idx * 8) in\n let pud := pud_p @ (pt_pgd_pool lnpt) in\n let pud_p0 := Z.lor (phys_page pgd0) (pud_idx0 * 8) in\n let pud0 := pud_p0 @ (pt_pgd_pool lnpt) in\n let pmd_p := Z.lor (phys_page pud) (pmd_idx * 8) in\n let pmd := pmd_p @ (pt_pud_pool lnpt) in\n let pmd_p0 := Z.lor (phys_page pud0) (pmd_idx0 * 8) in\n let pmd0 := pmd_p0 @ (pt_pud_pool lnpt) in\n forall (Hpgd_nz: pgd <> 0) (Hpgd0_nz: pgd0 <> 0)\n (Hpud_nz: pud <> 0) (Hpud0_nz: pud0 <> 0)\n (Hpmd_table: pmd_table pmd = PMD_TYPE_TABLE) (Hpmd_nz: pmd <>0)\n (Hpmd0_table: pmd_table pmd0 = PMD_TYPE_TABLE) (Hpmd0_nz: pmd0 <> 0),\n pgd_idx <> pgd_idx0 \\/ pud_idx <> pud_idx0 \\/ pmd_idx <> pmd_idx0 ->\n phys_page pmd <> phys_page pmd0.\nProof.\n intros. unfold pgd_index, pud_index, pmd_index in *.\n assert (pmd_p <> pmd_p0) as Hpmdp_ne. unfold pmd_p, pmd_p0 in *. unfold pmd_idx, pmd_idx0 in *.\n apply (or_index_ne_cond (phys_page pud) (phys_page pud0) (Z.shiftr addr PMD_SHIFT)\n (Z.shiftr addr0 PMD_SHIFT)); auto using phys_page_fixed.\n apply or_assoc in H. destruct H.\n left.\n apply (pud_index_diff_res_diff addr addr0 vmid lnpt Hvalid\n Hpgd_nz Hpgd0_nz Hpud_nz Hpud0_nz H).\n auto.\n destruct Hvalid.\n pose proof (Hpud_pool pmd_p) as Hpud_pool'.\n pose proof (Hpud_pool pmd_p0) as Hpud0_pool'.\n autounfold. intros. unfold pmd, pmd0 in H0.\n destruct Hpud_pool'. unfold pmd in Hpmd_nz. rewrite H1 in Hpmd_nz. auto.\n destruct Hpud0_pool'. unfold pmd0 in Hpmd0_nz. rewrite H2 in Hpmd0_nz. auto.\n destruct H1, H2; auto.\n destruct H1, H2. destruct H3, H4. autounfold in H5, H6. srewrite. auto.\nQed.\n\nLemma vttbr_val:\n forall vmid (Hvm: valid_vmid vmid),\n phys_page (pt_vttbr vmid) = pool_start vmid.\nProof.\n intros. unfold pool_start.\n unfold pt_vttbr. unfold PT_POOL_START, PT_POOL_PER_VM.\n replace (65536 + 33554432 * vmid) with ((1 + 512 * vmid) * 2^16).\n apply Z.bits_inj_iff'. intros.\n assert (0 <= n < 12 \\/ 12 <= n < 48 \\/ 48 <= n) as Hn by omega.\n destruct Hn as [Hn | [Hn | Hn]];\n rewrite ?phys_page_testbit_low, ?phys_page_testbit_mid, ?phys_page_testbit_high\n by auto with zarith.\n rewrite Z.mul_pow2_bits_low; auto with zarith.\n replace (281474976710656) with (2^48) by auto with zarith.\n rewrite Z.lor_spec. rewrite orb_comm. rewrite Z.mul_pow2_bits_low by auto with zarith.\n apply orb_false_l.\n autounfold in Hvm.\n replace (2 ^ 16) with 65536 by auto with zarith.\n assert (((1 + 512 * vmid) * 65536) <= 536936448). omega.\n apply Z.log2_le_mono in H0. replace (Z.log2 536936448) with 29 in H0 by auto with zarith.\n symmetry. apply Z.bits_above_log2; omega.\n autounfold in Hvm.\n replace (2 ^ 16) with 65536 by auto with zarith.\n rewrite Z.mul_comm, Z.mul_add_distr_l. auto with zarith.\nQed.\n\nHypothesis local_mmap_loop_512:\n forall gfn_pmd pfn pte pt pt' gfn' pfn'\n (Hmap: local_mmap_loop (Z.to_nat 512) (gfn_pmd * 512) pfn 2 pte pt = Some (gfn', pfn', pt')),\n forall gfn' (Hvalid: valid_addr (gfn_pmd * 512 * PAGE_SIZE))\n (Hvalid': valid_addr (gfn' * PAGE_SIZE)),\n (gfn' / PTRS_PER_PMD = gfn_pmd -> gfn' @ pt' = (pfn + (gfn' - gfn_pmd * 512), 2, pte)) /\\\n (gfn' / PTRS_PER_PMD <> gfn_pmd -> gfn' @ pt' = gfn' @ pt).\n", "meta": {"author": "VeriGu", "repo": "VRM-proof", "sha": "9e3c9751f31713a133a0a7e98f3d4c9600ca7bde", "save_path": "github-repos/coq/VeriGu-VRM-proof", "path": "github-repos/coq/VeriGu-VRM-proof/VRM-proof-9e3c9751f31713a133a0a7e98f3d4c9600ca7bde/sekvm/NPTWalk/ProofHighAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.23091975234373588, "lm_q1q2_score": 0.12086809734804776}} {"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Coq.Classes.RelationClasses Lia Program.\nFrom Fairness Require Export\n ITreeLib WFLib FairBeh NatStructs Mod pind Axioms\n Linking WMM Red IRed WeakestAdequacy FairLock Concurrency.\nFrom PromisingLib Require Import Loc Event.\nFrom PromisingSEQ Require Import View.\nFrom Ordinal Require Export ClassicalHessenberg.\nRequire Import Coq.Numbers.BinNums.\n\n\nSet Implicit Arguments.\n\nSection INIT.\n\n Definition loc_X: Loc.t := Loc.of_nat 2.\n\n Definition const_0: Const.t := Const.of_Z (BinIntDef.Z.of_nat 0).\n Definition const_42: Const.t := Const.of_Z (BinIntDef.Z.of_nat 42).\n\nEnd INIT.\n\nModule ClientImpl.\n\n Definition thread1:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n let tvw := View.bot in\n tvw <- (OMod.call \"lock\" (tvw: View.t));;\n tvw <- (OMod.call \"store\" (tvw: View.t, loc_X, const_42, Ordering.plain));;\n `tvw: View.t <- (OMod.call \"unlock\" (tvw: View.t));;\n _ <- trigger Yield;;\n Ret tt.\n\n Definition thread2:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n let tvw := View.bot in\n val_x <- ITree.iter\n (fun (tvw: View.t) =>\n tvw <- (OMod.call \"lock\" (tvw: View.t));;\n '(tvw, x) <- (OMod.call \"load\" (tvw: View.t, loc_X, Ordering.plain));;\n `tvw: View.t <- (OMod.call \"unlock\" (tvw: View.t));;\n b <- unwrap (Const.eqb const_0 x);;\n if (b: bool) then Ret (inl tvw) else Ret (inr x)) tvw;;\n b <- unwrap (Const.eqb const_42 val_x);;\n if (b: bool) then\n _ <- trigger Yield;;\n _ <- trigger (Observe 0 [42]);;\n _ <- trigger Yield;;\n Ret tt\n else UB.\n\n Definition omod: Mod.t :=\n Mod.mk\n tt\n (Mod.get_funs [(\"thread1\", Mod.wrap_fun thread1);\n (\"thread2\", Mod.wrap_fun thread2)])\n .\n\n Definition mod: Mod.t :=\n OMod.close\n (omod)\n (ModAdd WMem.mod AbsLockW.mod)\n .\n\nEnd ClientImpl.\n\nModule ClientSpec.\n Definition thread1:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n _ <- trigger Yield;; Ret tt.\n\n Definition thread2:\n ktree (programE void unit) unit unit\n :=\n fun _ =>\n _ <- trigger Yield;;\n _ <- trigger (Observe 0 [42]);;\n _ <- trigger Yield;;\n Ret tt.\n\n Definition mod: Mod.t :=\n Mod.mk\n tt\n (Mod.get_funs [(\"thread1\", Mod.wrap_fun thread1);\n (\"thread2\", Mod.wrap_fun thread2)])\n .\n\nEnd ClientSpec.\n\n\n\nFrom Fairness Require Import\n IProp IPM Weakest ModSim PCM MonotonePCM StateRA FairRA NatStructsLow NatMapRALow.\n\nSection LEMMA.\n\n Context `{Σ: GRA.t}.\n Variable A: Type.\n Context `{EXCL: @GRA.inG (Excl.t A) Σ}.\n\n Lemma excl_unique\n a0 a1\n :\n (OwnM (Excl.just a0: Excl.t A))\n -∗\n (OwnM (Excl.just a1: Excl.t A))\n -∗\n ⌜False⌝%I.\n Proof.\n iIntros \"I1 I2\". iCombine \"I1 I2\" as \"C\". iPoseProof (OwnM_valid with \"C\") as \"%C\". exfalso. ur in C. ss.\n Qed.\n\nEnd LEMMA.\n\nSection SIM.\n\n Context `{Σ: GRA.t}.\n\n Context `{MONORA: @GRA.inG monoRA Σ}.\n Context `{THDRA: @GRA.inG ThreadRA Σ}.\n Context `{STATESRC: @GRA.inG (stateSrcRA (unit)) Σ}.\n Context `{STATETGT: @GRA.inG (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod)))) Σ}.\n Context `{IDENTSRC: @GRA.inG (identSrcRA (void)) Σ}.\n Context `{IDENTTGT: @GRA.inG (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ}.\n\n Context `{OBLGRA: @GRA.inG ObligationRA.t Σ}.\n Context `{ARROWRA: @GRA.inG (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ}.\n Context `{EDGERA: @GRA.inG EdgeRA Σ}.\n Context `{ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ}.\n\n Context `{WMEMRA: @GRA.inG wmemRA Σ}.\n\n Context `{EXCL: @GRA.inG (Excl.t unit) Σ}.\n Context `{EXCL2: @GRA.inG (Excl.t (unit * unit)) Σ}.\n Context `{ONESHOTRA: @GRA.inG (OneShot.t nat) Σ}.\n Context `{REGIONRA: @GRA.inG (Region.t (thread_id * nat)) Σ}.\n Context `{CONSENTRA: @GRA.inG (@FiniteMap.t (Consent.t nat)) Σ}.\n Context `{AUTHNRA: @GRA.inG (Auth.t (Excl.t nat)) Σ}.\n Context `{AUTHVWRA: @GRA.inG (Auth.t (Excl.t View.t)) Σ}.\n Context `{AUTHVWRA2: @GRA.inG (Auth.t (Excl.t (View.t * unit))) Σ}.\n Context `{AUTHNMNRA: @GRA.inG (Auth.t (NatMapRA.t nat)) Σ}.\n\n Definition thread1_will_write (tvw: View.t) : iProp :=\n ∃ k, (∃ n, ObligationRA.black k n)\n ∗\n (ObligationRA.correl_thread k 1%ord)\n ∗\n (OwnM (OneShot.shot k))\n ∗\n ((ObligationRA.pending k (/2)%Qp ∗ wpoints_to loc_X const_0 tvw)\n ∨\n (ObligationRA.shot k ∗ wpoints_to loc_X const_42 tvw)).\n\n Definition o_w_cor: Ord.t := (Ord.omega × Ord.omega)%ord.\n\n Definition lock_will_unlock : iProp :=\n ∃ (own: bool) (tvw: View.t) (ing: bool) (mem: WMem.t) (wobl: NatMap.t nat) (j: nat),\n (OwnM (Auth.black (Some wobl: NatMapRA.t nat)))\n ∗\n ((OwnM (Auth.black (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.black (Excl.just (tvw, tt): Excl.t (View.t * unit)%type))))\n ∗\n (wmemory_black mem)\n ∗\n (St_tgt (tt, (mem, (((own, tvw), ing), key_set wobl))))\n ∗\n (FairRA.blacks (fun id => exists t, (id = (inr (inr (inr t)))) /\\ (~ NatMap.In t wobl)))\n ∗\n (natmap_prop_sum wobl\n (fun tid idx =>\n (own_thread tid)\n ∗\n (ObligationRA.correl (inr (inr (inr tid))) idx o_w_cor)\n ∗\n (ObligationRA.pending idx 1)\n ∗\n (ObligationRA.duty (inr (inr (inr tid))) [(idx, o_w_cor)])\n ))\n ∗\n (\n ((⌜own = false⌝)\n ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n (* points_to view *)\n ∗ (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n (* argument-passing view *)\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit)%type)))\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n )\n ∨\n ((⌜own = true⌝)\n ∗ (ObligationRA.pending j 1)\n ∗ (ObligationRA.black j o_w_cor)\n ∗ (ObligationRA.correl_thread j 1%ord)\n ∗ (natmap_prop_sum wobl (fun _ idx => ObligationRA.amplifier j idx 1%ord))\n )\n )\n ∗\n (\n ((⌜ing = false⌝)\n ∗ (OwnM (Excl.just (tt, tt): Excl.t (unit * unit)%type))\n )\n ∨\n ((⌜ing = true⌝)\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n (* ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat))) *)\n (* ∗ (∃ tvw', (OwnM (Auth.white (Excl.just tvw': Excl.t View.t))) ∗ (⌜View.le tvw tvw'⌝)) *)\n )\n )\n .\n\n Let I: list iProp :=\n [(∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t)))\n ∗ (thread1_will_write tvw))%I;\n lock_will_unlock].\n\n Section INITIAL.\n\n Variable tid1 tid2 : nat.\n Let init_ord := (((((Ord.omega × Ord.omega) × Ord.omega) ⊕ ((Ord.S Ord.O) × (o_w_cor))) ⊕ 10)%ord).\n Let init_ths :=\n (NatStructs.NatMap.add tid1 tt\n (NatStructs.NatMap.add tid2 tt\n (NatStructs.NatMap.empty unit))).\n\n Lemma init_sat Invs (H_TID : tid1 <> tid2) :\n (\n OwnM (OneShot.pending nat 1)\n ) ∗ (\n OwnM (Auth.black (Some (NatMap.empty nat) : NatMapRA.t nat))\n ∗ OwnM (Auth.black (Excl.just 0 : Excl.t nat))\n ∗ OwnM (Auth.white (Excl.just 0 : Excl.t nat))\n ∗ OwnM (Auth.black (Excl.just View.bot : Excl.t View.t))\n ∗ OwnM (Auth.white (Excl.just View.bot : Excl.t View.t))\n ∗ OwnM (Auth.black (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ∗ OwnM (Auth.white (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ∗ OwnM (Excl.just (tt,tt): Excl.t (unit * unit))\n ∗ OwnM (Excl.just () : Excl.t unit)\n ∗ OwnM (wmem_init_res loc_X (Loc.of_nat 5)))\n ∗\n WSim.initial_prop ClientSpec.mod ClientImpl.mod init_ths init_ord\n ⊢\n MUpd Invs (fairI (ident_tgt:=Mod.ident ClientImpl.mod)) [] [] (\n (∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t))) ∗ (thread1_will_write tvw))\n ∗\n (lock_will_unlock)\n ∗\n (∃ k, (own_thread tid1)\n ∗ (ObligationRA.duty (inl tid1) [(k, Ord.from_nat 1)])\n ∗ (ObligationRA.taxes [(k, Ord.from_nat 1)] init_ord)\n ∗ (OwnM (OneShot.shot k))\n ∗ (ObligationRA.pending k (/ 2))\n )\n ∗\n ((own_thread tid2) ∗ (ObligationRA.duty (inl tid2) []))\n ).\n Proof.\n iIntros \"(PEND & (B1 & B2 & W2 & B3 & W3 & B4 & W4 & E1 & E2 & E3) & INIT)\".\n iPoseProof (wmem_init_res_prop with \"E3\") as \"[[WPOINTS _] MBLACK]\".\n\n iMod (ObligationRA.alloc ((1 × Ord.omega) ⊕ ((1 × Ord.omega) × init_ord))%ord) as \"[% [[OBLIG1 OBLIG2] OBLIG3]]\".\n iMod (OwnM_Upd (OneShot.pending_shot k) with \"PEND\") as \"#SHOT\".\n rewrite <- Qp.inv_half_half.\n iPoseProof (ObligationRA.pending_split _ (/ 2)%Qp (/ 2)%Qp with \"OBLIG3\") as \"[OBPEND1 OBPEND2]\".\n\n unfold WSim.initial_prop.\n iDestruct \"INIT\" as \"[[[[[INIT0 INIT1] INIT2] INIT3] INIT4] INIT5]\".\n (* make thread_own, duty *)\n assert (NatStructs.NatMap.find tid1 init_ths = Some tt).\n { unfold init_ths. apply NatStructs.nm_find_add_eq. }\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT2\") as \"[DU1 INIT2]\".\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT3\") as \"[TH1 INIT3]\".\n clear H.\n assert (NatStructs.NatMap.find tid2 (NatStructs.NatMap.remove tid1 init_ths) = Some tt).\n { unfold init_ths.\n rewrite NatStructs.NatMapP.F.remove_neq_o; ss.\n rewrite NatStructs.nm_find_add_neq; ss.\n rewrite NatStructs.nm_find_add_eq. ss.\n }\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT2\") as \"[DU2 INIT2]\".\n iPoseProof (MonotonePCM.natmap_prop_remove_find _ _ _ H with \"INIT3\") as \"[TH2 INIT3]\".\n clear H.\n\n iPoseProof (ObligationRA.white_split_eq with \"OBLIG2\") as \"[O0 O1]\".\n iPoseProof (ObligationRA.duty_alloc with \"DU1 O0\") as \"> DU\".\n iPoseProof (ObligationRA.duty_correl with \"DU\") as \"#CORREL\".\n { ss. eauto. }\n\n iSplitL \"B3 OBLIG1 SHOT OBPEND1 WPOINTS\".\n { unfold thread1_will_write.\n iModIntro. iExists View.bot. iFrame. iExists k.\n iSplitL \"OBLIG1\". { iExists _. iFrame. }\n iSplitR. { iExists _. eauto. }\n iSplitL \"SHOT\". { iApply \"SHOT\". }\n iLeft. iFrame. iApply (init_points_to_wpoints_to with \"WPOINTS\").\n }\n\n (*\n Check FairRA.blacks_unfold.\n Search FairRA.blacks.\n set (s0 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => False%type\n | inr _ => True%type\n end).\n set (s1 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => i = inl tid1\n | inr _ => True%type\n end).\n set (s2 := λ i : nat + OMod.closed_ident ClientImpl.omod (ModAdd WMem.mod AbsLockW.mod),\n match i with\n | inl _ => i = inl tid1 \\/ i = inl tid2\n | inr _ => True%type\n end).\n Check FairRA.blacks_unfold s1 s0.\n *)\n (* iPoseProof (FairRA.blacks_unfold s1 s0 with \"BLACK\") as \"BLACK\". *)\n\n (* FairRA.blacks_unfold *)\n (* black_to_duty *)\n\n iSplitL \"B1 B2 W2 W3 B4 W4 E1 E2 MBLACK INIT1 INIT5\".\n { unfold lock_will_unlock.\n iExists false, View.bot, false, WMem.init, (NatMap.empty nat), 0.\n iModIntro.\n iFrame.\n iSplitL \"INIT5\". { ss. unfold OMod.closed_st_init, Mod.st_init. ss.\n rewrite key_set_empty_empty_eq. iFrame. }\n iSplitL \"INIT1\". { iApply FairRA.blacks_impl.\n 2: { iFrame. }\n i. des. subst. ss. }\n iSplitR. { ss. }\n iSplitL \"W2 W3 W4 E2\". { iLeft. iFrame. ss. }\n { iLeft. iFrame. ss. }\n }\n\n iSplitL \"O1 OBPEND2 TH1 DU\".\n { iExists k. iSplitL \"TH1\"; ss. iModIntro. iFrame. auto. }\n iModIntro. iFrame.\n Qed.\n\n (*\n Definition thread1_will_write (tvw: View.t) : iProp :=\n ∃ k, (∃ n, ObligationRA.black k n)\n ∗\n (ObligationRA.correl_thread k 1%ord)\n ∗\n (OwnM (OneShot.shot k))\n ∗\n ((ObligationRA.pending k (/2)%Qp ∗ wpoints_to loc_X const_0 tvw)\n ∨\n (ObligationRA.shot k ∗ wpoints_to loc_X const_42 tvw)).\n\n\n Definition lock_will_unlock : iProp :=\n ∃ (own: bool) (tvw: View.t) (ing: bool) (mem: WMem.t) (wobl: NatMap.t nat) (j: nat),\n (OwnM (Auth.black (Some wobl: NatMapRA.t nat)))\n ∗\n ((OwnM (Auth.black (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.black (Excl.just (tvw, tt): Excl.t (View.t * unit)%type))))\n ∗\n (wmemory_black mem)\n ∗\n (St_tgt (tt, (mem, (((own, tvw), ing), key_set wobl))))\n ∗\n (FairRA.blacks (fun id => exists t, (id = (inr (inr (inr t)))) /\\ (~ NatMap.In t wobl)))\n ∗\n (natmap_prop_sum wobl\n (fun tid idx =>\n (own_thread tid)\n ∗\n (ObligationRA.correl (inr (inr (inr tid))) idx o_w_cor)\n ∗\n (ObligationRA.pending idx 1)\n ∗\n (ObligationRA.duty (inr (inr (inr tid))) [(idx, o_w_cor)])\n ))\n ∗\n (\n ((⌜own = false⌝)\n ∗ (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n ∗ (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit)%type)))\n ∗ (OwnM (Excl.just tt: Excl.t unit))\n )\n ∨\n (* ((⌜own = true⌝) *)\n (* ∗ (ObligationRA.pending j 1) *)\n (* ∗ (ObligationRA.black j o_w_cor) *)\n (* ∗ (ObligationRA.correl_thread j 1%ord) *)\n (* ∗ (natmap_prop_sum wobl (fun _ idx => ObligationRA.amplifier j idx 1%ord)) *)\n (* ) *)\n )\n ∗\n (\n ((⌜ing = false⌝)\n ∗ (OwnM (Excl.just (tt, tt): Excl.t (unit * unit)%type))\n )\n ∨\n (* ((⌜ing = true⌝) *)\n (* ∗ (OwnM (Excl.just tt: Excl.t unit)) *)\n (* ) *)\n )\n .\n *)\n End INITIAL.\n\n Lemma AbsLock_lock\n R_src R_tgt tid\n (src: thread void (sE unit) R_src)\n tgt\n r g\n (Q: R_src -> R_tgt -> iProp)\n (l: list (nat * Ord.t)%type)\n (num_line: nat)\n (tvw0: View.t)\n :\n ((own_thread tid)\n ∗\n (ObligationRA.duty (inl tid) l)\n ∗\n (ObligationRA.taxes\n l ((((Ord.omega × Ord.omega) × Ord.omega)\n ⊕\n ((Ord.S Ord.O) × (o_w_cor)))\n ⊕ 9)%ord))\n ∗\n (∀ tvw1,\n ((⌜View.le tvw0 tvw1⌝)\n ∗\n (own_thread tid)\n ∗\n (∃ j, (ObligationRA.duty (inl tid) ((j, Ord.S Ord.O) :: l))\n ∗\n (ObligationRA.white j (Ord.omega × (Ord.from_nat num_line))%ord)\n ∗\n (OwnM (Auth.white (Excl.just j: Excl.t nat)))\n )\n ∗\n (∃ tvw,\n (OwnM (Auth.white (Excl.just tvw: Excl.t View.t)))\n ∗ (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit))))\n ∗ (⌜(View.le tvw tvw1)⌝)\n )\n ∗\n (OwnM (Excl.just tt: Excl.t unit))\n )\n -∗\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tgt tvw1)))\n ⊢\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tvw' <- (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (R:=View.t) (OMod.call \"lock\" tvw0));; (tgt tvw'))).\n Proof.\n Opaque key_set.\n iIntros \"[[TH [DUTY TAXES]] SIM]\".\n rewrite close_itree_call. ss. rred. unfold OMod.emb_callee, emb_r. rewrite <- map_event_compose. rewrite <- plmap_compose.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"TAXES\".\n { eapply Hessenberg.lt_add_r. apply OrdArith.lt_from_nat. instantiate (1:=8). auto. }\n iMod \"TAXES\". iDestruct \"TAXES\" as \"[TAXES TAX]\".\n\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n unfold AbsLockW.lock_fun, Mod.wrap_fun. rred.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"TAXES\".\n { eapply Hessenberg.lt_add_r. apply OrdArith.lt_from_nat. instantiate (1:=7). auto. }\n iMod \"TAXES\". iDestruct \"TAXES\" as \"[TAXES TAX]\".\n\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tidR. rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iPoseProof (ObligationRA.alloc\n (((Ord.omega × Ord.omega) × Ord.omega)\n ⊕ ((Ord.S Ord.O) × (o_w_cor)))%ord) as \"A\".\n iMod \"A\" as \"[% [[MYB MYW] PEND]]\".\n iPoseProof (ObligationRA.white_split_eq with \"MYW\") as \"[MYW YOUW]\".\n iDestruct \"I1\" as \"[BLKS [SUM [CASES INGS]]]\".\n\n iAssert (⌜~ NatMap.In tid wobl⌝)%I as \"%\".\n { iAssert (⌜(NatMap.In tid wobl)⌝ ∨ ⌜(~ NatMap.In tid wobl)⌝)%I as \"%\".\n { iPureIntro. pose NatMapP.F.In_dec. specialize (s _ wobl tid). destruct s; auto. }\n destruct H as [IN | NI].\n 2: auto.\n iPoseProof (natmap_prop_sum_impl with \"SUM\") as \"SUM\".\n { instantiate (1:= fun tid0 idx => own_thread tid0). i. iIntros \"[F1 F2]\". iFrame. }\n apply NatMapP.F.in_find_iff in IN.\n destruct (NatMap.find tid wobl) eqn:FIND; ss.\n iPoseProof (natmap_prop_sum_in with \"SUM\") as \"TH2\". eauto.\n iPoseProof (own_thread_unique with \"TH TH2\") as \"F\". iPure \"F\" as F. ss.\n }\n\n (* update ObligationRA.duty: get [] by black_to_duty, update with MYW; then correl *)\n set (blks2 :=\n (λ id : nat + (Mod.ident ClientImpl.omod + (Mod.ident (WMem.mod) + NatMap.key)),\n (∃ t : NatMap.key, id = inr (inr (inr t)) ∧ ¬ NatMap.In (elt:=nat) t (NatMap.add tid k wobl))%type)).\n iPoseProof (FairRA.blacks_unfold with \"BLKS\") as \"[BLKS MYDUTY]\".\n { instantiate (1:=inr (inr (inr tid))). instantiate (1:=blks2). i. des.\n { subst blks2. ss. des. esplits; eauto. ii; apply IN0. apply NatMapP.F.add_in_iff; auto. }\n { subst blks2. ss. esplits; eauto. }\n }\n { subst blks2. ss. ii. des. clarify. apply H1. apply NatMapP.F.add_in_iff. auto. }\n iPoseProof (black_to_duty with \"MYDUTY\") as \"MYDUTY\".\n iPoseProof (ObligationRA.duty_alloc with \"MYDUTY\") as \"MYDUTY\".\n iPoseProof (\"MYDUTY\" with \"MYW\") as \"> MYDUTY\".\n iPoseProof (ObligationRA.duty_correl with \"MYDUTY\") as \"# MYCOR\".\n { ss. left; eauto. }\n\n (* make (Auth.white singleton tid k) and update wobl *)\n iPoseProof (OwnM_Upd with \"B1\") as \"OWN1\".\n { eapply Auth.auth_alloc. instantiate (1:=NatMapRA.singleton tid k).\n instantiate (1:=Some (NatMap.add tid k wobl)). eapply NatMapRA.add_local_update.\n eapply NatMapP.F.not_find_in_iff; auto.\n }\n iMod \"OWN1\" as \"[OWNB1 MYSING]\".\n\n (* need to make amp; need ObligationRA.black j *)\n iAssert (\n (\n (⌜own = false⌝ **\n (OwnM (Auth.white (Excl.just j: Excl.t nat))\n ** (OwnM (Auth.white (Excl.just tvw: Excl.t View.t))\n ** (OwnM (Auth.white (Excl.just (tvw, tt): Excl.t (View.t * unit))) ** OwnM (Excl.just tt: Excl.t unit)))\n ))\n ∨ (⌜own = true⌝ **\n (ObligationRA.pending j 1 **\n (ObligationRA.black j o_w_cor **\n (ObligationRA.correl_thread j 1 **\n natmap_prop_sum wobl (λ _ idx : nat, ObligationRA.amplifier j idx 1))))))\n ∗\n #=( ObligationRA.edges_sat )=>((⌜own = true⌝) -∗ (ObligationRA.amplifier j k 1))\n )%I\n with \"[CASES YOUW]\" as \"[CASES AMP]\".\n { iDestruct \"CASES\" as \"[OWNF | [OT [PEND [JBLK [JCOR ALLAMP]]]]]\".\n { iDestruct \"OWNF\" as \"[% OW]\". iSplitL \"OW\". iLeft. iFrame. auto.\n iModIntro. iIntros \"OT\". iPure \"OT\" as OT. clarify.\n }\n iPoseProof (\"JBLK\") as \"# JBLK\". iSplitR \"YOUW\".\n { iRight. iFrame. auto. }\n iPoseProof (ObligationRA.amplifier_intro with \"JBLK\") as \"AMP\".\n iPoseProof (\"AMP\" with \"YOUW\") as \"AMP2\". iMod \"AMP2\". iModIntro.\n iIntros \"OT\". iFrame.\n }\n iMod \"AMP\".\n\n (* now close invariant *)\n iMod (\"K1\" with \"[TH OWNB1 B2 MEM SUM CASES INGS STGT PEND BLKS MYDUTY MYCOR AMP]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw, ing, mem, (NatMap.add tid k wobl), j. iFrame.\n rewrite key_set_pull_add_eq. iFrame. iSplitL \"SUM TH MYDUTY MYCOR PEND\".\n { iApply (natmap_prop_sum_add with \"SUM\"). iFrame. auto. }\n iDestruct \"CASES\" as \"[OWNF | [OT [PEND [JBLK [JCOR ALLAMP]]]]]\". iFrame.\n iRight. iPure \"OT\" as OT. iFrame. iSplit; auto.\n iApply (natmap_prop_sum_add with \"ALLAMP\"). iApply \"AMP\". auto.\n }\n { msubtac. }\n\n (* induction *)\n rred. iApply stsim_discard.\n { instantiate (1:=topset I). msubtac. }\n remember (((Ord.omega × Ord.omega) × Ord.omega)\n ⊕ Ord.S Ord.O × o_w_cor)%ord as wd.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAXKEEP]\".\n { instantiate (1:= (wd ⊕ 6)%ord). apply Hessenberg.lt_add_r.\n apply OrdArith.lt_from_nat. lia.\n }\n remember (wd ⊕ 6)%ord as credit.\n assert (RICH: (wd < credit)%ord).\n { subst; apply Hessenberg.add_lt_l. rewrite <- Ord.from_nat_O.\n apply OrdArith.lt_from_nat. lia.\n }\n clear Heqwd Heqcredit.\n clear own mem blks2 j H wobl. iClear \"MYCOR\".\n iStopProof. revert l k credit RICH. pattern wd. revert wd.\n apply (well_founded_induction Ord.lt_well_founded). intros wd IH. intros l k credit RICH.\n iIntros \"[SIM [DUTY [MYB [MYW [TAXES TAXKEEP]]]]]\".\n rewrite unfold_iter_eq. rred.\n\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\". eauto.\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY WTH\". rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n destruct own.\n\n (* someone is holding the lock *)\n { rred. iApply stsim_tauR. rred.\n\n iAssert (⌜NatMap.find tid wobl = Some k⌝)%I as \"%\".\n { iPoseProof (OwnM_valid with \"[MYW B1]\") as \"%\".\n { instantiate (1:= (Auth.black (Some wobl: NatMapRA.t nat)) ⋅ (Auth.white (NatMapRA.singleton tid k: NatMapRA.t nat))). iSplitL \"B1\"; iFrame. }\n eapply Auth.auth_included in H. eapply NatMapRA.extends_singleton_iff in H.\n auto.\n }\n rename H into FIND.\n\n iDestruct \"I1\" as \"[BLKS [SUM [CASES INGS]]]\".\n iDestruct \"CASES\" as \"[[%OWNF [LOCK EXCL]] | [%OWNT [JPEND [JBLK [#JCOR AMPs]]]]]\".\n { inversion OWNF. }\n\n (* induction *)\n { iAssert (ObligationRA.amplifier j k 1)%I with \"[AMPs]\" as \"#AMP\".\n { iPoseProof (natmap_prop_remove_find with \"AMPs\") as \"[# AMP AMPs]\".\n { eapply FIND. }\n auto.\n }\n iPoseProof (ObligationRA.correl_thread_correlate with \"JCOR WTH\") as \"> DEC\".\n iDestruct \"DEC\" as \"[DEC | DONE]\"; cycle 1.\n { iPoseProof (ObligationRA.pending_not_shot with \"JPEND DONE\") as \"CONTRA\". auto. }\n { iPoseProof (ObligationRA.amplifier_amplify with \"AMP DEC\") as \"> DEC\".\n iPoseProof (ObligationRA.black_white_decr with \"MYB DEC\") as \"> [% [MYB %]]\".\n assert (RENEW: (o2 < wd)%ord).\n { eapply Ord.lt_le_lt. 2: eauto. apply Hessenberg.add_lt_l.\n rewrite <- Ord.from_nat_O. rewrite <- Jacobsthal.mult_from_nat.\n apply OrdArith.lt_from_nat. ss.\n }\n iMod (\"K1\" with \"[B1 B2 MEM STGT BLKS SUM JPEND JBLK AMPs INGS]\") as \"_\".\n { unfold lock_will_unlock. iExists true, tvw1, ing0, mem, wobl, j. iFrame.\n iRight. iFrame. iSplit; auto.\n }\n { msubtac. }\n iApply IH. eapply RENEW. eapply RENEW.\n iFrame.\n }\n }\n }\n\n (* no one is holding the lock *)\n { rred.\n iClear \"TAXES\". clear IH credit RICH.\n iApply stsim_getR. iSplit. iFrame. rred.\n iDestruct \"I1\" as \"[BLKS [SUM [[[%VW [LOCK EXCL]] | [%CONTRA _]] INGS]]]\".\n 2:{ inversion CONTRA. }\n inv VW.\n iDestruct \"INGS\" as \"[[%INGF INGEX] | [_ CONTRA]]\".\n 2:{ iDestruct \"EXCL\" as \"[_ [_ EXCL]]\". iPoseProof (excl_unique with \"EXCL CONTRA\") as \"%C\". inv C. }\n subst. rred.\n\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw'. rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iAssert (⌜NatMap.find tid wobl = Some k⌝)%I as \"%\".\n { iPoseProof (OwnM_valid with \"[MYW B1]\") as \"%\".\n { instantiate (1:= (Auth.black (Some wobl: NatMapRA.t nat)) ⋅ (Auth.white (NatMapRA.singleton tid k: NatMapRA.t nat))). iSplitL \"B1\"; iFrame. }\n eapply Auth.auth_included in H. eapply NatMapRA.extends_singleton_iff in H.\n auto.\n }\n rename H into FIND.\n\n iPoseProof (natmap_prop_remove_find with \"SUM\") as \"[[MYTH [_ [MYPEND MYDUTY]]] SUM]\".\n eapply FIND. iPoseProof (ObligationRA.pending_shot with \"MYPEND\") as \"> MYDONE\".\n iPoseProof (ObligationRA.duty_done with \"MYDUTY MYDONE\") as \"> MYDUTY\".\n iApply (stsim_fairR with \"[MYDUTY]\").\n 4:{ instantiate (1:=[(inr (inr tid), [])]). ss. iFrame. }\n { clear. i. unfold prism_fmap in *. des_ifs. ss. eapply Prism.review_preview in Heq. auto. }\n { instantiate (1:= List.map (fun '(j, _) => inr (inr j)) (NatMap.elements (NatMap.remove tid (key_set wobl)))). clear. i. unfold prism_fmap.\n assert (A: exists j, (i = inr (inr j)) /\\ (NatMap.In j (NatMap.remove tid (key_set wobl)))).\n { apply in_map_iff in IN. des. des_ifs. destruct u. esplits; eauto.\n remember (NatMap.remove tid (key_set wobl)) as M. clear HeqM.\n apply NatMapP.F.elements_in_iff. exists (). apply SetoidList.InA_alt.\n exists (k, ()). ss.\n }\n des. subst. unfold Prism.preview; ss. des_ifs.\n exfalso. eapply NatMap.remove_1. reflexivity. eapply A0.\n }\n { eapply FinFun.Injective_map_NoDup.\n { unfold FinFun.Injective. i. des_ifs. destruct u, u0. ss. }\n apply NoDupA_NoDup. apply NatMap.elements_3w.\n }\n iIntros \"MYDUTY WHITES\". rred.\n\n (* close invariant *)\n iPoseProof (OwnM_Upd with \"[B1 MYW]\") as \"> B1\".\n 2:{ instantiate (1:= (Auth.black (Some wobl: NatMapRA.t nat)) ⋅ (Auth.white (NatMapRA.singleton tid k: NatMapRA.t nat))). iSplitL \"B1\"; iFrame. }\n { eapply Auth.auth_dealloc. eapply NatMapRA.remove_local_update. }\n rewrite <- key_set_pull_rm_eq in *. remember (NatMap.remove tid wobl) as new_wobl.\n\n iPoseProof (MonotonePCM.list_prop_sum_cons_unfold with \"MYDUTY\") as \"[MYDUTY _]\".\n iPoseProof (duty_to_black with \"MYDUTY\") as \"MYBEX\".\n iPoseProof (FairRA.blacks_fold with \"[BLKS MYBEX]\") as \"BLKS\".\n 2:{ iFrame. }\n { instantiate (1:=\n (λ id : nat + (Mod.ident ClientImpl.omod + (Mod.ident (WMem.mod) + NatMap.key)),\n ∃ t : NatMap.key, id = inr (inr (inr t)) ∧ ¬ NatMap.In (elt:=nat) t new_wobl)).\n i. ss. des. destruct (tid_dec t tid) eqn:DEC.\n - clarify. auto.\n - left. esplits; eauto. ii. apply IN0. subst. apply NatMapP.F.remove_in_iff.\n split; auto.\n }\n\n ss. repeat (unfold Lens.set; ss).\n iClear \"MYB\".\n clear Heqnew_wobl FIND wd k wobl.\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (ObligationRA.alloc o_w_cor) as \"> [% [[NEWB NEWW] NEWP]]\".\n iPoseProof (OwnM_Upd with \"[B2 LOCK]\") as \"> B2\".\n 2:{ instantiate (1:= (Auth.black (Excl.just j: Excl.t nat)) ⋅ (Auth.white (Excl.just j: Excl.t nat))). iSplitL \"B2\"; iFrame. }\n { eapply Auth.auth_update. do 2 instantiate (1:=Excl.just k).\n clear. ii. des. split.\n - ur. ss.\n - ur. ur in FRAME. des_ifs.\n }\n iDestruct \"B2\" as \"[B2 LOCK]\". clear j.\n\n iAssert (natmap_prop_sum new_wobl (fun tid0 idx => ObligationRA.correl (inr (inr (inr tid0))) idx (Ord.omega × Ord.omega)%ord)) with \"[SUM]\" as \"#CORs\".\n { iApply natmap_prop_sum_impl. 2: iFrame.\n i. iIntros \"[_ [CORS _]]\". iFrame.\n }\n iPoseProof (ObligationRA.white_mon with \"NEWW\") as \"> NEWW\".\n { unfold o_w_cor. instantiate (1:= (Ord.omega × (Ord.S (Ord.S num_line)))%ord).\n apply Ord.lt_le. apply Jacobsthal.lt_mult_r.\n rewrite <- Ord.from_nat_S. rewrite <- Ord.from_nat_S. apply Ord.omega_upperbound.\n rewrite <- Ord.from_nat_O. apply Ord.omega_upperbound.\n }\n iPoseProof (ObligationRA.white_eq with \"NEWW\") as \"NEWW\".\n { apply Jacobsthal.mult_S. }\n iPoseProof (ObligationRA.white_split_eq with \"NEWW\") as \"[NEWW1 NEWW2]\".\n iPoseProof (ObligationRA.white_eq with \"NEWW2\") as \"NEWW2\".\n { apply Jacobsthal.mult_S. }\n iPoseProof (ObligationRA.white_split_eq with \"NEWW2\") as \"[NEWWTAX NEWW2]\".\n iPoseProof (ObligationRA.white_eq with \"NEWW1\") as \"NEWW1\".\n { symmetry. apply Jacobsthal.mult_1_l. }\n iPoseProof (ObligationRA.duty_alloc with \"DUTY NEWW1\") as \"> DUTY\".\n iPoseProof (ObligationRA.duty_correl_thread with \"DUTY\") as \"#NEWCORTH\".\n { ss. left; eauto. }\n\n (* need amps == need pendings; *)\n iAssert (natmap_prop_sum new_wobl (fun k _ => FairRA.white (inr (inr (inr k))) 1))%I with \"[WHITES]\" as \"WHITES\".\n { Transparent key_set. unfold key_set. rewrite <- list_map_elements_nm_map. unfold natmap_prop_sum.\n remember (NatMap.elements new_wobl) as ml. clear Heqml. rewrite List.map_map.\n iClear \"CORs NEWCORTH\". clear. iStopProof. induction ml.\n { iIntros \"SUM\". ss. }\n ss. des_ifs. iIntros \"[WH SUM]\". iFrame. iApply IHml. auto.\n }\n iPoseProof (natmap_prop_sum_impl2 with \"[WHITES]\") as \"CASES\".\n 2:{ iSplitR \"WHITES\". iApply \"CORs\". iApply \"WHITES\". }\n { i. ss. iIntros \"[COR WH]\". iApply (ObligationRA.correl_correlate with \"COR WH\"). }\n Unshelve. 2,3: auto.\n iPoseProof (natmap_prop_sum_pull_bupd with \"CASES\") as \"CASES\". iMod \"CASES\".\n iPoseProof (natmap_prop_sum_or_cases_l with \"CASES\") as \"[WHITEs|SHOT]\"; cycle 1.\n { iDestruct \"SHOT\" as \"[% [% [%FIND SHOT]]]\".\n iPoseProof (natmap_prop_sum_in with \"SUM\") as \"[_ [_ [PEND _]]]\". eapply FIND.\n iPoseProof (ObligationRA.pending_not_shot with \"PEND SHOT\") as \"FALSE\". ss.\n }\n iPoseProof \"NEWB\" as \"#NEWB\".\n iPoseProof (natmap_prop_sum_sepconj with \"[WHITEs]\") as \"WHITEs\".\n { iSplitR \"WHITEs\". 2: iApply \"WHITEs\".\n instantiate (1:=fun _ _ => ObligationRA.black k o_w_cor).\n iClear \"CORs NEWCORTH\". unfold natmap_prop_sum. remember (NatMap.elements new_wobl) as ml.\n clear. iStopProof. induction ml; ss. auto.\n iIntros \"#BLK\". des_ifs. iSplit; auto. iApply IHml. auto.\n }\n iPoseProof (natmap_prop_sum_impl with \"WHITEs\") as \"AMPs\".\n { i. ss. iIntros \"[BLK WHI]\".\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { symmetry. apply Jacobsthal.mult_1_l. }\n iPoseProof (ObligationRA.amplifier_intro with \"BLK WHI\") as \"AMP\". iApply \"AMP\".\n }\n iPoseProof (natmap_prop_sum_pull_bupd with \"AMPs\") as \"> AMPs\".\n\n iDestruct \"EXCL\" as \"[EXCL [EXCL2 EXCL3]]\".\n iPoseProof (black_white_update with \"B3 EXCL2\") as \">[B3 EXCL2]\".\n instantiate (1:= (tvw1, tt)).\n\n iMod (\"K1\" with \"[B1 B2 B3 MEM STGT BLKS SUM NEWP AMPs INGEX]\") as \"_\".\n { unfold lock_will_unlock. iExists true, tvw1, false, mem, new_wobl, k. iFrame. iSplitR \"INGEX\".\n - iRight. iFrame. auto.\n - iLeft. iFrame. auto.\n }\n { msubtac. }\n iApply stsim_discard. instantiate (1:=topset I). msubtac.\n\n iApply (stsim_yieldR with \"[DUTY TAXKEEP NEWWTAX]\"). msubtac.\n { iSplitL \"DUTY\". iFrame. iFrame. iApply ObligationRA.white_eq.\n { symmetry. apply Jacobsthal.mult_1_l. }\n iFrame.\n }\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n\n (* iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [I0B I0]]\". *)\n (* iDestruct \"I0\" as \"[% I0]\". iDestruct \"I0\" as \"[I01 [I02 [I03 I04]]]\". *)\n (* iPoseProof (black_white_equal with \"I0B EXCL\") as \"%\". subst. *)\n (* iAssert ( *)\n (* ((ObligationRA.pending k0 (/ 2) ** wpoints_to loc_X const_0 tvw1) *)\n (* ∨ (ObligationRA.shot k0 ** wpoints_to loc_X const_42 tvw1)) *)\n (* -∗ *)\n (* ((ObligationRA.pending k0 (/ 2) ** wpoints_to loc_X const_0 tvw') *)\n (* ∨ (ObligationRA.shot k0 ** wpoints_to loc_X const_42 tvw')) *)\n (* )%I with \"[]\" as \"I04a\". *)\n (* { iIntros \"I\". iDestruct \"I\" as \"[[A B] | [A B]]\". *)\n (* - iLeft. iFrame. iApply wpoints_to_view_mon. 2: iFrame. *)\n (* etrans. 2: eapply l0. apply View.join_r. *)\n (* - iRight. iFrame. iApply wpoints_to_view_mon. 2: iFrame. *)\n (* etrans. 2: eapply l0. apply View.join_r. *)\n (* } *)\n (* iPoseProof (\"I04a\" with \"I04\") as \"I04\". *)\n (* iPoseProof (black_white_update with \"I0B EXCL\") as \">[I0B EXCL]\". *)\n (* instantiate (1:= tvw1). *)\n (* iMod (\"K0\" with \"[I0B I01 I02 I03 I04]\") as \"_\". *)\n (* { iExists tvw1. iFrame. unfold thread1_will_write. iExists k0. iFrame. } *)\n (* msubtac. *)\n\n iPoseProof (\"SIM\" with \"[MYTH DUTY NEWW2 EXCL EXCL2 EXCL3 LOCK]\") as \"SIM\".\n { instantiate (1:= tvw'). iFrame. iSplit.\n { iPureIntro. etrans. 2: eapply l0. apply View.join_l. }\n iSplitL \"DUTY NEWW2 LOCK\". iExists k. iFrame.\n iExists _. iFrame. iPureIntro.\n etrans. 2: eapply l0. apply View.join_r.\n }\n iApply stsim_reset. iFrame.\n }\n\n Qed.\n\n Lemma AbsLock_unlock\n R_src R_tgt tid\n (src: thread void (sE unit) R_src)\n tgt\n r g\n (Q: R_src -> R_tgt -> iProp)\n l\n (tvw0 lvw: View.t)\n :\n ((OwnM (Excl.just tt: Excl.t unit))\n ∗\n (OwnM (Auth.white (Excl.just tvw0: Excl.t View.t)))\n ∗\n ((OwnM (Auth.white (Excl.just (lvw, tt): Excl.t (View.t * unit)))) ∗ (⌜View.le lvw tvw0⌝))\n ∗\n (∃ k, (ObligationRA.duty (inl tid) ((k, Ord.S Ord.O) :: l))\n ∗ (OwnM (Auth.white (Excl.just k: Excl.t nat)))\n ∗ (ObligationRA.taxes ((k, Ord.S Ord.O) :: l) 4%ord))\n )\n ∗\n (∀ tvw1,\n ((ObligationRA.duty (inl tid) l)\n ∗ (⌜View.le tvw0 tvw1⌝)\n )\n -∗\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tgt tvw1)))\n ⊢\n (stsim I tid (topset I) r g Q\n false false\n (trigger Yield;;; src)\n (tvw' <- OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (R:=View.t) (OMod.call \"unlock\" tvw0);; (tgt tvw'))).\n Proof.\n iIntros \"[[EXCLTT [EXCL [[EXCL2 %LVW] [% [DUTY [LOCK TAXES]]]]]] SIM]\".\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\".\n { instantiate (1:= 3%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX1]\".\n { instantiate (1:= 2%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX2]\".\n { instantiate (1:= 1%ord). apply OrdArith.lt_from_nat. lia. }\n iPoseProof (ObligationRA.taxes_single_is_tax with \"TAXES\") as \"TAX3\".\n\n rewrite close_itree_call. ss. rred. unfold OMod.emb_callee, emb_r. rewrite <- map_event_compose. rewrite <- plmap_compose.\n iApply (stsim_yieldR with \"[DUTY TAX]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n unfold AbsLockW.unlock_fun, Mod.wrap_fun. rred.\n iApply (stsim_yieldR with \"[DUTY TAX1]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT [BLKS [SUM [[CONTRA | CASE] INGS]]]]]]]\".\n { iDestruct \"CONTRA\" as \"[_ [_ [EXCL3 _]]]\".\n iPoseProof (white_white_excl with \"EXCL EXCL3\") as \"%FF\". inversion FF.\n }\n iDestruct \"CASE\" as \"[% [JPEND [JBLK [JCOR AMPs]]]]\". subst own.\n iApply stsim_getR. iSplit. iFrame. ss.\n\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (black_white_equal with \"B3 EXCL2\") as \"%EQ\". inv EQ.\n destruct (excluded_middle_informative (View.le lvw tvw0)).\n 2:{ rred. exfalso. clarify. }\n\n rred. iDestruct \"INGS\" as \"[[%INGF INGEXCL] | [_ CONTRA]]\".\n 2:{ iPoseProof (excl_unique with \"EXCLTT CONTRA\") as \"%FF\". inv FF. }\n subst ing. rred. ss. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred. ss. repeat (unfold Lens.set; ss).\n\n iPoseProof (black_white_equal with \"B2 LOCK\") as \"%EQ\". subst k.\n iMod (\"K1\" with \"[EXCLTT B1 B2 B3 MEM BLKS SUM STGT JPEND JBLK JCOR AMPs]\") as \"_\".\n { unfold lock_will_unlock. iExists true, lvw, true, mem, wobl, j. iFrame. iSplitR \"EXCLTT\".\n - iRight. iSplit. auto. iFrame.\n - iRight. iSplit. auto. iFrame.\n }\n msubtac.\n iApply (stsim_yieldR with \"[DUTY TAX2]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[B1 [B2 [MEM [STGT [BLKS [SUM [[CONTRA | CASE] INGS]]]]]]]\".\n { iDestruct \"CONTRA\" as \"[_ [_ [_ [CONTRA _]]]]\".\n iPoseProof (white_white_excl with \"EXCL2 CONTRA\") as \"%FF\". inversion FF.\n }\n iDestruct \"CASE\" as \"[% [JPEND [JBLK [JCOR AMPs]]]]\". subst own.\n\n iDestruct \"B2\" as \"[B2 B3]\".\n iPoseProof (black_white_equal with \"B3 EXCL2\") as \"%EQ\". inv EQ.\n iDestruct \"INGS\" as \"[[_ CONTRA] | [%INGT EXCLTT]]\".\n { iPoseProof (excl_unique with \"INGEXCL CONTRA\") as \"%FF\". inv FF. }\n subst ing. rred.\n\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw_V. rewrite put_rmw. rred.\n (* iApply stsim_chooseR. iIntros \"%\". rename x into tvw_V. rred. *)\n iApply (stsim_rmwR with \"STGT\"). iIntros \"STGT\". rred.\n\n iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw'. rred.\n\n iPoseProof (black_white_equal with \"B2 LOCK\") as \"%\". subst.\n iPoseProof (black_white_update with \"B3 EXCL2\") as \">[B3 EXCL2]\".\n instantiate (1:= (tvw_V, tt)).\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [I0B I0]]\".\n iDestruct \"I0\" as \"[% I0]\". iDestruct \"I0\" as \"[I01 [I02 [I03 I04]]]\".\n iPoseProof (black_white_equal with \"I0B EXCL\") as \"%\". subst.\n iAssert (\n ((ObligationRA.pending k (/ 2) ** wpoints_to loc_X const_0 tvw0)\n ∨ (ObligationRA.shot k ** wpoints_to loc_X const_42 tvw0))\n -∗\n ((ObligationRA.pending k (/ 2) ** wpoints_to loc_X const_0 tvw_V)\n ∨ (ObligationRA.shot k ** wpoints_to loc_X const_42 tvw_V))\n )%I with \"[]\" as \"I04a\".\n { iIntros \"I\". iDestruct \"I\" as \"[[A B] | [A B]]\".\n - iLeft. iFrame. iApply wpoints_to_view_mon. 2: iFrame. auto.\n - iRight. iFrame. iApply wpoints_to_view_mon. 2: iFrame. auto.\n }\n iPoseProof (\"I04a\" with \"I04\") as \"I04\".\n iPoseProof (black_white_update with \"I0B EXCL\") as \">[I0B EXCL]\".\n instantiate (1:= tvw_V).\n\n iMod (\"K0\" with \"[I0B I01 I02 I03 I04]\") as \"_\".\n { iExists tvw_V. iFrame. unfold thread1_will_write. iExists k. iFrame. }\n iMod (\"K1\" with \"[INGEXCL EXCLTT EXCL EXCL2 LOCK B1 B2 B3 MEM BLKS SUM STGT]\") as \"_\".\n { unfold lock_will_unlock. iExists false, tvw_V, false, mem0, wobl0, j. iFrame. iSplitR \"INGEXCL\".\n - iLeft. iSplit. auto. iFrame.\n - iLeft. iSplit. auto. iFrame.\n }\n { msubtac. }\n iPoseProof (ObligationRA.pending_shot with \"JPEND\") as \"> SHOT\".\n iPoseProof (ObligationRA.duty_done with \"DUTY SHOT\") as \"> DUTY\".\n\n (* iApply stsim_chooseR. iIntros \"%\". destruct x. rename x into tvw''. rred. *)\n (* iApply stsim_tauR. rred. *)\n\n iApply (stsim_yieldR with \"[DUTY TAX3]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iPoseProof (ObligationRA.tax_cons_unfold with \"TAX3\") as \"[_ TAX2]\". iFrame.\n }\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_reset. iApply \"SIM\". iFrame.\n iPureIntro. etrans. 2: eapply l2. auto.\n\n Qed.\n\n Lemma correct_thread1 tid:\n (∃ k, (own_thread tid)\n ∗ (ObligationRA.duty (inl tid) [(k, Ord.from_nat 1)])\n ∗ (ObligationRA.taxes\n [(k, Ord.from_nat 1)]\n ((((Ord.omega × Ord.omega) × Ord.omega) ⊕ ((Ord.S Ord.O) × (o_w_cor))) ⊕ 10)%ord\n )\n ∗ (OwnM (OneShot.shot k))\n ∗ (ObligationRA.pending k (/ 2))\n )\n ⊢\n (stsim I tid (topset I) ibot7 ibot7\n (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n false false\n (ClientSpec.thread1 tt)\n (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (ClientImpl.thread1 tt))).\n Proof.\n iIntros \"[% [TH [DUTY [TAXES [#KSHOT KPENDh]]]]]\".\n unfold ClientSpec.thread1, ClientImpl.thread1. rred.\n iPoseProof (ObligationRA.taxes_ord_split_one with \"TAXES\") as \"> [TAXES TAX]\".\n { apply Hessenberg.lt_add_r. instantiate (1:=9). apply OrdArith.lt_from_nat. auto. }\n iApply AbsLock_lock. iFrame.\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:=9). rred.\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1 TAX]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY _\". rred. unfold WMem.store_fun, Mod.wrap_fun. rred.\n\n iopen 0 \"I0\" \"K0\".\n iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw0.\n\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n 2:{ iDestruct \"i0SHOT\" as \"[i0SHOT PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"KPENDh i0SHOT\") as \"FALSE\". ss.\n }\n iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_sum with \"KPENDh i0PENDh\") as \"KPEND\".\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\". rred.\n destruct x. destruct x as [[[lc1 to] sc1] mem1]. des. rename y into WRITE.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_store with \"i1MEM i0PTR\") as \"[%VW2 >[i1MEM i0PTR]]\".\n eapply WRITE. eauto. eauto. eauto. eauto.\n\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n (* instantiate (1:= [inr (inl (loc_X, to))]) in IN. *)\n (* inv IN; ss. des_ifs. *)\n { econs. }\n { auto. }\n iIntros \"_ _\". rred. rewrite put_rmw. rred.\n iApply (stsim_rmwR with \"i1STGT\"). iIntros \"i1STGT\". rred. iApply stsim_tauR. rred.\n\n rewrite Qp.inv_half_half.\n iPoseProof (ObligationRA.pending_shot with \"KPEND\") as \"> #OBLKSHOT\".\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists (TView.TView.cur tview). iFrame.\n unfold thread1_will_write. iExists k. iFrame. iSplitR; auto. }\n\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, _, wobl, j0. iFrame. }\n msubtac.\n\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n\n iPoseProof (ObligationRA.duty_permutation with \"DUTY\") as \"DUTY\".\n { eapply perm_swap. }\n iPoseProof (ObligationRA.duty_done with \"DUTY OBLKSHOT\") as \"> DUTY\".\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"EXCL EXCL2 EXCLTT LOCK WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. eapply VW1. auto. }\n iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW3]\". rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_ret. iApply MUpd_intro. iFrame. auto.\n\n Qed.\n\n Lemma correct_thread2 tid:\n ((own_thread tid)\n ∗ (ObligationRA.duty (inl tid) [])\n )\n ⊢\n (stsim I tid (topset I) ibot7 ibot7\n (fun r_src r_tgt => own_thread tid ** ObligationRA.duty (inl tid) [] ** ⌜r_src = r_tgt⌝)\n false false\n (ClientSpec.thread2 tt)\n (OMod.close_itree ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod) (ClientImpl.thread2 tt))).\n Proof.\n iIntros \"[MYTH DUTY]\".\n unfold ClientSpec.thread2, ClientImpl.thread2. rred.\n iopen 0 \"I0\" \"K0\".\n iDestruct \"I0\" as \"[% [EXCLB I0]]\". iDestruct \"I0\" as \"[% [[% #KBLK] [#KCOR [#KSHOT I0]]]]\".\n iMod (\"K0\" with \"[EXCLB I0]\") as \"_\".\n { iExists tvw. iFrame. unfold thread1_will_write. iExists k. iFrame. auto. }\n { msubtac. }\n\n (* induction *)\n rred. iApply stsim_discard.\n { instantiate (1:=topset I). msubtac. }\n remember View.bot as tvw_base. clear tvw Heqtvw_base.\n iStopProof. revert tid k tvw_base. pattern n. revert n.\n apply (well_founded_induction Ord.lt_well_founded). intros n IH. intros.\n iIntros \"[#[KBLK [KCOR KSHOT]] [MYTH DUTY]]\".\n rewrite unfold_iter_eq. rred.\n iApply AbsLock_lock. iSplitL \"MYTH DUTY\".\n { iFrame. }\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:= 9). rred.\n\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY OWHTH\". rred. unfold WMem.load_fun, Mod.wrap_fun. rred.\n\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw0.\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n\n (* iterate case *)\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW2 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR i0PENDh]\") as \"_\".\n { iExists (TView.TView.cur tview). iFrame. unfold thread1_will_write. iExists k. iFrame. iSplitR; auto. iLeft; iFrame. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW3]\". rred. iApply stsim_tauR. rred.\n iClear \"i0KSHOT\".\n iPoseProof (ObligationRA.correl_thread_correlate with \"KCOR OWHTH\") as \"> [KWHI|#KDONE]\".\n (* thread 1 not done; induction *)\n { iPoseProof (ObligationRA.black_white_decr_one with \"KBLK KWHI\") as \"> [% [#KBLK2 %DECR]]\".\n iClear \"KBLK\". iApply stsim_reset. iApply IH. apply DECR. iFrame. eauto.\n }\n\n (* thread 1 done; exit *)\n { iClear \"KBLK KCOR\". clear_upto I.\n rewrite unfold_iter_eq. rred.\n iApply stsim_reset. iApply AbsLock_lock. iSplitL \"MYTH DUTY\".\n { iFrame. }\n iIntros \"% [%VW0 [MYTH [SUM1 [SUM2 EXCLTT]]]]\".\n iDestruct \"SUM1\" as \"[% [DUTY [WHI LOCK]]]\". iDestruct \"SUM2\" as \"[% [EXCL [EXCL2 %VW1]]]\".\n instantiate (1:= 9). rred.\n\n iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"i0PENDh KDONE\") as \"FALSE\". ss.\n }\n iDestruct \"i0SHOT\" as \"[_ i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n rewrite close_itree_call. ss. unfold OMod.emb_callee, emb_l. rewrite <- map_event_compose. rewrite <- plmap_compose. rred.\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n msubtac.\n iPoseProof (ObligationRA.white_eq with \"WHI\") as \"WHI\".\n { rewrite Ord.from_nat_S. rewrite Jacobsthal.mult_S. reflexivity. }\n iPoseProof (ObligationRA.white_split_eq with \"WHI\") as \"[WHI1 WHI2]\".\n iApply (stsim_yieldR with \"[DUTY WHI1]\"). msubtac.\n { iSplitL \"DUTY\". iFrame.\n iApply ObligationRA.tax_cons_fold. iSplitL \"WHI1\"; auto.\n iApply ObligationRA.white_eq. 2: iFrame. symmetry; apply Jacobsthal.mult_1_l.\n }\n iIntros \"DUTY _\". rred. unfold WMem.load_fun, Mod.wrap_fun. rred.\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iClear \"i0KSHOT\". iopen 0 \"I0\" \"K0\". iDestruct \"I0\" as \"[% [EXCLB I0]]\".\n iDestruct \"I0\" as \"[% [i0BLK [i0KCOR [#i0KSHOT [i0PEND | i0SHOT]]]]]\".\n { iDestruct \"i0PEND\" as \"[i0PENDh i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (ObligationRA.pending_not_shot with \"i0PENDh KDONE\") as \"FALSE\". ss.\n }\n iDestruct \"i0SHOT\" as \"[_ i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n iPoseProof (black_white_equal with \"EXCLB EXCL\") as \"%EQ\". subst tvw4.\n\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW3 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw3, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 promises to released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW4]\". rred.\n\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_observe. iIntros. rred.\n iApply stsim_tauR. rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_ret.\n iApply MUpd_intro. iFrame. auto.\n }\n }\n\n { iDestruct \"i0SHOT\" as \"[#KDONE i0PTR]\".\n iPoseProof (OwnM_valid with \"[KSHOT i0KSHOT]\") as \"%AGR\".\n { instantiate (1:= (OneShot.shot k) ⋅ (OneShot.shot k0)). iSplitL \"KSHOT\"; auto. }\n apply OneShot.shot_agree in AGR. subst k0.\n\n iopen 1 \"I1\" \"K1\". do 6 (iDestruct \"I1\" as \"[% I1]\").\n iDestruct \"I1\" as \"[i1B1 [i1B2 [i1MEM [i1STGT I1]]]]\".\n iApply stsim_getR. iSplit. iFrame. rred.\n iApply stsim_chooseR. iIntros \"%\".\n destruct x. destruct x as [[lc1 val] to]. des. rename y into READ. rred.\n iPoseProof (wpoints_to_view_mon with \"i0PTR\") as \"i0PTR\". eapply VW1.\n iPoseProof (wmemory_ra_load with \"i1MEM i0PTR\") as \"[i1MEM [%VW3 >i0PTR]]\".\n eapply READ. eauto. eauto. des. subst val.\n iPoseProof (black_white_update with \"EXCLB EXCL\") as \">[EXCLB EXCL]\".\n instantiate (1:= TView.TView.cur (Local.Local.tview lc1)). destruct lc1. ss. rred.\n iApply stsim_fairR.\n { i. instantiate (1:= []). ss. clear - IN.\n unfold prism_fmap, WMem.missed in IN. des_ifs.\n }\n { i. instantiate (1:=[]) in IN. inv IN. }\n { econs. }\n { auto. }\n iIntros \"_ _\". rred.\n iApply stsim_tauR. rred.\n\n iMod (\"K0\" with \"[EXCLB i0BLK i0KCOR i0PTR]\") as \"_\".\n { iExists _. iFrame. unfold thread1_will_write. iExists _. iFrame. iSplitR; auto. }\n iMod (\"K1\" with \"[i1B1 i1B2 i1MEM i1STGT I1]\") as \"_\".\n { unfold lock_will_unlock. iExists own, tvw0, ing, mem, wobl, j0. iFrame. }\n msubtac.\n clear own mem wobl j0 promises to released READ.\n iPoseProof (ObligationRA.white_mon with \"WHI2\") as \">WHI2\".\n { instantiate (1:= (Ord.omega × 4)%ord). apply Jacobsthal.le_mult_r. apply OrdArith.le_from_nat. lia. }\n iApply stsim_reset. iApply AbsLock_unlock. iSplitL \"LOCK EXCLTT EXCL EXCL2 WHI2 DUTY\".\n { iSplitL \"EXCLTT\". iFrame. iSplitL \"EXCL\". iFrame. iSplitL \"EXCL2\".\n { iFrame. iPureIntro. etrans. 2: eauto. auto. }\n iFrame. iExists j. iFrame. iApply ObligationRA.taxes_cons_fold. iSplitL; auto.\n iApply ObligationRA.white_eq. 2: iFrame.\n rewrite Jacobsthal.mult_1_l. reflexivity.\n }\n iIntros \"% [DUTY %VW4]\". rred.\n\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred. iApply stsim_tauR. rred.\n iApply stsim_observe. iIntros. rred.\n iApply stsim_tauR. rred.\n iApply (stsim_sync with \"[DUTY]\"). msubtac. iFrame.\n iIntros \"DUTY _\". rred.\n iApply stsim_tauR. rred.\n iApply stsim_ret.\n iApply MUpd_intro. iFrame. auto.\n }\n\n Qed.\n\nEnd SIM.\n\nFrom Fairness Require Import WeakestAdequacy.\n\nModule LockClientCorrect.\n Definition config := [(\"thread1\", tt↑); (\"thread2\", tt↑)].\n\n Local Instance Σ: GRA.t:=\n GRA.of_list [monoRA;\n ThreadRA;\n (stateSrcRA (unit));\n (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))));\n (identSrcRA (void));\n (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type);\n ObligationRA.t;\n (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type);\n EdgeRA;\n (@FiniteMap.t (OneShot.t unit));\n wmemRA;\n (Excl.t unit);\n (Excl.t (unit * unit));\n (OneShot.t nat);\n (Region.t (thread_id * nat));\n (@FiniteMap.t (Consent.t nat));\n (Auth.t (Excl.t nat));\n (Auth.t (Excl.t View.t));\n (Auth.t (Excl.t (View.t * unit)));\n (Auth.t (NatMapRA.t nat))].\n\n Local Instance MONORA: @GRA.inG monoRA Σ := (@GRA.InG _ _ 0 (@eq_refl _ _)).\n Local Instance THDRA: @GRA.inG ThreadRA Σ := (@GRA.InG _ _ 1 (@eq_refl _ _)).\n Local Instance STATESRC: @GRA.inG (stateSrcRA (unit)) Σ := (@GRA.InG _ _ 2 (@eq_refl _ _)).\n Local Instance STATETGT: @GRA.inG (stateTgtRA ((OMod.closed_state ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod)))) Σ := (@GRA.InG _ _ 3 (@eq_refl _ _)).\n Local Instance IDENTSRC: @GRA.inG (identSrcRA (void)) Σ := (@GRA.InG _ _ 4 (@eq_refl _ _)).\n Local Instance IDENTTGT: @GRA.inG (identTgtRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ := (@GRA.InG _ _ 5 (@eq_refl _ _)).\n Local Instance OBLGRA: @GRA.inG ObligationRA.t Σ := (@GRA.InG _ _ 6 (@eq_refl _ _)).\n Local Instance ARROWRA: @GRA.inG (ArrowRA (OMod.closed_ident ClientImpl.omod (ModAdd (WMem.mod) AbsLockW.mod))%type) Σ := (@GRA.InG _ _ 7 (@eq_refl _ _)).\n Local Instance EDGERA: @GRA.inG EdgeRA Σ := (@GRA.InG _ _ 8 (@eq_refl _ _)).\n Local Instance ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ := (@GRA.InG _ _ 9 (@eq_refl _ _)).\n Local Instance WMEMRA: @GRA.inG wmemRA Σ := (@GRA.InG _ _ 10 (@eq_refl _ _)).\n Local Instance EXCL: @GRA.inG (Excl.t unit) Σ := (@GRA.InG _ _ 11 (@eq_refl _ _)).\n Local Instance EXCL2: @GRA.inG (Excl.t (unit * unit)) Σ := (@GRA.InG _ _ 12 (@eq_refl _ _)).\n Local Instance ONESHOTRA: @GRA.inG (OneShot.t nat) Σ := (@GRA.InG _ _ 13 (@eq_refl _ _)).\n Local Instance REGIONRA: @GRA.inG (Region.t (thread_id * nat)) Σ := (@GRA.InG _ _ 14 (@eq_refl _ _)).\n Local Instance CONSENTRA: @GRA.inG (@FiniteMap.t (Consent.t nat)) Σ := (@GRA.InG _ _ 15 (@eq_refl _ _)).\n Local Instance AUTHNRA: @GRA.inG (Auth.t (Excl.t nat)) Σ := (@GRA.InG _ _ 16 (@eq_refl _ _)).\n Local Instance AUTHVWRA: @GRA.inG (Auth.t (Excl.t View.t)) Σ := (@GRA.InG _ _ 17 (@eq_refl _ _)).\n Local Instance AUTHVWRA2: @GRA.inG (Auth.t (Excl.t (View.t * unit))) Σ := (@GRA.InG _ _ 18 (@eq_refl _ _)).\n Local Instance AUTHNMNRA: @GRA.inG (Auth.t (NatMapRA.t nat)) Σ := (@GRA.InG _ _ 19 (@eq_refl _ _)).\n\n\n Let init_res :=\n (GRA.embed (OneShot.pending nat 1))\n ⋅ GRA.embed (Auth.black (Some (NatMap.empty nat) : NatMapRA.t nat))\n ⋅ GRA.embed (Auth.black (Excl.just 0 : Excl.t nat) ⋅ Auth.white (Excl.just 0 : Excl.t nat))\n ⋅ GRA.embed (Auth.black (Excl.just View.bot : Excl.t View.t) ⋅ Auth.white (Excl.just View.bot : Excl.t View.t))\n ⋅ GRA.embed (Auth.black (Excl.just (View.bot, ()) : Excl.t (View.t * unit))\n ⋅ Auth.white (Excl.just (View.bot, ()) : Excl.t (View.t * unit)))\n ⋅ GRA.embed (Excl.just (tt,tt): Excl.t (unit * unit))\n ⋅ GRA.embed (Excl.just () : Excl.t unit)\n ⋅ GRA.embed (wmem_init_res loc_X (Loc.of_nat 5))\n .\n\n Lemma correct:\n UserSim.sim ClientSpec.mod ClientImpl.mod (prog2ths ClientSpec.mod config) (prog2ths ClientImpl.mod config).\n Proof.\n eapply WSim.whole_sim_implies_usersim. econs.\n { instantiate (1:=init_res). rr. splits.\n { unfold init_res, default_initial_res. disj_tac. }\n { ndtac. }\n { unfold init_res. grawf_tac.\n { ur. auto. }\n { ur. split; auto.\n { eexists. eapply URA.unit_idl. }\n { ur. auto. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. split.\n { eexists _. rewrite URA.unit_idl. eapply URA.unit_id. }\n { ur. ss. }\n }\n { ur. ss. }\n { ur. ss. }\n { apply wmem_init_res_wf. ss. }\n }\n }\n unfold init_res. repeat rewrite <- GRA.embed_add.\n eexists _. iIntros \"[[[[[[[[A B] [C0 C1]] [D0 D1]] [E0 E1]] F] G] H] M]\".\n iModIntro.\n iExists [(∃ tvw, (OwnM (Auth.black (Excl.just tvw: Excl.t View.t)))\n ∗ (thread1_will_write tvw))%I;\n lock_will_unlock].\n iPoseProof (init_sat with \"[A B C0 C1 D0 D1 E0 E1 F G H M]\") as \"> [[% [H0 H1]] [H2 [[% [H3 [H5 [H6 [H7 H8]]]]] H4]]]\".\n { instantiate (1:=1). instantiate (1:=0). ss. }\n { iFrame. }\n iIntros \"INIT\".\n iModIntro. ss. iFrame. iSplitL \"H0 H1\".\n { unfold nth_default. ss. iExists _. iFrame. }\n unfold MonotonePCM.natmap_prop_sum. ss.\n iSplitL \"H3 H5 H6 H7 H8\".\n { unfold fn2th. ss. unfold Mod.wrap_fun. lred. rred.\n iApply stsim_bind_top. iApply (stsim_wand with \"[H3 H5 H6 H7 H8]\").\n { iApply correct_thread1. iExists k. iFrame. }\n { iIntros (? ?) \"[H %]\". iModIntro. rred. iApply stsim_ret. iModIntro.\n iFrame. subst. auto.\n }\n }\n { unfold fn2th. ss. unfold Mod.wrap_fun. iSplitL; auto. lred. rred.\n iApply stsim_bind_top. iApply (stsim_wand with \"[H4]\").\n { iApply correct_thread2. iFrame. }\n { iIntros (? ?) \"[H %]\". iModIntro. rred. iApply stsim_ret. iModIntro.\n iFrame. subst. auto.\n }\n }\n Qed.\nEnd LockClientCorrect.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/example/LockClient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.21733753118592733, "lm_q1q2_score": 0.12050724197001249}} {"text": "From ITree Require Import ITree.\nFrom compcert Require Import Maps AST Values Memory Globalenvs Ctypes.\nFrom compcert Require Coqlib Clight Clightdefs.\nFrom Paco Require Import paco.\n\nRequire Import Arith ZArith Bool.\nRequire Import String List Lia.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt ITreeTac.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import OSModel OSNodes.\nRequire Import ProgSem CProgEventSem.\nRequire Import ProgSim CProgSimLemmas.\nRequire Import RTSysEnv MWITree.\n\n(* Require Import SystemParams. *)\n(* Require Import SystemDefs ITreeSpec. *)\n(* Require Import SystemEventSem. *)\nRequire Import config_prm main_prm SystemProgs.\nRequire Import dev.\nRequire Import VerifProgBase.\nRequire Import VerifMainUtil.\nRequire Import PALSSystem.\n\nRequire Import AcStSystem.\nRequire Import LinkDevice.\nRequire Import SpecDevice.\nRequire Import VerifDevice_Base.\n(* Require Import VerifController_Sync VerifController_Updq. *)\n\nImport Clight Clightdefs.\nImport ITreeNotations.\n(* Import ActiveStandby. *)\n\nImport DevState.\n\nSet Nested Proofs Allowed.\nLocal Transparent Archi.ptr64.\nLocal Opaque Z.of_nat Z.to_nat.\nArguments Nat.mul: simpl never.\n\nOpaque globalenv.\n\nLocal Open Scope Z.\n\n\nSection VERIF_FUNC.\n Variable tid: nat.\n Variable cprog: Clight.program.\n Variable r: nat -> itree progE unit -> Clight.state -> Prop.\n\n Notation prog := (prog_of_clight cprog).\n Notation ge := (globalenv cprog).\n\n Hypothesis RANGE_TID: (tid < num_tasks)%nat.\n\n Hypothesis GENV_PROPS\n : genv_props (globalenv cprog)\n (main_gvar_ilist tid ++ dev_gvar_ilist)\n (main_gfun_ilist ++ dev_gfun_ilist)\n (main_cenv_ilist ++ dev_cenv_ilist).\n\n Let GENV_PROPS_MAIN\n : genv_props (globalenv cprog)\n (main_gvar_ilist tid)\n (main_gfun_ilist)\n (main_cenv_ilist).\n Proof.\n eapply genv_props_incl.\n - apply GENV_PROPS.\n - apply incl_appl. ss.\n - apply incl_appl. ss.\n - apply incl_appl. ss.\n Qed.\n\n\n Definition idx_sync: nat := 20.\n\n Lemma sim_sync_dev_state\n (itr: itree progE unit)\n (m: mem) (k: cont) (idx_ret: nat)\n st inb\n b_dst b_mst ofs_inb\n (BLOCKS_DIFF: b_dst <> b_mst)\n (CALL_CONT: is_call_cont k)\n (WF_ST: DevState.wf st)\n (MEM_DST: mem_dst_blk m st b_dst)\n (MEM_MSTORE: Mem_inbox m b_mst ofs_inb inb)\n (RANGE_OFS_HB: 0 <= ofs_inb <= 4 + inb_sz)\n (SIM_RET:\n forall m' st'\n (ST': st' = sync_dev_state inb st)\n (MEM_DST: mem_dst_blk m' st' b_dst)\n (MEM_CH_BLK: mem_changed_block b_dst m m')\n ,\n paco3 (_sim_itree prog) r\n idx_ret itr\n (Returnstate Vundef k m'))\n : paco3 (_sim_itree prog) r\n (idx_ret + idx_sync)%nat itr\n (Callstate (Internal f_sync_dev_state)\n [Vptr b_mst (Ptrofs.repr ofs_inb);\n Vptr b_dst Ptrofs.zero] k m).\n Proof.\n unfold idx_sync.\n start_func.\n { econs. }\n\n hexploit (in_cenv_ilist _inbox_t); [sIn|].\n intro CO_INBOX.\n hexploit (in_cenv_ilist _msg_entry_t); [sIn|].\n intro CO_MENTRY.\n hexploit (in_cenv_ilist __dev_state); [sIn|].\n intro CO_DEV_STATE.\n\n pose proof ptr_range_mstore as PRANGE_MSTORE.\n replace (Z.of_nat (4 + inb_nsz + inb_nsz)) with\n (4 + inb_sz + inb_sz) in PRANGE_MSTORE by nia.\n\n assert (PRANGE1: mentry_sz * 3 <= inb_sz).\n { hexploit (within_inb_nsz1 3).\n { unfold num_tasks. ss. nia. }\n nia.\n }\n\n fw. fw. fw.\n { econs. eval_comput.\n rewrite CO_INBOX. s.\n change main_prm._msg_entry_t with _msg_entry_t.\n rewrite CO_MENTRY.\n unfold align_attr, Coqlib.align. s.\n repr_tac.\n rewrite Z.add_0_r.\n rewrite Z.mul_1_r. ss.\n }\n upd_lenv.\n\n fw. fw. fw.\n { econs. eval_comput.\n rewrite CO_INBOX. s.\n change main_prm._msg_entry_t with _msg_entry_t.\n rewrite CO_MENTRY.\n unfold align_attr, Coqlib.align. s.\n repr_tac.\n rewrite Z.add_0_r. ss.\n }\n upd_lenv.\n\n r in MEM_MSTORE. des.\n rewrite iForall_nth in MSG_ENTRIES.\n\n hexploit (nth_error_Some2 _ inb 1%nat).\n { rewrite NUM_ENTRIES.\n unfold num_tasks. ss. nia. }\n i. des. renames e1 NTH_EX into ment1 MENT1.\n hexploit (nth_error_Some2 _ inb 2%nat).\n { rewrite NUM_ENTRIES.\n unfold num_tasks. ss. nia. }\n i. des. renames e1 NTH_EX into ment2 MENT2.\n\n hexploit (MSG_ENTRIES 1%nat).\n rewrite MENT1. s. intro MEM_MENT1.\n hexploit (MSG_ENTRIES 2%nat).\n rewrite MENT2. s. intro MEM_MENT2.\n\n eapply Mem_msg_entry_inv2 in MEM_MENT1. des.\n renames MENT_RCV MENT_CONT into MENT_RCV1 MENT_CONT1.\n eapply Mem_msg_entry_inv2 in MEM_MENT2. des.\n renames MENT_RCV MENT_CONT into MENT_RCV2 MENT_CONT2.\n\n fw. fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_MENTRY. s.\n unfold align_attr, Coqlib.align. s.\n rewrite Ptrofs.add_zero.\n repr_tac.\n\n rewrite Nat.mul_1_r in MENT_RCV1.\n rewrite MENT_RCV1. reflexivity.\n - instantiate (1:= if ment1 then true else false).\n destruct ment1; ss.\n }\n\n assert (STORE: exists m',\n Mem.store Mint8signed\n m b_dst 0 (Vint (Int.repr 1)) = Some m').\n { apply inhabited_sig_to_exists.\n econs.\n apply Mem.valid_access_store.\n rr. split; ss.\n 2: { apply Z.divide_1_l. }\n ii. apply MEM_DST. nia. }\n des.\n\n unfold sync_dev_state in SIM_RET.\n erewrite nth_error_nth in SIM_RET; eauto.\n erewrite nth_error_nth in SIM_RET; eauto.\n\n destruct ment1.\n { (* Be owner *)\n fw.\n { econs. eval_comput. ss. }\n upd_lenv.\n fw. fw.\n { econs.\n - eval_comput. ss.\n - ss.\n }\n rewrite Int.eq_false by ss. s.\n\n fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero. ss.\n - eval_comput. ss.\n - s. ss.\n - eval_comput.\n rewrite sign_ext_byte_range by range_stac.\n apply STORE.\n }\n\n fw.\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n - eapply store_set_owner_status; eauto.\n - eapply Mem.store_unchanged_on; eauto.\n }\n\n fw.\n { econs. eval_comput.\n rewrite CO_MENTRY. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero.\n repr_tac.\n\n replace (mentry_sz * 2) with (Z.of_nat (mentry_nsz * 2)) by nia.\n rewrite MENT_RCV2.\n instantiate (1:= if ment2 then Vtrue else Vfalse).\n destruct ment2; ss.\n }\n upd_lenv.\n\n fw. fw.\n { econs.\n - eval_comput. ss.\n - instantiate (1:= if ment2 then true else false).\n destruct ment2; ss.\n }\n\n destruct ment2.\n { (* Be owner *)\n fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero. ss.\n - eval_comput. ss.\n - s. ss.\n - eval_comput.\n rewrite sign_ext_byte_range by range_stac.\n apply STORE.\n }\n\n fw.\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n - eapply store_set_owner_status; eauto.\n - eapply Mem.store_unchanged_on; eauto.\n }\n\n fw.\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n eapply Mem.unchanged_on_refl.\n Qed.\n\n\n Definition idx_ndmd: nat := 20.\n\n Lemma sim_get_new_demand\n (ktr_app: nat -> itree appE DevState.t)\n (ktr: list bool * DevState.t -> itree progE unit)\n (m: mem) (k: cont) (idx_ret: nat)\n txs sytm sh\n (CALL_CONT: is_call_cont k)\n (SIM_RET:\n forall (d: nat)\n (DMD_UBND: (d <= MAX_TIMEOUT)%nat),\n paco3 (_sim_itree prog) r\n idx_ret (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (ktr_app d)\n sh ;;\n ktr ret)\n (Returnstate (Vint (IntNat.of_nat d)) k m))\n : paco3 (_sim_itree prog) r\n (idx_ret + idx_ndmd)%nat\n (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (d <- get_new_demand ;;\n ktr_app d)\n sh ;;\n ktr ret)\n (Callstate (Internal f_get_new_demand)\n [] k m).\n Proof.\n unfold idx_ndmd.\n start_func.\n { econs. }\n ss.\n\n fw. clear STEP_ENTRY.\n fw. fw. fw.\n { step_fptr_tac. }\n\n unfold get_new_demand.\n pfold. econs 3.\n { r. ss.\n econs; eauto.\n - ss. econs 2; eauto; ss.\n { intros ? ? OSE. inv OSE; ss. }\n econs 1; eauto.\n - ss.\n }\n { erewrite (MWITree.unfold_interp_vis_sys\n tid dev_mod).\n 2: { simpl_itree_goal.\n simpl_itree_goal.\n ss. }\n unf_resum.\n simpl_itree_goal.\n econs 1.\n }\n { ss. }\n\n intros d_raw. i. ss.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT.\n existT_elim. subst.\n unf_resum. subst.\n inv MATCH_RETV. existT_elim. subst.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n pose (retz:= Int.signed ret).\n\n exists 1%nat. left.\n fw_tau (idx_ret + 30)%nat.\n { simpl_itree_goal. ss. }\n upd_lenv.\n\n fw. fw.\n { econs. eval_comput. ss. }\n upd_lenv.\n rewrite <- (Int.repr_signed ret) in LENV_EQUIV.\n\n fw. fw.\n { econs.\n - eval_comput. repr_tac0; cycle 1.\n { ss. }\n { r. apply Int.signed_range. }\n fold retz.\n reflexivity.\n (* replace 5 with (Z.of_nat MAX_TIMEOUT) by ss. *)\n (* rewrite Int.repr_signed *)\n (* rewrite <- Nat2Z_inj_ltb. *)\n (* reflexivity. *)\n - rewrite bool_val_of_bool. ss.\n }\n\n match goal with\n | |- context[ interp _ ?t _ ] =>\n remember t as itr eqn: ITREE\n end.\n symmetry in ITREE.\n simpl_itree_hyp ITREE.\n subst itr.\n\n fold retz.\n replace (MAX_TIMEOUT itree appE DevState.t)\n (ktr: list bool * DevState.t -> itree progE unit)\n (m: mem) (k: cont) (idx_ret: nat)\n st b_dst\n txs sytm sh\n (CALL_CONT: is_call_cont k)\n (WF_ST: DevState.wf st)\n (MEM_DST: mem_dst_blk m st b_dst)\n (SIM_RET:\n forall m' (st': t) dmd_new (retb: bool) retv\n (ST': st' = set_demand dmd_new st)\n (WF_ST': wf st')\n (MEM_DST: mem_dst_blk m' st' b_dst)\n (MEM_UNCH: mem_changed_block b_dst m m')\n (RETV: retv = if retb then Vtrue else Vfalse)\n ,\n paco3 (_sim_itree prog) r\n idx_ret (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (ktr_app (st', retb))\n sh ;;\n ktr ret)\n (Returnstate retv k m'))\n : paco3 (_sim_itree prog) r\n (idx_ret + idx_udmd)%nat\n (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (ret <- update_demand st ;;\n ktr_app ret)\n sh ;;\n ktr ret)\n (Callstate (Internal f_update_demand)\n [Vptr b_dst Ptrofs.zero] k m).\n Proof.\n unfold idx_udmd.\n start_func.\n { econs. }\n ss.\n\n hexploit (in_cenv_ilist __dev_state); [sIn|].\n intro CO_DEV_STATE.\n\n assert (MAX_TIMEOUT_BYTE_RANGE: Z.of_nat MAX_TIMEOUT < Byte.max_signed) by ss.\n\n fw. clear STEP_ENTRY.\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero_l.\n repr_tac.\n\n erewrite Mem.loadbytes_load; cycle 1.\n { apply MEM_DST. }\n { ss. solve_divide. }\n eval_comput.\n rewrite decode_byte.\n rewrite sign_ext_byte_range_u.\n 2: { inv WF_ST. s.\n range_stac. }\n rewrite Int_eq_repr_signed; cycle 1.\n { inv WF_ST. s. range_stac. }\n { range_stac. }\n\n replace 0 with (Z.of_nat O) by ss.\n rewrite Nat2Z_inj_eqb. ss.\n\n - rewrite bool_val_of_bool. ss.\n }\n\n unfold update_demand.\n\n destruct (Nat.eqb_spec (demand st) O)\n as [DMD_Z | DMD_NZ].\n 2: { (* ret 0 *)\n fw. fw.\n { econs.\n - eval_comput. reflexivity.\n - ss.\n - ss. }\n rewrite call_cont_is_call_cont by ss. s.\n\n simpl_itree_interp.\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n - instantiate (1:= demand st).\n destruct st; ss.\n - apply Mem.unchanged_on_refl.\n }\n simpl_itree_interp.\n\n fw. fw. fw.\n { step_fptr_tac. }\n\n red_idx (idx_ret + 20 + idx_ndmd)%nat.\n eapply sim_get_new_demand.\n { ss. }\n\n i.\n fw. upd_lenv.\n fw. fw.\n { econs. eval_comput.\n unfold IntNat.of_nat.\n rewrite sign_ext_byte_range by range_stac.\n reflexivity. }\n upd_lenv.\n\n fw. fw.\n { econs.\n - eval_comput.\n repr_tac.\n replace 0 with (Z.of_nat O) by ss.\n rewrite <- Nat2Z_inj_ltb. reflexivity.\n - ss. rewrite bool_val_of_bool. ss.\n }\n\n destruct (Nat.ltb_spec 0 d).\n 2: {\n fw. fw.\n { econs.\n - eval_comput. ss.\n - ss.\n - ss. }\n simpl_itree_interp.\n ss. rewrite call_cont_is_call_cont by ss.\n\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n - instantiate (1:= demand st).\n destruct st; ss.\n - eapply Mem.unchanged_on_refl.\n }\n\n assert (STORE: exists m',\n Mem.store Mint8signed m b_dst 1\n (Vint (IntNat.of_nat d)) = Some m').\n { apply inhabited_sig_to_exists.\n econs.\n apply Mem.valid_access_store.\n rr. split; ss.\n 2: { apply Z.divide_1_l. }\n ii. apply MEM_DST. nia. }\n des.\n\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero_l. ss.\n - eval_comput. ss.\n - ss.\n - eval_comput.\n rewrite sign_ext_byte_range by range_stac.\n repr_tac.\n unfold IntNat.of_nat in STORE.\n eauto.\n }\n\n fw. fw.\n { econs.\n - eval_comput. ss.\n - ss.\n - ss. }\n\n red_idx idx_ret.\n simpl_itree_interp.\n ss. rewrite call_cont_is_call_cont by ss.\n\n eapply SIM_RET; eauto.\n - eapply wf_set_demand. eauto.\n - eapply store_set_demand; eauto.\n - eapply Mem.store_unchanged_on; eauto.\n Qed.\n\n\n Definition idx_rund: nat := 30.\n\n Lemma sim_run_device\n (ktr_app: t -> itree appE DevState.t)\n (ktr: list bool * DevState.t -> itree progE unit)\n (m: mem) (k: cont) (idx_ret: nat)\n st b_dst\n txs sytm sh\n (CALL_CONT: is_call_cont k)\n (WF_ST: DevState.wf st)\n (MEM_DST: mem_dst_blk m st b_dst)\n (SIM_RET:\n forall m' (st': t)\n (WF_ST': wf st')\n (MEM_DST: mem_dst_blk m' st' b_dst)\n (MEM_UNCH: mem_changed_block b_dst m m')\n ,\n paco3 (_sim_itree prog) r\n idx_ret (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (ktr_app st')\n sh ;;\n ktr ret)\n (Returnstate Vundef k m'))\n : paco3 (_sim_itree prog) r\n (idx_ret + idx_rund)%nat\n (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (ret <- run_device st ;;\n ktr_app ret)\n sh ;;\n ktr ret)\n (Callstate (Internal f_run_device)\n [Vptr b_dst Ptrofs.zero] k m).\n Proof.\n unfold idx_rund.\n start_func.\n { econs. }\n ss.\n\n hexploit (in_cenv_ilist __dev_state); [sIn|].\n intro CO_DEV_STATE.\n\n assert (MAX_TIMEOUT_BYTE_RANGE: Z.of_nat MAX_TIMEOUT < Byte.max_signed) by ss.\n\n fw. clear STEP_ENTRY.\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero_l.\n repr_tac.\n\n erewrite Mem.loadbytes_load; cycle 1.\n { apply MEM_DST. }\n { ss. solve_divide. }\n s.\n rewrite decode_byte.\n rewrite sign_ext_byte_range_u.\n 2: { inv WF_ST. s.\n range_stac. }\n rewrite sign_ext_byte_range.\n 2: { inv WF_ST. s.\n range_stac. }\n ss.\n }\n upd_lenv.\n\n fw. fw.\n { econs.\n - eval_comput.\n s. repr_tac0; cycle 1.\n { range_stac. }\n { inv WF_ST. s.\n range_stac. }\n\n replace 0 with (Z.of_nat O) by ss.\n rewrite <- Nat2Z_inj_ltb. ss.\n - ss. rewrite bool_val_of_bool. ss.\n }\n\n unfold run_device.\n\n destruct (Nat.ltb_spec 0 (demand st)).\n 2: {\n simpl_itree_interp.\n fw.\n red_idx idx_ret.\n eapply SIM_RET; eauto.\n eapply Mem.unchanged_on_refl.\n }\n\n fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { r. ss.\n econs; eauto.\n - ss. econs 2; eauto; ss.\n { intros ? ? OSE. inv OSE; ss. }\n econs 2; ss.\n - ss.\n }\n { erewrite (MWITree.unfold_interp_vis_sys\n tid dev_mod).\n 2: { simpl_itree_goal.\n simpl_itree_goal.\n ss. }\n unf_resum.\n simpl_itree_goal.\n econs 1.\n }\n { ss. }\n\n intros []. i. ss.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT.\n existT_elim. subst.\n unf_resum. subst.\n inv MATCH_RETV.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n rename m' into m.\n exists 1%nat. left.\n\n fw_tau (idx_ret + 20)%nat.\n { simpl_itree_goal. ss. }\n\n fw. fw. fw.\n { econs. eval_comput.\n repr_tac0; cycle 1.\n { inv WF_ST. s. range_stac. }\n { range_stac. }\n replace 1 with (Z.of_nat 1) by ss.\n rewrite <- Nat2Z.inj_sub by ss.\n rewrite sign_ext_byte_range.\n 2: { inv WF_ST. s. range_stac. }\n ss.\n }\n upd_lenv.\n\n assert (STORE: exists m',\n Mem.store Mint8signed m b_dst 1\n (Vint (IntNat.of_nat (demand st - 1))) = Some m').\n { apply inhabited_sig_to_exists.\n econs.\n apply Mem.valid_access_store.\n rr. split; ss.\n 2: { apply Z.divide_1_l. }\n ii. apply MEM_DST. nia. }\n des.\n\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold Coqlib.align, align_attr. s.\n rewrite Ptrofs.add_zero_l. ss.\n - eval_comput. ss.\n - ss.\n - eval_comput.\n rewrite sign_ext_byte_range.\n 2: { inv WF_ST. s. range_stac. }\n repr_tac.\n unfold IntNat.of_nat in STORE.\n eauto.\n }\n fw.\n simpl_itree_interp.\n red_idx idx_ret.\n\n eapply SIM_RET.\n - eapply wf_reduce_demand. ss.\n - rewrite reduce_demand_eq.\n rewrite <- Nat.sub_1_r.\n eapply store_set_demand; eauto.\n - eapply Mem.store_unchanged_on; eauto.\n Qed.\n\n Inductive inv_mw (m: mem) txs sytm sh : Prop :=\n InvMW\n b_sbuf b_sh\n bs_old\n (MEM_CONSTS: mem_consts ge m tid)\n (MEM_SH: mem_sh ge m sh)\n (MEM_TXS: mem_txs ge m txs)\n (MEM_SBUF: mem_sbuf ge m (sytm + period) tid bs_old)\n\n (RANGE_TXS: IntRange.sint txs)\n (RANGE_SYTM: IntRange.uint64 sytm)\n (RANGE_SYTM2: IntRange.uint64 (sytm + period))\n\n (FSYMB_SBUF: Genv.find_symbol ge _send_buf = Some b_sbuf)\n (FSYMB_SH: Genv.find_symbol ge _send_hist = Some b_sh)\n .\n\n Lemma inv_mw_unch\n m txs sytm sh m'\n (INV: inv_mw m txs sytm sh)\n (MEM_UNCH: Mem.unchanged_on\n (blocks_of ge main_gvar_ids) m m')\n : inv_mw m' txs sytm sh.\n Proof.\n inv INV.\n econs; eauto.\n - eapply mem_consts_unch; eauto.\n eapply Mem.unchanged_on_implies; eauto.\n clear. unfold blocks_of.\n intros b ofs [id [IN1 FSYMB]] _. ss.\n des; ss;\n (subst; esplits; try apply FSYMB; sIn).\n - eapply mem_sh_unch; eauto.\n eapply Mem.unchanged_on_implies; eauto.\n clear. unfold blocks_of.\n intros b ofs FSYMB _. ss.\n subst; esplits; try apply FSYMB; sIn.\n - eapply mem_txs_unch; eauto.\n eapply Mem.unchanged_on_implies; eauto.\n clear. unfold blocks_of.\n intros b ofs FSYMB _. ss.\n subst; esplits; try apply FSYMB; sIn.\n - eapply mem_sbuf_unch; eauto.\n eapply Mem.unchanged_on_implies; eauto.\n clear. unfold blocks_of.\n intros b ofs FSYMB _. ss.\n subst; esplits; try apply FSYMB; sIn.\n Qed.\n\n\n Local Opaque idx_psend idx_sync idx_udmd idx_rund.\n Definition idx_jobdev: nat := idx_psend + idx_sync + idx_udmd +\n idx_rund + 50.\n\n Lemma sim_job_device\n (ktr: list bool * DevState.t -> itree progE unit)\n (m: mem) (k: cont) (idx_ret: nat)\n st (* b_dst *)\n txs sh sytm\n inb b_dst b_mst ofs_inb\n (CALL_CONT: is_call_cont k)\n (INV_MW: inv_mw m txs sytm sh)\n (INV_DEV: inv_dev ge st m)\n (FSYMB_DST: Genv.find_symbol ge _state = Some b_dst)\n (FSYMB_MST: Genv.find_symbol ge _mstore = Some b_mst)\n (MEM_INB: Mem_inbox m b_mst ofs_inb inb)\n (RANGE_OFS_INB: 0 <= ofs_inb <= 4 + inb_sz)\n\n (SIM_RET:\n forall m' (st': t) sh'\n (INV_MW: inv_mw m' txs sytm sh')\n (INV_DEV: inv_dev ge st' m')\n (MEM_UNCH: Mem.unchanged_on (blocks_of ge app_unch_gvar_ids) m m')\n ,\n paco3 (_sim_itree prog) r\n idx_ret (ktr (sh', st'))\n (Returnstate Vundef k m'))\n : paco3 (_sim_itree prog) r\n (idx_ret + idx_jobdev)%nat\n (ret <- interp (MWITree.send_handler\n tid txs sytm)\n (job_device_itree (Z.of_nat sytm) st inb)\n sh ;;\n ktr ret)\n (Callstate (Internal f_job_device)\n [Vint (IntNat.of_nat tid);\n Vptr b_dst Ptrofs.zero;\n Vlong (IntNat.of_nat64 sytm);\n Vptr b_mst (Ptrofs.repr ofs_inb)]\n k m).\n Proof.\n unfold idx_jobdev.\n start_func.\n { econs. }\n\n (* hexploit (in_cenv_ilist _inbox_t); [sIn|]. *)\n (* intro CO_INBOX. *)\n (* hexploit (in_cenv_ilist _msg_entry_t); [sIn|]. *)\n (* intro CO_MENTRY. *)\n hexploit (in_cenv_ilist __dev_state); [sIn|].\n intro CO_DEV_STATE.\n r in INV_DEV. des.\n hexploit (in_gvar_ids _rel_msg); [sIn|].\n intros (b_rel & FSYMB_REL).\n hexploit (in_gvar_ids _acq_msg); [sIn|].\n intros (b_acq & FSYMB_ACQ).\n\n fw. fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold_align.\n rewrite Ptrofs.add_zero.\n r in MEM_DST.\n hexploit MEM_DST; eauto.\n clear MEM_DST. intro MEM_DST.\n (* rewrite MEM_DST. *)\n\n erewrite loadbytes_load_byte; cycle 1.\n { eapply MEM_DST. }\n { destruct (owner_status st); ss.\n destruct b; ss. }\n eval_comput.\n repr_tac0; cycle 1.\n { destruct (owner_status st); ss.\n destruct b; ss. }\n { ss. }\n\n ss.\n - rewrite bool_val_of_bool. ss.\n }\n unfold job_device_itree.\n\n destruct st as [own dmd]. ss.\n destruct own as [is_owner|].\n 2: { (* Uninit *)\n s.\n\n assert (STORE: exists m',\n Mem.store Mint8signed m b_dst 0\n (Vint (IntNat.of_nat 2)) = Some m').\n { apply inhabited_sig_to_exists.\n econs.\n apply Mem.valid_access_store.\n rr. split; ss.\n 2: { apply Z.divide_1_l. }\n ii. apply MEM_DST; eauto. nia. }\n des.\n\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold_align.\n rewrite Ptrofs.add_zero. ss.\n - eval_comput. ss.\n - s. ss.\n - eval_comput.\n rewrite sign_ext_byte_range by ss.\n eauto.\n }\n\n fw. fw. fw.\n { step_fptr_tac.\n - rewrite FSYMB_REL. s.\n rewrite sign_ext_byte_range by ss.\n reflexivity.\n }\n\n hexploit store_unchanged_on'; eauto. intro UNCH.\n eapply inv_mw_unch in INV_MW.\n 2: { eapply Mem.unchanged_on_implies; eauto.\n unfold mem_range. unfold blocks_of.\n clear - FSYMB_DST.\n ii. des. subst. ss.\n revert FSYMB_DST.\n des; subst; ss;\n eapply global_addresses_distinct'; eauto; ss.\n }\n inv INV_MW.\n red_idx (idx_psend + (idx_ret + 10))%nat.\n\n erewrite (MWITree.unfold_interp_vis_send tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. s.\n\n change (f_pals_send (Z.of_nat 1) (Z.of_nat 16) (Z.of_nat 8)) with\n (f_pals_send (Z.of_nat msg_size_k) (Z.of_nat max_num_tasks) (Z.of_nat max_num_mcasts)).\n\n eapply sim_pals_send; eauto; ss.\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n { assert (b_rel <> b_dst).\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n eapply Mem.loadbytes_unchanged_on; eauto.\n unfold mem_range. ii. des. ss. }\n rename m' into m1.\n i. rename m' into m_f.\n fw_tau (idx_ret + 10)%nat.\n { simpl_itree_goal. ss. }\n\n fw. fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { s. econs; eauto; s.\n - econs 2; eauto; ss.\n { intros ? ? OSE. inv OSE; ss. }\n econs 2; ss.\n - ss. }\n { econs 1. }\n { erewrite (MWITree.unfold_interp_vis_sys tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. ss. }\n\n intros []. i.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT. existT_elim.\n unf_resum. subst.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n inv MATCH_RETV.\n rename m' into m_f.\n\n exists (idx_ret + 5)%nat.\n left.\n fw. fw.\n simpl_itree_goal.\n fw_tau idx_ret.\n erewrite (MWITree.unfold_interp_ret _ dev_mod) by ss.\n simpl_itree_goal.\n\n rewrite call_cont_is_call_cont by ss.\n (* red_idx idx_ret. *)\n\n assert (UNCH_EXC: mem_unchanged_except (blocks_of ge [_send_buf; _send_hist; _state]) m m_f).\n { eapply Mem.unchanged_on_trans; eauto.\n - eapply Mem.unchanged_on_implies; try apply UNCH.\n unfold blocks_of. unfold mem_range.\n intros b ofs C _ [? ?].\n apply C. clear C.\n clarify. ss. esplits; eauto.\n - eapply Mem.unchanged_on_implies; try apply MEM_UNCH.\n unfold blocks_of.\n intros b ofs C _ [? ?].\n apply C. clear C.\n des; ss.\n des; clarify.\n + exists _send_buf; eauto.\n + exists _send_hist; eauto.\n }\n\n eapply SIM_RET.\n - econs; eauto.\n - assert (UNCH_AUX: Mem.unchanged_on (blocks_of ge [_acq_msg; _rel_msg]) m m_f).\n { i. eapply unchanged_on_disjoint_ids; eauto.\n r. ii. des; ss. des; subst; ss. }\n\n r. splits.\n + inv DST_WF.\n econs; eauto.\n + cut (mem_dst ge m1 (set_owner_status false (mk None dmd))).\n { intro MEM_DST_P.\n eapply mem_dst_unch; eauto.\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of. clear.\n ii. des; ss.\n cut (b <> b).\n { ss. }\n eapply (@Genv.global_addresses_distinct\n _ _ ge id id0); eauto.\n des; subst; ss.\n }\n\n ii. clarify.\n eapply store_set_owner_status; eauto.\n + ii. clarify.\n eapply Mem.loadbytes_unchanged_on; eauto.\n ii. unfold blocks_of.\n esplits; eauto. sIn.\n + ii. clarify.\n eapply Mem.loadbytes_unchanged_on; eauto.\n ii. unfold blocks_of.\n esplits; eauto. sIn.\n\n - eapply unchanged_on_disjoint_ids; eauto.\n clear.\n ii. ss. des; subst; ss.\n }\n\n (* initialized state *)\n (* simpl_itree_interp. s. *)\n s.\n replace ((if is_owner then 1 else 2) =? 0) with false.\n 2: { destruct is_owner; ss. }\n\n fw. fw. fw.\n { step_fptr_tac. }\n\n red_idx (idx_ret + idx_psend + idx_udmd +\n idx_rund + 40 + idx_sync)%nat.\n eapply sim_sync_dev_state; eauto.\n { eapply Genv.global_addresses_distinct;\n cycle 1; eauto. ss. }\n { ss. }\n\n clear MEM_DST. i.\n fw. fw. fw. fw. fw.\n { step_fptr_tac. }\n\n red_idx (idx_ret + idx_psend +\n idx_rund + 30 + idx_udmd)%nat.\n eapply sim_update_demand.\n { ss. }\n { eapply wf_sync_dev_state. ss. }\n { rewrite <- ST'. ss. }\n\n renames m' MEM_CH_BLK into m1 MEM_CH_BLK1.\n renames st' ST' into st1 ST1.\n clear MEM_DST. i.\n\n fw. upd_lenv.\n fw. fw.\n { econs. eval_comput. ss. }\n upd_lenv.\n\n fw. fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold_align. s.\n rewrite Ptrofs.add_zero.\n erewrite loadbytes_load_byte; cycle 1.\n { eapply MEM_DST. }\n { destruct (owner_status st') as [[]|] ; ss. }\n\n eval_comput.\n repr_tac0; cycle 1.\n { destruct (owner_status st') as [[]|] ; ss. }\n { range_stac. }\n reflexivity.\n - rewrite bool_val_of_bool. ss.\n }\n renames st' ST' WF_ST' into st2 ST2 WF_ST2.\n destruct st2 as [own2 dmd2]. s.\n destruct own2 as [is_owner2 |].\n 2: { exfalso.\n clear - ST2.\n unfold set_demand, sync_dev_state in *. ss.\n desf. }\n\n assert (MAX_TIMEOUT_BYTE_RANGE: Z.of_nat MAX_TIMEOUT < Byte.max_signed) by ss.\n\n destruct is_owner2.\n - (* this is the owner *)\n s.\n fw. fw.\n { step_fptr_tac. }\n\n red_idx (idx_ret + idx_psend + 20 + idx_rund)%nat.\n eapply sim_run_device; eauto.\n { ss. }\n renames m' MEM_UNCH into m2 MEM_UNCH2.\n clear MEM_DST. i.\n renames st' WF_ST' into st3 WF_ST3.\n\n destruct st3 as [own3 dmd3].\n\n fw. fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold_align.\n rewrite Ptrofs.add_zero_l.\n erewrite loadbytes_load_byte; cycle 1.\n { apply MEM_DST. }\n { ss. inv WF_ST3.\n range_stac. }\n eval_comput.\n repr_tac0; cycle 1.\n { inv WF_ST3. range_stac. }\n { range_stac. }\n\n replace 0 with (Z.of_nat O) by ss.\n rewrite Nat2Z_inj_eqb. ss.\n - rewrite bool_val_of_bool. ss.\n }\n\n assert (UNCH_03: mem_unchanged_except (blocks_of ge [_state]) m m').\n { eapply Mem.unchanged_on_trans.\n { eapply Mem.unchanged_on_implies; try apply MEM_CH_BLK1.\n unfold blocks_of.\n intros b _ C _ BEQ. subst.\n apply C. clear C. ss.\n esplits; eauto. }\n eapply Mem.unchanged_on_trans.\n { eapply Mem.unchanged_on_implies; try apply MEM_UNCH2.\n unfold blocks_of.\n intros b _ C _ BEQ. subst.\n apply C. clear C. ss.\n esplits; eauto. }\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of.\n intros b _ C _ BEQ. subst.\n apply C. clear C. ss.\n esplits; eauto.\n }\n\n destruct (Nat.eqb_spec dmd3 0).\n 2: {\n fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { s. econs; eauto; s.\n - econs 2; eauto; ss.\n { intros ? ? OSC. inv OSC; ss. }\n econs 2; ss.\n - ss. }\n { econs 1. }\n { erewrite (MWITree.unfold_interp_vis_sys tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. ss. }\n\n intros []. i.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT. existT_elim.\n unf_resum. subst.\n inv MATCH_RETV.\n rename m'0 into m_f.\n\n exists (idx_ret + 5)%nat.\n left.\n fw.\n simpl_itree_goal.\n fw_tau idx_ret.\n erewrite (MWITree.unfold_interp_ret _ dev_mod) by ss.\n simpl_itree_goal.\n\n eapply SIM_RET.\n - eapply inv_mw_unch; try apply INV_MW.\n eapply unchanged_on_disjoint_ids; eauto.\n clear.\n ii. ss. des; subst; ss.\n - r. esplits; ss.\n + ii. clarify.\n + eapply mem_acq_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear.\n ii. ss. des; subst; ss.\n + eapply mem_rel_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear.\n ii. ss. des; subst; ss.\n - eapply unchanged_on_disjoint_ids; eauto.\n clear.\n ii. ss. des; subst; ss.\n }\n\n (* release resource lock *)\n renames m' MEM_UNCH into m3 MEM_UNCH3.\n\n assert (STORE: exists m4,\n Mem.store Mint8signed m3 b_dst 0\n (Vint (IntNat.of_nat 2)) = Some m4).\n { apply inhabited_sig_to_exists.\n econs.\n apply Mem.valid_access_store.\n rr. split; ss.\n 2: { apply Z.divide_1_l. }\n ii. apply MEM_DST; eauto. nia. }\n des.\n\n fw. fw.\n { econs.\n - eval_comput.\n rewrite CO_DEV_STATE. s.\n unfold_align. rewrite Ptrofs.add_zero. ss.\n - eval_comput. ss.\n - s. ss.\n - eval_comput.\n rewrite sign_ext_byte_range by range_stac.\n eauto.\n }\n\n fw. fw.\n { step_fptr_tac.\n rewrite FSYMB_REL.\n rewrite sign_ext_byte_range by range_stac.\n reflexivity. }\n\n red_idx (idx_psend + (idx_ret + 10))%nat.\n\n erewrite (MWITree.unfold_interp_vis_send tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. s.\n\n change (f_pals_send (Z.of_nat 1) (Z.of_nat 16) (Z.of_nat 8)) with\n (f_pals_send (Z.of_nat msg_size_k) (Z.of_nat max_num_tasks) (Z.of_nat max_num_mcasts)).\n\n assert (UNCH04: mem_unchanged_except (blocks_of ge [_state]) m m4).\n { eapply Mem.unchanged_on_trans; try apply UNCH_03.\n eapply Mem.store_unchanged_on; eauto.\n unfold blocks_of. s.\n intros i RI C.\n apply C. clear C.\n esplits; eauto. }\n\n assert (INV_MW4: inv_mw m4 txs sytm sh).\n { eapply inv_mw_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify. }\n\n eapply (mem_rel_unch_diffblk ge m m4) in MEM_REL; cycle 1.\n { instantiate (1:= b_dst).\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of. ss. ii. des; clarify. }\n { eapply global_addresses_distinct'; eauto. ss. }\n eapply (mem_acq_unch_diffblk ge m m4) in MEM_ACQ; cycle 1.\n { instantiate (1:= b_dst).\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of. ss. ii. des; clarify. }\n { eapply global_addresses_distinct'; eauto. ss. }\n\n inv INV_MW4.\n eapply sim_pals_send; eauto; ss.\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n\n clear MEM_CONSTS MEM_SH MEM_TXS MEM_SBUF. i.\n simpl_itree_goal.\n\n fw_tau (idx_ret + 10)%nat.\n fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { s. econs; eauto; s.\n - econs 2; eauto; ss.\n { intros ? ? OSC. inv OSC; ss. }\n econs 2; ss.\n - ss. }\n { econs 1. }\n { erewrite (MWITree.unfold_interp_vis_sys tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. ss. }\n\n intros []. i.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT. existT_elim.\n unf_resum. subst.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n inv MATCH_RETV.\n rename m'0 into m_f.\n\n exists (idx_ret + 5)%nat.\n left.\n fw.\n simpl_itree_goal.\n fw_tau idx_ret.\n erewrite (MWITree.unfold_interp_ret _ dev_mod) by ss.\n simpl_itree_goal.\n\n eapply SIM_RET.\n + econs; eauto.\n + r.\n esplits.\n * econs. nia.\n * eapply mem_dst_unch.\n 2: { eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify. }\n ii. clarify.\n eapply store_set_owner_status in MEM_DST; eauto.\n * eapply mem_acq_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n * eapply mem_rel_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n + eapply Mem.unchanged_on_trans with (m2:= m4).\n * eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of.\n ii. des. ss.\n cut (b <> b).\n { ss. }\n eapply (@Genv.global_addresses_distinct\n _ _ ge id id0); ss.\n des; clarify.\n * eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n\n - (* send ACQ *)\n s.\n fw.\n { econs.\n - eval_comput.\n instantiate (1:= retv).\n subst retv. destruct retb; ss.\n - subst retv. ss.\n instantiate (1:= retb).\n destruct retb; ss.\n }\n\n assert (UNCH_TOT: mem_unchanged_except\n (blocks_of ge [_state]) m m').\n { eapply Mem.unchanged_on_trans with (m2 := m1).\n - eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of.\n intros b _ C _ AUX.\n apply C. clear C. ss. subst.\n esplits; eauto.\n - eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of.\n intros b _ C _ AUX.\n apply C. clear C. ss. subst.\n esplits; eauto.\n }\n\n destruct retb.\n 2: {\n simpl_itree_interp.\n fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { s. econs; eauto; s.\n - econs 2; eauto; ss.\n { intros ? ? OSC. inv OSC; ss. }\n econs 2; ss.\n - ss. }\n { econs 1. }\n { erewrite (MWITree.unfold_interp_vis_sys tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. ss. }\n\n intros []. i.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT. existT_elim.\n unf_resum. subst.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n inv MATCH_RETV.\n rename m'0 into m_f.\n\n exists (idx_ret + 5)%nat.\n left.\n fw.\n simpl_itree_goal.\n fw_tau idx_ret.\n erewrite (MWITree.unfold_interp_ret _ dev_mod) by ss.\n simpl_itree_goal.\n\n eapply SIM_RET.\n - eapply inv_mw_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n - r. esplits; ss.\n * ii. clarify.\n * eapply mem_acq_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n * eapply mem_rel_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n - eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n }\n\n fw.\n { step_fptr_tac.\n rewrite FSYMB_ACQ.\n rewrite sign_ext_byte_range by range_stac.\n reflexivity. }\n\n red_idx (idx_psend + (idx_ret + 10))%nat.\n\n erewrite (MWITree.unfold_interp_vis_send tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. s.\n\n change (f_pals_send (Z.of_nat 1) (Z.of_nat 16) (Z.of_nat 8)) with\n (f_pals_send (Z.of_nat msg_size_k) (Z.of_nat max_num_tasks) (Z.of_nat max_num_mcasts)).\n\n assert (INV_MW': inv_mw m' txs sytm sh).\n { eapply inv_mw_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify. }\n\n eapply (mem_rel_unch_diffblk ge m m') in MEM_REL; cycle 1.\n { instantiate (1:= b_dst).\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of. ss. ii. des; clarify. }\n { eapply global_addresses_distinct'; eauto. ss. }\n eapply (mem_acq_unch_diffblk ge m m') in MEM_ACQ; cycle 1.\n { instantiate (1:= b_dst).\n eapply Mem.unchanged_on_implies; eauto.\n unfold blocks_of. ss. ii. des; clarify. }\n { eapply global_addresses_distinct'; eauto. ss. }\n\n inv INV_MW'.\n eapply sim_pals_send; eauto; ss.\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n { eapply Genv.global_addresses_distinct; eauto. ss. }\n renames m' MEM_UNCH into m2 MEM_UNCH2.\n\n clear MEM_CONSTS MEM_SH MEM_TXS MEM_SBUF. i.\n simpl_itree_goal.\n\n fw_tau (idx_ret + 10)%nat.\n fw. fw.\n { step_fptr_tac. }\n\n pfold. econs 3.\n { s. econs; eauto; s.\n - econs 2; eauto; ss.\n { intros ? ? OSC. inv OSC; ss. }\n econs 2; ss.\n - ss. }\n { econs 1. }\n { erewrite (MWITree.unfold_interp_vis_sys tid dev_mod).\n 2: { simpl_itree_goal. ss. }\n simpl_itree_goal. ss. }\n\n intros []. i.\n inv RET. inv CPROG_AFTER_EVENT; ss.\n inv EVENT. existT_elim.\n unf_resum. subst.\n (* inv SYS_ESTEP. existT_elim. subst. *)\n inv MATCH_RETV.\n rename m'0 into m_f.\n\n exists (idx_ret + 5)%nat.\n left.\n fw.\n simpl_itree_goal.\n fw_tau idx_ret.\n erewrite (MWITree.unfold_interp_ret _ dev_mod) by ss.\n simpl_itree_goal.\n\n eapply SIM_RET.\n + econs; eauto.\n + r. esplits; ss.\n * eapply mem_dst_unch; eauto.\n { ii. clarify. eauto. }\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n * eapply mem_acq_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n * eapply mem_rel_unch; eauto.\n eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n + eapply Mem.unchanged_on_trans.\n * eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n * eapply unchanged_on_disjoint_ids; eauto.\n clear. ii. ss. des; clarify.\n Qed.\n\n\n Local Opaque idx_jobdev.\n Definition idx_dev : nat := idx_jobdev + 10.\n (* idx_job_ctrl + 10. *)\n\n\n (* Local Opaque idx_job_ctrl. *)\n\n Lemma sim_job_func_dev\n : forall (b_mst : block)\n (txs idx' : nat) (ast : DevState.t)\n (ki : list bool * DevState.t -> itree progE unit)\n (m : mem) (kp : cont) (sytm : nat) (cflg : bool)\n (ofsc ofsn : Z) (inbc inbn : list (bytes?))\n (* (sh : list bool) *) (mcont : bytes)\n (CALL_CONT: is_call_cont kp)\n (RANGE_SYTM: IntRange.uint64 sytm)\n (RANGE_NXT_SYTM: IntRange.uint64 (sytm + period))\n (RANGE_TXS: IntRange.sint txs)\n (INV_APP: inv_dev ge ast m)\n (FSYMB_MST: Genv.find_symbol ge _mstore = Some b_mst)\n (MEM_CONSTS: mem_consts ge m tid)\n (MEM_SBUF: mem_sbuf ge m (sytm + RTSysEnv.period) tid mcont)\n (MEM_MSTORE: mem_mstore ge m cflg ofsc ofsn inbc inbn)\n (MEM_SH: mem_sh ge m (repeat false num_tasks))\n (MEM_TXS: mem_txs ge m txs)\n (SIM_RET: forall (sh' : list bool) (ast' : DevState.t)\n (m' : mem) (mcont' : bytes)\n (MEM_UNCH: Mem.unchanged_on (blocks_of ge app_unch_gvar_ids) m m')\n (MEM_SH: mem_sh ge m' sh')\n (MEM_SBUF: mem_sbuf ge m' (sytm + RTSysEnv.period) tid mcont')\n (INV_APP: inv_dev ge ast' m'),\n paco3 (_sim_itree prog) r\n idx' (ki (sh', ast')) (Returnstate Vundef kp m'))\n ,\n paco3 (_sim_itree prog) r (idx' + idx_dev)%nat\n (` ret : list bool * DevState.t <-\n MWITree.interp_send\n tid dev_mod txs sytm\n (repeat false num_tasks) ast inbc;;\n ki ret)\n (Callstate (Internal f_job)\n [Vlong (IntNat.of_nat64 sytm);\n Vptr b_mst (Ptrofs.repr ofsc)] kp m)\n .\n Proof.\n (* pose proof (genv_props_ctrl tid) as GENV_PROPS. i. *)\n (* rewrite <- CPROG_EQ in *. i. *)\n i. unfold idx_dev.\n start_func.\n { econs. }\n\n (* pose proof cprog_opaque as CPROG_EQ. des. *)\n (* guardH CPROG_EQ. *)\n (* subst prog. subst ge. *)\n (* rewrite <- CPROG_EQ in *. *)\n\n fw. clear STEP_ENTRY.\n\n hexploit (in_gvar_ids _TASK_ID); [sIn|].\n intros (b_tid & FSYMB_TID).\n hexploit (in_gvar_ids _state); [sIn|].\n intros (b_dst & FSYMB_DST).\n\n fw.\n { step_fptr_tac.\n rewrite FSYMB_DST.\n rewrite FSYMB_TID.\n erewrite mem_consts_task_id; eauto.\n }\n\n red_idx (idx' + 5 + idx_jobdev)%nat.\n unfold MWITree.interp_send. s.\n\n replace (Int.sign_ext 8 (IntNat.of_nat tid)) with\n (IntNat.of_nat tid).\n 2: { unfold IntNat.of_nat.\n rewrite sign_ext_byte_range.\n 2: { pose proof range_num_tasks.\n range_stac. }\n ss.\n }\n\n hexploit (in_gvar_ids _send_hist); [sIn|].\n intros (b_sh & FSYMB_SH).\n hexploit (in_gvar_ids _send_buf); [sIn|].\n intros (b_sbuf & FSYMB_SBUF).\n\n unfold dev_job.\n eapply sim_job_device; eauto; ss.\n { econs; eauto. }\n { r in MEM_MSTORE.\n hexploit MEM_MSTORE; eauto.\n intro MBLK.\n inv MBLK. eauto. }\n { r in MEM_MSTORE.\n hexploit MEM_MSTORE; eauto.\n intro MBLK.\n inv MBLK.\n clear.\n pose proof ptr_range_mstore.\n destruct cflg.\n - range_stac.\n - range_stac.\n }\n\n i.\n fw. fw.\n\n red_idx idx'.\n inv INV_MW.\n eapply SIM_RET; eauto.\n Qed.\n\nEnd VERIF_FUNC.\n\n\nSection SIM_APP_DEV.\n Variable tid: Tid.\n (* Hypothesis DEV_TASK_ID: (tid = 3 \\/ tid = 4 \\/ tid = 5)%nat. *)\n Hypothesis DEV_TASK_ID: (tid < num_tasks)%nat.\n\n Program Definition SimApp_dev\n : SimApp tid (prog_dev (Z.of_nat tid)) dev_mod :=\n {| app_gvar_ilist := dev_gvar_ilist ;\n app_gfun_ilist := dev_gfun_ilist ;\n app_cenv_ilist := dev_cenv_ilist ;\n\n inv_app := inv_dev ;\n job_func := f_job ;\n idx_job := idx_dev;\n sim_job_func := _ ;\n |}.\n Next Obligation.\n ss. unfold main_gvar_ids.\n r. intros x y X_IN Y_IN.\n r in Y_IN. des; ss.\n - des; clarify.\n - des; clarify.\n - des; clarify.\n Qed.\n Next Obligation.\n ss. unfold main_gfun_ids.\n r. intros x y X_IN Y_IN.\n r in Y_IN.\n (* clear CPROG_EQ. *)\n des; ss;\n (des; clarify).\n Qed.\n Next Obligation.\n ss.\n r. ii. ss. clarify.\n des; clarify.\n Qed.\n Next Obligation.\n ss.\n Qed.\n Next Obligation.\n ss. sIn.\n Qed.\n Next Obligation.\n unfold num_tasks. ss.\n Qed.\n Next Obligation.\n eapply inv_dev_dep_app_blocks; eauto.\n Qed.\n Next Obligation.\n (* rewrite <- CPROG_EQ in *. s. *)\n apply (inv_dev_init tid); ss.\n Qed.\n Next Obligation.\n assert (CPROG_EQ: exists cprog, cprog = prog_dev (Z.of_nat tid)).\n { esplits; eauto. }\n des.\n pose proof (genv_props_dev tid) as GENV_PROPS.\n rewrite <- CPROG_EQ in *.\n clear CPROG_EQ.\n\n eapply (sim_job_func_dev tid cprog); eauto.\n Qed.\n\nEnd SIM_APP_DEV.\n\n\nProgram Definition task_dev1\n : PALSTask.t :=\n {| PALSTask.tid := 3 ;\n PALSTask.cprog_app := dev.prog 3 ;\n PALSTask.cprog_tot := prog_dev 3 ;\n PALSTask.app_mod := dev_mod ;\n PALSTask.sim_app := SimApp_dev 3 _ ;\n |}.\nNext Obligation.\n unfold num_tasks. ss. nia.\nQed.\nNext Obligation.\n apply prog_dev_linked.\nQed.\nNext Obligation.\n apply prog_dev_defs_norep.\nQed.\nNext Obligation.\n replace 3 with (Z.of_nat 3) by ss.\n apply prog_dev_gvs_ok. ss.\nQed.\nNext Obligation.\n replace 3 with (Z.of_nat 3) by ss.\n apply prog_dev_gfs_ok. ss.\nQed.\nNext Obligation.\n replace 3 with (Z.of_nat 3) by ss.\n apply prog_dev_cenvs_ok. ss.\nQed.\nNext Obligation.\n apply prog_dev_init_mem_ok.\nQed.\n\nProgram Definition task_dev2\n : PALSTask.t :=\n {| PALSTask.tid := 4 ;\n PALSTask.cprog_app := dev.prog 4 ;\n PALSTask.cprog_tot := prog_dev 4 ;\n PALSTask.app_mod := dev_mod ;\n PALSTask.sim_app := SimApp_dev 4 _ ;\n |}.\nNext Obligation.\n unfold num_tasks. ss. nia.\nQed.\nNext Obligation.\n apply prog_dev_linked.\nQed.\nNext Obligation.\n apply prog_dev_defs_norep.\nQed.\nNext Obligation.\n replace 4 with (Z.of_nat 4) by ss.\n apply prog_dev_gvs_ok. ss.\nQed.\nNext Obligation.\n replace 4 with (Z.of_nat 4) by ss.\n apply prog_dev_gfs_ok. ss.\nQed.\nNext Obligation.\n replace 4 with (Z.of_nat 4) by ss.\n apply prog_dev_cenvs_ok. ss.\nQed.\nNext Obligation.\n apply prog_dev_init_mem_ok.\nQed.\n\n\nProgram Definition task_dev3\n : PALSTask.t :=\n {| PALSTask.tid := 5 ;\n PALSTask.cprog_app := dev.prog 5 ;\n PALSTask.cprog_tot := prog_dev 5 ;\n PALSTask.app_mod := dev_mod ;\n PALSTask.sim_app := SimApp_dev 5 _ ;\n |}.\nNext Obligation.\n unfold num_tasks. ss.\nQed.\nNext Obligation.\n apply prog_dev_linked.\nQed.\nNext Obligation.\n apply prog_dev_defs_norep.\nQed.\nNext Obligation.\n replace 5 with (Z.of_nat 5) by ss.\n apply prog_dev_gvs_ok. ss.\nQed.\nNext Obligation.\n replace 5 with (Z.of_nat 5) by ss.\n apply prog_dev_gfs_ok. ss.\nQed.\nNext Obligation.\n replace 5 with (Z.of_nat 5) by ss.\n apply prog_dev_cenvs_ok. ss.\nQed.\nNext Obligation.\n apply prog_dev_init_mem_ok.\nQed.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/apps/active_standby/app_verif/VerifDevice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2337063569140403, "lm_q1q2_score": 0.11959142345783251}} {"text": "Require Import Coq.Strings.String.\nRequire Import Prog.\nRequire Import Word.\nRequire Import Rec.\nRequire Import List.\nRequire Import Pred PredCrash.\nRequire Import Eqdep_dec.\nRequire Import Arith.\nRequire Import Hoare.\nRequire Import SepAuto.\nRequire Import Cache.\nRequire Import AsyncDisk.\nRequire Import Omega.\nRequire Import FSLayout.\nRequire HexString.\n\nImport ListNotations.\nSet Implicit Arguments.\n\nModule SB.\n\n Local Hint Resolve goodSize_add_l goodSize_add_r.\n\n Definition magic_number :=\n # (natToWord addrlen (HexString.to_nat \"0xF5C\")). (* 0xF5C = FSC in C *)\n\n Definition superblock_type : Rec.type := Rec.RecF ([\n (\"data_start\", Rec.WordF addrlen);\n (\"log_header\", Rec.WordF addrlen);\n (\"log_descr\", Rec.WordF addrlen);\n (\"log_descrlen\", Rec.WordF addrlen);\n (\"log_data\", Rec.WordF addrlen);\n (\"log_len\", Rec.WordF addrlen);\n\n (\"ixstart\", Rec.WordF addrlen);\n (\"ixlen\", Rec.WordF addrlen);\n\n (\"bastart1\", Rec.WordF addrlen);\n (\"banblocks1\", Rec.WordF addrlen);\n (\"bastart2\", Rec.WordF addrlen);\n (\"banblocks2\", Rec.WordF addrlen);\n\n (\"iastart\", Rec.WordF addrlen);\n (\"ianblocks\", Rec.WordF addrlen);\n\n (\"root_inum\", Rec.WordF addrlen);\n (\"maxblock\", Rec.WordF addrlen);\n (\"magic\", Rec.WordF addrlen) \n ]).\n\n Definition superblock_padded : Rec.type := Rec.RecF ([\n (\"sb\", superblock_type);\n (\"pad\", Rec.WordF (valulen - (Rec.len superblock_type)))\n ]).\n\n Theorem superblock_padded_len :\n Rec.len superblock_padded = valulen.\n Proof.\n simpl. rewrite valulen_is. apply Nat.eqb_eq.\n compute. reflexivity.\n Qed.\n\n Definition superblock0 := @Rec.of_word superblock_type (wzero _).\n Definition superblock_pad0 := @Rec.of_word superblock_padded (wzero _).\n\n Definition pickle_superblock (fsxp : fs_xparams) : word (Rec.len superblock_padded) :=\n let (lxp, ixp, dbxp1, dbxp2, ibxp, rootinum, maxblock, magic) := fsxp in\n let sb := superblock0\n :=> \"data_start\" := addr2w (DataStart lxp)\n :=> \"log_header\" := addr2w (LogHeader lxp)\n :=> \"log_descr\" := addr2w (LogDescriptor lxp)\n :=> \"log_descrlen\":= addr2w (LogDescLen lxp)\n :=> \"log_data\" := addr2w (LogData lxp)\n :=> \"log_len\" := addr2w (LogLen lxp)\n :=> \"ixstart\" := addr2w (IXStart ixp)\n :=> \"ixlen\" := addr2w (IXLen ixp)\n :=> \"bastart1\" := addr2w (BmapStart dbxp1)\n :=> \"banblocks1\" := addr2w (BmapNBlocks dbxp1)\n :=> \"bastart2\" := addr2w (BmapStart dbxp2)\n :=> \"banblocks2\" := addr2w (BmapNBlocks dbxp2)\n :=> \"iastart\" := addr2w (BmapStart ibxp)\n :=> \"ianblocks\" := addr2w (BmapNBlocks ibxp)\n :=> \"root_inum\" := addr2w rootinum\n :=> \"maxblock\" := addr2w maxblock\n :=> \"magic\" := addr2w magic\n in Rec.to_word (superblock_pad0 :=> \"sb\" := sb).\n\n Definition unpickle_superblock (sbp : word (Rec.len superblock_padded)) : fs_xparams :=\n let sb := ((Rec.of_word sbp) :-> \"sb\") in\n let lxp := Build_log_xparams\n # (sb :-> \"data_start\") # (sb :-> \"log_header\")\n # (sb :-> \"log_descr\") # (sb :-> \"log_descrlen\")\n # (sb :-> \"log_data\") # (sb :-> \"log_len\") in\n let ixp := Build_inode_xparams\n # (sb :-> \"ixstart\") # (sb :-> \"ixlen\") in\n let dbxp1 := Build_balloc_xparams\n # (sb :-> \"bastart1\") # (sb :-> \"banblocks1\") in\n let dbxp2 := Build_balloc_xparams\n # (sb :-> \"bastart2\") # (sb :-> \"banblocks2\") in\n let ibxp := Build_balloc_xparams\n # (sb :-> \"iastart\") # (sb :-> \"ianblocks\") in\n let rootinum := # (sb :-> \"root_inum\") in\n let maxblock := # (sb :-> \"maxblock\") in\n let magic := # (sb :-> \"magic\") in\n Build_fs_xparams lxp ixp dbxp1 dbxp2 ibxp rootinum maxblock magic.\n\n\n Theorem pickle_unpickle_superblock : forall fsxp,\n fs_xparams_ok fsxp ->\n unpickle_superblock (pickle_superblock fsxp) = fsxp.\n Proof.\n unfold pickle_superblock, unpickle_superblock.\n destruct fsxp.\n repeat rewrite Rec.of_to_id.\n destruct FSXPLog.\n destruct FSXPInode.\n destruct FSXPInodeAlloc.\n destruct FSXPBlockAlloc1.\n destruct FSXPBlockAlloc2.\n unfold Rec.recget', Rec.recset'.\n unfold addr2w; simpl; intros.\n repeat rewrite wordToNat_natToWord_idempotent' by xparams_ok.\n auto.\n unfold Rec.well_formed.\n simpl.\n intuition.\n Qed.\n\n Definition v_pickle_superblock (fsxp : fs_xparams) : valu.\n remember (pickle_superblock fsxp) as sb; clear Heqsb.\n rewrite superblock_padded_len in *.\n exact sb.\n Defined.\n\n Definition v_unpickle_superblock (v : valu) : fs_xparams.\n rewrite <- superblock_padded_len in *.\n exact (unpickle_superblock v).\n Defined.\n\n Theorem v_pickle_unpickle_superblock : forall fsxp,\n fs_xparams_ok fsxp ->\n v_unpickle_superblock (v_pickle_superblock fsxp) = fsxp.\n Proof.\n intros.\n unfold v_pickle_superblock, v_unpickle_superblock.\n unfold eq_rec_r, eq_rec.\n rewrite eq_rect_nat_double.\n rewrite <- (eq_rect_eq_dec eq_nat_dec).\n apply pickle_unpickle_superblock; auto.\n Qed.\n\n Theorem goodSize_magic_number :\n goodSize addrlen magic_number.\n Proof.\n unfold magic_number.\n eapply wordToNat_natToWord_idempotent'_iff; eauto.\n Qed.\n\n Definition rep (fsxp : fs_xparams) : rawpred :=\n ([[ fs_xparams_ok fsxp ]] *\n [[ FSXPMagic fsxp = magic_number ]] *\n 0 |+> (v_pickle_superblock fsxp, nil))%pred.\n\n Definition load cs :=\n let^ (cs, v) <- BUFCACHE.read 0 cs;\n Ret ^(cs, v_unpickle_superblock v).\n\n Theorem load_ok : forall cs,\n {< m F fsxp,\n PRE:hm\n BUFCACHE.rep cs m * [[ (F * rep fsxp)%pred m ]]\n POST:hm' RET:^(cs',r)\n BUFCACHE.rep cs' m * [[ r = fsxp ]]\n CRASH:hm'\n exists cs', BUFCACHE.rep cs' m\n >} load cs.\n Proof.\n unfold load, rep.\n hoare.\n apply v_pickle_unpickle_superblock; auto.\n Qed.\n\n Definition init fsxp cs :=\n cs <- BUFCACHE.write 0 (v_pickle_superblock fsxp) cs;\n cs <- BUFCACHE.begin_sync cs;\n cs <- BUFCACHE.sync 0 cs;\n cs <- BUFCACHE.end_sync cs;\n Ret cs.\n\n Theorem init_ok : forall fsxp cs,\n {< m F,\n PRE:hm\n BUFCACHE.rep cs m * \n [[ fs_xparams_ok fsxp ]] *\n [[ FSXPMagic fsxp = magic_number ]] *\n [[ (F * 0 |->?)%pred m ]] *\n [[ sync_invariant F ]]\n POST:hm' RET:cs\n exists m',\n BUFCACHE.rep cs m' * [[ (F * rep fsxp)%pred m' ]]\n XCRASH:hm'\n exists cs' m' vs, BUFCACHE.rep cs' m' * \n [[ (F * 0 |+> vs)%pred m' ]]\n >} init fsxp cs.\n Proof.\n unfold rep, init.\n step.\n rewrite ptsto_pimpl_ptsto_subset; cancel.\n hoare.\n xcrash.\n xcrash.\n xcrash.\n xcrash.\n Qed.\n\n Hint Extern 1 ({{_}} Bind (load _) _) => apply load_ok : prog.\n Hint Extern 1 ({{_}} Bind (init _ _) _) => apply init_ok : prog.\n\n Theorem crash_xform_rep : forall fsxp,\n crash_xform (rep fsxp) <=p=> rep fsxp.\n Proof.\n unfold rep; intros; split;\n rewrite crash_xform_sep_star_dist;\n rewrite crash_xform_sep_star_dist;\n repeat rewrite crash_xform_lift_empty.\n\n rewrite crash_xform_ptsto_subset; cancel.\n rewrite ptsto_pimpl_ptsto_subset.\n subst; auto.\n\n rewrite <- crash_xform_ptsto_subset_r.\n cancel.\n rewrite ptsto_subset_pimpl_ptsto; eauto.\n unfold vsmerge; simpl; auto.\n Qed.\n\n Hint Rewrite crash_xform_rep : crash_xform.\n\n Theorem sync_invariant_rep : forall xp,\n sync_invariant (rep xp).\n Proof.\n unfold rep; eauto.\n Qed.\n\n Hint Resolve sync_invariant_rep.\n Hint Extern 0 (okToUnify (rep _) (rep _)) => constructor : okToUnify.\n\n Theorem rep_magic_number : forall fsxp,\n rep fsxp =p=> rep fsxp * [[ FSXPMagic fsxp = magic_number ]].\n Proof.\n unfold rep; intros; cancel.\n Qed.\n\nEnd SB.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/SuperBlock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.23651624182730094, "lm_q1q2_score": 0.11918199368712515}} {"text": "Require Import compcert.common.AST.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Values.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Maps.\nRequire Import MiscLemmas.\nRequire Import InetDiagConf.\nImport ListNotations.\n\nDefinition port := int.\n\nInductive location : Type :=\n | Reject : location\n | Loc : nat -> location\n .\n\nRecord hostcond : Type := mkhostcond {\n hcfamily : int;\n hcprefixlen : int;\n hcport : port;\n hcaddr : int\n}.\n\nInductive condition : Type :=\n | Sge : port -> condition\n | Sle : port -> condition\n | Dge : port -> condition\n | Dle : port -> condition\n .\n(* TODO Scond and Dcond *)\n\nInductive instruction : Type :=\n | Nop : instruction\n | Jmp : location -> instruction\n | Cjmp : condition -> location -> instruction\n .\n\nDefinition code := list instruction.\n\nSection SEMANTICS.\n\nDefinition function := code.\nDefinition fundef := AST.fundef function.\nDefinition program := AST.program fundef unit.\nDefinition genv := Genv.t fundef unit.\n\nDefinition checkhc (hc: hostcond) (e: block) := false. (* XXX TODO *)\n\nInductive state : Type :=\n | State:\n forall (c: code) (**r current program point *)\n (f: function) (**r current function *)\n (e: block) (**r input entry *)\n (m: mem), (**r memory state *)\n state\n | Callstate:\n forall (fd: fundef) (**r calling function *)\n (e: block) (**r input entry *)\n (m: mem), (**r memory state *)\n state\n | Returnstate:\n forall (v: int) (**r local return value *)\n (m: mem), (**r memory state *)\n state\n .\n\nDefinition field : Type := (memory_chunk * int)%type.\n\nDefinition e_saddr : field := (Mint32, Int.repr 0).\nDefinition e_daddr : field := (Mint32, Int.repr 4).\nDefinition e_sport : field := (Mint16unsigned, Int.repr 8).\nDefinition e_dport : field := (Mint16unsigned, Int.repr 10).\nDefinition e_family : field := (Mint16unsigned, Int.repr 12).\nDefinition e_userlocks : field := (Mint16unsigned, Int.repr 14).\n\nDefinition load_field (f: field) (e: block) (m: mem) : option val :=\n match f with\n | (mc, ofs) => Mem.load mc m e (Int.unsigned ofs)\n end.\n\nDefinition cond_field (cond: condition) : field :=\n match cond with\n | Sge _ | Sle _ => e_sport\n | Dge _ | Dle _ => e_dport\n end.\n\nDefinition eval_cond (cond: condition) (v: int) : bool :=\n match cond with\n | Sge p | Dge p => Int.cmpu Cge v p\n | Sle p | Dle p => Int.cmpu Cle v p\n end.\n\nInductive step (ge: genv) : state -> trace -> state -> Prop :=\n | ST_Accept : forall f e m,\n step ge (State nil f e m) E0 (Returnstate Int.one m)\n | ST_Nop : forall r f e m,\n step ge (State (Nop :: r) f e m) E0 (State r f e m)\n | ST_Jmp_Reject : forall r f e m,\n step ge (State (Jmp Reject :: r) f e m) E0 (Returnstate Int.zero m)\n | ST_Jmp_Loc : forall r f e m n,\n (n <= length r)%nat ->\n step ge (State (Jmp (Loc n) :: r) f e m) E0 (State (skipn n r) f e m)\n | ST_Cjmp_true : forall r f e m v cond loc,\n load_field (cond_field cond) e m = Some (Vint v) ->\n Is_true (eval_cond cond v) ->\n step ge (State (Cjmp cond loc :: r) f e m) E0 (State r f e m)\n | ST_Cjmp_Reject : forall r f e m v cond,\n load_field (cond_field cond) e m = Some (Vint v) ->\n ~ Is_true (eval_cond cond v) ->\n step ge (State (Cjmp cond Reject :: r) f e m) E0 (Returnstate Int.zero m)\n | ST_Cjmp_Loc : forall r f e m v cond n,\n (n <= length r)%nat ->\n load_field (cond_field cond) e m = Some (Vint v) ->\n ~ Is_true (eval_cond cond v) ->\n step ge (State (Cjmp cond (Loc n) :: r) f e m) E0 (State (skipn n r) f e m)\n .\n\nInductive initial_state (p: program): state -> Prop :=\n | initial_state_intro: forall b fd m0 m1 m2 pkt,\n let ge := Genv.globalenv p in\n Genv.init_mem p = Some m0 ->\n Genv.find_symbol ge p.(prog_main) = Some b ->\n Genv.find_funct_ptr ge b = Some fd ->\n Mem.alloc m0 0 sizeof_entry = (m1, pkt) ->\n Mem.storebytes m1 pkt 0 (Memdata.inj_bytes entry_input) = Some m2 ->\n initial_state p (Callstate fd pkt m2).\n\nInductive final_state: state -> int -> Prop :=\n | final_state_intro: forall v m,\n final_state (Returnstate v m) v.\n\nEnd SEMANTICS.\n", "meta": {"author": "utokyo-lzh", "repo": "Jitk", "sha": "7f7f6eb541c7e8a2613974fff5b4fc6fc0783182", "save_path": "github-repos/coq/utokyo-lzh-Jitk", "path": "github-repos/coq/utokyo-lzh-Jitk/Jitk-7f7f6eb541c7e8a2613974fff5b4fc6fc0783182/InetDiag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.22541662103868043, "lm_q1q2_score": 0.11710874095198921}} {"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Smallstep.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Memory.\nRequire Import Values.\nRequire Import Constants.\nRequire Import RData.\nRequire Import Asm.\nRequire Import AsmCode.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import Assembly.Asm.\nRequire Import Assembly.AsmCode.\nRequire Import Assembly.AsmSpec.\nRequire Import RefTactics.\n\nVariable ge: genv.\n\nInductive StarStep: RData -> RData -> Prop :=\n| NoStep: forall d, StarStep d d\n| OneStep:\n forall d d' d'',\n step ge d d' -> StarStep d' d'' -> StarStep d d''.\n\nLtac asm_one_internal_step Hf :=\n eapply OneStep; [\n eapply exec_step_internal; repeat autounfold;\n [simpl; grewrite; reflexivity | eapply Hf | reflexivity |\n simpl; repeat (autounfold; simpl; repeat grewrite; simpl);\n repeat (simpl_update_reg; simpl; repeat grewrite; simpl);\n repeat simpl_field; repeat swap_fields; repeat simpl_field; simpl_htarget; try reflexivity]\n | idtac ].\n\nLtac asm_prep_one_internal_step Hf :=\n eapply OneStep; [\n eapply exec_step_internal; repeat autounfold;\n [simpl; grewrite; reflexivity | eapply Hf | reflexivity |]|].\n\n\nDefinition el3_sync_lel_func : function :=\n {| fn_sig := null_signature;\n fn_code := el3_sync_lel_insn |}.\n\nDefinition save_el2_state_func : function :=\n {| fn_sig := null_signature;\n fn_code := save_el2_state_insn |}.\n\nDefinition restore_el2_state_func : function :=\n {| fn_sig := null_signature;\n fn_code := restore_el2_state_insn |}.\n\nHypothesis el3_sync_lel_function:\n Genv.find_funct_ptr ge (Z.to_pos el3_sync_lel) = Some (Internal el3_sync_lel_func).\nHypothesis save_el2_state_function:\n Genv.find_funct_ptr ge (Z.to_pos save_el2_state) = Some (Internal save_el2_state_func).\nHypothesis restore_el2_state_function:\n Genv.find_funct_ptr ge (Z.to_pos restore_el2_state) = Some (Internal restore_el2_state_func).\n\nVariable f_handle_std_service: external_function.\nHypothesis handle_std_service_function:\n Genv.find_funct_ptr ge (Z.to_pos handle_std_service) = Some (External f_handle_std_service).\n\nHint Unfold\n get_creg set_creg get_pc set_pc get_sp set_sp extend_stack shrink_stack\n nextinstr compare_long eval_testcond eval_testbit eval_testzero\n mem_load mem_store get_stack set_stack goto_label RA get_el3_regs set_el3_regs.\n\nLemma realm_save_el2_state:\n forall d lb ofs d'\n (Hpc: get_pc d = (save_el2_state, 0))\n (Hlabel: get_creg RA d / 10000 = lb)\n (Hoffset: get_creg RA d mod 10000 = ofs)\n (Harg: get_creg x0 d = percpu_data_start + CPUSTATE_REALM_OFFSET),\n let cregs := cpu_regs (priv d) in\n let realm_regs' :=\n (realm_regs_el3 (priv d)) {r_spsr_el3: (r_spsr_el3 cregs)} {r_elr_el3: (r_elr_el3 cregs)} {r_actlr_el2: (r_actlr_el2 cregs)}\n {r_afsr0_el2: (r_afsr0_el2 cregs)} {r_afsr1_el2: (r_afsr1_el2 cregs)} {r_amair_el2: (r_amair_el2 cregs)}\n {r_cnthctl_el2: (r_cnthctl_el2 cregs)} {r_cntvoff_el2: (r_cntvoff_el2 cregs)}\n {r_cptr_el2: (r_cptr_el2 cregs)} {r_elr_el2: (r_elr_el2 cregs)} {r_esr_el2: (r_esr_el2 cregs)}\n {r_far_el2: (r_far_el2 cregs)} {r_hacr_el2: (r_hacr_el2 cregs)} {r_hcr_el2: (r_hcr_el2 cregs)}\n {r_hpfar_el2: (r_hpfar_el2 cregs)} {r_hstr_el2: (r_hstr_el2 cregs)} {r_mair_el2: (r_mair_el2 cregs)}\n {r_mpam_el2: (r_mpam_el2 cregs)} {r_mpamhcr_el2: (r_mpamhcr_el2 cregs)} {r_pmscr_el2: (r_pmscr_el2 cregs)}\n {r_sctlr_el2: (r_sctlr_el2 cregs)} {r_scxtnum_el2: (r_scxtnum_el2 cregs)} {r_sp_el2: (r_sp_el2 cregs)}\n {r_spsr_el2: (r_spsr_el2 cregs)} {r_tcr_el2: (r_tcr_el2 cregs)} {r_tfsr_el2: (r_tfsr_el2 cregs)}\n {r_tpidr_el2: (r_tpidr_el2 cregs)} {r_trfcr_el2: (r_trfcr_el2 cregs)} {r_ttbr0_el2: (r_ttbr0_el2 cregs)}\n {r_ttbr1_el2: (r_ttbr1_el2 cregs)} {r_vbar_el2: (r_vbar_el2 cregs)} {r_vdisr_el2: (r_vdisr_el2 cregs)}\n {r_vmpidr_el2: (r_vmpidr_el2 cregs)} {r_vncr_el2: (r_vncr_el2 cregs)} {r_vpidr_el2: (r_vpidr_el2 cregs)}\n {r_vsesr_el2: (r_vsesr_el2 cregs)} {r_vstcr_el2: (r_vstcr_el2 cregs)} {r_vsttbr_el2: (r_vsttbr_el2 cregs)}\n {r_vtcr_el2: (r_vtcr_el2 cregs)} {r_vttbr_el2: (r_vttbr_el2 cregs)} {r_zcr_el2: (r_zcr_el2 cregs)}\n in\n let d0 := d {priv: (priv d) {realm_regs_el3: realm_regs'}\n {cpu_regs: (cpu_regs (priv d)) {r_x1: r_zcr_el2 (cpu_regs (priv d))}\n {r_x2: r_vttbr_el2 (cpu_regs (priv d))}\n {r_x30: -1}}\n {asm_regs : ((asm_regs (priv d)) {a_CZ : None} {a_PC: (lb, ofs)})}} in\n StarStep d0 d' -> StarStep d d'.\nProof.\n intros until d'.\n repeat autounfold. repeat simpl_update_reg. repeat simpl_field. repeat swap_fields. simpl. intros.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 4096 = false).\n grewrite. bool_rel. omega.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 0 = true).\n grewrite. bool_rel. omega.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n apply H.\nQed.\n\nLemma ns_save_el2_state:\n forall d lb ofs d'\n (Hpc: get_pc d = (save_el2_state, 0))\n (Hlabel: get_creg RA d / 10000 = lb)\n (Hoffset: get_creg RA d mod 10000 = ofs)\n (Harg: get_creg x0 d = percpu_data_start + CPUSTATE_NS_OFFSET),\n let cregs := cpu_regs (priv d) in\n let ns_regs' :=\n (ns_regs_el3 (priv d)) {r_spsr_el3: (r_spsr_el3 cregs)} {r_elr_el3: (r_elr_el3 cregs)} {r_actlr_el2: (r_actlr_el2 cregs)}\n {r_afsr0_el2: (r_afsr0_el2 cregs)} {r_afsr1_el2: (r_afsr1_el2 cregs)} {r_amair_el2: (r_amair_el2 cregs)}\n {r_cnthctl_el2: (r_cnthctl_el2 cregs)} {r_cntvoff_el2: (r_cntvoff_el2 cregs)}\n {r_cptr_el2: (r_cptr_el2 cregs)} {r_elr_el2: (r_elr_el2 cregs)} {r_esr_el2: (r_esr_el2 cregs)}\n {r_far_el2: (r_far_el2 cregs)} {r_hacr_el2: (r_hacr_el2 cregs)} {r_hcr_el2: (r_hcr_el2 cregs)}\n {r_hpfar_el2: (r_hpfar_el2 cregs)} {r_hstr_el2: (r_hstr_el2 cregs)} {r_mair_el2: (r_mair_el2 cregs)}\n {r_mpam_el2: (r_mpam_el2 cregs)} {r_mpamhcr_el2: (r_mpamhcr_el2 cregs)} {r_pmscr_el2: (r_pmscr_el2 cregs)}\n {r_sctlr_el2: (r_sctlr_el2 cregs)} {r_scxtnum_el2: (r_scxtnum_el2 cregs)} {r_sp_el2: (r_sp_el2 cregs)}\n {r_spsr_el2: (r_spsr_el2 cregs)} {r_tcr_el2: (r_tcr_el2 cregs)} {r_tfsr_el2: (r_tfsr_el2 cregs)}\n {r_tpidr_el2: (r_tpidr_el2 cregs)} {r_trfcr_el2: (r_trfcr_el2 cregs)} {r_ttbr0_el2: (r_ttbr0_el2 cregs)}\n {r_ttbr1_el2: (r_ttbr1_el2 cregs)} {r_vbar_el2: (r_vbar_el2 cregs)} {r_vdisr_el2: (r_vdisr_el2 cregs)}\n {r_vmpidr_el2: (r_vmpidr_el2 cregs)} {r_vncr_el2: (r_vncr_el2 cregs)} {r_vpidr_el2: (r_vpidr_el2 cregs)}\n {r_vsesr_el2: (r_vsesr_el2 cregs)} {r_vstcr_el2: (r_vstcr_el2 cregs)} {r_vsttbr_el2: (r_vsttbr_el2 cregs)}\n {r_vtcr_el2: (r_vtcr_el2 cregs)} {r_vttbr_el2: (r_vttbr_el2 cregs)} {r_zcr_el2: (r_zcr_el2 cregs)}\n in\n let d0 := d {priv: (priv d) {ns_regs_el3: ns_regs'}\n {cpu_regs: (cpu_regs (priv d)) {r_x1: r_zcr_el2 (cpu_regs (priv d))}\n {r_x2: r_vttbr_el2 (cpu_regs (priv d))}\n {r_x30: -1}}\n {asm_regs : ((asm_regs (priv d)) {a_CZ : None} {a_PC: (lb, ofs)})}} in\n StarStep d0 d' -> StarStep d d'.\nProof.\n intros until d'.\n repeat autounfold. repeat simpl_update_reg. repeat simpl_field. repeat swap_fields. simpl. intros.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 4096 = true).\n grewrite. bool_rel. omega.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 0 = false).\n grewrite. bool_rel. omega.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n asm_one_internal_step save_el2_state_function.\n apply H.\nQed.\n\n\nLemma ns_restore_el2_state:\n forall d lb ofs d'\n (Hpc: get_pc d = (restore_el2_state, 0))\n (Hlabel: get_creg RA d / 10000 = lb)\n (Hoffset: get_creg RA d mod 10000 = ofs)\n (Harg: get_creg x0 d = percpu_data_start + CPUSTATE_NS_OFFSET),\n let cregs := ns_regs_el3 (priv d) in\n let ns_regs' :=\n (cpu_regs (priv d)) {r_spsr_el3: (r_spsr_el3 cregs)} {r_elr_el3: (r_elr_el3 cregs)} {r_actlr_el2: (r_actlr_el2 cregs)}\n {r_afsr0_el2: (r_afsr0_el2 cregs)} {r_afsr1_el2: (r_afsr1_el2 cregs)} {r_amair_el2: (r_amair_el2 cregs)}\n {r_cnthctl_el2: (r_cnthctl_el2 cregs)} {r_cntvoff_el2: (r_cntvoff_el2 cregs)}\n {r_cptr_el2: (r_cptr_el2 cregs)} {r_elr_el2: (r_elr_el2 cregs)} {r_esr_el2: (r_esr_el2 cregs)}\n {r_far_el2: (r_far_el2 cregs)} {r_hacr_el2: (r_hacr_el2 cregs)} {r_hcr_el2: (r_hcr_el2 cregs)}\n {r_hpfar_el2: (r_hpfar_el2 cregs)} {r_hstr_el2: (r_hstr_el2 cregs)} {r_mair_el2: (r_mair_el2 cregs)}\n {r_mpam_el2: (r_mpam_el2 cregs)} {r_mpamhcr_el2: (r_mpamhcr_el2 cregs)} {r_pmscr_el2: (r_pmscr_el2 cregs)}\n {r_sctlr_el2: (r_sctlr_el2 cregs)} {r_scxtnum_el2: (r_scxtnum_el2 cregs)} {r_sp_el2: (r_sp_el2 cregs)}\n {r_spsr_el2: (r_spsr_el2 cregs)} {r_tcr_el2: (r_tcr_el2 cregs)} {r_tfsr_el2: (r_tfsr_el2 cregs)}\n {r_tpidr_el2: (r_tpidr_el2 cregs)} {r_trfcr_el2: (r_trfcr_el2 cregs)} {r_ttbr0_el2: (r_ttbr0_el2 cregs)}\n {r_ttbr1_el2: (r_ttbr1_el2 cregs)} {r_vbar_el2: (r_vbar_el2 cregs)} {r_vdisr_el2: (r_vdisr_el2 cregs)}\n {r_vmpidr_el2: (r_vmpidr_el2 cregs)} {r_vncr_el2: (r_vncr_el2 cregs)} {r_vpidr_el2: (r_vpidr_el2 cregs)}\n {r_vsesr_el2: (r_vsesr_el2 cregs)} {r_vstcr_el2: (r_vstcr_el2 cregs)} {r_vsttbr_el2: (r_vsttbr_el2 cregs)}\n {r_vtcr_el2: (r_vtcr_el2 cregs)} {r_vttbr_el2: (r_vttbr_el2 cregs)} {r_zcr_el2: (r_zcr_el2 cregs)}\n in\n let d0 := d {priv: (priv d)\n {cpu_regs: ns_regs' {r_x1: r_zcr_el2 (ns_regs_el3 (priv d))}\n {r_x2: r_vttbr_el2 (ns_regs_el3 (priv d))}\n {r_x30: -1}}\n {asm_regs : ((asm_regs (priv d)) {a_CZ : None} {a_PC: (lb, ofs)})}} in\n StarStep d0 d' -> StarStep d d'.\nProof.\n intros until d'.\n repeat autounfold. repeat simpl_update_reg. repeat simpl_field. repeat swap_fields. simpl. intros.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 4096 = true).\n grewrite. bool_rel. omega.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 0 = false).\n grewrite. bool_rel. omega.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n apply H.\nQed.\n\nLemma realm_restore_el2_state:\n forall d lb ofs d'\n (Hpc: get_pc d = (restore_el2_state, 0))\n (Hlabel: get_creg RA d / 10000 = lb)\n (Hoffset: get_creg RA d mod 10000 = ofs)\n (Harg: get_creg x0 d = percpu_data_start + CPUSTATE_REALM_OFFSET),\n let cregs := realm_regs_el3 (priv d) in\n let realm_regs' :=\n (cpu_regs (priv d)) {r_spsr_el3: (r_spsr_el3 cregs)} {r_elr_el3: (r_elr_el3 cregs)} {r_actlr_el2: (r_actlr_el2 cregs)}\n {r_afsr0_el2: (r_afsr0_el2 cregs)} {r_afsr1_el2: (r_afsr1_el2 cregs)} {r_amair_el2: (r_amair_el2 cregs)}\n {r_cnthctl_el2: (r_cnthctl_el2 cregs)} {r_cntvoff_el2: (r_cntvoff_el2 cregs)}\n {r_cptr_el2: (r_cptr_el2 cregs)} {r_elr_el2: (r_elr_el2 cregs)} {r_esr_el2: (r_esr_el2 cregs)}\n {r_far_el2: (r_far_el2 cregs)} {r_hacr_el2: (r_hacr_el2 cregs)} {r_hcr_el2: (r_hcr_el2 cregs)}\n {r_hpfar_el2: (r_hpfar_el2 cregs)} {r_hstr_el2: (r_hstr_el2 cregs)} {r_mair_el2: (r_mair_el2 cregs)}\n {r_mpam_el2: (r_mpam_el2 cregs)} {r_mpamhcr_el2: (r_mpamhcr_el2 cregs)} {r_pmscr_el2: (r_pmscr_el2 cregs)}\n {r_sctlr_el2: (r_sctlr_el2 cregs)} {r_scxtnum_el2: (r_scxtnum_el2 cregs)} {r_sp_el2: (r_sp_el2 cregs)}\n {r_spsr_el2: (r_spsr_el2 cregs)} {r_tcr_el2: (r_tcr_el2 cregs)} {r_tfsr_el2: (r_tfsr_el2 cregs)}\n {r_tpidr_el2: (r_tpidr_el2 cregs)} {r_trfcr_el2: (r_trfcr_el2 cregs)} {r_ttbr0_el2: (r_ttbr0_el2 cregs)}\n {r_ttbr1_el2: (r_ttbr1_el2 cregs)} {r_vbar_el2: (r_vbar_el2 cregs)} {r_vdisr_el2: (r_vdisr_el2 cregs)}\n {r_vmpidr_el2: (r_vmpidr_el2 cregs)} {r_vncr_el2: (r_vncr_el2 cregs)} {r_vpidr_el2: (r_vpidr_el2 cregs)}\n {r_vsesr_el2: (r_vsesr_el2 cregs)} {r_vstcr_el2: (r_vstcr_el2 cregs)} {r_vsttbr_el2: (r_vsttbr_el2 cregs)}\n {r_vtcr_el2: (r_vtcr_el2 cregs)} {r_vttbr_el2: (r_vttbr_el2 cregs)} {r_zcr_el2: (r_zcr_el2 cregs)}\n in\n let d0 := d {priv: (priv d)\n {cpu_regs: realm_regs' {r_x1: r_zcr_el2 (realm_regs_el3 (priv d))}\n {r_x2: r_vttbr_el2 (realm_regs_el3 (priv d))}\n {r_x30: -1}}\n {asm_regs : ((asm_regs (priv d)) {a_CZ : None} {a_PC: (lb, ofs)})}} in\n StarStep d0 d' -> StarStep d d'.\nProof.\n intros until d'.\n repeat autounfold. repeat simpl_update_reg. repeat simpl_field. repeat swap_fields. simpl. intros.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 4096 = false).\n grewrite. bool_rel. omega.\n assert(r_x0 (cpu_regs (priv d)) =? percpu_data_start + 0 = true).\n grewrite. bool_rel. omega.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n asm_one_internal_step restore_el2_state_function.\n apply H.\nQed.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/Assembly/AsmProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2254166158350767, "lm_q1q2_score": 0.11710873824860611}} {"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import strings gmap list.\nFrom iris.proofmode Require Import proofmode.\nFrom melocoton Require Import named_props.\nFrom melocoton.ml_lang Require Import lang_instantiation primitive_laws.\nFrom melocoton.interop Require Export prims.\nFrom melocoton.interop Require Import basics_resources gctoken prims.\n\nSection PrimsProto.\n\nContext `{SI: indexT}.\nContext {Σ : gFunctors}.\nContext `{!heapG_ML Σ, !heapG_C Σ}.\nContext `{!invG Σ}.\nContext `{!wrapperGCtokG Σ}.\n\nNotation C_proto := (protocol C_intf.val Σ).\nNotation ML_proto := (protocol ML_lang.val Σ).\n\n(* TODO: move *)\nDefinition wrap_proto (Ψ : ML_proto) : C_proto := (λ f ws Φ,\n ∃ θ vs lvs Φ',\n \"HGC\" ∷ GC θ ∗\n \"%Hrepr\" ∷ ⌜Forall2 (repr_lval θ) lvs ws⌝ ∗\n \"Hsim\" ∷ lvs ~~∗ vs ∗\n \"Hproto\" ∷ Ψ f vs Φ' ∗\n \"Cont\" ∷ ▷ (∀ θ' vret lvret wret,\n GC θ' -∗\n Φ' vret -∗\n lvret ~~ vret -∗\n ⌜repr_lval θ' lvret wret⌝ -∗\n Φ wret)\n)%I.\n\nLemma wrap_proto_mono Ψ Ψ' : Ψ ⊑ Ψ' → wrap_proto Ψ ⊑ wrap_proto Ψ'.\nProof using.\n iIntros (Hre ? ? ?) \"H\". unfold wrap_proto. iNamed \"H\".\n rewrite /named. iExists _, _, _, _. iFrame. iSplit; first done.\n by iApply Hre.\nQed.\n\nDefinition int2val_proto : C_proto := (λ fn vl Φ,\n ∃ θ z,\n \"->\" ∷ ⌜fn = \"int2val\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [C_intf.LitV $ C_intf.LitInt $ z]⌝ ∗\n \"Cont\" ∷ ▷ (∀ w, GC θ -∗ ⌜repr_lval θ (Lint z) w⌝ -∗ Φ w))%I.\n\nDefinition val2int_proto : C_proto := (λ fn vl Φ,\n ∃ θ w z,\n \"->\" ∷ ⌜fn = \"val2int\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w ]⌝ ∗\n \"%Hrepr\" ∷ ⌜repr_lval θ (Lint z) w⌝ ∗\n \"Cont\" ∷ ▷ (GC θ -∗ Φ (C_intf.LitV $ C_intf.LitInt $ z)))%I.\n\nDefinition registerroot_proto : C_proto := (λ fn vl Φ,\n ∃ θ l v w,\n \"->\" ∷ ⌜fn = \"registerroot\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ C_intf.LitV $ C_intf.LitLoc $ l ]⌝ ∗\n \"Hpto\" ∷ l ↦C w ∗\n \"%Hrepr\" ∷ ⌜repr_lval θ v w⌝ ∗\n \"Cont\" ∷ ▷ (GC θ -∗ l ↦roots v -∗ Φ (C_intf.LitV $ C_intf.LitInt $ 0)))%I.\n\nDefinition unregisterroot_proto : C_proto := (λ fn vl Φ,\n ∃ θ l v,\n \"->\" ∷ ⌜fn = \"unregisterroot\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ C_intf.LitV $ C_intf.LitLoc $ l ]⌝ ∗\n \"Hpto\" ∷ l ↦roots v ∗\n \"Cont\" ∷ ▷ (∀ w, GC θ -∗ l ↦C w -∗ ⌜repr_lval θ v w⌝ -∗ Φ (C_intf.LitV $ C_intf.LitInt $ 0)))%I.\n\nDefinition modify_proto : C_proto := (λ fn vl Φ,\n ∃ θ w i v' w' γ mut tg vs,\n \"->\" ∷ ⌜fn = \"modify\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w; C_intf.LitV $ C_intf.LitInt $ i; w' ]⌝ ∗\n \"%Hreprw\" ∷ ⌜repr_lval θ (Lloc γ) w⌝ ∗\n \"%Hptomut\" ∷ ⌜vblock_access_le M mut⌝ ∗\n \"Hpto\" ∷ γ ↦vblk[mut] (tg, vs) ∗\n \"%Hreprw'\" ∷ ⌜repr_lval θ v' w'⌝ ∗\n \"%Hi1\" ∷ ⌜0 ≤ i⌝%Z ∗\n \"%Hi2\" ∷ ⌜i < length vs⌝%Z ∗\n \"Cont\" ∷ ▷ (GC θ -∗\n γ ↦vblk[mut] (tg, <[Z.to_nat i:=v']> vs) -∗\n Φ (C_intf.LitV $ C_intf.LitInt $ 0)))%I.\n\nDefinition readfield_proto : C_proto := (λ fn vl Φ,\n ∃ θ w i γ dq m tg vs,\n \"->\" ∷ ⌜fn = \"readfield\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w; C_intf.LitV $ C_intf.LitInt $ i ]⌝ ∗\n \"%Hreprw\" ∷ ⌜repr_lval θ (Lloc γ) w⌝ ∗\n \"Hpto\" ∷ γ ↦vblk[m]{dq} (tg, vs) ∗\n \"%Hi1\" ∷ ⌜0 ≤ i⌝%Z ∗\n \"%Hi2\" ∷ ⌜i < length vs⌝%Z ∗\n \"Cont\" ∷ ▷ (∀ v' w', GC θ -∗\n γ ↦vblk[m]{dq} (tg, vs) -∗\n ⌜vs !! (Z.to_nat i) = Some v'⌝ -∗\n ⌜repr_lval θ v' w'⌝ -∗\n Φ w'))%I.\n\nDefinition alloc_proto : C_proto := (λ fn vl Φ,\n ∃ θ tg sz,\n \"->\" ∷ ⌜fn = \"alloc\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ C_intf.LitV $ C_intf.LitInt $ vblock_tag_as_int $ tg; C_intf.LitV $ C_intf.LitInt $ sz ]⌝ ∗\n \"%Hsz\" ∷ ⌜0 ≤ sz⌝%Z ∗\n \"Cont\" ∷ ▷ (∀ θ' γ w, GC θ' -∗\n γ ↦fresh (tg, List.repeat (Lint 0) (Z.to_nat sz)) -∗\n ⌜repr_lval θ' (Lloc γ) w⌝ -∗\n Φ w))%I.\n\nDefinition alloc_foreign_proto : C_proto := (λ fn vl Φ,\n ∃ θ,\n \"->\" ∷ ⌜fn = \"alloc_foreign\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ ]⌝ ∗\n \"Cont\" ∷ ▷ (∀ θ' γ w, GC θ' -∗\n γ ↦foreignO None -∗\n ⌜repr_lval θ' (Lloc γ) w⌝ -∗\n Φ w))%I.\n\nDefinition write_foreign_proto : C_proto := (λ fn vl Φ,\n ∃ θ γ w wo w',\n \"->\" ∷ ⌜fn = \"write_foreign\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w; w' ]⌝ ∗\n \"%Hreprw\" ∷ ⌜repr_lval θ (Lloc γ) w⌝ ∗\n \"Hpto\" ∷ γ ↦foreignO wo ∗\n \"Cont\" ∷ ▷ (GC θ -∗\n γ ↦foreign w' -∗\n Φ (C_intf.LitV (C_intf.LitInt 0))))%I.\n\nDefinition read_foreign_proto : C_proto := (λ fn vl Φ,\n ∃ θ γ w w',\n \"->\" ∷ ⌜fn = \"read_foreign\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w ]⌝ ∗\n \"%Hreprw\" ∷ ⌜repr_lval θ (Lloc γ) w⌝ ∗\n \"Hpto\" ∷ γ ↦foreign w' ∗\n \"Cont\" ∷ ▷ (GC θ -∗\n γ ↦foreign w' -∗\n Φ w'))%I.\n\nDefinition callback_proto E (Ψ : ML_proto) : C_proto := (λ fn vl Φ,\n ∃ θ w γ w' lv' v' f x e Φ',\n \"->\" ∷ ⌜fn = \"callback\"⌝ ∗\n \"HGC\" ∷ GC θ ∗\n \"->\" ∷ ⌜vl = [ w; w' ]⌝ ∗\n \"%Hreprw\" ∷ ⌜repr_lval θ (Lloc γ) w⌝ ∗\n \"Hclos\" ∷ γ ↦clos (f, x, e) ∗\n \"%Hreprw'\" ∷ ⌜repr_lval θ lv' w'⌝ ∗\n \"Hsim'\" ∷ lv' ~~ v' ∗\n \"WPcallback\" ∷ ▷ WP (App (Val (RecV f x e)) (Val v')) @ ⟨∅, Ψ⟩ ; E {{ Φ' }} ∗\n \"Cont\" ∷ ▷ (∀ θ' vret lvret wret,\n GC θ' -∗\n Φ' vret -∗\n lvret ~~ vret -∗\n ⌜repr_lval θ' lvret wret⌝ -∗\n Φ wret))%I.\n\nDefinition main_proto (E: coPset) (e : ML_lang.expr) (Ψ : ML_proto) : C_proto := (λ fn vl Φ,\n ∃ Φ',\n \"->\" ∷ ⌜fn = \"main\"⌝ ∗\n \"->\" ∷ ⌜vl = []⌝ ∗\n \"Hat_init\" ∷ at_init ∗\n \"WPmain\" ∷ ▷ WP e @ ⟨∅, Ψ⟩; E {{ Φ' }} ∗\n \"Cont\" ∷ ▷ (∀ θ' vret lvret wret,\n GC θ' -∗\n Φ' vret -∗\n lvret ~~ vret -∗\n ⌜repr_lval θ' lvret wret⌝ -∗\n Φ wret)\n )%I.\n\nDefinition prim_proto (p : prim) E (Ψ : ML_proto) : C_proto :=\n match p with\n | Pint2val => int2val_proto\n | Pval2int => val2int_proto\n | Pregisterroot => registerroot_proto\n | Punregisterroot => unregisterroot_proto\n | Pmodify => modify_proto\n | Preadfield => readfield_proto\n | Palloc => alloc_proto\n | Pallocforeign => alloc_foreign_proto\n | Pwriteforeign => write_foreign_proto\n | Preadforeign => read_foreign_proto\n | Pcallback => callback_proto E Ψ\n | Pmain e => main_proto E e Ψ\n end.\n\nDefinition prims_proto E e (Ψ : ML_proto) : C_proto :=\n (λ fn vs Φ, ∃ p, ⌜prims_prog e !! fn = Some p⌝ ∗\n prim_proto p E Ψ fn vs Φ)%I.\n\nLemma proto_prim_mask_mono E1 E2 e Ψ : E1 ⊆ E2 →\n ∀ fn vl Φ, prims_proto E1 e Ψ fn vl Φ -∗ prims_proto E2 e Ψ fn vl Φ.\nProof using.\n iIntros (H fn vl Φ) \"H\". iDestruct \"H\" as (p Hp) \"H\". iExists p.\n iSplit; first done.\n destruct p; try done. all: cbn; iNamed \"H\".\n { do 10 iExists _; unfold named.\n iFrame. do 4 (iSplit; first done).\n iNext. iApply wp_mask_mono. 1: done.\n iFrame. }\n { unfold main_proto, named. iExists Φ'. iFrame. do 2 (iSplit; first done).\n iNext. iApply wp_mask_mono; first done. iFrame. }\nQed.\n\nLemma prims_proto_except_dom E e Ψ :\n (prims_proto E e Ψ) except (dom (prims_prog e)) ⊑ ⊥.\nProof using.\n iIntros (? ? ?) \"H\". rewrite /proto_except.\n iDestruct \"H\" as (Hdom p ?) \"H\".\n apply not_elem_of_dom in Hdom.\n destruct p; unfold prim_proto; iNamed \"H\"; by exfalso.\nQed.\n\n(* some boilerplate *)\nLocal Ltac tac p :=\n iIntros (? ? ?) \"H\"; iExists p; (iSplit; last iFrame); by iNamed \"H\".\nLemma int2val_refines_prims_proto E e Ψ : int2val_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pint2val. Qed.\nLemma val2int_refines_prims_proto E e Ψ : val2int_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pval2int. Qed.\nLemma registerroot_refines_prims_proto E e Ψ : registerroot_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pregisterroot. Qed.\nLemma unregisterroot_refines_prims_proto E e Ψ : unregisterroot_proto ⊑ prims_proto E e Ψ.\nProof using. tac Punregisterroot. Qed.\nLemma modify_refines_prims_proto E e Ψ : modify_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pmodify. Qed.\nLemma readfield_refines_prims_proto E e Ψ : readfield_proto ⊑ prims_proto E e Ψ.\nProof using. tac Preadfield. Qed.\nLemma alloc_refines_prims_proto E e Ψ : alloc_proto ⊑ prims_proto E e Ψ.\nProof using. tac Palloc. Qed.\nLemma alloc_foreign_refines_prims_proto E e Ψ : alloc_foreign_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pallocforeign. Qed.\nLemma write_foreign_refines_prims_proto E e Ψ : write_foreign_proto ⊑ prims_proto E e Ψ.\nProof using. tac Pwriteforeign. Qed.\nLemma read_foreign_refines_prims_proto E e Ψ : read_foreign_proto ⊑ prims_proto E e Ψ.\nProof using. tac Preadforeign. Qed.\nLemma callback_refines_prims_proto E e Ψ : callback_proto E Ψ ⊑ prims_proto E e Ψ.\nProof using. tac Pcallback. Qed.\nLemma main_refines_prims_proto E e Ψ : main_proto E e Ψ ⊑ prims_proto E e Ψ.\nProof using. tac (Pmain e). Qed.\n\nEnd PrimsProto.\n\nGlobal Hint Resolve int2val_refines_prims_proto : core.\nGlobal Hint Resolve val2int_refines_prims_proto : core.\nGlobal Hint Resolve registerroot_refines_prims_proto : core.\nGlobal Hint Resolve unregisterroot_refines_prims_proto : core.\nGlobal Hint Resolve modify_refines_prims_proto : core.\nGlobal Hint Resolve readfield_refines_prims_proto : core.\nGlobal Hint Resolve alloc_refines_prims_proto : core.\nGlobal Hint Resolve alloc_foreign_refines_prims_proto : core.\nGlobal Hint Resolve write_foreign_refines_prims_proto : core.\nGlobal Hint Resolve read_foreign_refines_prims_proto : core.\nGlobal Hint Resolve callback_refines_prims_proto : core.\nGlobal Hint Resolve main_refines_prims_proto : core.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/interop/prims_proto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.22815649691270326, "lm_q1q2_score": 0.1167514679413649}} {"text": "(** Sharpened ADT for an expression grammar with parentheses *)\nRequire Import Coq.Init.Wf Coq.Arith.Wf_nat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List Coq.Strings.String.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.Wf.\nRequire Import Fiat.Common.Enumerable.\nRequire Import Fiat.Common.LogicFacts.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.Splitters.BruteForce.\nRequire Import Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.BooleanRecognizerFull.\nRequire Import Fiat.Parsers.BooleanRecognizerCorrect.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.ForallChars.\nRequire Import Fiat.Parsers.StringLike.FirstChar.\nRequire Import Fiat.Parsers.StringLike.FirstCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.LastChar.\nRequire Import Fiat.Parsers.StringLike.LastCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.MinimalParseOfParse.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fold.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidProperties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.Refinement.DisjointLemmasEarlyDeclarations.\nRequire Import Fiat.Parsers.Refinement.PossibleTerminalsSets.\nRequire Import Fiat.Common.BoolFacts.\nRequire Fiat.Parsers.Reachable.All.MinimalReachable.\nRequire Fiat.Parsers.Reachable.All.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.All.ReachableParse.\nRequire Fiat.Parsers.Reachable.OnlyFirst.MinimalReachable.\nRequire Fiat.Parsers.Reachable.OnlyFirst.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.OnlyFirst.ReachableParse.\nRequire Fiat.Parsers.Reachable.OnlyLast.MinimalReachable.\nRequire Fiat.Parsers.Reachable.OnlyLast.MinimalReachableOfReachable.\nRequire Fiat.Parsers.Reachable.OnlyLast.ReachableParse.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.Core.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.MinimalOfCore.\nRequire Fiat.Parsers.Reachable.MaybeEmpty.OfParse.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_like_scope.\n\nLocal Arguments string_beq : simpl never.\n\nSection search_forward.\n Context {G : pregrammar' Ascii.ascii}\n {HSLM : StringLikeMin Ascii.ascii}\n {HSL : StringLike Ascii.ascii}\n {HSI : StringIso Ascii.ascii}\n {HSLP : StringLikeProperties Ascii.ascii}\n {HSIP : StringIsoProperties Ascii.ascii}\n (pdata : possible_data G).\n\n Local Notation possible_terminals_of nt\n := (@all_possible_ascii_of_nt G pdata nt).\n Local Notation possible_first_terminals_of_production its\n := (@possible_first_ascii_of_production G pdata its).\n Local Notation might_be_empty_of_production its\n := (@might_be_empty_of_pr_production G pdata its).\n\n Lemma terminals_disjoint_search_for_not'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq\n (possible_terminals_of nt)\n (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars__char_in (take n str) (possible_terminals_of nt)\n /\\ ((length str <= n /\\ might_be_empty_of_production its)\n \\/ (for_first_char\n (drop n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt)))\n /\\ n < length str)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.le_dec (length str) n); [ left | right ].\n { split; trivial.\n pose proof (drop_length str n) as H.\n rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption.\n generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP.\n intros.\n eapply might_be_empty_pr_parse_of_production; eassumption. }\n { split; try omega; [].\n eapply first_char_in__impl__for_first_char;\n [\n | apply possible_first_ascii_parse_of_production; eassumption ].\n intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } }\n { apply (all_possible_ascii_of_item_nt pit). }\n Qed.\n\n Lemma terminals_disjoint_search_for_not\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_first_char_such_that\n (might_be_empty_of_production its)\n str\n n\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt))).\n Proof.\n pose proof (terminals_disjoint_search_for_not' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | H1]]; solve [ left; eauto | right; eauto ] ].\n revert H0.\n apply forall_chars__char_in__impl__forall_chars.\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H''.\n apply H''.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption.\n Qed.\n\n Lemma terminals_disjoint_search_for'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars (take n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_first_terminals_of_production its)))\n /\\ ((length str <= n /\\ might_be_empty_of_production its)\n \\/ (first_char_in\n (drop n str)\n (possible_first_terminals_of_production its)\n /\\ n < length str)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.le_dec (length str) n); [ left | right ].\n { split; trivial.\n pose proof (drop_length str n) as H.\n rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption.\n generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP.\n intros.\n eapply might_be_empty_pr_parse_of_production; eassumption. }\n { split; try omega; try assumption.\n apply possible_first_ascii_parse_of_production; assumption. } }\n { eapply forall_chars__char_in__impl__forall_chars.\n { intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. }\n { apply all_possible_ascii_of_item_nt; assumption. } }\n Qed.\n\n Lemma terminals_disjoint_search_for\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_first_char_such_that\n (might_be_empty_of_production its)\n str\n n\n (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production its)).\n Proof.\n pose proof (terminals_disjoint_search_for' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | [H1 ?]]]; [ right | left; split ]; eauto ].\n { revert H0.\n apply forall_chars_Proper; [ reflexivity | ].\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H'.\n apply H'.\n assumption. }\n { revert H1.\n apply first_char_in__impl__for_first_char.\n intros ch H'.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. }\n Qed.\nEnd search_forward.\n\nSection search_backward.\n Context {G : pregrammar' Ascii.ascii}\n {HSLM : StringLikeMin Ascii.ascii}\n {HSL : StringLike Ascii.ascii}\n {HSI : StringIso Ascii.ascii}\n {HSLP : StringLikeProperties Ascii.ascii}\n {HSIP : StringIsoProperties Ascii.ascii}\n (pdata : possible_data G).\n\n Local Notation possible_terminals_of_production its\n := (@all_possible_ascii_of_production G pdata its).\n Local Notation possible_last_terminals_of nt\n := (@possible_last_ascii_of_nt G pdata nt).\n Local Notation might_be_empty_of nt\n := (@might_be_empty_of_pr_nt G pdata nt).\n\n Lemma terminals_disjoint_rev_search_for_not'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars__char_in (drop n str) (possible_terminals_of_production its)\n /\\ ((n = 0 /\\ might_be_empty_of nt)\n \\/ (for_last_char\n (take n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its)))\n /\\ n > 0)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.zerop n); [ left | right ].\n { split; trivial; []; subst.\n eapply might_be_empty_pr_parse_of_item_nt; try eassumption.\n rewrite take_length; reflexivity. }\n { split; try omega; [].\n eapply last_char_in__impl__for_last_char;\n [\n | apply possible_last_ascii_parse_of_item_nt; eassumption ].\n intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } }\n { apply all_possible_ascii_of_parse_of_production; assumption. }\n Qed.\n\n Lemma terminals_disjoint_rev_search_for_not\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_after_last_char_such_that\n str\n n\n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its))).\n Proof.\n pose proof (terminals_disjoint_rev_search_for_not' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | H1]];\n destruct_head and;\n try solve [ left; eauto\n | right; eauto\n | assumption\n | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ].\n revert H0.\n apply forall_chars__char_in__impl__forall_chars.\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H''.\n apply H''; clear H''.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption.\n Qed.\n\n Lemma terminals_disjoint_rev_search_for'\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : forall_chars (drop n str)\n (fun ch => negb (list_bin ascii_beq ch (possible_last_terminals_of nt)))\n /\\ ((n = 0 /\\ might_be_empty_of nt)\n \\/ (last_char_in\n (take n str)\n (possible_last_terminals_of nt)\n /\\ n > 0)).\n Proof.\n destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ].\n pose proof HinV as HinV';\n rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'.\n apply and_comm; split.\n { destruct (Compare_dec.zerop n); [ left | right ].\n { split; trivial; [].\n eapply might_be_empty_pr_parse_of_item_nt; try eassumption.\n rewrite take_length; subst; reflexivity. }\n { split; try omega; try assumption; [].\n apply possible_last_ascii_parse_of_item_nt; assumption. } }\n { eapply forall_chars__char_in__impl__forall_chars.\n { intros ch H'.\n apply Bool.negb_true_iff, Bool.not_true_iff_false.\n intro H''.\n apply list_in_bl in H''; [ | apply (@ascii_bl) ].\n eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ].\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint.\n apply H_disjoint.\n apply list_in_lb; [ apply (@ascii_lb) | eassumption ]. }\n { apply all_possible_ascii_of_parse_of_production; assumption. } }\n Qed.\n\n Lemma terminals_disjoint_rev_search_for\n (str : @String Ascii.ascii HSLM)\n {nt its}\n (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its))\n {n}\n (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt))\n (pits : parse_of_production G (StringLike.drop n str) its)\n (H_reachable : production_is_reachable G (NonTerminal nt :: its))\n : is_after_last_char_such_that\n str\n n\n (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt)).\n Proof.\n pose proof (terminals_disjoint_rev_search_for' _ H_disjoint pit pits H_reachable) as H.\n split;\n [ destruct H as [H0 H1]\n | destruct H as [H0 [[H1 H2] | [H1 ?]]];\n try solve [ right; eauto\n | left; split; eauto\n | assumption\n | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ].\n { revert H0.\n apply forall_chars_Proper; [ reflexivity | ].\n intros ch H' H''.\n apply Bool.negb_true_iff, Bool.not_true_iff_false in H'.\n apply H'.\n assumption. }\n { revert H1.\n apply last_char_in__impl__for_last_char.\n intros ch H'.\n apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. }\n Qed.\nEnd search_backward.\n\nLtac get_grammar :=\n lazymatch goal with\n | [ |- context[ParserInterface.split_list_is_complete_idx ?G] ] => G\n end.\n\n(*Ltac pose_rvalid_for G :=\n lazymatch goal with\n | [ H : is_true (grammar_rvalid G) |- _ ] => idtac\n | _ => let Hvalid := fresh \"Hvalid\" in\n assert (Hvalid : is_true (grammar_rvalid G))\n by (vm_compute; reflexivity)\n end.\nLtac pose_rvalid := let G := get_grammar in pose_rvalid_for G.*)\n\nModule Export Exports.\n Export DisjointLemmasEarlyDeclarations.\n (** hide the arguments to Build_disjoint_search_data *)\n Local Arguments FromAbstractInterpretation.Build_fold_grammar_data' {_ _ _ _ _} _ _ : assert.\n Notation precomputed_search_data\n := (FromAbstractInterpretation.Build_fold_grammar_data' _ _).\n\n Ltac do_disjoint_precomputations _ ::=\n let G := get_grammar in\n lazymatch goal with\n | [ |- context[@ParserInterface.split_list_is_complete_idx _ G ?HSLM ?HSL] ]\n => pose (_ : @StringLikeProperties _ HSLM HSL)\n end;\n pose_possible_data_for G.\nEnd Exports.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Parsers/Refinement/DisjointLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.21733751597763018, "lm_q1q2_score": 0.11629696328124098}} {"text": "Require Import msl.Coqlib2.\nRequire Import msl.eq_dec.\nRequire Import msl.seplog.\nRequire Import msl.age_to.\nRequire Import veric.aging_lemmas.\nRequire Import veric.juicy_mem.\nRequire Import veric.juicy_mem_lemmas.\nRequire Import veric.compcert_rmaps.\nRequire Import veric.Clight_new.\nRequire Import veric.semax.\nRequire Import veric.semax_ext.\nRequire Import veric.juicy_extspec.\nRequire Import veric.juicy_extspec.\nRequire Import veric.tycontext.\nRequire Import veric.res_predicates.\nRequire Import veric.mem_lessdef.\nRequire Import veric.coqlib4.\nRequire Import concurrency.lksize.\nRequire Import concurrency.sync_preds_defs.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nLemma resource_decay_LK {b phi phi' loc rsh sh n pp} :\n resource_decay b phi phi' ->\n phi @ loc = YES rsh sh (LK n) pp ->\n phi' @ loc = YES rsh sh (LK n) (preds_fmap (approx (level phi')) (approx (level phi')) pp).\nProof.\n intros [L R] E.\n specialize (R loc).\n rewrite E in *.\n destruct R as [N [R|[R|[R|R]]]].\n - rewrite <- R.\n reflexivity.\n - destruct R as [sh' [v [v' [R H]]]]. simpl in R. congruence.\n - destruct R as [v [v' R]]. specialize (N ltac:(auto)). congruence.\n - destruct R as [v [pp' [R H]]]. congruence.\nQed.\n\nLemma resource_decay_CT {b phi phi' loc rsh sh n} :\n resource_decay b phi phi' ->\n phi @ loc = YES rsh sh (CT n) NoneP ->\n phi' @ loc = YES rsh sh (CT n) NoneP.\nProof.\n intros [L R] E.\n specialize (R loc).\n rewrite E in *.\n destruct R as [N [R|[R|[R|R]]]].\n - rewrite <- R.\n unfold resource_fmap in *; f_equal.\n - destruct R as [sh' [v [v' [R H]]]]. simpl in R. congruence.\n - destruct R as [v [v' R]]. specialize (N ltac:(auto)). congruence.\n - destruct R as [v [pp' [R H]]]. congruence.\nQed.\n\nLemma resource_decay_LK_inv {b phi phi' loc rsh sh n pp'} :\n resource_decay b phi phi' ->\n phi' @ loc = YES rsh sh (LK n) pp' ->\n exists pp,\n pp' = preds_fmap (approx (level phi')) (approx (level phi')) pp /\\\n phi @ loc = YES rsh sh (LK n) pp.\nProof.\n intros [L R] E.\n specialize (R loc).\n rewrite E in *.\n destruct R as [N [R|[R|[R|R]]]].\n - destruct (phi @ loc); simpl in R; try discriminate.\n eexists.\n injection R. intros; subst.\n split; reflexivity.\n - destruct R as [sh' [v [v' [R H]]]]; congruence.\n - destruct R as [v [v' R]]; congruence.\n - destruct R as [v [pp [R H]]]; congruence.\nQed.\n\nLemma resource_decay_identity {b phi phi' loc} :\n resource_decay b phi phi' ->\n (fst loc < b)%positive ->\n identity (phi @ loc) ->\n identity (phi' @ loc).\nProof.\n intros [lev RD] LT ID; specialize (RD loc).\n destruct RD as [N [RD|[RD|[RD|RD]]]].\n destruct (phi @ loc) as [t | t p k p0 | k p]; simpl in RD; try rewrite <- RD.\n - auto.\n - apply YES_not_identity in ID. tauto.\n - apply PURE_identity.\n - destruct RD as (? & sh & _ & E & _).\n destruct (phi @ loc); simpl in E; try discriminate.\n apply YES_not_identity in ID. tauto.\n - destruct RD. auto with *.\n - destruct RD as (? & ? & ? & ->).\n apply NO_identity.\nQed.\n\nLemma resource_decay_LK_at {b phi phi' R sh loc} :\n resource_decay b phi phi' ->\n (fst loc < b)%positive ->\n (LK_at R sh loc) phi ->\n (LK_at (approx (level phi) R) sh loc) phi'.\nProof.\n intros RD LT LKAT loc'.\n specialize (LKAT loc').\n destruct (adr_range_dec loc LKSIZE loc') as [range|notrange]; swap 1 2.\n - rewrite jam_false in *; auto.\n - rewrite jam_true in *; auto.\n destruct (eq_dec loc loc') as [<-|noteq].\n + rewrite jam_true in *; auto.\n destruct LKAT as [p E]; simpl in E.\n apply (resource_decay_LK RD) in E.\n eexists.\n hnf.\n rewrite E.\n reflexivity.\n + rewrite jam_false in *; auto.\n destruct LKAT as [p E]; simpl in E.\n eexists; simpl.\n apply (resource_decay_CT RD) in E.\n rewrite E.\n reflexivity.\nQed.\n\nLemma resource_decay_lkat' {b phi phi' R loc} :\n resource_decay b phi phi' ->\n (fst loc < b)%positive ->\n (lkat R loc) phi ->\n (lkat (approx (level phi) R) loc) phi'.\nProof.\n intros RD LT LKAT loc' r.\n specialize (LKAT loc' r).\n destruct LKAT as (sh & rsh & E); exists sh, rsh.\n if_tac.\n - apply (resource_decay_LK RD) in E. rewrite E; reflexivity.\n - apply (resource_decay_CT RD) in E. rewrite E; reflexivity.\nQed.\n\nLemma resource_decay_lkat {b phi phi' R loc} :\n resource_decay b phi phi' ->\n (fst loc < b)%positive ->\n (lkat R loc) phi ->\n (lkat (approx (level phi') R) loc) phi'.\nProof.\n intros RD LT LKAT loc' r.\n specialize (LKAT loc' r).\n destruct LKAT as (sh & rsh & E); exists sh, rsh.\n if_tac.\n - apply (resource_decay_LK RD) in E. rewrite E. f_equal.\n unfold preds_fmap in *.\n unfold pack_res_inv in *.\n f_equal.\n unfold fmap.\n simpl.\n extensionality Ts.\n destruct RD as (Hlev, _).\n pose proof approx_oo_approx' (level phi') (level phi) as RR'.\n pose proof approx_oo_approx (level phi') as RR.\n autospec RR'.\n unfold \"oo\" in *.\n rewrite (equal_f RR' R).\n rewrite (equal_f RR R).\n reflexivity.\n - apply (resource_decay_CT RD) in E. rewrite E; reflexivity.\nQed.\n\nLemma resource_decay_LK_at' {b phi phi' R sh loc} :\n resource_decay b phi phi' ->\n (fst loc < b)%positive ->\n (LK_at R sh loc) phi ->\n (LK_at (approx (level phi') R) sh loc) phi'.\nProof.\n intros RD LT LKAT loc'.\n specialize (LKAT loc').\n destruct (adr_range_dec loc LKSIZE loc') as [range|notrange]; swap 1 2.\n - rewrite jam_false in *; auto.\n - rewrite jam_true in *; auto.\n destruct (eq_dec loc loc') as [<-|noteq].\n + rewrite jam_true in *; auto.\n destruct LKAT as [p E]; simpl in E.\n apply (resource_decay_LK RD) in E.\n eexists.\n hnf.\n rewrite E.\n f_equal.\n simpl.\n f_equal.\n extensionality.\n change (approx (level phi') (approx (level phi) R)) with\n ((approx (level phi') oo approx (level phi)) R).\n rewrite approx_oo_approx' by apply RD.\n unfold \"oo\".\n change (approx (level phi') (approx (level phi') R))\n with ((approx (level phi') oo approx (level phi')) R).\n rewrite approx_oo_approx.\n reflexivity.\n + rewrite jam_false in *; auto.\n destruct LKAT as [p E]; simpl in E.\n eexists; simpl.\n apply (resource_decay_CT RD) in E.\n rewrite E.\n reflexivity.\nQed.\n\nLemma resource_decay_PURE {b phi phi'} :\n resource_decay b phi phi' ->\n forall loc sh P,\n phi @ loc = PURE sh P ->\n phi' @ loc = PURE sh (preds_fmap (approx (level phi')) (approx (level phi')) P).\nProof.\n intros [L RD] loc sh P PAT.\n specialize (RD loc).\n destruct RD as [N [RD|[RD|[RD|RD]]]].\n - rewrite PAT in RD; simpl in RD. rewrite RD; auto.\n - rewrite PAT in RD; simpl in RD. destruct RD as (?&?&?&?&?). congruence.\n - rewrite PAT in N. pose proof (N (proj1 RD)). congruence.\n - rewrite PAT in RD; simpl in RD. destruct RD as (?&?&?&?). congruence.\nQed.\n\nLemma resource_decay_PURE_inv {b phi phi'} :\n resource_decay b phi phi' ->\n forall loc sh P',\n phi' @ loc = PURE sh P' ->\n exists P,\n phi @ loc = PURE sh P /\\\n P' = preds_fmap (approx (level phi')) (approx (level phi')) P.\nProof.\n intros [L RD] loc sh P PAT.\n specialize (RD loc).\n destruct RD as [N [RD|[RD|[RD|RD]]]].\n all: rewrite PAT in *; destruct (phi @ loc); simpl in *.\n all: inversion RD; subst; eauto.\n all: repeat match goal with H : ex _ |- _ => destruct H end.\n all: repeat match goal with H : and _ _ |- _ => destruct H end.\n all: discriminate.\nQed.\n\nLemma resource_decay_func_at' {b phi phi'} :\n resource_decay b phi phi' ->\n forall loc fs,\n seplog.func_at' fs loc phi ->\n seplog.func_at' fs loc phi'.\nProof.\n intros RD loc [f cc A P Q] [pp E]; simpl.\n rewrite (resource_decay_PURE RD _ _ _ E).\n eexists. reflexivity.\nQed.\n\nLemma resource_decay_func_at'_inv {b phi phi'} :\n resource_decay b phi phi' ->\n forall loc fs,\n seplog.func_at' fs loc phi' ->\n seplog.func_at' fs loc phi.\nProof.\n intros RD loc [f cc A P Q] [pp E]; simpl.\n destruct (resource_decay_PURE_inv RD _ _ _ E) as [pp' [Ephi E']].\n pose proof resource_at_approx phi loc as H.\n rewrite Ephi in H at 1. rewrite <-H.\n eexists. reflexivity.\nQed.\n\nLemma resource_decay_same_locks {b phi phi'} :\n resource_decay b phi phi' -> same_locks phi phi'.\nProof.\n intros R loc; split; intros (rsh & sh & n & pp & E).\n - repeat eexists. eapply resource_decay_LK in E; eauto.\n - destruct (resource_decay_LK_inv R E) as [pp' [E' ->]].\n repeat eexists.\nQed.\n\nLemma resource_decay_same_locks_sized {b phi phi'} :\n resource_decay b phi phi' -> same_locks_sized phi phi'.\nProof.\n intros R loc n; split; intros (rsh & sh & pp & E).\n - repeat eexists. eapply resource_decay_LK in E; eauto.\n - destruct (resource_decay_LK_inv R E) as [pp' [E' ->]].\n repeat eexists.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/resource_decay_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2200071048600902, "lm_q1q2_score": 0.11086293769923791}} {"text": "(* *********************************************************************)\n(* *)\n(* The CertiKOS Certified Kit Operating System *)\n(* *)\n(* The FLINT Group, Yale University *)\n(* *)\n(* Copyright The FLINT Group, Yale University. All rights reserved. *)\n(* This file is distributed under the terms of the Yale University *)\n(* Non-Commercial License Agreement. *)\n(* *)\n(* *********************************************************************)\n(* *********************************************************************)\n(* *)\n(* Layers of PM: Assembly Verification for PKContext *)\n(* *)\n(* Ronghui Gu *)\n(* *)\n(* Yale Flint Group *)\n(* *)\n(* *********************************************************************)\n\n(** This file provide the contextual refinement proof between MPTInit layer and MPTBit layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Locations.\nRequire Import AuxStateDataType.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import FlatMemory.\nRequire Import RefinementTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import Constant.\nRequire Import AsmImplLemma.\nRequire Import AsmImplTactic.\nRequire Import GlobIdent.\nRequire Import CommonTactic.\n\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compcertx.MakeProgram.\n(*Require Import LAsmModuleSem.*)\nRequire Import LAsm.\n\nRequire Import MContainer.\nRequire Import PTIntroGenSpec.\nRequire Import PTIntroGenAsmSource.\nRequire Import LAsmModuleSemSpec.\nRequire Import LinkTactic.\n\nRequire Import AbstractDataType.\n\nSection ASM_VERIFICATION.\n\n Local Open Scope string_scope.\n Local Open Scope error_monad_scope.\n Local Open Scope Z_scope.\n\n Context `{real_params: RealParams}.\n\n Notation LDATA := RData. \n Notation LDATAOps := (cdata (cdata_ops := mcontainer_data_ops) LDATA).\n\n Section WITHMEM.\n\n Context `{Hstencil: Stencil}.\n Context `{Hmem: Mem.MemoryModel}.\n Context `{Hmwd: UseMemWithData mem}.\n Context `{make_program_ops: !MakeProgramOps function Ctypes.type fundef unit}.\n Context `{make_program_prf: !MakeProgram function Ctypes.type fundef unit}.\n\n Lemma pt_in_code_correct:\n asm_spec_le (pt_in ↦ pt_in_spec_low)\n (〚pt_in ↦ ptin_function 〛 mcontainer).\n Proof.\n eapply asm_sem_intro; try reflexivity; simpl.\n intros. inv H. \n eapply make_program_make_globalenv in H0.\n exploit (make_globalenv_stencil_matches (D:= LDATAOps)); eauto.\n intros Hstencil_matches.\n assert(Hfun: Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal ptin_function)).\n {\n assert (Hmodule: get_module_function pt_in (pt_in ↦ ptin_function) = OK (Some ptin_function)) by\n reflexivity.\n assert (HInternal: make_internal ptin_function = OK (AST.Internal ptin_function)) by reflexivity.\n eapply make_globalenv_get_module_function in H0; eauto.\n destruct H0 as [?[Hsymbol ?]].\n inv Hstencil_matches.\n rewrite stencil_matches_symbols in Hsymbol.\n rewrite H1 in Hsymbol. inv Hsymbol.\n assumption.\n }\n refine_split'.\n - reflexivity.\n - econstructor; eauto.\n one_step_forward 0.\n + reflexivity.\n + econstructor.\n + reflexivity.\n - reflexivity.\n - inv H4. inv inv_inject_neutral.\n eapply Mem.neutral_inject in inv_mem_inject_neutral.\n assumption.\n - lift_trivial.\n reflexivity.\n - intros reg.\n repeat (rewrite Pregmap.gsspec).\n simpl_destruct_reg.\n constructor.\n - esplit; reflexivity.\n Qed.\n\n Lemma pt_out_code_correct:\n asm_spec_le (pt_out ↦ pt_out_spec_low)\n (〚pt_out ↦ ptout_function 〛 mcontainer).\n Proof.\n eapply asm_sem_intro; try reflexivity; simpl.\n intros. inv H. \n eapply make_program_make_globalenv in H0.\n exploit (make_globalenv_stencil_matches (D:= LDATAOps)); eauto.\n intros Hstencil_matches.\n assert(Hfun: Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal ptout_function)).\n {\n assert (Hmodule: get_module_function pt_out (pt_out ↦ ptout_function) = OK (Some ptout_function)) by\n reflexivity.\n assert (HInternal: make_internal ptout_function = OK (AST.Internal ptout_function)) by reflexivity.\n eapply make_globalenv_get_module_function in H0; eauto.\n destruct H0 as [?[Hsymbol ?]].\n inv Hstencil_matches.\n rewrite stencil_matches_symbols in Hsymbol.\n rewrite H1 in Hsymbol. inv Hsymbol.\n assumption.\n }\n refine_split'.\n - reflexivity.\n - econstructor; eauto.\n one_step_forward 0.\n + reflexivity.\n + econstructor.\n + reflexivity.\n - reflexivity.\n - inv H4. inv inv_inject_neutral.\n eapply Mem.neutral_inject in inv_mem_inject_neutral.\n assumption.\n - lift_trivial.\n reflexivity.\n - intros reg.\n repeat (rewrite Pregmap.gsspec).\n simpl_destruct_reg. \n constructor.\n - esplit; reflexivity.\n Qed.\n\n End WITHMEM.\n\nEnd ASM_VERIFICATION.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTIntroGenAsm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.21733751597763015, "lm_q1q2_score": 0.11036657240420256}} {"text": "(** * UseAuto: Theory and Practice of Automation in Coq Proofs *)\n\n(* $Date: 2011-04-20 14:26:52 -0400 (Wed, 20 Apr 2011) $ *)\n(* Chapter maintained by Arthur Chargueraud *)\n\n(** In a machine-checked proof, every single detail has to be\n justified. This can result in huge proof scripts. Fortunately,\n Coq comes with a proof-search mechanism and decision procedures\n that enable the system to automatically synthetizes simple pieces\n of proof. Automation is very powerful when set up\n appropriately. The purpose of this chapter is to explain the\n basics of working of automation.\n\n The chapter is organized in two parts. The first part focuses on a\n general mechanism called \"proof search.\" In short, proof search\n consists in naively trying to apply lemmas and assumptions in all\n possible ways until proving the goal. The second part describes\n \"decision procedures,\" which are tactics that are very good at\n solving proof obligations that fall in some particular fragment of\n the logic of Coq.\n\n The examples from this chapter include small lemmas made up to\n illustrate particular aspects of automation as well as larger\n examples taken from the rest of the Software Foundations\n development. For the larger examples, tactics from the library\n [LibTactics.v] are used. Those tactics are described in the\n chapter [UseTactics.v]. (You will need to read that chapter to\n understand the later parts of this one, but the earlier parts can\n be read on their own.) *)\n\nRequire Import LibTactics.\n\n\n(* ####################################################### *)\n(** * Basic Features of Proof Search *)\n\n(** The idea of proof search is to replace a sequence of tactics\n applying lemmas and assumptions with a call to a single tactic,\n for example [auto]. This form of proof automation saves a lot of\n effort. It typically leads to much shorter proof scripts, and to\n scripts that are typically more robust to change. If one makes a\n little change to a definition, a proof that exploits automation\n probably won't need to be modified at all. Of course, using too\n much automation is a bad idea. When a proof script no longer\n records the main arguments of a proof, it becomes difficult to fix\n it when it gets broken after a change in a definition. Overall, a\n reasonable use of automation is generally a big win, as it saves a\n lot of time both in building proof scripts and in subsequently\n maintaining those proof scripts. *)\n\n\n(* ####################################################### *)\n(** ** Strength of Proof Search *)\n\n(** We are going to study four proof-search tactics: [auto], [eauto],\n [iauto] and [jauto]. The tactics [auto] and [eauto] are builtin\n in Coq. The tactic [iauto] is a shorthand for the builtin tactic\n [try solve [intuition eauto]]. The tactic [jauto] is defined in\n the library [LibTactics], and simply performs some preprocessing\n of the goal before calling [eauto]. The goal of this chapter is \n to explain the general principles of proof search and to give \n rule of thumbs for guessing which of the four tactics mentioned\n above is best suited for solving a given goal.\n \n Proof search is a compromise between efficiency and\n expressiveness, that is, a tradeoff between how complex goals the\n tactic can solve and how much time the tactic requires for\n terminating. The tactic [auto] builds proofs only by using the\n basic tactics [reflexivity], [assumption], and [apply]. The tactic\n [eauto] can also exploit [eapply]. The tactic [jauto] extends\n [eauto] by being able to open conjunctions and existentials that\n occur in the context. The tactic [iauto] is able to deal with\n conjunctions, disjunctions, and negation in a quite clever way;\n however it is not able to open existentials from the\n context. Also, [iauto] usually gets very slow when the goal\n involves several disjunctions.\n \n Note that proof search tactics never perform any rewriting\n step (tactics [rewrite], [subst]), nor any case analysis on an\n arbitrary data structure or predicate (tactics [destruct] and\n [inversion]), nor any proof by induction (tactic [induction]). So,\n proof search is really intended to automate the final steps from\n the various branches of a proof. It is not able to discover the\n overall structure of a proof. *)\n\n\n(* ####################################################### *)\n(** ** Basics *)\n\n(** The tactic [auto] is able to solve a goal that can be proved\n using a sequence of [intros], [apply], [assumption], and [reflexivity].\n Two examples follow. The first one shows the ability for\n [auto] to call [reflexivity] at any time. In fact, calling \n [reflexivity] is always the first thing that [auto] tries to do. *)\n\nLemma solving_by_reflexivity : \n 2 + 3 = 5.\nProof. auto. Qed.\n\n(** The second example illustrates a proof where a sequence of \n two calls to [apply] are needed. The goal is to prove that\n if [Q n] implies [P n] for any [n] and if [Q n] holds for any [n],\n then [P 2] holds. *)\n\nLemma solving_by_apply : forall (P Q : nat->Prop),\n (forall n, Q n -> P n) -> \n (forall n, Q n) ->\n P 2.\nProof. auto. Qed.\n\n(** We can ask [auto] to tell us what proof it came up with,\n by invoking [info auto] in place of [auto]. *)\n \nLemma solving_by_apply' : forall (P Q : nat->Prop),\n (forall n, Q n -> P n) -> \n (forall n, Q n) ->\n P 2.\nProof. info auto. Qed.\n (* The output is: *)\n (* [intro P; intro Q; intro H; intro H0; simple apply H; simple apply H0]. *)\n (* which can be reformulated as [intros P Q H H0; apply H; apply H0]. *)\n\n(** The tactic [auto] can invoke [apply] but not [eapply]. So, [auto]\n cannot exploit lemmas whose instantiation cannot be directly\n deduced from the proof goal. To exploit such lemmas, one needs to\n invoke the tactic [eauto], which is able to call [eapply].\n \n In the following example, the first hypothesis asserts that [P n]\n is true when [Q m] is true for some [m], and the goal is to prove\n that [Q 1] implies [P 2]. This implication follows direction from\n the hypothesis by instantiating [m] as the value [1]. The\n following proof script shows that [eauto] successfully solves the\n goal, whereas [auto] is not able to do so. *)\n\nLemma solving_by_eapply : forall (P Q : nat->Prop),\n (forall n m, Q m -> P n) ->\n Q 1 -> P 2.\nProof. auto. eauto. Qed.\n\n(** Remark: Again, we can use [info eauto] to see what proof [eauto]\n comes up with. *)\n\n\n(* ####################################################### *)\n(** ** Conjunctions *)\n\n(** So far, we've seen that [eauto] is stronger than [auto] in the\n sense that it can deal with [eapply]. In the same way, we are going\n to see how [jauto] and [iauto] are stronger than [auto] and [eauto] \n in the sense that they provide better support for conjunctions. *)\n \n(** The tactics [auto] and [eauto] can prove a goal of the form\n [F /\\ F'], where [F] and [F'] are two propositions, as soon as\n both [F] and [F'] can be proved in the current context. \n An example follows. *)\n\nLemma solving_conj_goal : forall (P : nat->Prop) (F : Prop),\n (forall n, P n) -> F -> F /\\ P 2.\nProof. auto. Qed.\n\n(** However, when an assumption is a conjunction, [auto] and [eauto]\n are not able to exploit this conjunction. It can be quite\n surprising at first that [eauto] can prove very complex goals but\n that it fails to prove that [F /\\ F'] implies [F]. The tactics\n [iauto] and [jauto] are able to decompose conjunctions from the context. \n Here is an example. *)\n\nLemma solving_conj_hyp : forall (F F' : Prop),\n F /\\ F' -> F.\nProof. auto. eauto. jauto. (* or [iauto] *) Qed.\n\n(** The tactic [jauto] is implemented by first calling a\n pre-processing tactic called [jauto_set], and then calling\n [eauto]. So, to understand how [jauto] works, one can directly\n call the tactic [jauto_set]. *)\n\nLemma solving_conj_hyp' : forall (F F' : Prop),\n F /\\ F' -> F.\nProof. intros. jauto_set. eauto. Qed.\n\n(** Next is a more involved goal that can be solved by [iauto] and\n [jauto]. *)\n\nLemma solving_conj_more : forall (P Q R : nat->Prop) (F : Prop),\n (F /\\ (forall n m, (Q m /\\ R n) -> P n)) ->\n (F -> R 2) -> \n Q 1 ->\n P 2 /\\ F.\nProof. jauto. (* or [iauto] *) Qed.\n\n(** The strategy of [iauto] and [jauto] is to run a global analysis of\n the top-level conjunctions, and then call [eauto]. For this\n reason, those tactics are not good at dealing with conjunctions\n that occur as the conclusion of some universally quantified\n hypothesis. The following example illustrates a general weakness\n of Coq proof search mechanisms. *)\n\nLemma solving_conj_hyp_forall : forall (P Q : nat->Prop),\n (forall n, P n /\\ Q n) -> P 2.\nProof. \n auto. eauto. iauto. jauto.\n (* Nothing works, so we have to do some of the work by hand *)\n intros. destruct (H 2). auto.\nQed.\n\n(** This situation is slightly disappointing, since automation is \n able to prove the following goal, which is very similar. The \n only difference is that the universal quantification has been\n distributed over the conjunction. *)\n\nLemma solved_by_jauto : forall (P Q : nat->Prop) (F : Prop),\n (forall n, P n) /\\ (forall n, Q n) -> P 2.\nProof. jauto. (* or [iauto] *) Qed.\n\n\n(* ####################################################### *)\n(** ** Disjunctions *)\n\n(** The tactics [auto] and [eauto] can handle disjunctions that\n occur in the goal. *)\n\nLemma solving_disj_goal : forall (F F' : Prop),\n F -> F \\/ F'.\nProof. auto. Qed.\n\n(** However, only [iauto] is able to automate reasoning on the\n disjunctions that appear in the context. For example, [iauto] can\n prove that [F \\/ F'] entails [F' \\/ F]. *)\n\nLemma solving_disj_hyp : forall (F F' : Prop),\n F \\/ F' -> F' \\/ F.\nProof. auto. eauto. jauto. iauto. Qed.\n\n(** More generally, [iauto] can deal with complex combinations of\n conjunctions, disjunctions, and negations. Here is an example. *)\n\nLemma solving_tauto : forall (F1 F2 F3 : Prop),\n ((~F1 /\\ F3) \\/ (F2 /\\ ~F3)) ->\n (F2 -> F1) ->\n (F2 -> F3) -> \n ~F2.\nProof. iauto. Qed.\n\n(** However, the ability of [iauto] to automatically perform a case\n analysis on disjunctions comes with a downside: [iauto] can get\n very slow. If the context involves several hypotheses with\n disjunctions, [iauto] typically generates an exponential number of\n subgoals on which [eauto] is called. One advantage of [jauto]\n compared with [iauto] is that it never spends time performing this\n kind of case analyses. *)\n\n\n(* ####################################################### *)\n(** ** Existentials *)\n\n(** The tactics [eauto], [iauto], and [jauto] can prove goals whose\n conclusion is an existential. For example, if the goal is [exists\n x, f x], the tactic [eauto] introduces an existential variable,\n say [?25], in place of [x]. The remaining goal is [f ?25], and\n [eauto] tries to solve this goal, allowing itself to instantiate\n [?25] with any appropriate value. For example, if an assumption [f\n 2] is available, then the variable [?25] gets instantiated with\n [2] and the goal is solved, as shown below. *)\n\nLemma solving_exists_goal : forall (f : nat->Prop),\n f 2 -> exists x, f x.\nProof. \n auto. (* [auto] does not deal with existentials *)\n eauto. (* [eauto], [iauto] and [jauto] solve the goal *) \nQed.\n\n(** A major strength of [jauto] over the other proof search tactics is\n that it is able to exploit the existentially quantified\n _hypotheses_, i.e., those of the form [exists x, P]. *)\n\nLemma solving_exists_hyp : forall (f g : nat->Prop),\n (forall x, f x -> g x) ->\n (exists a, f a) -> \n (exists a, g a).\nProof. \n auto. eauto. iauto. (* All of these tactics fail, *)\n jauto. (* whereas [jauto] succeeds. *)\n (* For the details, run [intros. jauto_set. eauto] *)\nQed.\n\n\n(* ####################################################### *)\n(** ** Negation *)\n\n(** The tactics [auto] and [eauto] suffer from some limitations with\n respect to the manipulation of negations, mostly related to the\n fact that negation, written [~ P], is defined as [P -> False] but\n that the unfolding of this definition is not performed\n automatically. Consider the following example. *)\n\nLemma negation_study_1 : forall (P : nat->Prop),\n P 0 -> (forall x, ~ P x) -> False.\nProof.\n intros P H0 HX.\n eauto. (* It fails to see that [HX] applies, *)\n unfold not in *. eauto. (* unless the negation is unfolded *)\nQed.\n\n(** For this reason, the tactics [iauto] and [jauto] systematically\n invoke [unfold not in *] as part of their pre-processing. So,\n they are able to solve the previous goal right away. *)\n \nLemma negation_study_2 : forall (P : nat->Prop),\n P 0 -> (forall x, ~ P x) -> False.\nProof. jauto. (* or [iauto] *) Qed.\n\n(** (We will come back later to the behavior of proof search with\n respect to the unfolding of definitions.) *)\n \n\n(* ####################################################### *)\n(** ** Equalities *)\n\n(** Coq's proof-search feature is not good at exploiting equalities.\n It can do very basic operations, like exploiting reflexivity\n and symmetry, but that's about it. Here is a simple example \n that [auto] can solve, by first calling [symmetry] and then\n applying the hypothesis. *)\n\nLemma equality_by_auto : forall (f g : nat->Prop),\n (forall x, f x = g x) -> g 2 = f 2.\nProof. auto. Qed.\n\n(** To automate more advanced reasoning on equalities, one should\n rather try to use the tactic [congruence], which is presented at\n the end of this chapter in the \"Decision Procedures\" section. *)\n\n\n(* ####################################################### *)\n(** * How Proof Search Works *)\n\n(* ####################################################### *)\n(** ** Search Depth *)\n\n(** The tactic [auto] works as follows. It first tries to call\n [reflexivity] and [assumption]. If one of these calls solves the\n goal, the job is done. Otherwise [auto] tries to apply the most\n recently introduced assumption that can be applied to the goal\n without producing and error. This application produces\n subgoals. There are two possible cases. If the sugboals produced\n can be solved by a recursive call to [auto], then the job is done.\n Otherwise, if this application produces at least one subgoal that\n [auto] cannot solve, then [auto] starts over by trying to apply\n the second most recently introduced assumption. It continues in a\n similar fashion until it finds a proof or until no assumption\n remains to be tried.\n \n It is very important to have a clear idea of the backtracking\n process involved in the execution of the [auto] tactic; otherwise\n its behavior can be quite puzzling. For example, [auto] is not\n able to solve the following triviality. *)\n\nLemma search_depth_0 : \n True /\\ True /\\ True /\\ True /\\ True /\\ True.\nProof.\n auto. \nAdmitted.\n\n(** The reason [auto] fails to solve the goal is because there are\n too many conjunctions. If there had been only five of them, [auto]\n would have successfully solved the proof, but six is too many.\n The tactic [auto] limits the number of lemmas and hypotheses\n that can be applied in a proof, so as to ensure that the proof \n search eventually terminates. By default, the maximal number \n of steps is five. One can specify a different bound, writing \n for example [auto 6] to search for a proof involving at most \n six steps. For example, [auto 6] would solve the previous lemma.\n (Similarly, one can invoke [eauto 6] or [intuition eauto 6].)\n The argument [n] of [auto n] is called the \"search depth.\"\n The tactic [auto] is simply defined as a shorthand for [auto 5].\n\n The behavior of [auto n] can be summarized as follows. It first\n tries to solve the goal using [reflexivity] and [assumption]. If\n this fails, it tries to apply a hypothesis (or a lemma that has\n been registered in the hint database), and this application\n produces a number of sugoals. The tactic [auto (n-1)] is then\n called on each of those subgoals. If all the subgoals are solved,\n the job is completed, otherwise [auto n] tries to apply a\n different hypothesis.\n \n During the process, [auto n] calls [auto (n-1)], which in turn\n might call [auto (n-2)], and so on. The tactic [auto 0] only\n tries [reflexivity] and [assumption], and does not try to apply\n any lemma. Overall, this means that when the maximal number of \n steps allowed has been exceeded, the [auto] tactic stops searching \n and backtracks to try and investigate other paths. *)\n\n(** The following lemma admits a unique proof that involves exactly\n three steps. So, [auto n] proves this goal iff [n] is greater than\n three. *)\n\nLemma search_depth_1 : forall (P : nat->Prop),\n P 0 ->\n (P 0 -> P 1) ->\n (P 1 -> P 2) ->\n (P 2).\nProof. \n auto 0. (* does not find the proof *)\n auto 1. (* does not find the proof *)\n auto 2. (* does not find the proof *)\n auto 3. (* finds the proof *)\n (* more generally, [auto n] solves the goal if [n >= 3] *)\nQed. \n\n(** We can generalize the example by introducing an assumption\n asserting that [P k] is derivable from [P (k-1)] for all [k],\n and keep the assumption [P 0]. The tactic [auto], which is the \n same as [auto 5], is able to derive [P k] for all values of [k]\n less than 5. For example, it can prove [P 4]. *)\n\nLemma search_depth_3 : forall (P : nat->Prop),\n (* Hypothesis H1: *) (P 0) -> \n (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> \n (* Goal: *) (P 4).\nProof. auto. Qed.\n\n(** However, to prove [P 5], one needs to call at least [auto 6]. *)\n\nLemma search_depth_4 : forall (P : nat->Prop),\n (* Hypothesis H1: *) (P 0) -> \n (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> \n (* Goal: *) (P 5).\nProof. auto. auto 6. Qed.\n\n(** Because [auto] looks for proofs at a limited depth, there are\n cases where [auto] can prove a goal [F] and can prove a goal \n [F'] but cannot prove [F /\\ F']. In the following example, \n [auto] can prove [P 4] but it is not able to prove [P 4 /\\ P 4],\n because the splitting of the conjunction consumes one proof step. \n To prove the conjunction, one needs to increase the search depth,\n using at least [auto 6]. *)\n\nLemma search_depth_5 : forall (P : nat->Prop),\n (* Hypothesis H1: *) (P 0) -> \n (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> \n (* Goal: *) (P 4 /\\ P 4).\nProof. auto. auto 6. Qed.\n\n\n(* ####################################################### *)\n(** ** Backtracking *)\n\n(** In the previous section, we have considered proofs where\n at each step there was a unique assumption that [auto]\n could apply. In general, [auto] can have several choices\n at every step. The strategy of [auto] consists of trying all \n of the possibilities (using a depth-first search exploration).\n\n To illustrate how automation works, we are going to extend the\n previous example with an additional assumption asserting that\n [P k] is also derivable from [P (k+1)]. Adding this hypothesis\n offers a new possibility that [auto] could consider at every step. \n \n There exists a special command that one can use for tracing\n all the steps that proof-search considers. To view such a\n trace, one should write [debug eauto]. (For some reason, the\n command [debug auto] does not exist, so we have to use the\n command [debug eauto] instead.) *)\n\nLemma working_of_auto_1 : forall (P : nat->Prop),\n (* Hypothesis H1: *) (P 0) -> \n (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> \n (* Hypothesis H3: *) (forall k, P (k-1) -> P k) ->\n (* Goal: *) (P 2).\n(* Uncomment \"debug\" in the following line to see the debug trace: *)\nProof. intros P H1 H2 H3. (* debug *) eauto. Qed.\n\n(** The output message produced by [debug eauto] is as follows.\n<<\n depth=5 \n depth=4 apply H3\n depth=3 apply H3\n depth=3 exact H1\n>>\n The depth indicates the value of [n] with which [eauto n] is \n called. The tactics shown in the message indicate that the first \n thing that [eauto] has tried to do is to apply [H3]. The effect of \n applying [H3] is to replace the goal [P 2] with the goal [P 1]. \n Then, again, [H3] has been applied, changing the goal [P 1] into \n [P 0]. At that point, the goal was exactly the hypothesis [H1]. \n\n It seems that [eauto] was quite lucky there, as it never even\n tried to use the hypothesis [H2] at any time. The reason is that\n [auto] always tries to use the most recently introduced hypothesis\n first, and [H3] is a more recent hypothesis than [H2] in the goal.\n So, let's permute the hypotheses [H2] and [H3] and see what\n happens. *)\n\nLemma working_of_auto_2 : forall (P : nat->Prop),\n (* Hypothesis H1: *) (P 0) -> \n (* Hypothesis H3: *) (forall k, P (k-1) -> P k) ->\n (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> \n (* Goal: *) (P 2).\nProof. intros P H1 H3 H2. (* debug *) eauto. Qed.\n\n(** This time, the output message suggests that the proof search \n investigates many possibilities. Replacing [debug eauto] with\n [info eauto], we observe that the proof that [eauto] comes up \n with is actually not the simplest one.\n [apply H2; apply H3; apply H3; apply H3; exact H1]\n This proof goes through the proof obligation [P 3], even though \n it is not any useful. The following tree drawing describes\n all the goals that automation has been through. \n<< \n |5||4||3||2||1||0| -- below, tabulation indicates the depth\n\n [P 2]\n -> [P 3]\n -> [P 4]\n -> [P 5]\n -> [P 6]\n -> [P 7]\n -> [P 5] \n -> [P 4]\n -> [P 5]\n -> [P 3] \n --> [P 3]\n -> [P 4]\n -> [P 5]\n -> [P 3] \n -> [P 2]\n -> [P 3]\n -> [P 1] \n -> [P 2]\n -> [P 3]\n -> [P 4]\n -> [P 5]\n -> [P 3] \n -> [P 2]\n -> [P 3]\n -> [P 1] \n -> [P 1]\n -> [P 2]\n -> [P 3]\n -> [P 1] \n -> [P 0]\n -> !! Done !! \n>>\n The first few lines read as follows. To prove [P 2], [eauto 5] \n has first tried to apply [H2], producing the subgoal [P 3]. \n To solve it, [eauto 4] has tried again to apply [H2], producing\n the goal [P 4]. Similarly, the search goes through [P 5], [P 6] \n and [P 7]. When reaching [P 7], the tactic [eauto 0] is called \n but as it is not allowed to try and apply any lemma, it fails. \n So, we come back to the goal [P 6], and try this time to apply \n hypothesis [H3], producing the subgoal [P 5]. Here again,\n [eauto 0] fails to solve this goal.\n \n The process goes on and on, until backtracking to [P 3] and trying\n to apply [H2] three times in a row, going through [P 2] and [P 1]\n and [P 0]. This search tree explains why [eauto] came up with a \n proof starting with [apply H2]. *) \n\n\n(* ####################################################### *)\n(** ** Adding Hints *)\n\n(** By default, [auto] (and [eauto]) only tries to apply the\n hypotheses that appear in the proof context. There are two\n possibilities for telling [auto] to exploit a lemma that have\n been proved previously: either adding the lemma as an assumption\n just before calling [auto], or adding the lemma as a hint, so\n that it can be used by every calls to [auto].\n\n The first possibility is useful to have [auto] exploit a lemma\n that only serves at this particular point. To add the lemma as\n hypothesis, one can type [generalize mylemma; intros], or simply\n [lets: mylemma] (the latter requires [LibTactics.v]).\n \n The second possibility is useful for lemmas that needs to be\n exploited several times. The syntax for adding a lemma as a hint\n is [Hint Resolve mylemma]. For example, the lemma asserting than\n any number is less than or equal to itself, [forall x, x <= x],\n called [Le.le_refl] in the Coq standard library, can be added as a\n hint as follows. *)\n\nHint Resolve Le.le_refl.\n \n(** A convenient shorthand for adding all the constructors of an\n inductive datatype as hints is the command [Hint Constructors\n mydatatype].\n \n Warning: some lemmas, such as transitivity results, should\n not be added as hints as they would very badly affect the\n performance of proof search. The description of this problem\n and the presentation of a general work-around for transitivity\n lemmas appear further on. *)\n\n\n(* ####################################################### *)\n(** ** Integration of Automation in Tactics *)\n\n(** The library \"LibTactics\" introduces a convenient feature for\n invoking automation after calling a tactic. In short, it suffices\n to add the symbol star ([*]) to the name of a tactic. For example,\n [apply* H] is equivalent to [apply H; auto_star], where [auto_star]\n is a tactic that can be defined as needed. By default, [auto_star] \n first tries to solve the goal using [auto], and if this does not\n succeed then it tries to call [jauto]. Even though [jauto] is\n strictly stronger than [auto], it makes sense to call [auto] first:\n when [auto] succeeds it may save a lot of time, and when [auto]\n fails to prove the goal, it fails very quickly.\n\n The definition of [auto_star], which determines the meaning of the\n star symbol, can be modified whenever needed. Simply write:\n[[\n Ltac auto_star ::= a_new_definition.\n]] \n Observe the use of [::=] instead of [:=], which indicates that the\n tactic is being rebound to a new definition. So, the default\n definition is as follows. *)\n\nLtac auto_star ::= try solve [ auto | jauto ].\n\n(** Nearly all standard Coq tactics and all the tactics from\n \"LibTactics\" can be called with a star symbol. For example, one\n can invoke [subst*], [destruct* H], [inverts* H], [lets* I: H x],\n [specializes* H x], and so on... There are two notable exceptions.\n The tactic [auto*] is just another name for the tactic\n [auto_star]. And the tactic [apply* H] calls [eapply H] (or the\n more powerful [applys H] if needed), and then calls [auto_star].\n Note that there is no [eapply* H] tactic, use [apply* H]\n instead. *)\n\n(** In large developments, it can be convenient to use two degrees of\n automation. Typically, one would use a fast tactic, like [auto],\n and a slower but more powerful tactic, like [jauto]. To allow for\n a smooth coexistence of the two form of automation, [LibTactics.v[\n also defines a \"tilde\" version of tactics, like [apply~ H],\n [destruct~ H], [subst~], [auto~] and so on. The meaning of the\n tilde symbol is described by the [auto_tilde] tactic, whose\n default implementation is [auto]. *)\n\nLtac auto_tilde ::= auto.\n\n(** In the examples that follow, only [auto_star] is needed. *)\n\n\n(* ####################################################### *)\n(** * Examples of Use of Automation *)\n\n(** Let's see how to use proof search in practice on the main theorems\n of the \"Software Foundations\" course, proving in particular\n results such as determinacy, preservation and progress... *)\n\n\n(* ####################################################### *)\n(** ** Determinacy *)\n\nModule DeterministicImp.\n Require Import Imp.\n\n(** Recall the original proof of the determinacy lemma for the IMP\n language, shown below. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n intros c st st1 st2 E1 E2.\n generalize dependent st2.\n (ceval_cases (induction E1) Case); intros st2 E2; inversion E2; subst. \n Case \"E_Skip\". reflexivity.\n Case \"E_Ass\". reflexivity.\n Case \"E_Seq\". \n assert (st' = st'0) as EQ1.\n SCase \"Proof of assertion\". apply IHE1_1; assumption.\n subst st'0.\n apply IHE1_2. assumption. \n Case \"E_IfTrue\". \n SCase \"b1 evaluates to true\".\n apply IHE1. assumption.\n SCase \"b1 evaluates to false (contradiction)\".\n rewrite H in H5. inversion H5.\n Case \"E_IfFalse\". \n SCase \"b1 evaluates to true (contradiction)\".\n rewrite H in H5. inversion H5.\n SCase \"b1 evaluates to false\".\n apply IHE1. assumption.\n Case \"E_WhileEnd\". \n SCase \"b1 evaluates to true\".\n reflexivity.\n SCase \"b1 evaluates to false (contradiction)\".\n rewrite H in H2. inversion H2.\n Case \"E_WhileLoop\". \n SCase \"b1 evaluates to true (contradiction)\".\n rewrite H in H4. inversion H4.\n SCase \"b1 evaluates to false\".\n assert (st' = st'0) as EQ1.\n SSCase \"Proof of assertion\". apply IHE1_1; assumption.\n subst st'0.\n apply IHE1_2. assumption. \nQed.\n\n(** Exercise: rewrite this proof using [auto] whenever possible. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n (* FILL IN HERE *) admit.\nQed.\n\n(** In fact, using automation is not just a matter of calling [auto]\n in place of one or two other tactics. Using automation is about\n rethinking the organization of sequences of tactics so as to\n minimize the effort involved in writing and maintaining the proof.\n This process is eased by the use of the tactics from\n [LibTactics.v]. So, before trying to optimize the way automation\n is used, let's first rewrite the proof of determinacy:\n - use [introv H] instead of [intros x H],\n - use [gen x] instead of [generalize dependent x],\n - use [inverts H] instead of [inversion H; subst],\n - use [tryfalse] to handle contradictions, and get rid of\n the cases where [beval st b1 = true] and [beval st b1 = false]\n both appear in the context,\n - stop using [ceval_cases] to label subcases. *) \n\nTheorem ceval_deterministic'': forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n introv E1 E2. gen st2. \n induction E1; intros; inverts E2; tryfalse.\n auto.\n auto.\n assert (st' = st'0). auto. subst. auto.\n auto.\n auto.\n auto.\n assert (st' = st'0). auto. subst. auto.\nQed.\n\n(** To obtain a nice clean proof script, we have to remove the calls\n [assert (st' = st'0)]. Such a tactic invokation is not nice\n because it refers to some variables whose name has been\n automatically generated. This kind of tactics tend to be very\n brittle. The tactic [assert (st' = st'0)] is used to assert the\n conclusion that we want to derive from the induction\n hypothesis. So, rather than stating this conclusion explicitly, we\n are going to ask Coq to instantiate the induction hypothesis,\n using automation to figure out how to instantiate it. The tactic\n [forwards], described in [LibTactics.v] precisely helps with\n instantiating a fact. So, let's see how it works out on our\n example. *)\n\nTheorem ceval_deterministic''': forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n (* Let's replay the proof up to the [assert] tactic. *)\n introv E1 E2. gen st2. \n induction E1; intros; inverts E2; tryfalse.\n auto. auto.\n (* Let's duplicate the goal to compare the old proof with the new one *) \n dup 4.\n\n (* The old proof: *)\n assert (st' = st'0). apply IHE1_1. apply H1.\n (* produces [H: st' = st'0]. *) skip.\n\n (* The new proof, without automation: *)\n forwards: IHE1_1. apply H1.\n (* produces [H: st' = st'0]. *) skip.\n\n (* The new proof, with automation: *)\n forwards: IHE1_1. eauto.\n (* produces [H: st' = st'0]. *) skip.\n\n (* The new proof, with integrated automation: *)\n forwards*: IHE1_1. \n (* produces [H: st' = st'0]. *) skip.\n\nAdmitted.\n\n(** To polish the proof script, it remains to factorize the calls\n to [auto], using the star symbol. The proof of determinacy can then\n be rewritten in only four lines, including no more than 10 tactics. *)\n\nTheorem ceval_deterministic'''': forall c st st1 st2,\n c / st || st1 ->\n c / st || st2 ->\n st1 = st2.\nProof. \n introv E1 E2. gen st2. \n induction E1; intros; inverts* E2; tryfalse.\n forwards*: IHE1_1. subst*.\n forwards*: IHE1_1. subst*.\nQed.\n\nEnd DeterministicImp.\n\n\n(* ####################################################### *)\n(** ** Preservation for STLC *)\n\nModule PreservationProgressStlc.\n Require Import Stlc. \n Import STLC.\n\n(** Recall the proof of perservation of STLC, shown next.\n This proof already uses [eauto] through the triple-dot\n mechanism. *)\n\nTheorem preservation : forall t t' T,\n has_type empty t T ->\n t ==> t' ->\n has_type empty t' T.\nProof with eauto.\n remember (@empty ty) as Gamma. \n intros t t' T HT. generalize dependent t'. \n (has_type_cases (induction HT) Case); intros t' HE; subst Gamma.\n Case \"T_Var\".\n inversion HE. \n Case \"T_Abs\".\n inversion HE. \n Case \"T_App\".\n inversion HE; subst...\n (* (step_cases (inversion HE) SCase); subst...*)\n (* The ST_App1 and ST_App2 cases are immediate by induction, and\n auto takes care of them *)\n SCase \"ST_AppAbs\".\n apply substitution_preserves_typing with T11...\n inversion HT1... \n Case \"T_True\". \n inversion HE.\n Case \"T_False\".\n inversion HE.\n Case \"T_If\".\n inversion HE; subst...\nQed.\n\n(** Exercise: rewrite this proof using tactics from [LibTactics] \n and calling automation using the star symbol rather than the\n triple-dot notation. More precisely, make use of the tactics \n [inverts*] and [applys*] to call [auto*] after a call to \n [inverts] or to [applys]. The solution is three lines long.*)\n\nTheorem preservation' : forall t t' T,\n has_type empty t T ->\n t ==> t' ->\n has_type empty t' T.\nProof.\n (* FILL IN HERE *) admit.\nQed.\n\n\n(* ####################################################### *)\n(** ** Progress for STLC *)\n\n(** Recall the proof of the progress theorem. *)\n\nTheorem progress : forall t T, \n has_type empty t T ->\n value t \\/ exists t', t ==> t'.\nProof with eauto.\n intros t T Ht.\n remember (@empty ty) as Gamma.\n (has_type_cases (induction Ht) Case); subst Gamma...\n Case \"T_Var\".\n inversion H. \n Case \"T_App\".\n right. destruct IHHt1...\n SCase \"t1 is a value\".\n destruct IHHt2...\n SSCase \"t2 is a value\".\n inversion H; subst; try solve by inversion. \n exists (subst t2 x t)...\n SSCase \"t2 steps\".\n destruct H0 as [t2' Hstp]. exists (tm_app t1 t2')...\n SCase \"t1 steps\".\n destruct H as [t1' Hstp]. exists (tm_app t1' t2)...\n Case \"T_If\". \n right. destruct IHHt1...\n destruct t1; try solve by inversion...\n inversion H. exists (tm_if x t2 t3)...\nQed.\n\n\n\n(** Exercise: optimize the proof of the progress theorem.\n Hint: make use of [destruct*] and [inverts*].\n The solution is 10 lines long (short lines). *)\n\nTheorem progress' : forall t T, \n has_type empty t T ->\n value t \\/ exists t', t ==> t'.\nProof.\n (* FILL IN HERE *) admit.\nQed.\n\nEnd PreservationProgressStlc.\n\n\n(* ####################################################### *)\n(** ** BigStep and SmallStep *)\n\nModule Semantics.\nRequire Import Smallstep.\n\n(** Recall the proof relating a small-step reduction judgment \n to a big-step reduction judgment. *)\n\nTheorem stepmany__eval : forall t v,\n normal_form_of t v -> t || v.\nProof.\n intros t v Hnorm.\n unfold normal_form_of in Hnorm.\n inversion Hnorm as [Hs Hnf]; clear Hnorm.\n apply nf_is_value in Hnf. inversion Hnf. clear Hnf.\n (rsc_cases (induction Hs) Case); subst.\n Case \"rsc_refl\".\n apply E_Const.\n Case \"rsc_step\".\n eapply step__eval. eassumption. apply IHHs. reflexivity. \nQed.\n\n(** Exercise: optimize the above proof, using [introv],\n [invert], and [applys*]. The solution is 4 lines long. *)\n\nTheorem stepmany__eval' : forall t v,\n normal_form_of t v -> t || v.\nProof.\n (* FILL IN HERE *) admit.\nQed.\n\nEnd Semantics.\n\n\n(* ####################################################### *)\n(** ** Preservation for STLCRef *)\n\nModule PreservationProgressReferences.\n Require Import References.\n Import STLCRef.\n Hint Resolve store_weakening extends_refl.\n\n(** The proof of preservation for [STLCRef] can be found\n in the file [References.v]. It contains 58 lines (not\n counting the labelling of cases). The optimized proof \n script is more than twice shorter. The following material \n explains how to build the optimized proof script. \n The resulting optimized proof script for the preservation \n theorem appears afterwards. *)\n\nTheorem preservation : forall ST t t' T st st',\n has_type empty ST t T ->\n store_well_typed ST st ->\n t / st ==> t' / st' ->\n exists ST',\n (extends ST' ST /\\ \n has_type empty ST' t' T /\\\n store_well_typed ST' st').\nProof.\n (* old: [Proof. with eauto using store_weakening, extends_refl.] \n new: [Proof.], and the two lemmas are registered as hints\n before the proof of the lemma, possibly inside a section in\n order to restrict the scope of the hints. *)\n\n remember (@empty ty) as Gamma. introv Ht. gen t'.\n (has_type_cases (induction Ht) Case); introv HST Hstep; \n (* old: [subst; try (solve by inversion); inversion Hstep; subst;\n try (eauto using store_weakening, extends_refl)] \n new: [subst Gamma; inverts Hstep; eauto.]\n We want to be more precise on what exactly we substitute,\n and we do not want to call [try (solve by inversion)] which\n is way to slow. *)\n subst Gamma; inverts Hstep; eauto.\n\n Case \"T_App\". \n SCase \"ST_AppAbs\". \n (* old:\n exists ST. inversion Ht1; subst.\n split; try split... eapply substitution_preserves_typing... *)\n (* new: we use [inverts] in place of [inversion] and [splits] to\n split the conjunction, and [applys*] in place of [eapply...] *)\n exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing.\n\n SCase \"ST_App1\".\n (* old: \n eapply IHHt1 in H0...\n inversion H0 as [ST' [Hext [Hty Hsty]]].\n exists ST'... *)\n (* new: The tactic [eapply IHHt1 in H0...] applies [IHHt1] to [H0].\n But [H0] is only thing that [IHHt1] could be applied to, so\n there [eauto] can figure this out on its own. The tactic\n [forwards] is used to instantiate all the arguments of [IHHt1],\n creating existential variables and producing subgoals when needed. *)\n forwards: IHHt1. eauto. eauto. eauto.\n (* At this point, we need to decompose the hypothesis [H] that has\n just been created by [forwards]. This is done by the first part \n of the preprocessing phase of [jauto]. *)\n jauto_set_hyps; intros.\n (* It remains to decompose the goal, which is done by the second part\n of the preprocessing phase of [jauto]. *)\n jauto_set_goal; intros.\n (* All the subgoals produced can then be solved by [eauto]. *)\n eauto. eauto. eauto. \n\n SCase \"ST_App2\".\n (* old:\n eapply IHHt2 in H5...\n inversion H5 as [ST' [Hext [Hty Hsty]]].\n exists ST'... *)\n (* new: this time, we need to call [forwards] on [IHHt2],\n and we call [jauto] right away, by writing [forwards*],\n proving the goal in a single tactic! *)\n forwards*: IHHt2.\n \n (* The same trick works for many of the other subgoals. *)\n forwards*: IHHt. \n forwards*: IHHt. \n forwards*: IHHt1. \n forwards*: IHHt2. \n forwards*: IHHt1. \n\n Case \"T_Ref\".\n SCase \"ST_RefValue\". \n (* old:\n exists (snoc ST T1). \n inversion HST; subst.\n split.\n apply extends_snoc.\n split.\n replace (ty_Ref T1) with (ty_Ref (store_ty_lookup (length st) (snoc ST T1))).\n apply T_Loc. \n rewrite <- H. rewrite length_snoc. omega.\n unfold store_ty_lookup. rewrite <- H. rewrite nth_eq_snoc...\n apply store_well_typed_snoc; assumption. *)\n (* new: in this proof case, we need to perform an inversion without\n removing the hypothesis. The tactic [inverts keep] serves that purpose. *)\n exists (snoc ST T1). inverts keep HST. splits. \n (* The proof of the first subgoal needs not be changed *)\n apply extends_snoc.\n (* For the second subgoal, we use the tactic [applys_eq] to avoid\n a manual [replace] before [T_loc] can be applied. *)\n applys_eq T_Loc 1. \n (* To justify the inequality, there is no need to call [rewrite <- H],\n because the tactic [omega] is able to exploit [H] on its own. \n So, only the rewriting of [lenght_snoc] and the call to [omega] remain. *)\n rewrite length_snoc. omega.\n (* The next proof case is hard to polish because it relies on the\n lemma [nth_eq_snoc] whose statement is not automation-friendly.\n We'll come back to this proof case further on. *)\n unfold store_ty_lookup. rewrite <- H. rewrite* nth_eq_snoc.\n (* Last, we replace [apply ..; assumption] with [apply* ..] *)\n apply* store_well_typed_snoc.\n\n forwards*: IHHt. \n\n Case \"T_Deref\".\n SCase \"ST_DerefLoc\".\n (* old:\n exists ST. split; try split...\n destruct HST as [_ Hsty].\n replace T11 with (store_ty_lookup l ST).\n apply Hsty...\n inversion Ht; subst... *)\n (* new: we start by calling [exists ST] and [splits*]. *)\n exists ST. splits*. \n (* new: we replace [destruct HST as [_ Hsty]] by the following *)\n lets [_ Hsty]: HST.\n (* new: then we use the tactic [applys_eq] to avoid the need to\n perform a manual [replace] before applying [Hsty]. *)\n applys_eq* Hsty 1.\n (* new: finally, we can call [inverts] in place of [inversion;subst] *)\n inverts* Ht.\n\n forwards*: IHHt. \n\n Case \"T_Assign\".\n SCase \"ST_Assign\".\n (* old: \n exists ST. split; try split...\n eapply assign_pres_store_typing...\n inversion Ht1; subst... *)\n (* new: simply using nicer tactics *)\n exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1.\n\n forwards*: IHHt1. \n forwards*: IHHt2. \nQed.\n\n(** Let's come back to the proof case that was hard to optimize. \n The difficulty comes from the statement of [nth_eq_snoc], which\n takes the form [nth (length l) (snoc l x) d = x]. This lemma is\n hard to exploit because its first argument, [length l], mentions\n a list [l] that has to be exactly the same as the [l] occuring in\n [snoc l x]. In practice, the first argument is often a natural \n number [n] that is provably equal to [length l] yet that is not\n syntactically equal to [length l]. There is a simple fix for\n making [nth_eq_snoc] easy to apply: introduce the intermediate\n variable [n] explicitly, so that the goal becomes\n [nth n (snoc l x) d = x], with a premise asserting [n = length l]. *)\n\nLemma nth_eq_snoc' : forall (A : Type) (l : list A) (x d : A) (n : nat),\n n = length l -> nth n (snoc l x) d = x.\nProof. intros. subst. apply nth_eq_snoc. Qed.\n\n(** The proof case for [ref] from the preservation theorem then\n becomes much easier to prove, because [rewrite nth_eq_snoc']\n now succeeds. *)\n \nLemma preservation_ref : forall (st:store) (ST : store_ty) T1,\n length ST = length st ->\n ty_Ref T1 = ty_Ref (store_ty_lookup (length st) (snoc ST T1)).\nProof.\n intros. dup. \n\n (* A first proof, with an explicit [unfold] *)\n unfold store_ty_lookup. rewrite* nth_eq_snoc'.\n\n (* A second proof, with a call to [fequal] *)\n fequal. symmetry. apply* nth_eq_snoc'.\nQed.\n\n\n(** The optimized proof of preservation is summarized next. *)\n\nTheorem preservation' : forall ST t t' T st st',\n has_type empty ST t T ->\n store_well_typed ST st ->\n t / st ==> t' / st' ->\n exists ST',\n (extends ST' ST /\\ \n has_type empty ST' t' T /\\\n store_well_typed ST' st').\nProof.\n remember (@empty ty) as Gamma. introv Ht. gen t'.\n induction Ht; introv HST Hstep; subst Gamma; inverts Hstep; eauto.\n exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. \n forwards*: IHHt1. \n forwards*: IHHt2. \n forwards*: IHHt. \n forwards*: IHHt. \n forwards*: IHHt1. \n forwards*: IHHt2. \n forwards*: IHHt1. \n exists (snoc ST T1). inverts keep HST. splits. \n apply extends_snoc.\n applys_eq T_Loc 1. \n rewrite length_snoc. omega.\n unfold store_ty_lookup. rewrite* nth_eq_snoc'.\n apply* store_well_typed_snoc.\n forwards*: IHHt. \n exists ST. splits*. lets [_ Hsty]: HST.\n applys_eq* Hsty 1. inverts* Ht.\n forwards*: IHHt. \n exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1.\n forwards*: IHHt1. \n forwards*: IHHt2. \nQed.\n\n\n(* ####################################################### *)\n(** ** Progress for STLCRef *)\n\n(** The proof of progress for [STLCRef] can be found in \n the file [References.v]. It contains 53 lines and the \n optimized proof script is, here again, twice shorter. *)\n\nTheorem progress : forall ST t T st,\n has_type empty ST t T ->\n store_well_typed ST st ->\n (value t \\/ exists t', exists st', t / st ==> t' / st').\nProof.\n introv Ht HST. remember (@empty ty) as Gamma.\n induction Ht; subst Gamma; tryfalse; try solve [left*].\n right. destruct* IHHt1 as [K|].\n inverts K; inverts Ht1.\n destruct* IHHt2.\n right. destruct* IHHt as [K|].\n inverts K; try solve [inverts Ht]. eauto.\n right. destruct* IHHt as [K|].\n inverts K; try solve [inverts Ht]. eauto.\n right. destruct* IHHt1 as [K|].\n inverts K; try solve [inverts Ht1].\n destruct* IHHt2 as [M|].\n inverts M; try solve [inverts Ht2]. eauto.\n right. destruct* IHHt1 as [K|].\n inverts K; try solve [inverts Ht1]. destruct* n.\n right. destruct* IHHt.\n right. destruct* IHHt as [K|].\n inverts K; inverts Ht as M.\n inverts HST as N. rewrite* N in M.\n right. destruct* IHHt1 as [K|].\n destruct* IHHt2.\n inverts K; inverts Ht1 as M.\n inverts HST as N. rewrite* N in M.\nQed.\n\nEnd PreservationProgressReferences.\n\n\n(* ####################################################### *)\n(** ** Subtyping *)\n\nModule SubtypingInversion.\n Require Import Subtyping.\n\n(** Recall the inversion lemma for typing judgment \n of abstractions in a type system with subtyping. *)\n\nLemma abs_arrow : forall x S1 s2 T1 T2, \n has_type empty (tm_abs x S1 s2) (ty_arrow T1 T2) ->\n subtype T1 S1 \n /\\ has_type (extend empty x S1) s2 T2.\nProof with eauto.\n intros x S1 s2 T1 T2 Hty.\n apply typing_inversion_abs in Hty.\n destruct Hty as [S2 [Hsub Hty]].\n apply sub_inversion_arrow in Hsub.\n destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].\n inversion Heq; subst... \nQed.\n\n(** Exercise: optimize the proof script, using \n [introv], [lets] and [inverts*]. In particular,\n you will find it useful to replace the pattern \n [apply K in H. destruct H as I] with [lets I: K H]. \n The solution is 4 lines. *)\n \nLemma abs_arrow' : forall x S1 s2 T1 T2, \n has_type empty (tm_abs x S1 s2) (ty_arrow T1 T2) ->\n subtype T1 S1 \n /\\ has_type (extend empty x S1) s2 T2.\nProof.\n (* FILL IN HERE *) admit.\nQed.\n\n(** The lemma [substitution_preserves_typing] has already been\n used to illustrate the working of [lets] and [applys] in\n the file [UseTactics.v]. Optimize further this proof using\n automation (with the star symbol), and using the tactic\n [cases_if']. The solution is 33 lines, including the\n [Case] instructions. *)\n\nLemma substitution_preserves_typing : forall Gamma x U v t S,\n has_type (extend Gamma x U) t S ->\n has_type empty v U ->\n has_type Gamma (subst v x t) S.\nProof.\n (* FILL IN HERE *) admit.\nQed.\n\nEnd SubtypingInversion.\n\n\n(* ####################################################### *)\n(** * Advanced Topics in Proof Search *)\n\n(* ####################################################### *)\n(** ** Stating Lemmas in the Right Way *)\n\n(** Due to its depth-first strategy, [eauto] can get exponentially\n slower as the depth search increases, even when a short proof\n exists. In general, to make proof search run reasonably fast, one\n should avoid using a depth search greater than 5 or 6. Moreover,\n one should try to minimize the number of applicable lemmas, and\n usually put first the hypotheses whose proof usefully instantiates\n the existential variables.\n\n In fact, the ability for [eauto] to solve certain goals actually\n depends on the order in which the hypotheses are stated. This point\n is illustrated through the following example, in which [P] is \n a predicate on natural numbers. This predicate is such that \n [P n] holds for any [n] as soon as [P m] holds for at least one [m]\n different from zero. The goal is to prove that [P 2] implies [P 1]. \n When the hypothesis about [P] is stated in the form\n [forall n m, P m -> m <> 0 -> P n], then [eauto] works. However, with\n [forall n m, m <> 0 -> P m -> P n], the tactic [eauto] fails. *)\n \nLemma order_matters_1 : forall (P : nat->Prop),\n (forall n m, P m -> m <> 0 -> P n) -> P 2 -> P 1.\nProof. \n eauto. (* Success *)\n (* The proof: [intros P H K. eapply H. apply K. auto.] *)\nQed.\n\nLemma order_matters_2 : forall (P : nat->Prop),\n (forall n m, m <> 0 -> P m -> P n) -> P 5 -> P 1.\nProof.\n eauto. (* Failure *)\n\n (* To understand why, let us replay the previous proof *)\n intros P H K. \n eapply H. \n (* The application of [eapply] has left two subgoals,\n [?X <> 0] and [P ?X], where [?X] is an existential variable. *)\n (* Solving the first subgoal is easy for [eauto]: it suffices\n to instantiate [?X] as the value [1], which is the simplest\n value that satisfies [?X <> 0]. *)\n eauto.\n (* But then the second goal becomes [P 1], which is where we\n started from. So, [eauto] gets stuck at this point. *)\nAdmitted.\n\n(** What is important to understand is that the hypothesis [forall n\n m, P m -> m <> 0 -> P n] is eauto-friendly, whereas [forall n m, m\n <> 0 -> P m -> P n] really isn't. Guessing a value of [m] for\n which [P m] holds and then checking that [m <> 0] holds works well\n because there are few values of [m] for which [P m] holds. So, it\n is likely that [eauto] comes up with the right one. On the other\n hand, guessing a value of [m] for which [m <> 0] and then checking\n that [P m] holds does not work well, because there are many values\n of [m] that satisfy [m <> 0] but not [P m]. *)\n\n\n(* ####################################################### *)\n(** ** Unfolding of Definitions During Proof-Search *)\n\n(** The use of intermediate definitions is generally encouraged in a\n formal development as it usually leads to more concise and more\n readable statements. Yet, definitions can make it a little harder\n to automate proofs. The problem is that it is not obvious for a\n proof search mechanism to know when definitions need to be\n unfolded. Note that a naive strategy that consists of unfolding\n all definitions before calling proof search does not scale up to\n large proofs, so we avoid it. This section introduces a few\n techniques for avoiding to manually unfold definitions before\n calling proof search. *)\n\n(** To illustrate the treatment of definitions, let [P] be an abstract\n predicate on natural numbers, and let [myFact] be a definition\n denoting the proposition [P x] holds for any [x] less than or\n equal to 3. *)\n\nAxiom P : nat -> Prop.\n\nDefinition myFact := forall x, x <= 3 -> P x.\n\n(** Proving that [myFact] under the assumption that [P x] holds for\n any [x] should be trivial. Yet, [auto] fails to prove it unless we\n unfold the definition of [myFact] explicitly. *)\n\nLemma demo_hint_unfold_goal_1 : \n (forall x, P x) -> myFact.\nProof.\n auto. (* Proof search doesn't know what to do, *)\n unfold myFact. auto. (* unless we unfold the definition. *)\nQed.\n\n(** To automate the unfolding of definitions that appear as proof\n obligation, one can use the command [Hint Unfold myFact] to tell\n Coq that it should always try to unfold [myFact] when [myFact]\n appears in the goal. *)\n\nHint Unfold myFact.\n\n(** This time, automation is able to see through the definition\n of [myFact]. *)\n\nLemma demo_hint_unfold_goal_2 : \n (forall x, P x) -> myFact.\nProof. auto. Qed.\n\n(** However, the [Hint Unfold] mechanism only works for unfolding\n definitions that appear in the goal. In general, proof search does\n not unfold definitions from the context. For example, assume we\n want to prove that [P 3] holds under the assumption that [True ->\n myFact]. *)\n\nLemma demo_hint_unfold_context_1 : \n (True -> myFact) -> P 3.\nProof.\n intros.\n auto. (* fails *)\n unfold myFact in *. auto. (* succeeds *)\nQed.\n\n(** Note: there is one exception to the previous rule: a constant from\n the context is automatically unfolded when it directly applies to\n the goal. For example, if the assumption is [myFact] instead of\n [True -> myFact], then [auto] solves the proof. *)\n\n\n(* ####################################################### *)\n(** ** Automation for Proving Absurd Goals *)\n\n(** In this section, we'll see that lemmas concluding on a negation\n are generally not useful as hints, and that lemmas whose\n conclusion is [False] can be useful hints but having too many of\n them makes proof search inefficient. We'll also see a practical\n work-around to the efficiency issue. *)\n\n(** Consider the following lemma, which asserts that a number\n less than or equal to 3 is not greater than 3. *)\n\nParameter le_not_gt : forall x,\n (x <= 3) -> ~ (x > 3).\n\n(** Equivalently, one could state that a number greater than three is\n not less than or equal to 3. *)\n\nParameter gt_not_le : forall x,\n (x > 3) -> ~ (x <= 3).\n\n(** In fact, both statements are equivalent to a third one stating\n that [x <= 3] and [x > 3] are contradictory, in the sense that\n they imply [False]. *)\n\nParameter le_gt_false : forall x,\n (x <= 3) -> (x > 3) -> False.\n\n(** The following investigation aim at figuring out which of the three\n statments is the most convenient with respect to proof\n automation. The following material is enclosed inside a [Section],\n so as to restrict the scope of the hints that we are adding. In\n other words, after the end of the section, the hints added within\n the section will no longer be active.*)\n\nSection DemoAbsurd1.\n\n(** Let's try to add the first lemma, [le_not_gt], as hint,\n and see whether we can prove that the proposition\n [exists x, x <= 3 /\\ x > 3] is absurd. *)\n\nHint Resolve le_not_gt.\n\nLemma demo_auto_absurd_1 : \n (exists x, x <= 3 /\\ x > 3) -> False.\nProof. \n intros. jauto_set. (* decomposes the assumption *)\n (* debug *) eauto. (* does not see that [le_not_gt] could apply *)\n eapply le_not_gt. eauto. eauto.\nQed.\n\n(** The lemma [gt_not_le] is symmetric to [le_not_gt], so it will not\n be any better. The third lemma, [le_gt_false], is a more useful\n hint, because it concludes on [False], so proof search will try to\n apply it when the current goal is [False]. *)\n\nHint Resolve le_gt_false.\n\nLemma demo_auto_absurd_2 : \n (exists x, x <= 3 /\\ x > 3) -> False.\nProof. \n dup.\n\n (* detailed version: *)\n intros. jauto_set. (* debug *) eauto.\n\n (* short version: *)\n jauto. \nQed.\n\n(** In summary, a lemma of the form [H1 -> H2 -> False] is a much more\n effective hint than [H1 -> ~ H2], even though the two statments\n are equivalent up to the definition of the negation symbol [~]. *)\n\n(** That said, one should be careful with adding lemmas whose\n conclusion is [False] as hint. The reason is that whenever\n reaching the goal [False], the proof search mechanism will\n potentially try to apply all the hints whose conclusion is [False]\n before applying the appropriate one. *)\n\nEnd DemoAbsurd1.\n\n(** Adding lemmas whose conclusion is [False] as hint can be, locally,\n a very effective solution. However, this approach does not scale\n up for global hints. For most practical applications, it is\n reasonable to give the name of the lemmas to be exploited for\n deriving a contradiction. The tactic [false H] is useful for that\n purpose: it replaces the goal with [False] and calls [eapply\n H]. Its behavior is described next. Observe that any of the three\n statements [le_not_gt], [gt_not_le] or [le_gt_false] can be\n used. *)\n\nLemma demo_false : forall x, \n (x <= 3) -> (x > 3) -> 4 = 5.\nProof. \n intros. dup 4.\n \n (* A failed proof: *)\n false. eapply le_gt_false.\n auto. (* [auto] does not prove [?x <= 3] using [H], but instead\n using the lemma [le_refl : forall x, x <= x]. *)\n (* The second subgoal becomes [3 > 3], which is not provable. *)\n skip.\n\n (* A correct proof: *)\n false. eapply le_gt_false.\n eauto. (* [eauto] uses [H], as expected, to prove [?x <= 3] *)\n eauto. (* so the second subgoal becomes [x > 3] *)\n\n (* The same proof using [false]: *)\n false le_gt_false. eauto. eauto.\n\n (* The lemmas [le_not_gt] and [gt_not_le] work as well *)\n false le_not_gt. eauto. eauto.\nQed.\n\n(** In the above example, [false le_gt_false; eauto] proves the goal,\n but [false le_gt_false; auto] does not, because [auto] does not\n correctly instantiate the existential variable. Note that [false*\n le_gt_false] would not work either, because the [*] symbol tries\n to call [auto] first. So, there are two possibilities for\n completing the proof: either call [false le_gt_false; eauto], or\n call [false* (le_gt_false 3)]. *)\n\n\n(* ####################################################### *)\n(** ** Automation for Transitivity Lemmas *)\n\n(** Some lemmas should never be added as hints, because they would\n very badly slow down proof search. The typical example is that of\n transitivity results. This section describes the problem and\n presents a general workaround.\n\n Consider a subtyping relation, written [subtype S T], that relates\n two object [S] and [T] of type [typ]. Assume that this relation\n has been proved reflexive and transitive. The corresponding lemmas\n are named [subtype_refl] and [subtype_trans]. *)\n\nParameter typ : Type.\n\nParameter subtype : typ -> typ -> Prop.\n\nParameter subtype_refl : forall T, \n subtype T T.\n\nParameter subtype_trans : forall S T U,\n subtype S T -> subtype T U -> subtype S U.\n\n(** Adding reflexivity as hint is generally a good idea,\n so let's add reflexivity of subtyping as hint. *)\n\nHint Resolve subtype_refl.\n\n(** Adding transitivity as hint is generally a bad idea. To\n understand why, let's add it as hint and see what happens.\n Because we cannot remove hints once we've added them, we are going\n to open a \"Section,\" so as to restrict the scope of the\n transitivity hint to that section. *)\n \nSection HintsTransitivity.\n\nHint Resolve subtype_trans.\n\n(** Now, consider the goal [forall S T, subtype S T], which clearly has\n no hope of being solved. Let's call [eauto] on this goal. *)\n\nLemma transitivity_bad_hint_1 : forall S T,\n subtype S T.\nProof. \n intros. (* debug *) eauto. (* Investigates 106 applications... *)\nAdmitted.\n\n(** Note that after closing the section, the hint [subtype_trans]\n is no longer active. *)\n\nEnd HintsTransitivity.\n\n(** In the previous example, the proof search has spent a lot of time\n trying to apply transitivity and reflexivity in every possible\n way. Its process can be summarized as follows. The first goal is\n [subtype S T]. Since reflexivity does not apply, [eauto] invokes\n transitivity, which produces two subgoals, [subtype S ?X] and\n [subtype ?X T]. Solving the first subgoal, [subtype S ?X], is\n straightforward, it suffices to apply reflexivity. This unifies\n [?X] with [S]. So, the second sugoal, [subtype ?X T], becomes\n becomes [subtype S T], which is exactly what we started from...\n\n The problem with the transitivity lemma is that it is applicable\n to any goal concluding on a subtyping relation. Because of this,\n [eauto] keeps trying to apply it even though it most often doesn't\n help to solve the goal. So, one should never add a transitivity\n lemma as a hint for proof search. *)\n\n(** There is a general workaround for having automation to exploit\n transitivity lemmas without giving up on efficiency. This workaround\n relies on a powerful mechanism called \"external hint.\" This \n mechanism allows to manually describe the condition under which\n a particular lemma should be tried out during proof search. \n \n For the case of transitivity of subtyping, we are going to tell\n Coq to try and apply the transitivity lemma on a goal of the form\n [subtype S U] only when the proof context already contains an\n assumption either of the form [subtype S T] or of the form\n [subtype T U]. In other words, we only apply the transitivity\n lemma when there is some evidence that this application might\n help. To set up this \"external hint,\" one has to write the\n following. *)\n\nHint Extern 1 (subtype ?S ?U) =>\n match goal with \n | H: subtype S ?T |- _ => apply (@subtype_trans S T U)\n | H: subtype ?T U |- _ => apply (@subtype_trans S T U)\n end.\n\n(** This hint declaration can be understood as follows.\n - \"Hint Extern\" introduces the hint.\n - The number \"1\" corresponds to a priority for proof search. \n It doesn't matter so much what priority is used in practice.\n - The pattern [subtype ?S ?U] describes the kind of goal on\n which the pattern should apply. The question marks are used\n to indicate that the variables [?S] and [?U] should be bound\n to some value in the rest of the hint description.\n - The construction [match goal with ... end] tries to recognize\n patterns in the goal, or in the proof context, or both. \n - The first pattern is [H: subtype S ?T |- _]. It indices that\n the context should contain an hypothesis [H] of type \n [subtype S ?T], where [S] has to be the same as in the goal,\n and where [?T] can have any value.\n - The symbol [|- _] at the end of [H: subtype S ?T |- _] indicates\n that we do not impose further condition on how the proof \n obligation has to look like.\n - The branch [=> apply subtype_trans with (T:=T)] that follows\n indicate that if the goal has the form [subtype S U] and if\n there exists an hypothesis of the form [subtype S T], then\n we should try and apply transitivity lemma instantiated on\n the arguments [S], [T] and [U]. (Note: the symbol [@] in front of\n [subtype_trans] is only actually needed when the \"Implicit Arguments\"\n feature is activated.)\n - The other branch, which corresponds to an hypothesis of the form\n [H: subtype ?T U] is symmetrical. \n\n Note: the same external hint can be reused for any other transitive \n relation, simply by renaming [subtype] into the name of that relation. *)\n\n(** Let us see an example illustrating how the hint works. *)\n\nLemma transitivity_workaround_1 : forall T1 T2 T3 T4,\n subtype T1 T2 -> subtype T2 T3 -> subtype T3 T4 -> subtype T1 T4.\nProof.\n intros. (* debug *) eauto. (* The trace shows the external hint being used *)\nQed.\n\n(** We may also check that the new external hint does not suffer from the \n complexity blow up. *)\n\nLemma transitivity_workaround_2 : forall S T,\n subtype S T.\nProof.\n intros. (* debug *) eauto. (* Investigates 0 applications *)\nAdmitted.\n\n\n(* ####################################################### *)\n(** * Decision Procedures *)\n\n(** A decision procedure is able to solve proof obligations whose\n statement admits a particular form. This section describes three\n useful decision procedures. The tactic [omega] handles goals\n involving arithmetic and inequalities, but not general\n multiplications. The tactic [ring] handles goals involving\n arithmetic, including multiplications, but does not support\n inequalities. The tactic [congruence] is able to prove equalities\n and inequalities by exploiting equalities available in the proof\n context. *)\n\n\n(* ####################################################### *)\n(** ** Omega *)\n\n(** The tactic [omega] supports natural numbers (type [nat]) as well as\n integers (type [Z], available by including the module [ZArith]).\n It supports addition, substraction, equalities and inequalities. \n Before using [omega], one needs to import the module [Omega],\n as follows. *)\n\nRequire Import Omega.\n\n(** Here is an example. Let [x] and [y] be two natural numbers\n (they cannot be negative). Assume [y] is less than 4, assume\n [x+x+1] is less than [y], and assume [x] is not zero. Then, \n it must be the case that [x] is equal to one. *)\n\nLemma omega_demo_1 : forall (x y : nat),\n (y <= 4) -> (x + x + 1 <= y) -> (x <> 0) -> (x = 1).\nProof. intros. omega. Qed.\n\n(** Another example: if [z] is the mean of [x] and [y], and if the \n difference between [x] and [y] is at most [4], then the difference \n between [x] and [z] is at most 2. *)\n\nLemma omega_demo_2 : forall (x y z : nat),\n (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2).\nProof. intros. omega. Qed.\n\n(** One can proof [False] using [omega] if the mathematical facts\n from the context are contradictory. In the following example,\n the constraints on the values [x] and [y] cannot be all\n satisfied in the same time. *)\n\nLemma omega_demo_3 : forall (x y : nat),\n (x + 5 <= y) -> (y - x < 3) -> False.\nProof. intros. omega. Qed.\n\n(** Note: [omega] can prove a goal by contradiction only if its \n conclusion is reduced [False]. The tactic [omega] always fails \n when the conclusion is an arbitrary proposition [P], even though\n [False] implies any proposition [P] (by [ex_falso_quodlibet]). *)\n\nLemma omega_demo_4 : forall (x y : nat) (P : Prop),\n (x + 5 <= y) -> (y - x < 3) -> P.\nProof.\n intros. \n (* Calling [omega] at this point fails with the message:\n \"Omega: Can't solve a goal with proposition variables\" *)\n (* So, one needs to replace the goal by [False] first. *)\n false. omega.\nQed.\n\n\n(* ####################################################### *)\n(** ** Ring *)\n\n(** Compared with [omega], the tactic [ring] adds support for\n multiplications, however it gives up the ability to reason on\n inequations. Moreover, it supports only integers (type [Z]) and\n not natural numbers (type [Z]). Here is an example showing how to\n use [ring]. *)\n\nModule RingDemo.\n Require Import ZArith.\n Open Scope Z_scope. (* \"+\" and \"-\" and \"*\" should be interpreted in [Z] *)\n\nLemma ring_demo : forall (x y z : Z), \n x * (y + z) - z * 3 * x\n = x * y - 2 * x * z.\nProof. intros. ring. Qed.\n\nEnd RingDemo. \n\n\n(* ####################################################### *)\n (** ** Congruence *)\n\n(** The tactic [congruence] is able to exploit equalities from the\n proof context in order to automatically perform the rewriting\n operations necessary to establish a goal. It is slightly more\n powerful than the tactic [subst], which can only handle equalities\n of the form [x = e] where [x] is a variable and [e] an\n expression. *)\n\nLemma congruence_demo_1 : \n forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), \n f (g x) (g y) = z ->\n 2 = g x ->\n g y = h z ->\n f 2 (h z) = z.\nProof. intros. congruence. Qed.\n\n(** Moreover, [congruence] is able to exploit universally quantified\n equalities, for example [forall a, g a = h a]. *)\n\nLemma congruence_demo_2 : \n forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), \n (forall a, g a = h a) ->\n f (g x) (g y) = z ->\n g x = 2 ->\n f 2 (h y) = z.\nProof. congruence. Qed.\n\n(** Next is an example where [congruence] is very useful. *)\n\nLemma congruence_demo_4 : forall (f g : nat->nat),\n (forall a, f a = g a) ->\n f (g (g 2)) = g (f (f 2)).\nProof. congruence. Qed.\n\n(** The tactic [congruence] is able to prove a contradiction if the\n goal entails an equality that contradicts an inequality available\n in the proof context. *)\n\nLemma congruence_demo_3 : \n forall (f g h : nat->nat) (x : nat), \n (forall a, f a = h a) ->\n g x = f x ->\n g x <> h x ->\n False.\nProof. congruence. Qed.\n\n(** One of the strengths of [congruence] is that it is a very fast\n tactic. So, one should not hesitate to invoke it wherever it might\n help. *)\n", "meta": {"author": "Blaisorblade", "repo": "Software-Foundations", "sha": "aeb1b49fd922a346b774b330694fe6c16caf9626", "save_path": "github-repos/coq/Blaisorblade-Software-Foundations", "path": "github-repos/coq/Blaisorblade-Software-Foundations/Software-Foundations-aeb1b49fd922a346b774b330694fe6c16caf9626/UseAuto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.22000709974589316, "lm_q1q2_score": 0.11000354987294658}} {"text": "(** * Spinlock well synchronized and spinlock clean*)\nRequire Import compcert.lib.Axioms.\n\nRequire Import VST.concurrency.sepcomp. Import SepComp.\nRequire Import VST.sepcomp.semantics_lemmas.\n\nRequire Import VST.concurrency.pos.\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n after Ssreflect eqtype.*)\nRequire Import compcert.common.AST. (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Memory.\nRequire Import compcert.lib.Integers.\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import VST.concurrency.threads_lemmas.\nRequire Import VST.concurrency.permissions.\nRequire Import VST.concurrency.permjoin_def.\nRequire Import VST.concurrency.concurrent_machine.\nRequire Import VST.concurrency.memory_lemmas.\nRequire Import VST.concurrency.dry_context.\nRequire Import VST.concurrency.dry_machine_lemmas.\nRequire Import VST.concurrency.dry_machine_step_lemmas.\nRequire Import VST.concurrency.executions.\nRequire Import Coqlib.\nRequire Import VST.msl.Coqlib2.\n\nSet Bullet Behavior \"None\".\nSet Bullet Behavior \"Strict Subproofs\".\n\nModule SpinLocks (SEM: Semantics)\n (SemAxioms: SemanticsAxioms SEM)\n (Machines: MachinesSig with Module SEM := SEM)\n (AsmContext: AsmContext SEM Machines).\n Import Machines DryMachine ThreadPool AsmContext.\n Import event_semantics.\n Import Events.\n\n Module ThreadPoolWF := ThreadPoolWF SEM Machines.\n Module CoreLanguage := CoreLanguage SEM SemAxioms.\n Module CoreLanguageDry := CoreLanguageDry SEM SemAxioms DryMachine.\n Module StepLemmas := StepLemmas SEM Machines.\n Module Executions := Executions SEM SemAxioms Machines AsmContext.\n\n Import Executions CoreLanguage CoreLanguageDry ThreadPoolWF StepLemmas.\n\n Section Spinlocks.\n\n Hypothesis EM: ClassicalFacts.excluded_middle.\n\n (** True if two events access at least one common byte*)\n Definition sameLocation ev1 ev2 :=\n match Events.location ev1, Events.location ev2 with\n | Some (b1, ofs1, size1), Some (b2, ofs2, size2) =>\n b1 = b2 /\\ exists ofs, Intv.In ofs (ofs1, (ofs1 + Z.of_nat size1)%Z) /\\\n Intv.In ofs (ofs2, (ofs2 + Z.of_nat size2)%Z)\n | _,_ => False\n end.\n\n (** Competing Events *)\n\n (** Actions that may compete*)\n Definition caction (ev : Events.machine_event) :=\n match ev with\n | internal _ (event_semantics.Write _ _ _) => Some Write\n | internal _ (event_semantics.Read _ _ _ _) => Some Read\n | internal _ (event_semantics.Alloc _ _ _) => None\n | internal _ (event_semantics.Free _) => None\n | external _ (release _ _) => Some Release\n | external _ (acquire _ _) => Some Acquire\n | external _ (mklock _) => Some Mklock\n | external _ (freelock _) => Some Freelock\n | external _ (spawn _ _ _) => None\n | external _ (failacq _) => Some Failacq\n end.\n\n (** Two events compete if they access the same location, from a\n different thread. *)\n\n (*this definition allows reads and writes to compete with release/acq - wrong*)\n (*Definition competes (ev1 ev2 : Events.machine_event) : Prop :=\n thread_id ev1 <> thread_id ev2 /\\\n sameLocation ev1 ev2 /\\\n caction ev1 /\\ caction ev2 /\\\n (caction ev1 = Some Write \\/\n caction ev2 = Some Write \\/\n caction ev1 = Some Mklock \\/\n caction ev2 = Some Mklock \\/\n caction ev1 = Some Freelock \\/\n caction ev2 = Some Freelock). *)\n\n (* this definition allows makelock/freelock to compete with\n freelock/makelock, that's probably desired*)\n Definition competes (ev1 ev2 : Events.machine_event) : Prop :=\n thread_id ev1 <> thread_id ev2 /\\ (* different threads*)\n sameLocation ev1 ev2 /\\ (* same location *)\n caction ev1 /\\ (* both are competing type*)\n caction ev2 /\\\n (is_internal ev1 ->\n is_internal ev2 ->\n (** if they are both internal, at least one of them is a Write*)\n action ev1 = Write \\/ action ev2 = Write) /\\\n (is_external ev1 \\/ is_external ev2 ->\n (** if one of them is external, then at least one of them is a Mklock or\n freelock*)\n action ev1 = Mklock \\/ action ev1 = Freelock\n \\/ action ev2 = Mklock \\/ action ev2 = Freelock).\n\n (** Spinlock well synchronized*)\n Definition spinlock_synchronized (tr : SC.event_trace) :=\n forall i j ev1 ev2,\n i < j ->\n List.nth_error tr i = Some ev1 ->\n List.nth_error tr j = Some ev2 ->\n competes ev1 ev2 ->\n (exists u v eu ev,\n i <= u < v /\\ v < j /\\\n List.nth_error tr u = Some eu /\\\n List.nth_error tr v = Some ev /\\\n action eu = Release /\\ action ev = Acquire /\\\n location eu = location ev) \\/\n (** we also consider spawn operations to be synchronizing*)\n (exists u eu,\n i < u < j /\\\n List.nth_error tr u = Some eu /\\\n action eu = Spawn).\n\n (** Spinlock clean*)\n Definition spinlock_clean (tr : FineConc.event_trace) :=\n forall i j evi evj\n (Hij: i < j)\n (Hi: List.nth_error tr i = Some evi)\n (Hj: List.nth_error tr j = Some evj)\n (Hmklock: action evi = Mklock)\n (Hfreelock: forall u evu, i < u < j ->\n List.nth_error tr u = Some evu ->\n action evu <> Freelock \\/\n location evu <> location evi)\n (Hlocation: sameLocation evj evi),\n action evj <> Write /\\ action evj <> Read.\n\n (** Spinlock clean for a single step*)\n Lemma fstep_clean:\n forall U U' tp m addr tr pre ev post tp' m' tidi\n (Hlock: lockRes tp addr)\n (HisLock: isLock tp addr)\n (Hlocation: sameLocation ev (external tidi (mklock addr)))\n (Hstep: FineConc.MachStep the_ge (U, tr, tp) m\n (U', tr ++ pre ++ [:: ev] ++ post, tp') m'),\n action ev <> Write /\\ action ev <> Read.\n Proof.\n intros.\n inversion Hstep; simpl in *;\n try match goal with\n | [H: ?X = app ?X ?Y |- _] =>\n rewrite <- app_nil_r in H at 1;\n apply app_inv_head in H\n end; subst;\n try match goal with\n | [H: nth_error [::] _ = _ |- _] =>\n rewrite nth_error_nil in H;\n discriminate\n end;\n try match goal with\n | [H: [::] = ?X ++ (_ :: _) |- _] =>\n destruct X; simpl in H; congruence\n end.\n { (** Case of internal step *)\n (*NOTE: Should spinlock clean also mention free and alloc?*)\n inversion Htstep; subst.\n apply app_inv_head in H5.\n apply ev_step_elim in Hcorestep.\n destruct Hcorestep as [Helim _].\n apply list_append_map_inv in H5.\n destruct H5 as (mpre & mpost & Hpre & Hevpost & Hev0).\n destruct mpost as [|mev mpost];\n simpl in Hevpost; first by discriminate.\n inv Hevpost.\n apply ev_elim_split in Helim.\n destruct Helim as (m2 & ? & Helim_ev).\n unfold sameLocation in Hlocation.\n destruct (location (internal tid mev))\n as [[[b1 ofs1] size1]|] eqn:Haccessed_loc; try by exfalso.\n (** Case location function is defined, i.e. for writes and reads*)\n simpl in Hlocation.\n destruct addr as [bl ofsl].\n destruct Hlocation as [Hb [ofs' [Hintv Hintvl]]].\n (** [ofs'] is the exact offset which both events access*)\n subst.\n (** hence there will be some lock permission that is above [Readable] on\n [address] (bl, ofs') by [isLock] *)\n specialize (HisLock ofs' Hintvl).\n (** and thus all threads will have at most [Nonempty]\n data permission on this [address] by [perm_coh]*)\n assert (Hperm:\n Mem.perm_order'' (Some Nonempty)\n ((getThreadR Htid).1 !! bl ofs')).\n { destruct HisLock as [[j [cntj Hperm]] | [laddr [rmap [Hres Hperm]]]].\n - pose proof ((thread_data_lock_coh Hinv cntj).1 _ Htid bl ofs') as Hcoh.\n clear - Hcoh Hperm.\n simpl in Hperm.\n destruct ((getThreadR Htid).1 !! bl ofs') as [p|]; simpl; auto;\n destruct ((getThreadR cntj).2 !! bl ofs') as [p0|]; simpl in Hperm;\n inversion Hperm; subst;\n simpl in Hcoh; destruct p;\n try (by exfalso); eauto using perm_order.\n - pose proof ((locks_data_lock_coh Hinv _ Hres).1 _ Htid bl ofs') as Hcoh.\n clear - Hcoh Hperm.\n simpl in Hperm.\n destruct ((getThreadR Htid).1 !! bl ofs') as [p|]; simpl; auto;\n destruct (rmap.2 !! bl ofs') as [p0|]; simpl in Hperm;\n inversion Hperm; subst;\n simpl in Hcoh; destruct p;\n try (by exfalso); eauto using perm_order.\n }\n\n (** [bl] must be a [Mem.valid_block]*)\n assert (Hvalid: Mem.valid_block m bl)\n by (destruct (lockRes tp (bl, ofsl)) as [rmap|] eqn:Hres; try (by exfalso);\n pose proof (lockRes_blocks Hcmpt (bl, ofsl) Hres);\n eauto).\n\n (** ev_elim steps cannot change the permission of the lock\n on the memory *)\n rewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid).1) in Hperm.\n assert (Hperm': Mem.perm_order'' (Some Writable) (permission_at (restrPermMap (Hcmpt tid Htid).1) bl ofs' Cur))\n by (eapply po_trans; eauto; simpl; eauto using perm_order).\n apply (proj2 (restrPermMap_valid (Hcmpt tid Htid).1 bl)) in Hvalid.\n pose proof (ev_elim_stable _ _ _ Hvalid Hperm' H) as Heq.\n simpl in Helim_ev.\n split; intros Haction; simpl in Haction;\n destruct mev; try discriminate;\n simpl in Haccessed_loc; inv Haccessed_loc.\n + (** Case the event is a Write *)\n destruct Helim_ev as [m'' [Hstore Helim']].\n clear - Hstore Heq Hperm Hintv.\n apply Mem.storebytes_range_perm in Hstore.\n specialize (Hstore ofs' Hintv).\n unfold Mem.perm in Hstore.\n unfold permission_at in *.\n destruct (((Mem.mem_access m2) !! bl ofs' Cur)) as [p|]; try destruct p;\n simpl in Hstore; inv Hstore; rewrite Heq in Hperm; simpl in Hperm;\n inv Hperm.\n + (** Case the event is a Read *)\n destruct Helim_ev as [Hload Helim'].\n clear - Hload Heq Hperm Hintv.\n assert (Hlength := Mem.loadbytes_length _ _ _ _ _ Hload).\n apply Mem.loadbytes_range_perm in Hload.\n rewrite Hlength in Hintv.\n unfold Mem.range_perm in Hload.\n rewrite nat_of_Z_max in Hintv.\n destruct (Z.max_dec n 0) as [Hmax | Hmax];\n rewrite Hmax in Hintv.\n * specialize (Hload ofs' Hintv).\n unfold Mem.perm in Hload.\n unfold permission_at in *.\n rewrite Heq in Hperm.\n destruct (((Mem.mem_access m2) !! bl ofs' Cur)) as [p|]; try destruct p;\n simpl in Hperm; inversion Hperm;\n simpl in Hload; inversion Hload.\n * rewrite Z.add_0_r in Hintv.\n destruct Hintv; simpl in *. omega.\n }\n { (** Case it's an external step*)\n apply app_inv_head in H5.\n destruct pre; simpl in H5;\n inv H5.\n simpl; destruct ev0; split; intro Hcontra; by discriminate.\n destruct pre; simpl in H1; inv H1.\n }\n Qed.\n\n (** FineConc is spinlock clean*)\n Theorem fineConc_clean:\n forall U tr tp m tp' m'\n (Hexec: multi_fstep (U, [::], tp) m ([::], tr, tp') m'),\n spinlock_clean tr.\n Proof.\n unfold spinlock_clean.\n intros.\n replace tr with ([::] ++ tr) in Hexec by reflexivity.\n (** break up the trace in the parts of interest*)\n apply multi_fstep_inv_ext with (i := i) (ev := evi) in Hexec; auto.\n destruct Hexec as (U' & U'' & tp'' & m'' & tr'' & tp''' & m'''\n & Hexec & Hstep & Hexec' & Hsize).\n destruct evi as [|tidi evi'];\n simpl in Hmklock. destruct m0; discriminate.\n destruct evi'; try discriminate.\n simpl in *.\n rewrite <- app_nil_r with (l := [:: external tidi (mklock a)]) in Hstep;\n rewrite <- app_nil_l with (l := [:: external tidi (mklock a)]) in Hstep;\n rewrite <- app_assoc in Hstep;\n assert (Hsched: U' = tidi :: U'')\n by (eapply fstep_event_sched in Hstep;\n simpl in Hstep; assumption).\n rewrite Hsched in Hstep.\n (** The thread that executed the [mklock] operation must be in the threadpool*)\n destruct (fstep_ev_contains _ _ _ Hstep) as [cnti cnti'].\n (** since there was a [mklock] event, [a] will be in [lockRes] and the\n thread will have lock-permission on it*)\n apply Mklock_lockRes in Hstep.\n destruct Hstep as [HlockRes''' Hperm'''].\n assert (exists trj, tr = tr'' ++ [:: external tidi (mklock a)] ++ trj)\n by (eapply multi_fstep_trace_monotone in Hexec';\n destruct Hexec' as [? Hexec'];\n rewrite <- app_assoc in Hexec';\n eexists; eauto).\n destruct H as [trj H].\n subst.\n rewrite app_assoc in Hexec'.\n assert (Hj_trj:\n nth_error trj (j - length (tr'' ++ [:: external tidi (mklock a)])) =\n Some evj).\n { rewrite <- nth_error_app2.\n rewrite <- app_assoc. assumption.\n rewrite app_length. simpl. ssromega.\n }\n eapply multi_fstep_inv with (ev := evj) in Hexec'; eauto.\n destruct Hexec' as (Uj' & Uj'' & tpj'' & mj'' & trj'' & pre_j & post_j &\n tpj''' & mj''' & Hexecj' & Hstepj & Hexecj'' & Hsizej).\n erewrite nth_error_app2 in Hj by ssromega.\n assert (Hlock: lockRes tpj'' a /\\ isLock tpj'' a).\n { eapply remLockRes_Freelock_execution with\n (tr := tr'' ++ [:: external tidi (mklock a)]) (tr' := trj''); eauto.\n left.\n exists tidi, cnti'.\n erewrite Hperm''' by eauto.\n simpl; now constructor.\n intros u evu Hnth.\n assert (exists trj''', trj = trj'' ++ pre_j ++ [:: evj] ++ post_j ++ trj''').\n { eapply multi_fstep_trace_monotone in Hexecj''.\n destruct Hexecj'' as [? Hexecj''].\n do 3 rewrite <- app_assoc in Hexecj''.\n apply app_inv_head in Hexecj''.\n apply app_inv_head in Hexecj''.\n subst. do 3 rewrite <- app_assoc.\n eexists;\n by eauto.\n }\n destruct H as [trj''' H].\n subst.\n do 2 rewrite app_length in Hsizej.\n simpl in Hsizej.\n eapply (Hfreelock (length (tr'' ++ [:: external tidi (mklock a)]) + u)).\n apply/andP. split.\n rewrite app_length. simpl.\n ssromega.\n rewrite app_length.\n simpl.\n (** u is smaller than length of trj''*)\n assert (Hu: (u < length trj'')%coq_nat)\n by (erewrite <- nth_error_Some; intros Hcontra; congruence).\n rewrite <- ltn_subRL.\n rewrite <- Hsizej. ssromega.\n replace ((tr'' ++\n [:: external tidi (mklock a)] ++\n trj'' ++ pre_j ++ [:: evj] ++ post_j ++ trj''')) with\n ((tr'' ++ [:: external tidi (mklock a)]) ++\n trj'' ++ pre_j ++ [:: evj] ++\n post_j ++ trj''')\n by (rewrite <- app_assoc; reflexivity).\n erewrite <- nth_error_app with (ys := tr'' ++\n [:: external tidi (mklock a)]).\n rewrite nth_error_app1. eauto.\n erewrite <- nth_error_Some. intro Hcontra; congruence.\n }\n destruct Hlock as [HlockResj HisLockj].\n rewrite app_assoc in Hstepj.\n eapply fstep_clean; eauto.\n destruct evi; simpl in *; auto. destruct m0; discriminate.\n Qed.\n\n Lemma maximal_competing:\n forall i j tr evi evj\n (Hij: i < j)\n (Hi: nth_error tr i = Some evi)\n (Hj: nth_error tr j = Some evj)\n (Hcompetes: competes evi evj),\n exists k evk, i <= k < j /\\\n nth_error tr k = Some evk /\\\n competes evk evj /\\\n (forall k' evk', k < k' < j ->\n nth_error tr k' = Some evk' ->\n ~ competes evk' evj).\n Proof.\n intros i j tr.\n generalize dependent j.\n generalize dependent i.\n induction tr; intros.\n - rewrite nth_error_nil in Hi.\n discriminate.\n - (** Is there any competing with [evj] event in [tr]?*)\n assert (Hcompeting: (exists k' evk',\n i < k' < j /\\\n nth_error (a :: tr) k' = Some evk' /\\\n competes evk' evj) \\/\n ~ (exists k' evk',\n i < k' < j /\\\n nth_error (a :: tr) k' = Some evk' /\\\n competes evk' evj))\n by (eapply EM).\n destruct Hcompeting as [[k' [evk' [Horder [Hk' Hcompete']]]] |\n Hno_race].\n + (** If yes, then use this to instantiate the IH*)\n destruct k'; first by (exfalso; ssromega).\n destruct j; first by (exfalso; ssromega).\n simpl in *.\n destruct (IHtr k' j evk' evj ltac:(ssromega) Hk' Hj Hcompete')\n as (k & evk & Horder' & Hk & Hcompetekj & Hmaximal).\n exists (S k), evk.\n repeat (split; simpl; eauto).\n ssromega.\n intros k'0 evk'0 Horder'0 Hk'0.\n destruct k'0; first by (exfalso; ssromega).\n simpl in Hk'0.\n eapply Hmaximal; eauto.\n + (** Otherwise [evi] is the first event to compete with [evj] and hence maximal*)\n exists i, evi.\n repeat (split; eauto).\n ssromega.\n intros k' evk' Horder' Hk' Hcompetes'.\n (** but by [Hno_race] there is no event at k' [i < k'] s.t. it competes with evj*)\n eapply Hno_race.\n exists k', evk'.\n split; eauto.\n Qed.\n\n (** Actions that require a [Readable] permission*)\n Inductive raction ev : Prop :=\n | read: action ev = Read ->\n raction ev\n | acq: action ev = Acquire ->\n raction ev\n | rel: action ev = Release ->\n raction ev\n | facq: action ev = Failacq ->\n raction ev.\n\n (** Actions that require a [Writable] permission*)\n Inductive waction ev : Prop:=\n | write: action ev = Write ->\n waction ev\n | mk: action ev = Mklock ->\n waction ev\n | fl: action ev = Freelock ->\n waction ev.\n\n Lemma compete_cases:\n forall evi evj\n (Hcompetes: competes evi evj),\n (raction evi /\\ waction evj) \\/\n (waction evi /\\ caction evj).\n Proof.\n intros.\n destruct Hcompetes as (? & ? & Hact1 & Hact2 & Hint & Hext).\n unfold caction.\n destruct evi as [? evi | ? evi], evj as [? evj | ? evj];\n destruct evi, evj; auto 10 using raction, waction;\n simpl in *;\n try (by exfalso);\n try (destruct (Hint ltac:(auto 1) ltac:(auto 1)); discriminate);\n try (destruct (Hext ltac:(auto 2)) as [? | [? | [? | ?]]]; discriminate).\n Qed.\n\n Lemma fstep_ev_perm:\n forall U tr tp m U' tr_pre tr_post tp' m' ev\n (Hstep: FineConc.MachStep the_ge (U, tr, tp) m (U', tr ++ tr_pre ++ [:: ev] ++ tr_post , tp') m'),\n (waction ev ->\n forall (cnt: containsThread tp (thread_id ev)) (cnt': containsThread tp' (thread_id ev)),\n match location ev with\n | Some (b, ofs, sz) =>\n forall ofs', Intv.In ofs' (ofs, ofs + Z.of_nat sz)%Z ->\n (Mem.valid_block m b ->\n Mem.perm_order'' ((getThreadR cnt).1 !! b ofs') (Some Writable) \\/\n Mem.perm_order'' ((getThreadR cnt).2 !! b ofs') (Some Writable)) /\\\n ((Mem.perm_order'' ((getThreadR cnt').1 !! b ofs') (Some Writable) \\/\n Mem.perm_order'' ((getThreadR cnt').2 !! b ofs') (Some Writable)) \\/\n deadLocation tp' m' b ofs')\n | None => False\n end) /\\\n (caction ev ->\n forall (cnt: containsThread tp (thread_id ev)) (cnt': containsThread tp' (thread_id ev)),\n match location ev with\n | Some (b, ofs, sz) =>\n forall ofs', Intv.In ofs' (ofs, ofs + Z.of_nat sz)%Z ->\n (Mem.valid_block m b ->\n Mem.perm_order'' ((getThreadR cnt).1 !! b ofs') (Some Readable) \\/\n Mem.perm_order'' ((getThreadR cnt).2 !! b ofs') (Some Readable)) /\\\n ((Mem.perm_order'' ((getThreadR cnt').1 !! b ofs') (Some Readable) \\/\n Mem.perm_order'' ((getThreadR cnt').2 !! b ofs') (Some Readable)) \\/\n (tr_pre = [::] /\\ tr_post = [::] /\\ action ev = Release /\\\n (exists rmap, sz = lksize.LKSIZE_nat /\\\n lockRes tp' (b, ofs) = Some rmap /\\\n (Mem.perm_order'' (rmap.1 !! b ofs') (Some Readable) \\/\n Mem.perm_order'' (rmap.2 !! b ofs') (Some Readable)))) \\/\n deadLocation tp' m' b ofs')\n | None => False\n end).\n Proof.\n intros.\n inversion Hstep; simpl in *;\n try (apply app_eq_nil in H4;\n subst; destruct tr_pre;\n simpl in H4; discriminate).\n - (** case of internal steps*)\n apply app_inv_head in H5; subst.\n (** proof that the [thread_id] of the event and the head of the schedule match*)\n assert (Hin: List.In ev (map [eta internal tid] ev0))\n by (rewrite H5; apply in_app; right; simpl; auto).\n apply in_map_iff in Hin.\n destruct Hin as [mev [? Hin]].\n subst.\n assert (Hwritable:\n (waction (internal tid mev) ->\n forall (cnt : containsThread tp (thread_id (internal tid mev)))\n (cnt' : containsThread tp' (thread_id (internal tid mev))),\n match location (internal tid mev) with\n | Some (b, ofs, sz) =>\n forall ofs' : Z,\n Intv.In ofs' (ofs, (ofs + Z.of_nat sz)%Z) ->\n (Mem.valid_block m b ->\n Mem.perm_order'' (((getThreadR cnt)#1) # b ofs') (Some Writable) \\/\n Mem.perm_order'' (((getThreadR cnt)#2) # b ofs') (Some Writable)) /\\\n ((Mem.perm_order'' (((getThreadR cnt')#1) # b ofs') (Some Writable) \\/\n Mem.perm_order'' (((getThreadR cnt')#2) # b ofs') (Some Writable)) \\/\n deadLocation tp' (diluteMem m'0) b ofs')\n | None => False\n end) ).\n { simpl in *; inversion Htstep; subst.\n intros Haction Hcnt Hcnt';\n destruct mev;\n try (inv Haction; simpl in *; discriminate);\n pf_cleanup.\n (** Write case*)\n intros ofs' Hintv.\n pose proof (ev_step_elim _ _ _ _ _ _ _ Hcorestep) as Helim.\n destruct Helim as [Helim _].\n (** By case analysis on whether [b] was a valid block or not*)\n destruct (valid_block_dec m b).\n { (** case [b] is a valid block in [m]*)\n eapply elim_perm_valid_block in Helim; eauto.\n destruct Helim as [[Hfreeable Hempty] | [Hwrite Hread]].\n - (** case the block was freed by the internal step. This implies that\n [(b, ofs)] is now a [deadLocation]*)\n split.\n + intros. rewrite restrPermMap_Cur in Hfreeable.\n rewrite Hfreeable. simpl; left; now constructor.\n + right.\n constructor; eauto.\n eapply ev_step_validblock with (b := b) in Hcorestep.\n now eauto.\n now eauto.\n intros i cnti.\n rewrite restrPermMap_Cur in Hfreeable.\n pose proof (cntUpdate' cnti) as cnti0.\n eapply invariant_freeable_empty_threads with (j := i) (cntj := cnti0)\n in Hfreeable;\n eauto.\n destruct Hfreeable.\n destruct (i == tid) eqn:Heq; move/eqP:Heq=>Heq.\n subst. pf_cleanup.\n rewrite! gssThreadRes.\n simpl.\n rewrite getCurPerm_correct.\n split;\n now auto.\n rewrite! gsoThreadRes;\n now auto.\n intros.\n rewrite gsoThreadLPool in H.\n rewrite restrPermMap_Cur in Hfreeable.\n apply invariant_freeable_empty_locks with (laddr := l) (rmap := pmap)\n in Hfreeable;\n now eauto.\n - (** case the block was not freed*)\n split.\n + intros.\n left.\n rewrite! restrPermMap_Cur in Hwrite.\n eapply Hwrite;\n now eauto.\n + rewrite gssThreadRes.\n simpl.\n rewrite getCurPerm_correct.\n do 2 left; eapply Hwrite;\n now eauto.\n }\n { (** case [b] is an invalid block in [m]*)\n eapply elim_perm_invalid_block in Helim; eauto.\n split;\n first by (intros; exfalso; eauto).\n destruct Helim as [Hwrite _].\n rewrite gssThreadRes. simpl.\n destruct (Hwrite Hin) as [[Hallocated | Hfreed] Hvalid'].\n - left.\n rewrite getCurPerm_correct.\n rewrite Hallocated.\n simpl; left; now constructor.\n - right.\n econstructor; eauto.\n + intros.\n pose proof (cntUpdate' cnti) as cnti0.\n destruct (i == tid) eqn:Heq; move/eqP:Heq=>Heq.\n * subst. pf_cleanup.\n rewrite gssThreadRes.\n simpl. rewrite getCurPerm_correct.\n split; auto.\n now eapply (mem_compatible_invalid_block _ Hcmpt n).1.\n * rewrite gsoThreadRes; auto.\n now eapply (mem_compatible_invalid_block _ Hcmpt n).1.\n + intros.\n rewrite gsoThreadLPool in H.\n split;\n eapply (mem_compatible_invalid_block _ Hcmpt n).2;\n now eauto.\n }\n }\n simpl in *.\n inversion Htstep; subst.\n split; intros Haction Hcnt Hcnt';\n destruct mev;\n try (inv Haction; simpl in *; discriminate);\n pf_cleanup; eauto.\n + (** Write case*)\n intros ofs' Hintv.\n destruct (Hwritable ltac:(constructor; auto) Htid Hcnt' ofs' Hintv)\n as [Hperm Hperm'].\n split.\n intros Hvalid.\n destruct (Hperm Hvalid); [left | right];\n eapply po_trans; eauto; simpl; eauto using perm_order.\n destruct Hperm' as [Hperm' | Hdead]; eauto.\n left.\n destruct Hperm'; [left | right];\n eapply po_trans; eauto; simpl; eauto using perm_order.\n + (** Read case*)\n intros ofs' Hintv.\n pose proof (ev_step_elim _ _ _ _ _ _ _ Hcorestep) as Helim.\n destruct Helim as [Helim _].\n (** By case analysis on whether [b] was a valid block or not*)\n destruct (valid_block_dec m b).\n { (** case [b] is a valid block in [m]*)\n eapply elim_perm_valid_block in Helim; eauto.\n destruct Helim as [[Hfreeable Hempty] | [Hwrite Hread]].\n - (** case the block was freed by the internal step. This implies that\n [(b, ofs)] is now a [deadLocation]*)\n split.\n + intros. rewrite restrPermMap_Cur in Hfreeable.\n rewrite Hfreeable. simpl; left; now constructor.\n + right. right.\n constructor; eauto.\n eapply ev_step_validblock with (b := b) in Hcorestep.\n now eauto.\n now eauto.\n intros i cnti.\n rewrite restrPermMap_Cur in Hfreeable.\n pose proof (cntUpdate' cnti) as cnti0.\n eapply invariant_freeable_empty_threads with (j := i) (cntj := cnti0) in Hfreeable;\n eauto.\n destruct Hfreeable.\n destruct (i == tid) eqn:Heq; move/eqP:Heq=>Heq.\n subst. pf_cleanup.\n rewrite! gssThreadRes.\n simpl.\n rewrite getCurPerm_correct.\n split;\n now auto.\n rewrite! gsoThreadRes;\n now auto.\n intros.\n rewrite gsoThreadLPool in H.\n rewrite restrPermMap_Cur in Hfreeable.\n apply invariant_freeable_empty_locks with (laddr := l) (rmap := pmap) in Hfreeable;\n now eauto.\n - (** case the block was not freed*)\n split.\n + intros.\n rewrite! restrPermMap_Cur in Hread.\n left.\n eapply Hread;\n now eauto.\n + rewrite gssThreadRes.\n simpl.\n rewrite getCurPerm_correct.\n do 2 left; eapply Hread;\n now eauto.\n }\n { (** case [b] is an invalid block in [m]*)\n eapply elim_perm_invalid_block in Helim; eauto.\n split;\n first by (intros; exfalso; eauto).\n destruct Helim as [_ Hread].\n rewrite gssThreadRes. simpl.\n destruct (Hread _ Hin) as [[Hallocated | Hfreed] Hvalid'].\n - left.\n rewrite getCurPerm_correct.\n rewrite Hallocated.\n simpl; left; now constructor.\n - do 2 right.\n econstructor; eauto.\n + intros.\n pose proof (cntUpdate' cnti) as cnti0.\n destruct (i == tid) eqn:Heq; move/eqP:Heq=>Heq.\n * subst. pf_cleanup.\n rewrite gssThreadRes.\n simpl. rewrite getCurPerm_correct.\n split; auto.\n now eapply (mem_compatible_invalid_block _ Hcmpt n0).1.\n * rewrite gsoThreadRes; auto.\n now eapply (mem_compatible_invalid_block _ Hcmpt n0).1.\n + intros.\n rewrite gsoThreadLPool in H.\n split;\n eapply (mem_compatible_invalid_block _ Hcmpt n0).2;\n now eauto.\n }\n - (** case of external steps *)\n apply app_inv_head in H5.\n destruct (tr_pre); simpl;\n inv H5.\n assert (Hwritable:\n (waction (external tid ev0) ->\n forall (cnt : containsThread tp (thread_id (external tid ev0)))\n (cnt' : containsThread tp' (thread_id (external tid ev0))),\n match location (external tid ev0) with\n | Some (b, ofs, sz) =>\n forall ofs' : Z,\n Intv.In ofs' (ofs, (ofs + Z.of_nat sz)%Z) ->\n (Mem.valid_block m b ->\n Mem.perm_order'' (((getThreadR cnt)#1) # b ofs') (Some Writable) \\/\n Mem.perm_order'' (((getThreadR cnt)#2) # b ofs') (Some Writable)) /\\\n ((Mem.perm_order'' (((getThreadR cnt')#1) # b ofs') (Some Writable) \\/\n Mem.perm_order'' (((getThreadR cnt')#2) # b ofs') (Some Writable)) \\/\n deadLocation tp' m' b ofs')\n | None => False\n end)).\n { intros.\n destruct ev0; inv H; simpl in H0; try (discriminate);\n inv Htstep.\n - intros ofs' Hintv.\n pf_cleanup.\n split.\n intros Hvalid.\n specialize (Hfreeable _ Hintv).\n unfold Mem.perm in Hfreeable.\n erewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid)#1) by eauto.\n unfold permission_at. now eauto.\n left. rewrite gLockSetRes gssThreadRes.\n rewrite <- Hlock_perm.\n rewrite setPermBlock_same. right; simpl; auto using perm_order.\n eauto.\n - intros ofs' Hintv.\n pf_cleanup.\n split.\n intros Hvalid.\n specialize (Hfreeable _ Hintv).\n unfold Mem.perm in Hfreeable.\n erewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid)#2) by eauto.\n unfold permission_at.\n now eauto.\n left. rewrite gRemLockSetRes gssThreadRes.\n rewrite <- Hdata_perm.\n erewrite setPermBlock_var_same by eauto.\n left; simpl; auto using perm_order.\n specialize (Hneq_perms (nat_of_Z (ofs' - Int.intval ofs))).\n destruct Hintv. unfold lksize.LKSIZE_nat, lksize.LKSIZE in *.\n erewrite nat_of_Z_eq in Hneq_perms\n by (simpl in *; now ssromega).\n assert ((0 <= ofs' - Int.intval ofs < lksize.LKSIZE)%Z)\n by (simpl in *; unfold lksize.LKSIZE; ssromega).\n replace ((nat_of_Z (ofs' - Int.intval ofs)).+1) with\n (nat_of_Z (ofs' - Int.intval ofs +1)) in Hneq_perms\n by (zify;\n erewrite! nat_of_Z_eq\n by (unfold lksize.LKSIZE in *; simpl in *; ssromega);\n omega).\n now eauto.\n }\n split; auto.\n intros Haction cnt cnt'.\n destruct ev0; inv Htstep.\n + intros ofs' Hintv.\n pf_cleanup.\n split. intros. \n specialize (Haccess _ Hintv).\n rewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid).2).\n unfold permission_at, Mem.perm in *; now auto.\n rewrite gLockSetRes gssThreadRes.\n clear Hwritable Hstep.\n specialize (Haccess ofs' Hintv).\n unfold Mem.perm in Haccess.\n pose proof (restrPermMap_Cur (Hcmpt _ Htid).2 b ofs') as Heq.\n unfold permission_at in Heq.\n rewrite Heq in Haccess.\n specialize (Hangel2 b ofs').\n eapply permjoin_readable_iff in Hangel2.\n pose proof (Hangel2.1 Haccess) as Hperm.\n destruct Hperm as [Hperm | Hperm].\n simpl in Hperm.\n left. now auto.\n right. simpl in Hperm.\n left.\n repeat split; auto.\n exists virtueLP. split; auto.\n rewrite gssLockRes. repeat split; auto.\n + intros ofs' Hintv.\n pf_cleanup.\n split. intros.\n specialize (Haccess _ Hintv).\n rewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid).2).\n unfold permission_at, Mem.perm in *; now auto.\n rewrite gLockSetRes gssThreadRes.\n clear Hwritable Hstep.\n specialize (Haccess ofs' Hintv).\n unfold Mem.perm in Haccess.\n pose proof (restrPermMap_Cur (Hcmpt _ Htid).2 b ofs') as Heq.\n unfold permission_at in Heq.\n rewrite Heq in Haccess.\n specialize (Hangel2 b ofs').\n eapply permjoin_readable_iff in Hangel2.\n pose proof (Hangel2.2 (or_intror Haccess)) as Hperm.\n left; now auto.\n + intros ofs' Hintv.\n pf_cleanup.\n specialize (Hfreeable _ Hintv).\n pose proof (restrPermMap_Cur (Hcmpt _ Htid).1 b ofs') as Heq.\n unfold permission_at in Heq.\n unfold Mem.perm in Hfreeable.\n rewrite po_oo in Hfreeable.\n rewrite Heq in Hfreeable.\n split.\n intros.\n left.\n eapply po_trans; eauto; simpl; now constructor.\n left.\n rewrite gLockSetRes gssThreadRes.\n rewrite <- Hlock_perm. right.\n rewrite setPermBlock_same; simpl. now constructor.\n eauto.\n + intros ofs' Hintv.\n specialize (Hfreeable _ Hintv).\n pose proof (restrPermMap_Cur (Hcmpt _ Htid).2 b ofs') as Heq.\n unfold permission_at in Heq.\n unfold Mem.perm in Hfreeable.\n rewrite po_oo in Hfreeable.\n rewrite Heq in Hfreeable.\n pf_cleanup.\n split.\n intros.\n right.\n eapply po_trans; eauto; simpl; now constructor.\n left.\n rewrite gRemLockSetRes gssThreadRes.\n rewrite <- Hdata_perm.\n left.\n erewrite setPermBlock_var_same by eauto.\n specialize (Hneq_perms (nat_of_Z (ofs' - Int.intval ofs))).\n destruct Hintv. unfold lksize.LKSIZE_nat, lksize.LKSIZE in *.\n erewrite nat_of_Z_eq in Hneq_perms\n by (simpl in *; now ssromega).\n assert ((0 <= ofs' - Int.intval ofs < lksize.LKSIZE)%Z)\n by (simpl in *; unfold lksize.LKSIZE; ssromega).\n replace ((nat_of_Z (ofs' - Int.intval ofs)).+1) with\n (nat_of_Z (ofs' - Int.intval ofs +1)) in Hneq_perms\n by (zify;\n erewrite! nat_of_Z_eq\n by (unfold lksize.LKSIZE in *; simpl in *; ssromega);\n omega).\n eapply po_trans; eauto; simpl;\n eauto using perm_order.\n + simpl in Haction.\n by exfalso.\n + intros ofs' Hintv.\n pf_cleanup.\n specialize (Haccess _ Hintv).\n rewrite <- restrPermMap_Cur with (Hlt := (Hcmpt tid Htid).2).\n unfold permission_at, Mem.perm in *; now auto.\n + destruct l; simpl in H9; inv H9.\n Qed.\n\n Lemma waction_caction:\n forall ev,\n waction ev -> caction ev.\n Proof.\n intros; destruct ev as [? ev | ? ev]; destruct ev;\n inversion H; (auto || discriminate).\n Qed.\n\n Lemma raction_caction:\n forall ev,\n raction ev -> caction ev.\n Proof.\n intros; destruct ev as [? ev | ? ev]; destruct ev;\n inversion H; (auto || discriminate).\n Qed.\n\n Lemma raction_waction:\n forall ev,\n raction ev -> ~ waction ev.\n Proof.\n intros.\n intro Hcontra.\n inversion H; inv Hcontra; congruence.\n Qed.\n\n Lemma waction_raction:\n forall ev,\n waction ev -> ~ raction ev.\n Proof.\n intros.\n intro Hcontra.\n inversion H; inv Hcontra; congruence.\n Qed.\n\n Lemma caction_location:\n forall ev,\n caction ev ->\n exists b ofs sz, location ev = Some (b, ofs, sz).\n Proof.\n intros.\n destruct ev as [? ev | ? ev];\n destruct ev; simpl in *; try (by exfalso);\n try (destruct a);\n do 3 eexists; reflexivity.\n Qed.\n\n\n (** [FineConc.MachStep] preserves [spinlock_synchronized]*)\n Lemma fineConc_step_synchronized:\n forall U0 U U' tr tp0 m0 tp m tp' m' tr'\n (Hexec: multi_fstep (U0, [::], tp0) m0 (U, tr, tp) m)\n (Hstep: FineConc.MachStep the_ge (U, tr, tp) m (U', tr ++ tr', tp') m')\n (Hsynchronized: spinlock_synchronized tr),\n spinlock_synchronized (tr ++ tr').\n Proof.\n intros.\n (** Consider two competing events evi and evj*)\n intros i j evi evj Hneq Hi Hj Hcompetes.\n destruct (lt_dec j (length tr)) as [Hj_in_tr | Hj_not_in_tr].\n - (** If [evj] is in [tr] then so is [evi], by [i < j] and the goal is\n trivial by [Hsynchronized]*)\n assert (Hi_in_tr: (i < length tr)%coq_nat) by ssromega.\n eapply nth_error_app1 with (l' := tr') in Hj_in_tr.\n eapply nth_error_app1 with (l' := tr') in Hi_in_tr.\n rewrite Hi_in_tr in Hi.\n rewrite Hj_in_tr in Hj.\n destruct (Hsynchronized i j evi evj Hneq Hi Hj Hcompetes) as\n [[u [v [eu [ev [Horder [Hevu [Hevv [Hactu [Hactv Hloc]]]]]]]]] |\n [u [eu [Horder [Hu Hactu]]]]].\n + left.\n exists u, v, eu, ev.\n repeat (split; eauto using nth_error_app_inv).\n + right.\n exists u, eu.\n repeat (split; eauto using nth_error_app_inv).\n - (** Hence [evj] is in [tr'] *)\n (** By [maximal_competing] there must exist some maximal event [ek] s.t.\n it competes with [evj]*)\n destruct (maximal_competing _ _ _ Hneq Hi Hj Hcompetes)\n as (k & evk & Horder & Hk & Hcompetes_kj & Hmaximal).\n (** [evk] cannot be in [tr'] because this would imply that it is from\n the same thread as [j] and hence not competing*)\n assert (Hk_not_in_tr': (k < length tr)%coq_nat).\n { destruct (lt_dec k (length tr)); auto.\n erewrite nth_error_app2 in Hk by omega.\n destruct Hcompetes_kj.\n apply nth_error_In in Hk.\n erewrite nth_error_app2 in Hj by omega.\n apply nth_error_In in Hj.\n eapply fstep_event_tid with (ev := evk) (ev' := evj) in Hstep; eauto.\n exfalso; auto.\n }\n erewrite nth_error_app1 in Hk by assumption.\n\n (** To find the state that corresponds to [evk] we break the execution\n in [multi_fstep] chunks and the [FineConc.Machstep] that produces [evk]*)\n destruct (multi_fstep_inv _ _ Hk Hexec)\n as (Uk & Uk' & tp_k & m_k & tr0 & pre_k & post_k & tp_k'\n & m_k' & Hexeck & Hstepk & Hexec' & Hk_index).\n erewrite! app_nil_l in *.\n\n (** *** Useful Results*)\n (** tr' will be of the form tr'_pre ++ evj ++ tr'_post*)\n assert (Htr': exists tr'_pre tr'_post, tr' = tr'_pre ++ [:: evj] ++ tr'_post).\n { erewrite nth_error_app2 in Hj by ssromega.\n apply nth_error_split in Hj.\n destruct Hj as (tr'_pre & tr'_post & ? & ?).\n subst.\n exists tr'_pre, tr'_post.\n reflexivity.\n }\n destruct Htr' as (tr'_pre & tr'_post & Heq). subst.\n\n (** The threads that generated [evk] and [evj] are\n valid threads in the respective thread pools*)\n assert (cntk: containsThread tp_k (thread_id evk))\n by (eapply fstep_ev_contains in Hstepk;\n eapply Hstepk.1).\n assert (cntk': containsThread tp_k' (thread_id evk))\n by (eapply fstep_ev_contains in Hstepk;\n eapply Hstepk.2).\n assert (cntj: containsThread tp (thread_id evj))\n by (eapply fstep_ev_contains in Hstep;\n eapply Hstep.1).\n assert (cntj': containsThread tp' (thread_id evj))\n by (eapply fstep_ev_contains in Hstep;\n eapply Hstep.2).\n\n inversion Hcompetes_kj as (Hthreads_neq & Hsame_loc & Hcactionk & Hcactionj & _ & _).\n (** [location] is defined for [evk] as it is a competing event*)\n assert (Hloc_k: exists bk ofsk szk, location evk = Some (bk, ofsk, szk))\n by (eapply caction_location; eauto).\n (** [location] is defined for [evj] as it is a competing event*)\n assert (Hloc_j: exists bj ofsj szj, location evj = Some (bj, ofsj, szj))\n by (eapply caction_location; eauto).\n\n destruct Hloc_k as (b & ofsk & szk & Hloc_k).\n destruct Hloc_j as (b' & ofsj & szj & Hloc_j).\n (** Find the competing byte*)\n unfold sameLocation in Hsame_loc.\n rewrite Hloc_k Hloc_j in Hsame_loc.\n destruct Hsame_loc as [? [ofs [Hintvk Hintvj]]]; subst b'.\n\n pose proof (multi_fstep_trace_monotone Hexec') as Heq.\n subst.\n destruct Heq as [tr'' Heq]; subst.\n\n\n (** The states of the machine satisfy the [invariant]*)\n assert (Hinv: invariant tp)\n by (eapply fstep_invariant; eauto).\n assert (Hinvk': invariant tp_k').\n { destruct (multi_fstep_invariant Hexec') as [Hinvk' | [? _]].\n - now eapply Hinvk'.\n - subst.\n eapply fstep_invariant in Hstep.\n now eapply Hstep.\n }\n\n assert (cntk'_j: containsThread tp (thread_id evk))\n by (eapply fstep_ev_contains in Hstepk;\n destruct Hstepk;\n eapply multi_fstep_containsThread; eauto).\n\n (** [b] is valid if someone has permission on it*)\n assert (Hvalid_mk': forall p, Mem.perm_order'' ((getThreadR cntk').1 !! b ofs) (Some p) \\/\n Mem.perm_order'' ((getThreadR cntk').2 !! b ofs) (Some p) ->\n Mem.valid_block m_k' b).\n { intros.\n assert (Hlt: permMapLt ((getThreadR cntk').1) (getMaxPerm m_k') /\\\n permMapLt ((getThreadR cntk').2) (getMaxPerm m_k')).\n { destruct (multi_fstep_mem_compatible Hexec') as [Hcompk' | Heq].\n - destruct Hcompk'.\n now eapply (compat_th0 _ cntk').\n - destruct Heq as [? [? _]]; subst.\n eapply fstep_mem_compatible in Hstep.\n now eapply Hstep.\n }\n destruct Hlt.\n destruct H;\n eapply perm_order_valid_block;\n now eauto.\n }\n\n assert (Hvalid_m: forall p, Mem.perm_order'' ((getThreadR cntk').1 !! b ofs) (Some p) \\/\n Mem.perm_order'' ((getThreadR cntk').2 !! b ofs) (Some p) ->\n Mem.valid_block m b).\n { intros.\n eapply multi_fstep_valid_block; eauto.\n }\n\n assert (Hvalid_mk'2: pre_k = [::] /\\\n post_k = [::] /\\\n action evk = Release /\\\n (exists rmap : dry_machine.LocksAndResources.lock_info,\n szk = lksize.LKSIZE_nat /\\\n lockRes tp_k' (b, ofsk) = Some rmap /\\\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) \\/\n Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable))) ->\n Mem.valid_block m_k' b).\n { intros.\n destruct H as [? [? [? [rmap [? [Hres Hperm]]]]]].\n destruct (multi_fstep_mem_compatible Hexec') as [Hcompk' | Heq].\n - destruct Hcompk'.\n now eapply (lockRes_blocks0 _ _ Hres).\n - destruct Heq as [? [? _]]; subst.\n eapply fstep_mem_compatible in Hstep.\n now eapply (lockRes_blocks Hstep _ Hres).\n }\n\n assert (Hvalid_m2: pre_k = [::] /\\\n post_k = [::] /\\\n action evk = Release /\\\n (exists rmap : dry_machine.LocksAndResources.lock_info,\n szk = lksize.LKSIZE_nat /\\\n lockRes tp_k' (b, ofsk) = Some rmap /\\\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) \\/\n Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable))) ->\n Mem.valid_block m b).\n { intros.\n eapply multi_fstep_valid_block; eauto.\n }\n\n (** *** The Proof*)\n\n (** We proceed by a case analysis on whether [thread_id evj] was in\n the threadpool at index k. If not then there must have been a\n spawn event between u and j and we are done *)\n destruct (containsThread_dec (thread_id evj) tp_k') as [cntj_k' | Hnot_contained].\n { (** Case [thread_id evj] is in the threadpool*)\n (** by [compete_cases] there are two main cases:\n- evk is of type [Read], [Acquire], [AcquireFail], [Release] and [evj] is of type [Write], [Mklock], [Freelock] or\n- evk is of type [Write], [Mklock], [Freelock] and [evj] is of any type that competes*)\n pose proof (compete_cases Hcompetes_kj) as Hcases.\n\n (** *** Proving that the permissions required for [evk] and [evj]\n are above [Readable] and incompatible*)\n\n assert (Hpermissions: ((Mem.perm_order'' ((getThreadR cntk').1 !! b ofs) (Some Readable) \\/\n Mem.perm_order'' ((getThreadR cntk').2 !! b ofs) (Some Readable)) \\/\n (pre_k = [::] /\\\n post_k = [::] /\\\n action evk = Release /\\\n (exists rmap : dry_machine.LocksAndResources.lock_info,\n szk = lksize.LKSIZE_nat /\\\n lockRes tp_k' (b, ofsk) = Some rmap /\\\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) \\/\n Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable))))) /\\\n (Mem.perm_order'' ((getThreadR cntj).1 !! b ofs) (Some Readable) \\/\n Mem.perm_order'' ((getThreadR cntj).2 !! b ofs) (Some Readable)) /\\\n (waction evk ->\n Mem.perm_order'' ((getThreadR cntk').1 !! b ofs) (Some Writable) \\/\n Mem.perm_order'' ((getThreadR cntk').2 !! b ofs) (Some Writable)) /\\\n (waction evj ->\n Mem.perm_order'' ((getThreadR cntj).1 !! b ofs) (Some Writable) \\/\n Mem.perm_order'' ((getThreadR cntj).2 !! b ofs) (Some Writable))).\n { destruct(fstep_ev_perm _ _ _ Hstepk) as [Hwritek Hreadk].\n destruct(fstep_ev_perm _ _ _ Hstep) as [Hwritej Hreadj].\n rewrite Hloc_j in Hwritej Hreadj.\n rewrite Hloc_k in Hwritek, Hreadk.\n (** First we prove that [(b, ofs)] cannot be a [deadLocation] *)\n assert (Hnotdead: ~ deadLocation tp_k' m_k' b ofs).\n { (** Suppose that it was. [deadLocation] is preserved by\n [multi_fstep] and hence [evj] would not have sufficient permissions\n to perform a [caction]*)\n intros Hdead.\n (** [(b,ofs)] is [deadLocation] at [tp], [m]*)\n eapply multi_fstep_deadLocation with (tp' := tp) (m' := m) in Hdead; eauto.\n (** Hence [b] is a valid block in [m]*)\n inversion Hdead.\n (** Moreover permissions of the machine on [(b, ofs)] are None*)\n destruct (Hthreads _ cntj) as [Hperm1 Hperm2].\n (** The permissions of the thread [thread_id evj] must be above\n [Readable] by the fact that [evj] is a [caction] event,\n which leads to a contradiction*)\n pose proof ((Hreadj Hcactionj cntj cntj' ofs Hintvj).1 Hvalid) as Hperm.\n rewrite Hperm1 Hperm2 in Hperm.\n simpl in Hperm.\n destruct Hperm;\n now auto.\n }\n destruct Hcases as [[Hractionk Hwactionj] | [Hwactionk Hwractionj]];\n [ destruct (Hreadk (raction_caction Hractionk) cntk cntk' ofs Hintvk)\n as [_ [Hpermk | [Hrelease | Hcontra]]]\n | destruct (Hwritek Hwactionk cntk cntk' ofs Hintvk) as [_ [Hpermk | Hcontra]]];\n try (by exfalso); split;\n try (eapply po_trans; eauto;\n now constructor);\n try (specialize (Hvalid_m _ Hpermk));\n try (specialize (Hvalid_m2 Hrelease));\n repeat match goal with\n | [H: waction evj |- _] =>\n destruct (Hwritej H cntj cntj' ofs Hintvj) as [Hpermj _];\n try (specialize (Hpermj Hvalid_m));\n try (specialize (Hpermj Hvalid_m2));\n clear Hwritej\n | [H: is_true (isSome (caction evj)) |- _] =>\n destruct (Hreadj H cntj cntj' ofs Hintvj) as [Hpermj _];\n try (specialize (Hpermj Hvalid_m));\n try (specialize (Hpermj Hvalid_m2));\n clear Hreadj\n | [H: waction evk |- _] =>\n destruct (Hwritek H cntk cntk' ofs Hintvk) as [_ [Hpermk | Hcontra]];\n clear Hwritek\n | [H: is_true (isSome (caction evk)) |- _] =>\n destruct (Hreadk H cntk cntk' ofs Hintvk) as [_ [Hpermk| [Hrelease | Hcontra]]];\n clear Hreadk\n | [ |- _ /\\ _] =>\n split\n | [H: Mem.perm_order'' ?X ?Y |- Mem.perm_order'' ?X ?Y] =>\n assumption\n | [ |- Mem.perm_order'' _ _] =>\n eapply po_trans; eauto; simpl; now constructor\n | [H: Mem.perm_order'' _ _ \\/ Mem.perm_order'' _ _ |- _] =>\n destruct H\n | [H: Mem.perm_order'' ?X ?Y |- Mem.perm_order'' ?X ?Y \\/ _] =>\n left\n | [H: Mem.perm_order'' ?X ?Y |- _ \\/ Mem.perm_order'' ?X ?Y] =>\n right\n | [ |- _ -> _] => intros\n | [H: waction ?X, H2: raction ?X |- Mem.perm_order'' _ _] =>\n exfalso; eapply waction_raction\n | [H: deadLocation _ _ _ _, H2: ~ deadLocation _ _ _ _ |- _ ] =>\n exfalso; eauto\n end;\n eauto.\n }\n destruct Hpermissions as (Hperm_k & Hperm_j & Hwritablek & Hwritablej).\n\n (** By the [invariant] permissions of [thread_id evk] and\n [thread_id evj] will have compatible permissions at [tp] *)\n assert (Hcompatible11_j: perm_union ((getThreadR cntk'_j).1 !! b ofs)\n ((getThreadR cntj).1 !! b ofs))\n by (destruct ((no_race_thr Hinv cntk'_j cntj Hthreads_neq).1 b ofs) as [pu Hcompatiblek'j];\n rewrite Hcompatiblek'j; auto).\n\n assert (Hcompatible12_j: perm_coh ((getThreadR cntk'_j).1 !! b ofs)\n ((getThreadR cntj).2 !! b ofs))\n by (pose proof ((thread_data_lock_coh Hinv cntj).1 _ cntk'_j b ofs);\n auto).\n\n assert (Hcompatible21_j: perm_coh ((getThreadR cntj).1 !! b ofs)\n ((getThreadR cntk'_j).2 !! b ofs))\n by (pose proof ((thread_data_lock_coh Hinv cntk'_j).1 _ cntj b ofs);\n auto).\n\n assert (Hcompatible22_j: perm_union ((getThreadR cntk'_j).2 !! b ofs)\n ((getThreadR cntj).2 !! b ofs))\n by (destruct ((no_race_thr Hinv cntk'_j cntj Hthreads_neq).2 b ofs) as [pu Hcompatiblek'j];\n rewrite Hcompatiblek'j; auto).\n\n (** There are two main cases: 1. evk is a [raction], 2. evk is a [waction]*)\n destruct Hcases as [[Hractionk Hwactionj] | [Hwactionk _]].\n { (** Case [evk] is an [raction] and [evj] is an [waction]*)\n specialize (Hwritablej Hwactionj).\n assert (Hpermk'_j: ~ Mem.perm_order'' ((getThreadR cntk'_j).1 !! b ofs) (Some Readable)\n /\\ ~ Mem.perm_order'' ((getThreadR cntk'_j).2 !! b ofs) (Some Readable)).\n { clear - Hcompatible11_j Hcompatible12_j Hcompatible21_j\n Hcompatible22_j Hwritablej Hthreads_neq.\n destruct Hwritablej as [Hwritablej | Hwritablej];\n [destruct ((getThreadR cntj).1 !! b ofs) as [p1 | ] |\n destruct ((getThreadR cntj).2 !! b ofs) as [p1 | ]]; simpl in Hwritablej;\n inv Hwritablej;\n destruct ((getThreadR cntk'_j).1 !! b ofs);\n destruct ((getThreadR cntk'_j).2 !! b ofs);\n simpl; split; intros Hcontra;\n inv Hcontra; simpl in *;\n now auto.\n }\n destruct Hperm_k as [Hperm_k | Hrelease_k]. (*TODO: second case*)\n { (** Case permissions were not dropped by the step at k*)\n assert (Hperm_k_drop:\n (Mem.perm_order'' (((getThreadR cntk')#1) # b ofs)\n (Some Readable) /\\\n ~ Mem.perm_order'' (((getThreadR cntk'_j)#1) # b ofs)\n (Some Readable)) \\/\n (Mem.perm_order'' (((getThreadR cntk')#2) # b ofs)\n (Some Readable) /\\\n ~ Mem.perm_order'' (((getThreadR cntk'_j)#2) # b ofs)\n (Some Readable)))\n by (destruct Hperm_k; [left | right]; split; destruct Hpermk'_j;\n now auto).\n (** Hence by [permission_decrease_execution] we have four cases\n for how the permissions of [thread_id evk] dropped*)\n destruct (permission_decrease_execution _ b ofs cntk' cntk'_j Hexec' Hperm_k_drop)\n as (tr_pre_u & tru & ? & ? & tp_pre_u & m_pre_u &\n tp_dec & m_dec & Hexec_pre_u & Hstepu & Hexec_post_u & evu & Hspec_u).\n destruct Hspec_u as [Hfreed | [Hspawned | [Hfreelock | [Hmklock | Hrelease]]]].\n { (** Case permissions dropped by a [Free] event. This leads to a\n contradiction because it would be a [deadLocation] *)\n destruct Hfreed as (HIn & HFree & Hdead).\n inversion Hdead.\n specialize (Hthreads _ cntj).\n rewrite Hthreads.1 Hthreads.2 in Hperm_j.\n simpl in Hperm_j;\n destruct Hperm_j;\n by exfalso.\n }\n { (** Case permissions were dropped by a spawn event - we are done*)\n destruct Hspawned as (? & Hactionu).\n subst.\n right.\n remember (tr0 ++ pre_k ++ [:: evk] ++ post_k) as tr00.\n apply multi_fstep_trace_monotone in Hexec_post_u.\n destruct Hexec_post_u as [? Heq].\n rewrite <- app_assoc in Heq.\n apply app_inv_head in Heq. subst.\n exists (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_u)%list), evu.\n split. simpl.\n - apply/andP.\n split.\n + rewrite! app_length.\n clear - Horder. simpl.\n move/andP:Horder => [Hle ?].\n rewrite app_length in Hle.\n now ssromega.\n + clear - Hj_not_in_tr.\n erewrite! app_length in *.\n simpl in *.\n ssromega.\n - split.\n rewrite! app_assoc.\n rewrite <- app_assoc.\n rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n assumption.\n }\n { (** Case permissions were dropped by a [Freelock] event - this leads to\n a contradiction by the fact that [evu] will compete with [evj], while\n [evk] is the maximal competing event *)\n destruct Hfreelock as [Htru [Hactionu [Hthreadu Hlocu]]].\n subst.\n exfalso.\n remember (tr0 ++ pre_k ++ [:: evk] ++ post_k) as tr00.\n apply multi_fstep_trace_monotone in Hexec_post_u.\n destruct Hexec_post_u as [? Heq].\n rewrite <- app_assoc in Heq.\n apply app_inv_head in Heq. subst.\n eapply (Hmaximal (length (tr0 ++ pre_k ++ [:: evk] ++ post_k ++ tr_pre_u)%list) evu).\n - rewrite! app_length.\n apply/andP.\n split.\n + simpl. ssromega.\n + clear - Hj_not_in_tr.\n rewrite! app_length in Hj_not_in_tr.\n simpl in *.\n ssromega.\n - rewrite! app_assoc.\n rewrite <- addn0.\n do 2 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n reflexivity.\n - repeat split.\n + intros Hcontra.\n rewrite Hthreadu in Hcontra.\n now auto.\n + destruct (location evu) as [[[bu ofsu] szu]|] eqn:Hloc_u;\n try (by exfalso).\n unfold sameLocation.\n rewrite Hloc_u Hloc_j.\n simpl in Hlocu.\n destruct Hlocu as [? Hintvu]; subst.\n split; auto.\n exists ofs; split; now auto.\n + destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n simpl. now auto.\n + destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n simpl. now auto.\n + intros.\n destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n + intros.\n right; left.\n assumption.\n }\n { (** Case permissions were dropped by a [Mklock] event - this leads to\n a contradiction by the fact that [evu] will compete with [evj], while\n [evk] is the maximal competing event *)\n destruct Hmklock as [Htru [Hactionu [Hthreadu Hlocu]]].\n subst.\n exfalso.\n remember (tr0 ++ pre_k ++ [:: evk] ++ post_k) as tr00.\n apply multi_fstep_trace_monotone in Hexec_post_u.\n destruct Hexec_post_u as [? Heq].\n rewrite <- app_assoc in Heq.\n apply app_inv_head in Heq. subst.\n eapply (Hmaximal (length (tr0 ++ pre_k ++ [:: evk] ++ post_k ++ tr_pre_u)%list) evu).\n - rewrite! app_length.\n apply/andP.\n split.\n + simpl. ssromega.\n + clear - Hj_not_in_tr.\n rewrite! app_length in Hj_not_in_tr.\n simpl in *.\n ssromega.\n - rewrite! app_assoc.\n rewrite <- addn0.\n do 2 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n reflexivity.\n - repeat split.\n + intros Hcontra.\n rewrite Hthreadu in Hcontra.\n now auto.\n + destruct (location evu) as [[[bu ofsu] szu]|] eqn:Hloc_u;\n try (by exfalso).\n unfold sameLocation.\n rewrite Hloc_u Hloc_j.\n simpl in Hlocu.\n destruct Hlocu as [? Hintvu]; subst.\n split; auto.\n exists ofs; split; now auto.\n + destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n simpl. now auto.\n + destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n simpl. now auto.\n + intros.\n destruct evu as [? evu | ? evu];\n destruct evu; try discriminate.\n + intros.\n left.\n assumption.\n }\n { (** Case permissions were dropped by a [Release] event.*)\n destruct Hrelease as [? [Hrelease [Hthread_eq Hrmap]]];\n subst.\n destruct Hrmap as [rmap Hspec].\n destruct (location evu) as [[[bu ofsu] szu]|] eqn:Hlocu;\n try (by exfalso).\n destruct Hspec as [? [Hresu Hperm_rmap]].\n subst.\n (** There are two cases: either [(bu,ofsu)] is a lock at [tp] or it is not*)\n destruct (lockRes tp (bu,ofsu)) as [rmap'|] eqn:Hres.\n - (** Case [(bu, ofsu)] is still a lock at [tp]*)\n (** By the [invariant] its permissions must have dropped because\n [thread_id evj] has a Writable permission at that location*)\n assert (Hperm_res: ~ Mem.perm_order'' (rmap'.1 !! b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap'.2 !! b ofs) (Some Readable)).\n { clear - Hinv Hres Hwritablej.\n destruct ((no_race Hinv _ cntj Hres).1 b ofs) as [pu Hcomp].\n destruct ((no_race Hinv _ cntj Hres).2 b ofs) as [pu2 Hcomp2].\n pose proof ((thread_data_lock_coh Hinv cntj).2 _ _ Hres b ofs) as Hcoh.\n pose proof ((locks_data_lock_coh Hinv _ Hres).1 _ cntj b ofs) as Hcoh2.\n split; intros Hcontra; destruct Hwritablej;\n repeat match goal with\n | [H: Mem.perm_order'' ?X _ |- _] =>\n destruct X; simpl in H; inv H; simpl in *\n | [H: match ?X with _ => _ end = _ |- _] =>\n destruct X\n end; simpl in *;\n try (discriminate || by exfalso).\n }\n pose proof (multi_fstep_trace_monotone Hexec_post_u) as [tr''0 Heq].\n rewrite! app_assoc_reverse in Heq.\n do 4 apply app_inv_head in Heq; subst.\n rewrite! app_assoc in Hexec_post_u.\n\n assert (Hperm_res_drop:\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((rmap'#1) # b ofs) (Some Readable)) \\/\n (Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((rmap'.2) # b ofs) (Some Readable)))\n by (destruct Hperm_res; destruct Hperm_rmap; [left | right];\n now auto).\n (** Hence by [lockRes_permission_decrease_execution] there must\n have been some [Acquire] event on that lock*)\n destruct (lockRes_permission_decrease_execution _ _ _ _ Hresu Hres\n Hexec_post_u Hperm_res_drop)\n as (v & evv & Hev & Hactionv & Hlocv).\n left.\n exists (length ((tr0 ++ pre_k ++ [:: evk] ++ post_k) ++ tr_pre_u)%list),\n (length ((tr0 ++ pre_k ++ [:: evk] ++ post_k) ++ tr_pre_u ++ [:: evu])%list + v),\n evu, evv.\n repeat split; auto.\n + clear - Horder.\n erewrite! app_assoc.\n erewrite! app_length in *.\n now ssromega.\n + clear - Hj_not_in_tr Hev.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr''0 v).1 ltac:(intros Hcontra; congruence)).\n simpl in *.\n now ssromega.\n + rewrite! app_assoc.\n do 2 rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n + rewrite! app_assoc.\n rewrite <- app_assoc.\n rewrite <- nth_error_app.\n apply nth_error_app_inv;\n now eauto.\n + rewrite Hlocv Hlocu.\n reflexivity.\n - (** Case [(bu, ofsu)] is no longer a lock*)\n pose proof (multi_fstep_trace_monotone Hexec_post_u) as [tr_fl Heq].\n rewrite! app_assoc_reverse in Heq.\n do 4 apply app_inv_head in Heq; subst.\n rewrite! app_assoc in Hexec_post_u.\n destruct (lockRes_freelock_execution _ _ Hresu Hres Hexec_post_u)\n as (tr_pre_fl & evfl & ? & ? & tp_pre_fl &\n m_pre_fl & tp_fl & m_fl & Hexec_pre_fl & Hstep_fl &\n Hexec_post_fl & Haction_fl & Hloc_fl & rmap_fl & Hres_fl & Hres_fl_empty).\n (** Hence, at some point in the trace, the permissions at [(bu,\n ofsu)] dropped. This can only be done by an [Acquire] step*)\n assert (Hperm_rmap_empty: ~ Mem.perm_order'' ((empty_map, empty_map).1 !! b ofs)\n (Some Readable) /\\\n ~ Mem.perm_order'' ((empty_map, empty_map).2 !! b ofs)\n (Some Readable))\n by (rewrite empty_map_spec; now auto).\n\n assert (Hperm_rmap_drop:\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap_fl.1 # b ofs) (Some Readable)) \\/\n (Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap_fl.2 # b ofs) (Some Readable)))\n by (destruct Hperm_rmap_empty; destruct Hperm_rmap;\n erewrite (Hres_fl_empty b ofs).1;\n erewrite (Hres_fl_empty b ofs).2;\n [left | right];\n now auto).\n\n\n destruct (lockRes_permission_decrease_execution _ _ _ _ Hresu Hres_fl\n Hexec_pre_fl Hperm_rmap_drop)\n as (v & evv & Hv & Haction_v & Hloc_v).\n left.\n pose proof (multi_fstep_trace_monotone Hexec_post_fl) as [tr_fl' Heq].\n rewrite! app_assoc_reverse in Heq.\n do 6 apply app_inv_head in Heq; subst.\n exists (length ((tr0 ++ pre_k ++ [:: evk] ++ post_k) ++ tr_pre_u)%list),\n (length (((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_u) ++ [:: evu])%list + v),\n evu, evv.\n repeat split; auto.\n * clear - Horder.\n erewrite! app_assoc.\n erewrite! app_length in *.\n now ssromega.\n * clear - Hj_not_in_tr Hv.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr_pre_fl v).1 ltac:(intros Hcontra; congruence)).\n simpl in *.\n now ssromega.\n * rewrite! app_assoc.\n do 4 rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n * rewrite! app_assoc.\n do 3 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n apply nth_error_app_inv;\n now eauto.\n * rewrite Hloc_v Hlocu.\n reflexivity.\n }\n }\n { (** Case [evk] was a [Release] and it released the lock location itself*)\n destruct Hrelease_k as [? [? [Hrelease [rmap [? [Hresk' Hperm_rmap]]]]]];\n subst.\n (** There are two cases: either [(b,ofs)] is a lock at [tp] or it is not*)\n destruct (lockRes tp (b,ofsk)) as [rmap'|] eqn:Hres.\n - (** Case [(b, ofs)] is still a lock at [tp]*)\n (** By the [invariant] its permissions must have dropped because\n [thread_id evj] has a Writable permission at that location*)\n assert (Hperm_res: ~ Mem.perm_order'' (rmap'.1 !! b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap'.2 !! b ofs) (Some Readable)).\n { clear - Hinv Hres Hwritablej.\n destruct ((no_race Hinv _ cntj Hres).1 b ofs) as [pu Hcomp].\n destruct ((no_race Hinv _ cntj Hres).2 b ofs) as [pu2 Hcomp2].\n pose proof ((thread_data_lock_coh Hinv cntj).2 _ _ Hres b ofs) as Hcoh.\n pose proof ((locks_data_lock_coh Hinv _ Hres).1 _ cntj b ofs) as Hcoh2.\n split; intros Hcontra; destruct Hwritablej;\n repeat match goal with\n | [H: Mem.perm_order'' ?X _ |- _] =>\n destruct X; simpl in H; inv H; simpl in *\n | [H: match ?X with _ => _ end = _ |- _] =>\n destruct X\n end; simpl in *;\n try (discriminate || by exfalso).\n }\n\n assert (Hperm_res_drop:\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((rmap'#1) # b ofs) (Some Readable)) \\/\n (Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((rmap'.2) # b ofs) (Some Readable)))\n by (destruct Hperm_res; destruct Hperm_rmap; [left | right];\n now auto).\n (** Hence by [lockRes_permission_decrease_execution] there must\n have been some [Acquire] event on that lock*)\n simpl in Hexec'.\n destruct (lockRes_permission_decrease_execution _ _ _ _ Hresk' Hres\n Hexec' Hperm_res_drop)\n as (v & evv & Hev & Hactionv & Hlocv).\n left.\n simpl.\n exists (length tr0),\n (length ((tr0 ++ [:: evk]))%list + v),\n evk, evv.\n repeat split; auto.\n + clear - Horder Hev Hj_not_in_tr.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr'' v).1 ltac:(intros Hcontra; congruence)).\n simpl in *. now ssromega.\n + clear - Hj_not_in_tr Hev.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr'' v).1 ltac:(intros Hcontra; congruence)).\n simpl in *.\n now ssromega.\n + do 2 rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n + rewrite <- app_assoc.\n rewrite <- nth_error_app.\n apply nth_error_app_inv;\n now eauto.\n + rewrite Hloc_k Hlocv.\n reflexivity.\n - (** Case [(b, ofsk)] is no longer a lock*)\n destruct (lockRes_freelock_execution _ _ Hresk' Hres Hexec')\n as (tr_pre_fl & evfl & ? & ? & tp_pre_fl &\n m_pre_fl & tp_fl & m_fl & Hexec_pre_fl & Hstep_fl &\n Hexec_post_fl & Haction_fl & Hloc_fl & rmap_fl & Hres_fl & Hres_fl_empty).\n (** Hence, at some point in the trace, the permissions at [(b,\n ofsk)] dropped. This can only be done by an [Acquire] step*)\n assert (Hperm_rmap_empty: ~ Mem.perm_order'' ((empty_map, empty_map).1 !! b ofs)\n (Some Readable) /\\\n ~ Mem.perm_order'' ((empty_map, empty_map).2 !! b ofs)\n (Some Readable))\n by (rewrite empty_map_spec; now auto).\n\n assert (Hperm_rmap_drop:\n (Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap_fl.1 # b ofs) (Some Readable)) \\/\n (Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap_fl.2 # b ofs) (Some Readable)))\n by (destruct Hperm_rmap_empty; destruct Hperm_rmap;\n erewrite (Hres_fl_empty b ofs).1;\n erewrite (Hres_fl_empty b ofs).2;\n [left | right];\n now auto).\n\n\n destruct (lockRes_permission_decrease_execution _ _ _ _ Hresk' Hres_fl\n Hexec_pre_fl Hperm_rmap_drop)\n as (v & evv & Hv & Haction_v & Hloc_v).\n left.\n pose proof (multi_fstep_trace_monotone Hexec_post_fl) as [tr_fl' Heq].\n rewrite! app_assoc_reverse in Heq.\n simpl in Heq.\n apply app_inv_head in Heq; subst.\n inv Heq.\n simpl.\n exists (length tr0),\n (length ((tr0 ++ [::evk])%list) + v),\n evk, evv.\n repeat split; auto.\n * clear - Horder Hj_not_in_tr Hv.\n rewrite cats0 in Horder.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr_pre_fl v).1 ltac:(intros Hcontra; congruence)).\n simpl in *.\n now ssromega.\n * clear - Hj_not_in_tr Hv.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n pose proof ((nth_error_Some tr_pre_fl v).1 ltac:(intros Hcontra; congruence)).\n simpl in *.\n now ssromega.\n * rewrite! app_assoc_reverse.\n rewrite <- addn0.\n rewrite <- app_assoc.\n rewrite <- nth_error_app.\n reflexivity.\n * rewrite! app_assoc.\n do 2 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n apply nth_error_app_inv;\n now eauto.\n * rewrite Hloc_v Hloc_k.\n reflexivity.\n }\n }\n { (** Case [evk] is a [waction] *)\n specialize (Hwritablek Hwactionk).\n (** [thread_id evj] must have permissions that are below [Readable]*)\n assert (Hpermj_k': ~ Mem.perm_order'' ((getThreadR cntj_k').1 !! b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((getThreadR cntj_k').2 !! b ofs) (Some Readable)).\n { clear - Hperm_k Hinvk' Hwritablek Hthreads_neq.\n pose proof ((no_race_thr Hinvk' cntk' cntj_k' Hthreads_neq).1 b ofs) as Hcomp.\n assert (Hcompatible12_j: perm_coh ((getThreadR cntk').1 !! b ofs)\n ((getThreadR cntj_k').2 !! b ofs))\n by (pose proof ((thread_data_lock_coh Hinvk' cntj_k').1 _ cntk' b ofs);\n auto).\n\n assert (Hcompatible21_j: perm_coh ((getThreadR cntj_k').1 !! b ofs)\n ((getThreadR cntk').2 !! b ofs))\n by (pose proof ((thread_data_lock_coh Hinvk' cntk').1 _ cntj_k' b ofs);\n auto).\n\n pose proof ((no_race_thr Hinvk' cntk' cntj_k' Hthreads_neq).2 b ofs) as Hcomp2.\n destruct Hwritablek as [Hwritablek | Hwritablek];\n [destruct ((getThreadR cntk').1 !! b ofs) as [p1 | ] |\n destruct ((getThreadR cntk').2 !! b ofs) as [p1 | ]]; simpl in Hwritablek;\n inv Hwritablek;\n destruct ((getThreadR cntj_k').1 !! b ofs);\n destruct ((getThreadR cntj_k').2 !! b ofs);\n simpl; split; intros Hcontra;\n inv Hcontra; simpl in *;\n try (destruct Hcomp);\n try (destruct Hcomp2);\n try (auto || discriminate).\n }\n\n assert (Hperm_incr:\n (Mem.perm_order'' (((getThreadR cntj)#1) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (((getThreadR cntj_k')#1) # b ofs) (Some Readable)) \\/\n (Mem.perm_order'' (((getThreadR cntj)#2) # b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (((getThreadR cntj_k')#2) # b ofs) (Some Readable)))\n by (destruct Hpermj_k'; destruct Hperm_j; now auto).\n (** By [permission_increase_execution] we have four cases as\n to how the permissions increased*)\n destruct (permission_increase_execution _ ofs cntj_k' cntj Hexec' Hperm_incr)\n as (tr_pre_v & evv & ? & ? & tp_pre_v & m_pre_v &\n tp_inc & m_inc & Hexec_pre_v & Hstepv & Hexec_post_v & Hspec_v); eauto.\n (** Proof of equality of traces*)\n pose proof (multi_fstep_trace_monotone Hexec_post_v) as Heq_trace.\n destruct Heq_trace as [tr''0 Heq_trace].\n erewrite! app_assoc_reverse in Heq_trace.\n do 4 apply app_inv_head in Heq_trace. subst.\n rewrite! app_assoc.\n destruct Hspec_v as [Hactionv | [[Hactionv [Hthreadv Hloc_v]] |\n [[Hactionv [Hthreadv Hloc_v]] |\n [Hactionv [Hthreadv Hrmap]]]]].\n - (** Case permissions were increased by a [Spawn] event*)\n right.\n exists (length (((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_v)%list)), evv.\n repeat split.\n + clear - Hj_not_in_tr Horder.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n simpl.\n apply/andP.\n split.\n now ssromega.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n simpl in *.\n now ssromega.\n + rewrite <- addn0.\n do 2 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n now reflexivity.\n + assumption.\n - (** Case permissions were increased by a [Freelock] event*)\n (** In this case, [evv] competes with [evk] and by the premise\n that [tr] is [spinlock_synchronized] there will be a [Spawn] or\n [Release]-[Acquire] pair between them and hence between [evk]\n and [evj] as well *)\n assert (Hcompeteskj: competes evk evv).\n { repeat split; eauto.\n - rewrite Hthreadv.\n now auto.\n - unfold sameLocation.\n destruct (location evv) as [[[bv ofsv] szv]|]; try (by exfalso).\n destruct Hloc_v as [Heqb Hintvv].\n simpl in Heqb. subst.\n rewrite Hloc_k.\n split; auto.\n exists ofs.\n split; now auto.\n - destruct evv as [? evv | ? evv];\n destruct evv; simpl in Hactionv; simpl;\n try (by exfalso);\n now auto.\n - intros.\n exfalso.\n destruct evv as [? evv | ? evv];\n simpl in Hactionv;\n destruct evv; try (discriminate);\n try (by exfalso).\n }\n rewrite! app_assoc in Hsynchronized.\n specialize (Hsynchronized (length ((tr0 ++ pre_k)%list))\n (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_v)%list)\n evk evv).\n simpl in Hsynchronized.\n destruct (Hsynchronized ltac:(clear; erewrite! app_length in *; ssromega)\n ltac:(clear; do 4 rewrite <- app_assoc;\n rewrite <- addn0;\n rewrite <- nth_error_app; reflexivity)\n ltac:(clear;\n rewrite <- addn0;\n rewrite <- app_assoc;\n rewrite <- nth_error_app; reflexivity) Hcompeteskj)\n as [[r [a [er [ea [Horderra [Horderra' [Hevr [Heva [Hactr [Hacta Hloc_ra]]]]]]]]]] |\n [s [es [Horders [Hs Hacts]]]]].\n + (** Case there is a [Release]-[Acquire] pair between k and v*)\n left.\n exists r, a, er, ea.\n repeat split; auto.\n * clear - Horderra Horderra' Horder.\n rewrite! app_assoc_reverse in Horderra'.\n erewrite! app_length in *.\n apply/andP.\n split; now ssromega.\n * clear - Horderra Horderra' Horder Hj_not_in_tr.\n rewrite! app_assoc_reverse in Horderra'.\n erewrite! app_length in *.\n ssromega.\n * eapply nth_error_app_inv;\n eassumption.\n * eapply nth_error_app_inv;\n eassumption.\n + (** Case there is a [Spawn] event between k and v*)\n right.\n exists s, es.\n repeat split; auto.\n * clear - Horders Horder Hj_not_in_tr.\n erewrite! app_assoc_reverse in *.\n erewrite! app_length in *.\n ssromega.\n * eapply nth_error_app_inv;\n now eauto.\n - (** Case permissions were increased by a [Mklock] event*)\n (** In this case, [evv] competes with [evk] and by the premise\n that [tr] is [spinlock_synchronized] there will be a [Spawn] or\n [Release]-[Acquire] pair between them and hence between [evk]\n and [evj] as well *)\n assert (Hcompeteskj: competes evk evv).\n { repeat split; eauto.\n - rewrite Hthreadv.\n now auto.\n - unfold sameLocation.\n destruct (location evv) as [[[bv ofsv] szv]|]; try (by exfalso).\n destruct Hloc_v as [Heqb Hintvv].\n simpl in Heqb. subst.\n rewrite Hloc_k.\n split; auto.\n exists ofs.\n split; now auto.\n - destruct evv as [? evv | ? evv];\n destruct evv; simpl in Hactionv; simpl;\n try (by exfalso);\n now auto.\n - intros.\n exfalso.\n destruct evv as [? evv | ? evv];\n simpl in Hactionv;\n destruct evv; try (discriminate);\n try (by exfalso).\n }\n rewrite! app_assoc in Hsynchronized.\n specialize (Hsynchronized (length ((tr0 ++ pre_k)%list))\n (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_v)%list)\n evk evv).\n simpl in Hsynchronized.\n destruct (Hsynchronized ltac:(clear; erewrite! app_length in *; ssromega)\n ltac:(clear; do 4 rewrite <- app_assoc;\n rewrite <- addn0;\n rewrite <- nth_error_app; reflexivity)\n ltac:(clear;\n rewrite <- addn0;\n rewrite <- app_assoc;\n rewrite <- nth_error_app; reflexivity) Hcompeteskj)\n as [[r [a [er [ea [Horderra [Horderra' [Hevr [Heva [Hactr [Hacta Hloc_ra]]]]]]]]]] |\n [s [es [Horders [Hs Hacts]]]]].\n + (** Case there is a [Release]-[Acquire] pair between k and v*)\n left.\n exists r, a, er, ea.\n repeat split; auto.\n * clear - Horderra Horderra' Horder.\n rewrite! app_assoc_reverse in Horderra'.\n erewrite! app_length in *.\n apply/andP.\n split; now ssromega.\n * clear - Horderra Horderra' Horder Hj_not_in_tr.\n rewrite! app_assoc_reverse in Horderra'.\n erewrite! app_length in *.\n ssromega.\n * eapply nth_error_app_inv;\n eassumption.\n * eapply nth_error_app_inv;\n eassumption.\n + (** Case there is a [Spawn] event between k and v*)\n right.\n exists s, es.\n repeat split; auto.\n * clear - Horders Horder Hj_not_in_tr.\n erewrite! app_assoc_reverse in *.\n erewrite! app_length in *.\n ssromega.\n * eapply nth_error_app_inv;\n now eauto.\n - (** Case permissions were increased by an [Acquire] event*)\n destruct Hrmap as [rmap Hlocv].\n destruct (location evv) as [[laddr sz]|] eqn: Hloc_v; try (by exfalso).\n destruct Hlocv as [Hsz [HlockRes_v Hperm_res]]; subst.\n (** [rmap] at [tp_k'] will either not exist or if it exists will be below [Readable]*)\n destruct (lockRes tp_k' laddr) as [rmap_k|] eqn:Hres_k.\n + (** By [invariant] at [tp_k'] [rmap_k !! b ofs] will be below [Readable]*)\n assert (Hperm_rmap_k: ~ Mem.perm_order'' (rmap_k.1 !! b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' (rmap_k.2 !! b ofs) (Some Readable)).\n { clear - Hres_k Hinvk' Hwritablek.\n pose proof ((no_race Hinvk' _ cntk' Hres_k).1 b ofs) as [? Hcomp].\n pose proof ((no_race Hinvk' _ cntk' Hres_k).2 b ofs) as [? Hcomp2].\n pose proof ((thread_data_lock_coh Hinvk' cntk').2 _ _ Hres_k b ofs) as Hcoh.\n pose proof ((locks_data_lock_coh Hinvk' _ Hres_k).1 _ cntk' b ofs) as Hcoh2.\n destruct Hwritablek;\n split; intros Hcontra;\n repeat match goal with\n | [H: Mem.perm_order'' ?X _ |- _] =>\n destruct X; simpl in H; inv H; simpl in *\n | [H: match ?X with _ => _ end = _ |- _] =>\n destruct X\n end; simpl in *;\n try (discriminate || by exfalso).\n }\n\n assert (Hperm_incr':\n (~ Mem.perm_order'' ((rmap_k#1) # b ofs) (Some Readable) /\\\n Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable)) \\/\n (~ Mem.perm_order'' ((rmap_k#2) # b ofs) (Some Readable) /\\\n Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable)))\n by (destruct Hperm_rmap_k; destruct Hperm_res; now auto).\n (** Then there must have soome [Release] event on that lock to\n increase its permissions*)\n destruct (lockRes_permission_increase_execution _ _ _ _ Hres_k HlockRes_v\n Hexec_pre_v Hperm_incr')\n as (u & evu & Hu & Hactionu & Hlocu).\n left.\n exists ((length (((tr0 ++ pre_k) ++ [:: evk]) ++ post_k)%list) + u),\n (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_v)%list), evu, evv.\n repeat split.\n * clear - Hu Hj_not_in_tr Horder.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n simpl in *.\n apply/andP.\n move/andP:Horder=>[? ?].\n split. now ssromega.\n pose proof ((nth_error_Some tr_pre_v u).1 ltac:(intros Hcontra; congruence)).\n simpl.\n now ssromega.\n * clear - Hj_not_in_tr.\n erewrite! app_assoc in *;\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n simpl in *. now ssromega.\n * do 3 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n eapply nth_error_app_inv;\n now eauto.\n * do 2 rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n * assumption.\n * assumption.\n * rewrite Hloc_v Hlocu.\n reflexivity.\n + (** Case the lock was not created at index k*)\n (** Since the lock exists at v someone must have created it*)\n destruct (lockRes_mklock_execution _ _ Hres_k HlockRes_v Hexec_pre_v)\n as (tr_prew & evw & ? & ? & tp_prew & m_prew & tp_mk & m_mk\n & Hexec_prew & Hstep_mk & Hexec_postw & Hactionw & Hlocw & Hlock_mk).\n (** At that point it's resources would be empty. But later the\n lock has a [Readable] permission in it, hence there must be a\n [Release] on that lock*)\n assert (Hperm_mk:\n ~ Mem.perm_order'' ((empty_map, empty_map).1 !! b ofs) (Some Readable) /\\\n ~ Mem.perm_order'' ((empty_map, empty_map).2 !! b ofs) (Some Readable))\n by (rewrite empty_map_spec; simpl; now auto).\n destruct (multi_fstep_trace_monotone Hexec_postw) as [tr_post_mk Heq_tr].\n rewrite! app_assoc_reverse in Heq_tr.\n do 4 apply app_inv_head in Heq_tr; subst.\n rewrite! app_assoc in Hexec_postw.\n assert (Hperm_res_incr':\n (~ Mem.perm_order'' (((empty_map, empty_map)#1) # b ofs)\n (Some Readable) /\\\n Mem.perm_order'' ((rmap#1) # b ofs) (Some Readable)) \\/\n (~ Mem.perm_order'' (((empty_map, empty_map)#2) # b ofs)\n (Some Readable) /\\\n Mem.perm_order'' ((rmap#2) # b ofs) (Some Readable)))\n by (destruct Hperm_mk; destruct Hperm_res; now auto).\n destruct (lockRes_permission_increase_execution _ _ _ _ Hlock_mk HlockRes_v\n Hexec_postw Hperm_res_incr')\n as (u & evu & Hu & Hactionu & Hlocu).\n left.\n exists (length (((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_prew ++ [:: evw])%list) + u),\n (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_prew ++ [:: evw] ++\n tr_post_mk) %list), evu, evv.\n repeat split.\n * clear - Hu Hj_not_in_tr Horder.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n simpl in *.\n apply/andP.\n move/andP:Horder=>[? ?].\n split. now ssromega.\n pose proof ((nth_error_Some tr_post_mk u).1 ltac:(intros Hcontra; congruence)).\n simpl.\n now ssromega.\n * clear - Hj_not_in_tr.\n erewrite! app_assoc in *;\n erewrite! app_length in *.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n simpl in *. now ssromega.\n * rewrite! app_assoc.\n do 3 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n eapply nth_error_app_inv;\n now eauto.\n * do 2 rewrite <- app_assoc.\n rewrite <- addn0.\n rewrite <- nth_error_app.\n reflexivity.\n * assumption.\n * assumption.\n * rewrite Hloc_v Hlocu.\n reflexivity.\n }\n }\n\n { (** Case [thread_id evj] was not in the threadpool*)\n destruct (thread_spawn_execution _ Hnot_contained cntj Hexec')\n as (tr_pre_spawn & evv & ? & ? & tp_pre_spawn & m_pre_spawn &\n tp_spanwed & m_spanwed & Hexec_pre_spawn & Hstep_spawn &\n Hexec_post_spawn & Hactionv).\n right.\n destruct (multi_fstep_trace_monotone Hexec_post_spawn) as [tr''0 Heq].\n rewrite! app_assoc_reverse in Heq.\n do 4 apply app_inv_head in Heq; subst.\n rewrite! app_assoc.\n exists (length ((((tr0 ++ pre_k) ++ [:: evk]) ++ post_k) ++ tr_pre_spawn)%list), evv.\n repeat split.\n + clear - Hj_not_in_tr Horder.\n erewrite! app_assoc in *.\n erewrite! app_length in *.\n simpl.\n apply/andP.\n split.\n now ssromega.\n erewrite <- Nat.le_ngt in Hj_not_in_tr.\n simpl in *.\n now ssromega.\n + rewrite <- addn0.\n do 2 rewrite <- app_assoc.\n rewrite <- nth_error_app.\n now reflexivity.\n + assumption.\n }\n Qed.\n\n (** FineConc is spinlock well-synchronized, strengthened version of the theorem*)\n Theorem fineConc_spinlock_strong:\n forall U U0 U' tr tr' tp m tp0 m0 tp' m'\n (Hsynced: spinlock_synchronized tr)\n (Hexec0: multi_fstep (U0, [::], tp0) m0 (U, tr, tp) m)\n (Hexec: multi_fstep (U, tr, tp) m (U', tr ++ tr', tp') m'),\n spinlock_synchronized (tr ++ tr').\n Proof.\n intro.\n induction U; intros.\n - inversion Hexec.\n rewrite <- app_nil_r in H3 at 1;\n apply app_inv_head in H3;\n subst.\n rewrite <- catA.\n rewrite! cats0.\n assumption.\n - inversion Hexec.\n + rewrite <- app_nil_r in H3 at 1;\n apply app_inv_head in H3;\n subst.\n rewrite <- catA.\n rewrite! cats0.\n assumption.\n + subst.\n apply app_inv_head in H6; subst.\n pose proof H8 as Hfstep.\n eapply fineConc_step_synchronized in H8; eauto.\n specialize (IHU U0 U' (tr ++ tr'0) tr'').\n do 2 rewrite <- app_assoc in IHU.\n rewrite <- app_assoc_l.\n eapply IHU with (tp0 := tp0) (tp := tp'0) (m0 := m0) (m := m'0).\n eassumption.\n rewrite <- app_nil_l with (l := tr ++ tr'0).\n eapply multi_fstep_snoc; eauto.\n eauto.\n Qed.\n\n (** FineConc is spinlock well-synchronized*)\n Corollary fineConc_spinlock:\n forall U tr tp m tp' m'\n (Hexec: multi_fstep (U, [::], tp) m ([::], tr, tp') m'),\n spinlock_synchronized tr.\n Proof.\n intros.\n do 2 rewrite <- app_nil_l.\n eapply fineConc_spinlock_strong with (U0 := U) (tp0 := tp) (m0 := m);\n eauto.\n simpl.\n intros ? ? ? ? ? Hcontra.\n rewrite nth_error_nil in Hcontra. discriminate.\n simpl.\n now econstructor.\n Qed.\n\n End Spinlocks.\nEnd SpinLocks.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/spinlocks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988771, "lm_q2_score": 0.20181323186177208, "lm_q1q2_score": 0.10798994025285925}} {"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\n\nRequire Import Equivalence.\nRequire Import SemanticsSimple.\nRequire Import Equivalences.\nRequire Import SoundHyp.\nRequire Import SoundSubstitution.\nRequire Import ProperEquiv.\nRequire Import Defined.\nRequire Import PageCode.\nRequire Import PageType.\nRequire Import Subsumption.\n\n\nLocal Ltac prove_hygiene :=\n repeat (first [ apply hygiene_shift_permit\n | apply hygiene_auto; cbn; repeat2 split; auto\n ]);\n eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1;\n try (apply hygiene_var; cbn; auto; done).\n\n\nLemma lvinterp_nzero :\n lvinterp nzero (fin 0).\nProof.\nexists 0.\nsplit; auto.\nexact natinterp_nzero.\nQed.\n\n\nDefinition zeropg : page := \n mk_page (fin 0) (fin 0) (fin 0) (le_ord_zero _) (le_ord_zero _) (le_ord_refl _).\n\n\nLemma pginterp_nzero :\n pginterp nzero zeropg.\nProof.\nexists (fin 0).\ndo2 3 split; auto.\nexact lvinterp_nzero.\nQed.\n\n\nLemma sound_voidtp_formation :\n forall G,\n pseq G (deq voidtp voidtp (univ nzero)).\nProof.\ncut\n (forall G, seq G (deq voidtp voidtp (univ nzero))).\n {\n intros Hsound G.\n exists 0; intros j Hj.\n simpsub.\n apply Hsound.\n }\nintros G.\nrewrite -> seq_univ.\nintros i s s' Hs.\nexists zeropg, (iubase (void_urel stop)).\nsimpsub.\ndo2 5 split; auto using pginterp_nzero;\napply interp_eval_refl; apply interp_void.\nQed.\n\n\nLemma sound_voidtp_elim_pre :\n forall G m n p q a,\n hygiene (ctxpred G) p\n -> hygiene (ctxpred G) q\n -> hygiene (ctxpred G) a\n -> seq G (deq m n voidtp)\n -> seq G (deq p q a).\nProof.\nintros G m n p q a Hclp Hclq Hcla Hseq.\ninvertc Hseq; intro Hseq.\napply seq_i.\nintros i s s' Hs.\nso (Hseq _#3 Hs) as (R & Hvoid & _ & Hinh & _).\ninvert (basic_value_inv _#6 value_voidtp Hvoid).\nintros <-.\ndestruct Hinh.\nQed.\n\n\nLemma sound_voidtp_elim :\n forall G m n p q a,\n pseq G (deq m n voidtp)\n -> pseq G (deq p q a).\nProof.\nintros G m n p q a (i1 & Hseq).\nso (shut_term _ G p) as (i2 & Hclp).\nso (shut_term _ G q) as (i3 & Hclq).\nso (shut_term _ G a) as (i4 & Hcla).\nso (upper_bound_all 4 i1 i2 i3 i4) as (i & Hi1 & Hi2 & Hi3 & Hi4 & _).\nexists i.\nintros j Hj.\neapply sound_voidtp_elim_pre; eauto using le_trans.\nQed.\n\n\nLemma sound_unittp_kind_formation :\n forall G lv,\n pseq G (deq lv lv pagetp)\n -> pseq G (deq unittp unittp (kuniv lv)).\nProof.\nintros G lv.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseqlv.\nrewrite -> seq_eqkind.\ninvertc Hseqlv; intro Hseqlv.\nintros i s s' Hs.\nso (Hseqlv _#3 Hs) as (R & Hpagetp & _ & Hlv & _).\nso (interp_pagetp_invert _#7 Hpagetp Hlv) as (pg & Hlvl & Hlvr).\nexists pg, qone, (iubase (unit_urel stop i)), (pginterp_lt_top _ _ Hlvl).\nsimpsub.\ndo2 9 split; auto;\ntry (apply kinterp_eval_refl; apply interp_kunit);\napply interp_eval_refl; apply interp_unit.\nQed.\n\n\nLemma sound_unittp_formation :\n forall G,\n pseq G (deq unittp unittp (univ nzero)).\nProof.\nrefine (seq_pseq 0 0 _ _); cbn.\nintros G.\nrewrite -> seq_univ.\nintros i s s' Hs.\nexists zeropg, (iubase (unit_urel stop i)).\nsimpsub.\ndo2 5 split; auto using pginterp_nzero;\napply interp_eval_refl; apply interp_unit.\nQed.\n\n\nLemma sound_unittp_intro_pre :\n forall G,\n seq G (deq triv triv unittp).\nProof.\nintros G.\napply seq_i.\nintros i s s' Hs.\nexists (iubase (unit_urel stop i)).\nsimpsub.\ndo2 2 split; try (apply interp_eval_refl; apply interp_unit).\nassert (rel (unit_urel stop i) i triv triv) as H.\n {\n do2 5 split; auto using star_refl; prove_hygiene.\n }\nauto.\nQed.\n\n\nLemma sound_unittp_intro :\n forall G,\n pseq G (deq triv triv unittp).\nProof.\nrefine (seq_pseq 0 0 _ _); cbn.\nintros G.\napply sound_unittp_intro_pre.\nQed.\n\n\nLemma sound_unittp_eta :\n forall G p,\n pseq G (deq p p unittp)\n -> pseq G (deq p triv unittp).\nProof.\nintros G p.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseq.\ninvertc Hseq; intro Hseq.\napply seq_i.\nintros i s s' Hs.\nso (Hseq _#3 Hs) as (R & Hunitl & Hunitr & Hp & _).\nsimpsubin Hunitl.\nsimpsubin Hunitr.\ninvert (basic_value_inv _#6 value_unittp Hunitl).\nintros <-.\nexists (iubase (unit_urel stop i)).\ndo2 4 split; auto.\n {\n simpsub.\n apply unit_urel_triv; auto.\n }\n\n {\n simpsub.\n destruct Hp as (_ & _ & Hclsp & _ & Hsteps & _).\n do2 5 split; auto using star_refl; try prove_hygiene.\n }\nQed.\n\n\nLemma sound_unittp_eta_hyp :\n forall G1 G2 m n b,\n pseq (substctx (dot triv id) G2 ++ G1) (deq m n (subst (under (length G2) (dot triv id)) b))\n -> pseq (G2 ++ hyp_tm unittp :: G1) (deq (subst (under (length G2) sh1) m) (subst (under (length G2) sh1) n) b).\nProof.\nintros G1 G2 m n b Hseq.\neapply sound_property_eta_hyp; eauto.\nintros s pg z i R H.\nsimpsubin H.\ninvert (basic_value_inv _#6 value_unittp H).\nintros <-.\ndo 3 eexists.\nreflexivity.\nQed.\n\n\nLemma sound_booltp_formation :\n forall G,\n pseq G (deq booltp booltp (univ nzero)).\nProof.\nrefine (seq_pseq 0 0 _ _).\ncbn.\nintros G.\nrewrite -> seq_univ.\nintros i s s' Hs.\nexists zeropg, (iubase (bool_urel stop i)).\nsimpsub.\ndo2 5 split; auto using pginterp_nzero;\napply interp_eval_refl; apply interp_bool.\nQed.\n\n\nLemma sound_booltp_intro_btrue :\n forall G,\n pseq G (deq btrue btrue booltp).\nProof.\nrefine (seq_pseq 0 0 _ _).\nintros G.\napply seq_i.\nintros i s s' Hs.\nexists (iubase (bool_urel stop i)).\nsimpsub.\ndo2 2 split;\ntry (apply interp_eval_refl; apply interp_bool).\nassert (rel (bool_urel stop i) i btrue btrue) as H.\n {\n do2 3 split; auto; try prove_hygiene.\n left.\n split; apply star_refl.\n }\nauto.\nQed.\n\n\nLemma sound_booltp_intro_bfalse :\n forall G,\n pseq G (deq bfalse bfalse booltp).\nProof.\nrefine (seq_pseq 0 0 _ _).\nintros G.\napply seq_i.\nintros i s s' Hs.\nexists (iubase (bool_urel stop i)).\nsimpsub.\ndo2 2 split;\ntry (apply interp_eval_refl; apply interp_bool).\nassert (rel (bool_urel stop i) i bfalse bfalse) as H.\n {\n do2 3 split; auto; try prove_hygiene.\n right.\n split; apply star_refl.\n }\nauto.\nQed.\n\n\nLemma sound_booltp_elim_pre :\n forall G m n p q r s a,\n hygiene (ctxpred G) a\n -> hygiene (ctxpred G) m\n -> hygiene (ctxpred G) n\n -> hygiene (ctxpred G) p\n -> hygiene (ctxpred G) q\n -> hygiene (ctxpred G) r\n -> hygiene (ctxpred G) s\n -> seq G (deq m n booltp)\n -> seq G (deq p q (subst1 btrue a))\n -> seq G (deq r s (subst1 bfalse a))\n -> seq G (deq (bite m p r) (bite n q s) (subst1 m a)).\nProof.\nintros G m n p q r t a Hcla Hclm Hcln Hclp Hclq Hclr Hclt Hseqmn Hseqpq Hseqrt.\ninvertc Hseqmn; intro Hseqmn.\ninvertc Hseqpq; intro Hseqpq.\ninvertc Hseqrt; intro Hseqrt.\napply seq_i.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqmn _#3 Hs) as (R & Hbool & _ & Hm & Hn & Hmn).\nsimpsubin Hbool.\ninvert (basic_value_inv _#6 value_booltp Hbool).\nintros <-.\ndestruct Hm as (_ & _ & _ & H).\ndestruct H as [(Hstepsml & Hstepsmr) | (Hstepsml & Hstepsmr)].\n {\n destruct Hn as (_ & _ & _ & H).\n destruct H as [(Hstepsnl & Hstepsnr) | (_ & Hstepsnr)].\n 2:{\n exfalso.\n destruct Hmn as (_ & _ & _ & H).\n destruct H as [(_ & Hstepsnr') | (Hstepsml' & _)].\n {\n so (determinism_eval _#4 (conj Hstepsnr value_bfalse) (conj Hstepsnr' value_btrue)) as Heq.\n discriminate Heq.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsml value_btrue) (conj Hstepsml' value_bfalse)) as Heq.\n discriminate Heq.\n }\n }\n assert (forall (x y z : sterm),\n star step x btrue\n -> equiv y (bite x y z)) as Hequiv.\n {\n intros x y z Hsteps.\n apply equiv_symm.\n eapply equiv_trans.\n {\n apply equiv_bite; [| apply equiv_refl ..].\n apply steps_equiv; eauto.\n }\n apply steps_equiv; apply star_one.\n apply step_bite2.\n }\n so (Hseqpq _#3 Hs) as (A & Hal & Har & Hp & Hq & Hpq).\n exists A.\n do2 4 split.\n {\n simpsub.\n eapply basic_equiv; eauto.\n {\n eapply hygiene_subst; eauto.\n intros j Hj.\n destruct j as [| j].\n {\n simpsub.\n eapply subst_closub; eauto.\n }\n simpsub.\n cbn in Hj.\n replace (project s j) with (subst s (var j)) by (simpsub; reflexivity).\n eapply subst_closub; eauto.\n apply hygiene_var.\n rewrite -> ctxpred_length in Hj |- *.\n omega.\n }\n\n {\n simpsub.\n apply equiv_funct; auto using equiv_refl.\n apply equivsub_dot; auto using equivsub_refl.\n apply equiv_symm.\n eapply steps_equiv; eauto.\n }\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n {\n eapply hygiene_subst; eauto.\n intros j Hj.\n destruct j as [| j].\n {\n simpsub.\n eapply subst_closub; eauto.\n }\n simpsub.\n cbn in Hj.\n replace (project s' j) with (subst s' (var j)) by (simpsub; reflexivity).\n eapply subst_closub; eauto.\n apply hygiene_var.\n rewrite -> ctxpred_length in Hj |- *.\n omega.\n }\n\n {\n simpsub.\n apply equiv_funct; auto using equiv_refl.\n apply equivsub_dot; auto using equivsub_refl.\n apply equiv_symm.\n eapply steps_equiv; eauto.\n }\n }\n \n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hp); try (prove_hygiene; eapply subst_closub; eauto).\n }\n\n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hq); try (prove_hygiene; eapply subst_closub; eauto).\n }\n\n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hpq); try (prove_hygiene; eapply subst_closub; eauto).\n }\n }\n\n {\n destruct Hn as (_ & _ & _ & H).\n destruct H as [(_ & Hstepsnr) | (Hstepsnl & Hstepsnr)].\n {\n exfalso.\n destruct Hmn as (_ & _ & _ & H).\n destruct H as [(Hstepsml' & _) | (_ & Hstepsnr')].\n {\n so (determinism_eval _#4 (conj Hstepsml value_bfalse) (conj Hstepsml' value_btrue)) as Heq.\n discriminate Heq.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsnr value_btrue) (conj Hstepsnr' value_bfalse)) as Heq.\n discriminate Heq.\n }\n }\n assert (forall (x y z : sterm),\n star step x bfalse\n -> equiv z (bite x y z)) as Hequiv.\n {\n intros x y z Hsteps.\n apply equiv_symm.\n eapply equiv_trans.\n {\n apply equiv_bite; [| apply equiv_refl ..].\n apply steps_equiv; eauto.\n }\n apply steps_equiv; apply star_one.\n apply step_bite3.\n }\n so (Hseqrt _#3 Hs) as (A & Hal & Har & Hp & Hq & Hpq).\n exists A.\n do2 4 split.\n {\n simpsub.\n eapply basic_equiv; eauto.\n {\n eapply hygiene_subst; eauto.\n intros j Hj.\n destruct j as [| j].\n {\n simpsub.\n eapply subst_closub; eauto.\n }\n simpsub.\n cbn in Hj.\n replace (project s j) with (subst s (var j)) by (simpsub; reflexivity).\n eapply subst_closub; eauto.\n apply hygiene_var.\n rewrite -> ctxpred_length in Hj |- *.\n omega.\n }\n\n {\n simpsub.\n apply equiv_funct; auto using equiv_refl.\n apply equivsub_dot; auto using equivsub_refl.\n apply equiv_symm.\n eapply steps_equiv; eauto.\n }\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n {\n eapply hygiene_subst; eauto.\n intros j Hj.\n destruct j as [| j].\n {\n simpsub.\n eapply subst_closub; eauto.\n }\n simpsub.\n cbn in Hj.\n replace (project s' j) with (subst s' (var j)) by (simpsub; reflexivity).\n eapply subst_closub; eauto.\n apply hygiene_var.\n rewrite -> ctxpred_length in Hj |- *.\n omega.\n }\n\n {\n simpsub.\n apply equiv_funct; auto using equiv_refl.\n apply equivsub_dot; auto using equivsub_refl.\n apply equiv_symm.\n eapply steps_equiv; eauto.\n }\n }\n \n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hp); try (prove_hygiene; eapply subst_closub; eauto).\n }\n\n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hq); try (prove_hygiene; eapply subst_closub; eauto).\n }\n\n {\n simpsub.\n refine (urel_equiv _#7 _ _ _ _ Hpq); try (prove_hygiene; eapply subst_closub; eauto).\n }\n }\nQed.\n\n\nLemma sound_booltp_elim :\n forall G m n p q r s a,\n pseq G (deq m n booltp)\n -> pseq G (deq p q (subst1 btrue a))\n -> pseq G (deq r s (subst1 bfalse a))\n -> pseq G (deq (bite m p r) (bite n q s) (subst1 m a)).\nProof.\nintros G m n p q r t a (i1, Hmn) (i2, Hpq) (i3, Hrt).\nso (shut_term _ G m) as (i4, Hclm).\nso (shut_term _ G n) as (i5, Hcln).\nso (shut_term _ G p) as (i6, Hclp).\nso (shut_term _ G q) as (i7, Hclq).\nso (shut_term _ G r) as (i8, Hclr).\nso (shut_term _ G t) as (i9, Hclt).\nso (shut_term _ G a) as (i10, Hcla).\nso (upper_bound_all 10 i1 i2 i3 i4 i5 i6 i7 i8 i9 i10) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & Hi8 & Hi9 & Hi10 & _).\nexists i; intros j Hj.\neapply sound_booltp_elim_pre; eauto using le_trans.\nQed.\n\n\nLemma sound_booltp_elim_eqtype_pre :\n forall G m n p q r s,\n hygiene (ctxpred G) m\n -> hygiene (ctxpred G) n\n -> hygiene (ctxpred G) p\n -> hygiene (ctxpred G) q\n -> hygiene (ctxpred G) r\n -> hygiene (ctxpred G) s\n -> seq G (deq m n booltp)\n -> seq G (deqtype p q)\n -> seq G (deqtype r s)\n -> seq G (deqtype (bite m p r) (bite n q s)).\nProof.\nintros G m n p q r t Hclm Hcln Hclp Hclq Hclr Hclt Hseqmn Hseqpq Hseqrt.\nrewrite -> seq_eqtype in Hseqpq, Hseqrt |- *.\ninvertc Hseqmn; intro Hseqmn.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqmn _#3 Hs) as (R & Hbool & _ & Hm & Hn & Hmn).\nsimpsubin Hbool.\ninvert (basic_value_inv _#6 value_booltp Hbool).\nintros <-.\ndestruct Hm as (_ & _ & _ & H).\ndestruct H as [(Hstepsml & Hstepsmr) | (Hstepsml & Hstepsmr)].\n {\n destruct Hn as (_ & _ & _ & H).\n destruct H as [(Hstepsnl & Hstepsnr) | (_ & Hstepsnr)].\n 2:{\n exfalso.\n destruct Hmn as (_ & _ & _ & H).\n destruct H as [(_ & Hstepsnr') | (Hstepsml' & _)].\n {\n so (determinism_eval _#4 (conj Hstepsnr value_bfalse) (conj Hstepsnr' value_btrue)) as Heq.\n discriminate Heq.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsml value_btrue) (conj Hstepsml' value_bfalse)) as Heq.\n discriminate Heq.\n }\n }\n assert (forall (x y z : sterm),\n star step x btrue\n -> equiv y (bite x y z)) as Hequiv.\n {\n intros x y z Hsteps.\n apply equiv_symm.\n eapply equiv_trans.\n {\n apply equiv_bite; [| apply equiv_refl ..].\n apply steps_equiv; eauto.\n }\n apply steps_equiv; apply star_one.\n apply step_bite2.\n }\n so (Hseqpq _#3 Hs) as (P & Hpl & Hpr & Hql & Hqr).\n exists P.\n do2 3 split.\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n }\n\n {\n destruct Hn as (_ & _ & _ & H).\n destruct H as [(_ & Hstepsnr) | (Hstepsnl & Hstepsnr)].\n {\n exfalso.\n destruct Hmn as (_ & _ & _ & H).\n destruct H as [(Hstepsml' & _) | (_ & Hstepsnr')].\n {\n so (determinism_eval _#4 (conj Hstepsml value_bfalse) (conj Hstepsml' value_btrue)) as Heq.\n discriminate Heq.\n }\n\n {\n so (determinism_eval _#4 (conj Hstepsnr value_btrue) (conj Hstepsnr' value_bfalse)) as Heq.\n discriminate Heq.\n }\n }\n assert (forall (x y z : sterm),\n star step x bfalse\n -> equiv z (bite x y z)) as Hequiv.\n {\n intros x y z Hsteps.\n apply equiv_symm.\n eapply equiv_trans.\n {\n apply equiv_bite; [| apply equiv_refl ..].\n apply steps_equiv; eauto.\n }\n apply steps_equiv; apply star_one.\n apply step_bite3.\n }\n so (Hseqrt _#3 Hs) as (R & Hrl & Hrr & Htl & Htr).\n exists R.\n do2 3 split.\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n\n {\n simpsub.\n eapply basic_equiv; eauto.\n prove_hygiene; eapply hygiene_subst; eauto.\n }\n }\nQed.\n\n\nLemma sound_booltp_elim_eqtype :\n forall G m n p q r s,\n pseq G (deq m n booltp)\n -> pseq G (deqtype p q)\n -> pseq G (deqtype r s)\n -> pseq G (deqtype (bite m p r) (bite n q s)).\nProof.\nintros G m n p q r t (i1, Hmn) (i2, Hpq) (i3, Hrt).\nso (shut_term _ G m) as (i4, Hclm).\nso (shut_term _ G n) as (i5, Hcln).\nso (shut_term _ G p) as (i6, Hclp).\nso (shut_term _ G q) as (i7, Hclq).\nso (shut_term _ G r) as (i8, Hclr).\nso (shut_term _ G t) as (i9, Hclt).\nso (upper_bound_all 9 i1 i2 i3 i4 i5 i6 i7 i8 i9) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & Hi8 & Hi9 & _).\nexists i; intros j Hj.\neapply sound_booltp_elim_eqtype_pre; eauto using le_trans.\nQed.\n\n\nLemma equivsub_under_dot :\n forall object i (b : @term object) s,\n hygiene clo b\n -> star step (project s i) b\n -> equivsub (compose (under i (compose (dot b id) sh1)) s) s.\nProof.\nintros object i b s Hclb Hsteps.\nsimpsub.\nintro j.\nrewrite -> project_compose.\nso (lt_eq_lt_dec j i) as [[Hlt | Heq] | Hlt].\n {\n rewrite -> project_under_lt; auto.\n simpsub.\n apply equiv_refl.\n }\n\n {\n subst j.\n rewrite -> project_under_eq.\n simpsub.\n rewrite -> (subst_into_closed _ _ b); auto.\n apply equiv_symm.\n apply steps_equiv.\n exact Hsteps.\n }\n\n {\n rewrite -> project_under_geq; [| omega].\n replace (j - i) with (S (j - i - 1)) by omega.\n simpsub.\n replace (i + (1 + (j - i - 1))) with j by omega.\n apply equiv_refl.\n }\nQed.\n\n\nLemma sound_booltp_eta_hyp_pre :\n forall G1 G2 m n p q a,\n hygiene (ctxpred (substctx (dot btrue id) G2 ++ G1)) m\n -> hygiene (ctxpred (substctx (dot btrue id) G2 ++ G1)) n\n -> hygiene (ctxpred (substctx (dot bfalse id) G2 ++ G1)) p\n -> hygiene (ctxpred (substctx (dot bfalse id) G2 ++ G1)) q\n -> hygiene (ctxpred (G2 ++ hyp_tm booltp :: G1)) a\n -> seq (substctx (dot btrue id) G2 ++ G1) (deq m n (subst (under (length G2) (dot btrue id)) a))\n -> seq (substctx (dot bfalse id) G2 ++ G1) (deq p q (subst (under (length G2) (dot bfalse id)) a))\n -> seq (G2 ++ cons (hyp_tm booltp) G1) \n (deq \n (bite (var (length G2)) \n (subst (under (length G2) sh1) m)\n (subst (under (length G2) sh1) p))\n (bite (var (length G2))\n (subst (under (length G2) sh1) n) \n (subst (under (length G2) sh1) q))\n a).\nProof.\nintros G1 G2 m n p q a Hclm Hcln Hclp Hclq Hcla Hseqmn Hseqpq.\napply seq_i.\ninvertc Hseqmn; intro Hseqmn.\ninvertc Hseqpq; intro Hseqpq.\nintros i s s' Hs.\nassert (index (length G2) (G2 ++ hyp_tm booltp :: G1)%list (hyp_tm booltp)) as Hindex.\n {\n replace (length G2) with (0 + length G2) by omega.\n apply index_app_right.\n apply index_0.\n }\nso (seqctx_index _#6 (pwctx_impl_seqctx _#4 Hs) Hindex) as Hhyp.\nsimpsubin Hhyp.\nset (x := project s (length G2)) in Hhyp.\nset (y := project s' (length G2)) in Hhyp.\ninvertc Hhyp.\nintros R Hbool _ Hxy.\ninvert (basic_value_inv _#6 value_booltp Hbool).\nintros <-.\nclear Hbool Hindex.\ndestruct Hxy as (_ & Hclx & Hcly & Hxy).\nassert (exists b,\n hygiene clo b\n /\\ star step x b\n /\\ star step y b\n /\\ (forall j, rel (bool_urel stop j) j b b)\n /\\ forall s s',\n pwctx i s s' (substctx (dot b id) G2 ++ G1)\n -> exists A,\n interp toppg true i (subst s (subst (under (length G2) (dot b id)) a)) A\n /\\ interp toppg false i (subst s' (subst (under (length G2) (dot b id)) a)) A\n /\\ rel (den A) i (bite x (subst s m) (subst s p)) (bite y (subst s' m) (subst s' p))\n /\\ rel (den A) i (bite x (subst s n) (subst s q)) (bite y (subst s' n) (subst s' q))\n /\\ rel (den A) i (bite x (subst s m) (subst s p)) (bite y (subst s' n) (subst s' q))) as H.\n {\n destruct Hxy as [(Hstepsx & Hstepsy) | (Hstepsx & Hstepsy)].\n {\n exists btrue.\n do2 4 split; auto; try prove_hygiene.\n {\n intro j.\n do2 3 split; auto; try prove_hygiene.\n left; auto using star_refl.\n }\n\n {\n intros t t' Ht.\n so (pwctx_impl_closub _#4 Ht) as (Hclt & Hclt').\n rewrite -> ctxpred_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n rewrite -> app_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n rewrite -> length_substctx in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n so (Hseqmn i t t' Ht) as (R & Hl & Hr & Hm & Hn & Hmn).\n exists R.\n assert (forall z z', equiv z (bite x z z')) as Hequivx.\n {\n intros z z'.\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.\n exact Hstepsx.\n }\n apply star_one.\n apply step_bite2.\n }\n assert (forall z z', equiv z (bite y z z')) as Hequivy.\n {\n intros z z'.\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.\n exact Hstepsy.\n }\n apply star_one.\n apply step_bite2.\n }\n do2 4 split; auto.\n {\n refine (urel_equiv _#7 _ _ _ _ Hm); try prove_hygiene; eauto using subst_closub.\n }\n\n {\n refine (urel_equiv _#7 _ _ _ _ Hn); try prove_hygiene; eauto using subst_closub.\n }\n\n {\n refine (urel_equiv _#7 _ _ _ _ Hmn); try prove_hygiene; eauto using subst_closub.\n }\n }\n }\n\n {\n exists bfalse.\n do2 4 split; auto; try prove_hygiene.\n {\n intro j.\n do2 3 split; auto; try prove_hygiene.\n right; auto using star_refl.\n }\n\n {\n intros t t' Ht.\n so (pwctx_impl_closub _#4 Ht) as (Hclt & Hclt').\n rewrite -> ctxpred_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n rewrite -> app_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n rewrite -> length_substctx in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.\n so (Hseqpq i t t' Ht) as (R & Hl & Hr & Hp & Hq & Hpq).\n exists R.\n assert (forall z z', equiv z' (bite x z z')) as Hequivx.\n {\n intros z z'.\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.\n exact Hstepsx.\n }\n apply star_one.\n apply step_bite3.\n }\n assert (forall z z', equiv z' (bite y z z')) as Hequivy.\n {\n intros z z'.\n apply equiv_symm.\n apply steps_equiv.\n eapply star_trans.\n {\n apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.\n exact Hstepsy.\n }\n apply star_one.\n apply step_bite3.\n }\n do2 4 split; auto.\n {\n refine (urel_equiv _#7 _ _ _ _ Hp); try prove_hygiene; eauto using subst_closub.\n }\n\n {\n refine (urel_equiv _#7 _ _ _ _ Hq); try prove_hygiene; eauto using subst_closub.\n }\n\n {\n refine (urel_equiv _#7 _ _ _ _ Hpq); try prove_hygiene; eauto using subst_closub.\n }\n }\n }\n }\nclear Hclm Hcln Hclp Hclq Hseqmn Hseqpq Hxy.\ndestruct H as (b & Hclb & Hpb & Hqb & Hrelb & Hseq).\nexploit (subst_pwctx G1 G2 booltp b i s s' (iubase (bool_urel stop i))) as Ht; auto.\n {\n intros j u u' Hu.\n exists (iubase (bool_urel stop j)).\n simpsub.\n do2 2 split.\n {\n apply interp_eval_refl.\n apply interp_bool.\n }\n\n {\n apply interp_eval_refl.\n apply interp_bool.\n }\n\n {\n rewrite -> !(subst_into_closed _ _ b); auto.\n apply Hrelb.\n }\n }\n\n {\n apply interp_eval_refl.\n apply interp_bool.\n }\n\n {\n apply interp_eval_refl.\n apply interp_bool.\n }\n\n {\n rewrite -> !(subst_into_closed _ _ b); auto.\n apply Hrelb.\n }\n\n {\n rewrite -> !(subst_into_closed _ _ b); auto.\n apply (urel_equiv_1 _#3 b); auto.\n {\n apply equiv_symm.\n apply steps_equiv; auto.\n }\n\n {\n apply Hrelb.\n }\n }\nset (t := compose (under (length G2) sh1) s) in Ht.\nset (t' := compose (under (length G2) sh1) s') in Ht.\nso (Hseq _ _ Ht) as (A & Hal & Har & Hm & Hn & Hmn).\nclear Hseq.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nexists A.\nsimpsub.\ndo2 4 split; auto.\n {\n eapply basic_equiv; eauto.\n {\n eapply subst_closub; eauto.\n }\n simpsub. \n unfold t.\n rewrite <- compose_assoc.\n rewrite <- compose_under.\n apply equiv_funct; auto using equiv_refl.\n apply equivsub_under_dot; auto.\n }\n\n {\n eapply basic_equiv; eauto.\n {\n eapply subst_closub; eauto.\n }\n simpsub.\n apply equiv_funct; auto using equiv_refl.\n unfold t'.\n rewrite <- compose_assoc.\n rewrite <- compose_under.\n apply equivsub_under_dot; auto.\n }\nQed.\n\n\nLemma sound_booltp_eta_hyp :\n forall G1 G2 m n p q a,\n pseq (substctx (dot btrue id) G2 ++ G1) (deq m n (subst (under (length G2) (dot btrue id)) a))\n -> pseq (substctx (dot bfalse id) G2 ++ G1) (deq p q (subst (under (length G2) (dot bfalse id)) a))\n -> pseq (G2 ++ cons (hyp_tm booltp) G1) \n (deq \n (bite (var (length G2)) \n (subst (under (length G2) sh1) m)\n (subst (under (length G2) sh1) p))\n (bite (var (length G2))\n (subst (under (length G2) sh1) n) \n (subst (under (length G2) sh1) q))\n a).\nProof.\nintros G1 G2 m n p q a (i1, Hmn) (i2, Hpq).\nso (shut_term _ (substctx (dot btrue id) G2 ++ G1) m) as (i3, Hclm).\nso (shut_term _ (substctx (dot btrue id) G2 ++ G1) n) as (i4, Hcln).\nso (shut_term _ (substctx (dot bfalse id) G2 ++ G1) p) as (i5, Hclp).\nso (shut_term _ (substctx (dot bfalse id) G2 ++ G1) q) as (i6, Hclq).\nso (shut_term _ (G2 ++ hyp_tm booltp :: G1) a) as (i7, Hcla).\nso (upper_bound_all 7 i1 i2 i3 i4 i5 i6 i7) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & _).\nexists i; intros j Hj.\nautorewrite with canonlist.\napply sound_booltp_eta_hyp_pre; finish_pseq j.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/SoundSimple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.21206879439743004, "lm_q1q2_score": 0.10769104983840225}} {"text": "Require Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Simulation Ctypes Cop Ctyping Csyntax Clight.\nRequire SimMemId SimMemExt SimMemInj.\nRequire SoundTop UnreachC.\nRequire SimSymbId SimSymbDrop.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\n\nRequire Import MatchSimModSem.\nRequire Import mktac.\nRequire Import IntegersC.\nRequire Import IdSimExtra ClightC.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nLemma clight_step_readonly se ge st0 st1 tr\n (STEP: step se ge (function_entry2 ge) st0 tr st1):\n Mem.unchanged_on (loc_not_writable (get_mem st0)) (get_mem st0) (get_mem st1).\nProof.\n inv STEP; ss; try refl; try (by eapply mem_free_list_readonly; eauto); try (by eapply external_call_readonly; eauto).\n - inv H2.\n + unfold Mem.storev in *. eapply mem_store_readonly; eauto.\n + eapply Mem.storebytes_unchanged_on; eauto. ii. unfold loc_not_writable in *.\n eapply H9. eapply Mem.perm_cur. eapply Mem.storebytes_range_perm; eauto.\n - inv H. eapply alloc_variables_unchanged_on; eauto.\nQed.\n\nDefinition match_env (j: meminj) (env_src env_tgt: env) :=\n forall id,\n (<>) /\\\n (<>) /\\\n (<>)>>) \\/\n (<>) /\\\n (<>)>>).\n\nDefinition match_temp_env (j: meminj) (tenv_src tenv_tgt: temp_env) :=\n forall id,\n option_rel (Val.inject j) (tenv_src ! id) (tenv_tgt ! id).\n\nInductive match_cont (j: meminj): cont -> cont -> Prop :=\n| match_Kstop:\n match_cont j Kstop Kstop\n| match_Kseq\n stmt K_src K_tgt\n (CONT: match_cont j K_src K_tgt):\n match_cont j (Kseq stmt K_src) (Kseq stmt K_tgt)\n| match_Kloop1\n stmt0 stmt1 K_src K_tgt\n (CONT: match_cont j K_src K_tgt):\n match_cont j (Kloop1 stmt0 stmt1 K_src) (Kloop1 stmt0 stmt1 K_tgt)\n| match_Kloop2\n stmt0 stmt1 K_src K_tgt\n (CONT: match_cont j K_src K_tgt):\n match_cont j (Kloop2 stmt0 stmt1 K_src) (Kloop2 stmt0 stmt1 K_tgt)\n| match_Kswitch\n K_src K_tgt\n (CONT: match_cont j K_src K_tgt):\n match_cont j (Kswitch K_src) (Kswitch K_tgt)\n| match_Kcall\n id fn env_src env_tgt tenv_src tenv_tgt K_src K_tgt\n (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (CONT: match_cont j K_src K_tgt):\n match_cont j (Kcall id fn env_src tenv_src K_src) (Kcall id fn env_tgt tenv_tgt K_tgt).\n\nInductive match_states_clight_internal:\n state -> state -> meminj -> mem -> mem -> Prop :=\n| match_State\n fn stmt K_src K_tgt env_src env_tgt tenv_src tenv_tgt m_src m_tgt j\n (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (CONT: match_cont j K_src K_tgt):\n match_states_clight_internal\n (State fn stmt K_src env_src tenv_src m_src)\n (State fn stmt K_tgt env_tgt tenv_tgt m_tgt)\n j m_src m_tgt\n| match_Callstate\n fptr_src fptr_tgt ty args_src args_tgt K_src K_tgt m_src m_tgt j\n (INJ: Val.inject j fptr_src fptr_tgt)\n (VALS: Val.inject_list j args_src args_tgt)\n (CONT: match_cont j K_src K_tgt):\n match_states_clight_internal\n (Callstate fptr_src ty args_src K_src m_src)\n (Callstate fptr_tgt ty args_tgt K_tgt m_tgt)\n j m_src m_tgt\n| match_Returnstate\n retv_src retv_tgt K_src K_tgt m_src m_tgt j\n (INJ: Val.inject j retv_src retv_tgt)\n (CONT: match_cont j K_src K_tgt):\n match_states_clight_internal\n (Returnstate retv_src K_src m_src)\n (Returnstate retv_tgt K_tgt m_tgt)\n j m_src m_tgt.\n\nInductive match_states_clight\n : unit -> state -> state -> SimMemInj.t' -> Prop :=\n| match_states_clight_intro\n st_src st_tgt j m_src m_tgt sm0\n (MWFSRC: m_src = sm0.(SimMemInj.src))\n (MWFTGT: m_tgt = sm0.(SimMemInj.tgt))\n (MWFINJ: j = sm0.(SimMemInj.inj))\n (MATCHST: match_states_clight_internal st_src st_tgt j m_src m_tgt)\n (MWF: SimMemInj.wf' sm0):\n match_states_clight tt st_src st_tgt sm0.\n\nSection CLIGHTINJ.\n\n Variable se_src se_tgt: Senv.t.\n Variable ge_src ge_tgt: genv.\n Hypothesis CENV: genv_cenv ge_src = genv_cenv ge_tgt.\n\n Definition function_entry_inject\n (function_entry: genv -> function -> list val -> mem -> env -> temp_env -> mem -> Prop) :=\n forall fn vs_src vs_tgt sm0 env_src tenv_src m_src1\n (MWF: SimMemInj.wf' sm0)\n (VALS: Val.inject_list sm0.(SimMemInj.inj) vs_src vs_tgt)\n (ENTRY: function_entry ge_src fn vs_src sm0.(SimMemInj.src) env_src tenv_src m_src1),\n exists env_tgt tenv_tgt sm1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n\n Lemma alloc_variables_inject sm0 idl e_src0 e_tgt0 e_src1 m_src1\n (ALLOC: alloc_variables ge_src e_src0 (SimMemInj.src sm0) idl e_src1 m_src1)\n (ENV: match_env (SimMemInj.inj sm0) e_src0 e_tgt0)\n (MWF: SimMemInj.wf' sm0):\n exists e_tgt1 sm1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n revert sm0 MWF e_src0 e_tgt0 e_src1 m_src1 ENV ALLOC. induction idl.\n - i. inv ALLOC. esplits; eauto; try refl. econs.\n - i. inv ALLOC.\n exploit SimMemInj.alloc_parallel; eauto; try refl. i. des. clarify.\n exploit IHidl; eauto.\n { instantiate (1:=PTree.set id (blk_tgt, ty) e_tgt0).\n ii. repeat rewrite PTree.gsspec. des_ifs.\n - left. esplits; eauto.\n - destruct (ENV id0).\n + des. left. inv MLE. esplits; cycle 1; eauto.\n + right. eauto. }\n i. des. clarify. esplits; eauto; try etrans; eauto. econs; eauto. rewrite <- CENV. auto.\n Qed.\n\n Lemma assign_loc_inject ce ty sm0 blk_src blk_tgt ofs_src ofs_tgt v_src v_tgt m_src1\n (ASSIGN: assign_loc ce ty sm0.(SimMemInj.src) blk_src ofs_src v_src m_src1)\n (INJ: Val.inject sm0.(SimMemInj.inj) (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt))\n (VAL: Val.inject sm0.(SimMemInj.inj) v_src v_tgt)\n (MWF: SimMemInj.wf' sm0):\n exists sm1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n cinv MWF. inv ASSIGN.\n - exploit SimMemInj.storev_mapped; eauto. i. des. clarify. esplits; eauto. econs 1; eauto.\n - destruct (zeq (sizeof ce ty) 0).\n + cinv VAL. cinv INJ.\n assert (bytes = nil).\n { exploit (Mem.loadbytes_empty (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') (sizeof ce ty)).\n omega. congruence. } subst.\n destruct (Mem.range_perm_storebytes (SimMemInj.tgt sm0) blk_tgt (Ptrofs.unsigned (Ptrofs.add ofs_src (Ptrofs.repr delta0))) nil)\n as [tm' SB].\n { simpl. red; intros; omegaContradiction. }\n eexists (SimMemInj.mk _ tm' _ _ _ _ _ _ _); ss. esplits; cycle 3; eauto.\n * econs; ss; eauto; try (eapply Mem.storebytes_unchanged_on; eauto; i; ss; omega);\n try (ii; eapply Mem.perm_storebytes_2; eauto); try (econs; i; des; clarify).\n * econs 2; eauto; i; try omegaContradiction.\n { rewrite e; right; omega. }\n { apply Mem.loadbytes_empty. omega. }\n * inv MWF. econs; ss; eauto; try (erewrite Mem.nextblock_storebytes; eauto).\n { eapply Mem.storebytes_empty_inject; eauto. }\n { unfold SimMemInj.src_private, SimMemInj.valid_blocks, Mem.valid_block. ss.\n erewrite Mem.nextblock_storebytes; eauto. }\n { ii. exploit TGTEXT0; eauto.\n unfold SimMemInj.tgt_private, SimMemInj.valid_blocks, Mem.valid_block, loc_out_of_reach. ss.\n erewrite (@Mem.nextblock_storebytes _ _ _ _ _ SB). i.\n des_safe. split; eauto. ii.\n eapply H5; eauto. eapply Mem.perm_storebytes_2; eauto. }\n + assert (SZPOS: sizeof ce ty > 0).\n { generalize (sizeof_pos ce ty); omega. }\n cinv VAL. cinv INJ.\n assert (RPSRC: Mem.range_perm (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') (Ptrofs.unsigned ofs' + sizeof ce ty) Cur Nonempty).\n { eapply Mem.range_perm_implies; try eapply perm_any_N. eapply Mem.loadbytes_range_perm; eauto. }\n assert (RPDST: Mem.range_perm (SimMemInj.src sm0) blk_src (Ptrofs.unsigned ofs_src) (Ptrofs.unsigned ofs_src + sizeof ce ty) Cur Nonempty).\n { replace (sizeof ce ty) with (Z.of_nat (List.length bytes)).\n - eapply Mem.range_perm_implies; try eapply perm_any_N. eapply Mem.storebytes_range_perm; eauto.\n - exploit Mem.loadbytes_length; try apply H3; eauto. intros LEN.\n rewrite LEN. rewrite Z2Nat.id; try omega. }\n assert (PSRC: Mem.perm (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') Cur Nonempty) by (apply RPSRC; omega).\n assert (PDST: Mem.perm (SimMemInj.src sm0) blk_src (Ptrofs.unsigned ofs_src) Cur Nonempty) by (apply RPDST; omega).\n exploit Mem.address_inject; try apply PSRC; eauto. intros EQ1.\n exploit Mem.address_inject; try apply PDST; eauto. intros EQ2.\n exploit Mem.loadbytes_inject; eauto. intros [bytes2 [A B]].\n exploit SimMemInjC.storebytes_mapped; eauto. i. des_safe.\n exists sm1. splits; auto. econs 2; try rewrite EQ1; try rewrite EQ2; eauto.\n * intros; eapply Mem.aligned_area_inject with (m := SimMemInj.src sm0); eauto.\n { apply alignof_blockcopy_1248. }\n { apply sizeof_alignof_blockcopy_compat. }\n * intros; eapply Mem.aligned_area_inject with (m := SimMemInj.src sm0); eauto.\n { apply alignof_blockcopy_1248. }\n { apply sizeof_alignof_blockcopy_compat. }\n * eapply Mem.disjoint_or_equal_inject with (m := SimMemInj.src sm0); eauto; apply Mem.range_perm_max with Cur; auto.\n Qed.\n\n Lemma call_cont_match j K_src K_tgt\n (MATCH: match_cont j K_src K_tgt):\n match_cont j (call_cont K_src) (call_cont K_tgt).\n Proof.\n revert K_tgt MATCH. induction K_src; ss; i; inv MATCH; ss; eauto; econs; eauto.\n Qed.\n\n Lemma match_env_incr j0 j1\n (INCR: inject_incr j0 j1):\n match_env j0 <2= match_env j1.\n Proof.\n ii. destruct (PR id).\n - des. left. esplits; eauto.\n - des. right. esplits; eauto.\n Qed.\n\n Lemma match_temp_env_incr j0 j1\n (INCR: inject_incr j0 j1):\n match_temp_env j0 <2= match_temp_env j1.\n Proof.\n ii. destruct (PR id); econs. eapply val_inject_incr; eauto.\n Qed.\n\n Lemma match_cont_incr j0 j1\n (INCR: inject_incr j0 j1):\n match_cont j0 <2= match_cont j1.\n Proof.\n ii. revert INCR. induction PR; i; econs; eauto; try by (eapply match_expr_incr; eauto).\n - eapply match_env_incr; eauto.\n - eapply match_temp_env_incr; eauto.\n Qed.\n\n Lemma bind_parameters_inject e_src e_tgt sm0 idl vargs_src vargs_tgt m_src1\n (BIND: bind_parameters ge_src e_src (SimMemInj.src sm0) idl vargs_src m_src1)\n (ENV: match_env (SimMemInj.inj sm0) e_src e_tgt)\n (MWF: SimMemInj.wf' sm0)\n (VALS: Val.inject_list (SimMemInj.inj sm0) vargs_src vargs_tgt):\n exists sm1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n revert sm0 ENV vargs_src vargs_tgt m_src1 MWF VALS BIND. induction idl.\n - i. inv BIND. inv VALS. esplits; eauto; try refl. econs.\n - i. inv BIND. inv VALS.\n destruct (ENV id); des; clarify.\n exploit assign_loc_inject; eauto. i. des. clarify.\n exploit IHidl; try apply H6; eauto.\n { inv MLE. eapply match_env_incr; eauto. }\n { inv MLE. eapply val_inject_list_incr; eauto. }\n i. des. esplits; eauto; try etrans; eauto. econs; eauto. rewrite CENV in *. auto.\n Qed.\n\n Lemma set_match_temp_env j id v_src v_tgt tenv_src tenv_tgt\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (VAL: Val.inject j v_src v_tgt):\n match_temp_env j (PTree.set id v_src tenv_src) (PTree.set id v_tgt tenv_tgt).\n Proof.\n ii. repeat rewrite PTree.gsspec. des_ifs. econs; eauto.\n Qed.\n\n Lemma bind_parameter_temps_inject tenv_src0 tenv_tgt0 tenv_src1\n j idl vargs_src vargs_tgt\n (BIND: bind_parameter_temps idl vargs_src tenv_src0 = Some tenv_src1)\n (TENV: match_temp_env j tenv_src0 tenv_tgt0)\n (VALS: Val.inject_list j vargs_src vargs_tgt):\n exists tenv_tgt1,\n (<>) /\\\n (<>).\n Proof.\n revert tenv_src0 tenv_tgt0 tenv_src1 vargs_src BIND TENV vargs_tgt VALS.\n induction idl; i; ss; des_ifs_safe; inv VALS; eauto.\n exploit IHidl; eauto. eapply set_match_temp_env; eauto.\n Qed.\n\n Lemma create_undef_temps_match j l:\n match_temp_env j (create_undef_temps l) (create_undef_temps l).\n Proof.\n induction l; ss.\n - ii. repeat rewrite PTree.gempty. econs.\n - ii. des_ifs. rewrite PTree.gsspec. des_ifs. econs. eauto.\n Qed.\n\n Lemma function_entry1_inject: function_entry_inject function_entry1.\n Proof.\n ii. inv ENTRY.\n exploit alloc_variables_inject; eauto.\n { instantiate (1:=empty_env). ii. right. unfold empty_env. repeat rewrite PTree.gempty. auto. }\n i. des. clarify.\n exploit bind_parameters_inject; eauto.\n { cinv MLE. eapply val_inject_list_incr; eauto. } i. des.\n esplits; eauto; try (by etrans; eauto); try by (econs; eauto).\n - cinv MLE. cinv MLE0. eapply match_env_incr; eauto.\n - eapply create_undef_temps_match.\n Qed.\n\n Lemma function_entry2_inject: function_entry_inject function_entry2.\n Proof.\n ii. inv ENTRY.\n exploit alloc_variables_inject; eauto.\n { instantiate (1:=empty_env). ii. right.\n unfold empty_env. repeat rewrite PTree.gempty. auto. }\n i. des. clarify.\n exploit bind_parameter_temps_inject; eauto.\n { eapply create_undef_temps_match. } i. des.\n esplits; eauto; try (econs; eauto). cinv MLE. eapply match_temp_env_incr; eauto.\n Qed.\n\n Variable function_entry: genv -> function -> list val -> mem -> env -> temp_env -> mem -> Prop.\n Hypothesis FUNCTIONENTRY: function_entry_inject function_entry.\n\n Lemma deref_loc_inject j ty m_src m_tgt blk_src blk_tgt ofs_src ofs_tgt v_src\n (DEREF: deref_loc ty m_src blk_src ofs_src v_src)\n (INJECT: Mem.inject j m_src m_tgt)\n (VAL: Val.inject j (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt)):\n exists v_tgt,\n (<>) /\\\n (<>).\n Proof.\n inv DEREF; try (by esplits; eauto; econs; eauto).\n exploit Mem.loadv_inject; eauto. i. des. esplits; eauto. econs 1; eauto.\n Qed.\n\n Lemma eval_expr_lvalue_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt\n (GENV: meminj_match_globals eq ge_src ge_tgt j):\n (forall exp v_src\n (EVAL: eval_expr ge_src env_src tenv_src m_src exp v_src),\n forall (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (INJECT: Mem.inject j m_src m_tgt),\n exists v_tgt,\n (<>) /\\\n (<>)) /\\\n (forall exp blk_src ofs_src\n (EVAL: eval_lvalue ge_src env_src tenv_src m_src exp blk_src ofs_src),\n forall (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (INJECT: Mem.inject j m_src m_tgt),\n exists blk_tgt ofs_tgt,\n (<>) /\\\n (<>)).\n Proof.\n apply eval_expr_lvalue_ind; i; try (by esplits; eauto; econs; eauto).\n - cinv (TENV id); rewrite H in *; clarify. esplits; eauto. econs 5; eauto.\n - exploit H0; eauto. i. des. esplits; eauto. econs 6; eauto.\n - exploit H0; eauto. i. des. exploit sem_unary_operation_inject; eauto. i. des.\n esplits; eauto. econs 7; eauto.\n - exploit H0; eauto. i. des. exploit H2; eauto. i. des.\n exploit sem_binary_operation_inject; eauto. i. des.\n esplits; eauto. econs 8; eauto. rewrite <- CENV. auto.\n - exploit H0; eauto. i. des. exploit sem_cast_inject; eauto. i. des.\n esplits; eauto. econs 9; eauto.\n - esplits; eauto. rewrite CENV. econs 10; eauto.\n - esplits; eauto. rewrite CENV. econs 11; eauto.\n - exploit H0; eauto. i. des. exploit deref_loc_inject; eauto. i. des.\n esplits; eauto. econs 12; eauto.\n - cinv (ENV id); des; rewrite H in *; clarify. esplits; eauto. econs 1; eauto.\n - cinv (ENV id); des; rewrite H in *; clarify. inv GENV. exploit SYMBLE; eauto. i. des.\n esplits; eauto. econs 2; eauto.\n - exploit H0; eauto. i. des. cinv INJ. esplits; eauto. econs 3; eauto.\n - exploit H0; eauto. i. des. cinv INJ. rewrite CENV in *. esplits.\n + econs 4; eauto.\n + econs; eauto. repeat rewrite Ptrofs.add_assoc. f_equal. apply Ptrofs.add_commut.\n - exploit H0; eauto. i. des. cinv INJ. rewrite CENV in *. esplits; eauto. econs 5; eauto.\n Qed.\n\n Lemma eval_expr_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt exp v_src\n (EVAL: eval_expr ge_src env_src tenv_src m_src exp v_src)\n (GENV: meminj_match_globals eq ge_src ge_tgt j)\n (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (INJECT: Mem.inject j m_src m_tgt):\n exists v_tgt,\n (<>) /\\\n (<>).\n Proof.\n exploit eval_expr_lvalue_inject; eauto. i. des. eauto.\n Qed.\n\n Lemma eval_exprlist_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt tys\n exps vs_src\n (EVALS: eval_exprlist ge_src env_src tenv_src m_src exps tys vs_src)\n (GENV: meminj_match_globals eq ge_src ge_tgt j)\n (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (INJECT: Mem.inject j m_src m_tgt):\n exists vs_tgt,\n (<>) /\\\n (<>).\n Proof.\n revert tys vs_src EVALS ENV TENV INJECT. induction exps; i.\n - inv EVALS. exists []. esplits; eauto. econs; eauto.\n - inv EVALS. exploit IHexps; eauto. i. des.\n exploit eval_expr_inject; eauto. i. des.\n exploit sem_cast_inject; eauto. i. des.\n exists (tv :: vs_tgt). esplits; eauto. econs; eauto.\n Qed.\n\n Lemma eval_lvalue_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt exp blk_src ofs_src\n (EVAL: eval_lvalue ge_src env_src tenv_src m_src exp blk_src ofs_src)\n (GENV: meminj_match_globals eq ge_src ge_tgt j)\n (ENV: match_env j env_src env_tgt)\n (TENV: match_temp_env j tenv_src tenv_tgt)\n (INJECT: Mem.inject j m_src m_tgt):\n exists blk_tgt ofs_tgt,\n (<>) /\\\n (<>).\n Proof.\n exploit eval_expr_lvalue_inject; eauto. i. des. eauto.\n Qed.\n\n Definition match_loc j (loc_src loc_tgt: block * Z * Z): Prop :=\n match loc_src with\n | (blk_src, lo_src, hi_src) =>\n match loc_tgt with\n | (blk_tgt, lo_tgt, hi_tgt) =>\n exists delta,\n (<>) /\\\n (<>) /\\\n (<>)\n end\n end.\n\n Lemma free_list_inject_parallel\n sm0 locs_src locs_tgt m_src1\n (MWF: SimMemInj.wf' sm0)\n (LOCS: list_forall2 (match_loc (SimMemInj.inj sm0)) locs_src locs_tgt)\n (FREE: Mem.free_list (SimMemInj.src sm0) locs_src = Some m_src1):\n exists sm1,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n revert sm0 locs_tgt m_src1 MWF LOCS FREE. induction locs_src; ss.\n - i. clarify. inv LOCS. esplits; eauto. refl.\n - i. inv LOCS. unfold match_loc in H1. des_ifs. des. clarify. ss.\n exploit SimMemInj.free_parallel; eauto. i. des. clarify.\n exploit IHlocs_src; eauto.\n { eapply list_forall2_imply; eauto. i. unfold match_loc in *. des_ifs. des. inv MLE. esplits; eauto. }\n i. des. clarify. esplits; eauto; etrans; eauto. rewrite FREETGT. eauto.\n Qed.\n\n Lemma blocks_of_env_match j e_src e_tgt\n (ENV: match_env j e_src e_tgt):\n list_forall2 (match_loc j) (blocks_of_env ge_src e_src) (blocks_of_env ge_tgt e_tgt).\n Proof.\n set (R:=(fun (d_src d_tgt: block * type) =>\n let (b_src, t_src) := d_src in\n let (b_tgt, t_tgt) := d_tgt in\n (<>) /\\\n (<>))).\n exploit PTree.elements_canonical_order.\n - instantiate (1:=R). instantiate (1:=e_tgt). instantiate (1:=e_src).\n i. destruct (ENV i); des; clarify. esplits; eauto. ss.\n - i. destruct (ENV i); des; clarify. esplits; eauto. ss.\n - intros ALL. unfold blocks_of_env. revert ALL.\n generalize (PTree.elements e_tgt). generalize (PTree.elements e_src).\n induction l; ss; i.\n + inv ALL. econs.\n + inv ALL. ss. econs; eauto. unfold block_of_binding. des_ifs; ss; des; clarify.\n esplits; eauto. rewrite CENV. zsimpl. auto.\n Qed.\n\n Scheme statement_ind2 := Induction for statement Sort Prop\n with labeled_statements_ind2 := Induction for labeled_statements Sort Prop.\n Combined Scheme statement_labeled_statements_ind from statement_ind2, labeled_statements_ind2.\n\n Lemma find_label_label_ls_match_none j lbl:\n (forall stmt,\n forall K_src0 K_tgt0\n (LABEL: find_label lbl stmt K_src0 = None)\n (CONT: match_cont j K_src0 K_tgt0),\n find_label lbl stmt K_tgt0 = None) /\\\n (forall ls,\n forall K_src0 K_tgt0\n (LABEL: find_label_ls lbl ls K_src0 = None)\n (CONT: match_cont j K_src0 K_tgt0),\n find_label_ls lbl ls K_tgt0 = None).\n Proof.\n eapply statement_labeled_statements_ind; ss; i; try (by des_ifs_safe; erewrite H; eauto; econs; eauto).\n - des_ifs_safe. erewrite H; try econs; eauto. erewrite H0; try econs; eauto.\n Qed.\n\n Lemma find_label_match_none j lbl stmt K_src0 K_tgt0\n (LABEL: find_label lbl stmt K_src0 = None)\n (CONT: match_cont j K_src0 K_tgt0):\n find_label lbl stmt K_tgt0 = None.\n Proof.\n eapply find_label_label_ls_match_none; eauto.\n Qed.\n\n Lemma find_label_label_ls_match j lbl:\n (forall stmt K_src0 K_tgt0 stmt' K_src1\n (LABEL: find_label lbl stmt K_src0 = Some (stmt', K_src1))\n (CONT: match_cont j K_src0 K_tgt0),\n exists K_tgt1,\n (<>) /\\\n (<>)) /\\\n (forall ls K_src0 K_tgt0 stmt' K_src1\n (LABEL: find_label_ls lbl ls K_src0 = Some (stmt', K_src1))\n (CONT: match_cont j K_src0 K_tgt0),\n exists K_tgt1,\n (<>) /\\\n (<>)).\n Proof.\n eapply statement_labeled_statements_ind; ss; i.\n - destruct (find_label lbl s (Kseq s0 K_src0)) eqn:LABEL0.\n + clarify. exploit H; eauto.\n { econs; eauto. } i. des.\n rewrite LABEL. esplits; eauto.\n + exploit H0; eauto. i. des.\n exploit find_label_match_none; eauto.\n { econs; eauto. } intros LABEL2.\n rewrite LABEL1. rewrite LABEL2. esplits; eauto.\n - destruct (find_label lbl s K_src0) eqn:LABEL0.\n + clarify. exploit H; eauto. i. des. rewrite LABEL. esplits; eauto.\n + exploit find_label_match_none; eauto. intros LABEL1. rewrite LABEL1. exploit H0; eauto.\n - destruct (find_label lbl s (Kloop1 s s0 K_src0)) eqn:LABEL0.\n + clarify. exploit H; eauto.\n { econs; eauto. } i. des.\n rewrite LABEL. esplits; eauto.\n + exploit find_label_match_none; eauto.\n { econs; eauto. }\n intros LABEL1. rewrite LABEL1. exploit H0; eauto. econs; eauto.\n - exploit H; eauto. econs; eauto.\n - des_ifs.\n + esplits; eauto.\n + exploit H; eauto.\n - destruct (find_label lbl s (Kseq (seq_of_labeled_statement l) K_src0)) eqn:LABEL0.\n + clarify. exploit H; eauto.\n { econs; eauto. } i. des.\n rewrite LABEL. esplits; eauto.\n + exploit find_label_match_none; eauto.\n { econs; eauto. }\n intros LABEL1. rewrite LABEL1. exploit H0; eauto.\n Qed.\n\n Lemma find_label_match j lbl stmt K_src0 K_tgt0 stmt' K_src1\n (LABEL: find_label lbl stmt K_src0 = Some (stmt', K_src1))\n (CONT: match_cont j K_src0 K_tgt0):\n exists K_tgt1,\n (<>) /\\\n (<>).\n Proof.\n eapply find_label_label_ls_match; eauto.\n Qed.\n\n Lemma clight_step_preserve_injection\n u st_src0 st_tgt0 st_src1 sm0 tr\n (SYMBOLS: symbols_inject (SimMemInj.inj sm0) se_src se_tgt)\n (GENV: meminj_match_globals eq ge_src ge_tgt (SimMemInj.inj sm0))\n (MATCH: match_states_clight u st_src0 st_tgt0 sm0)\n (STEP: step se_src ge_src (function_entry ge_src) st_src0 tr st_src1):\n exists st_tgt1 sm1,\n (<>) /\\\n (<>) /\\\n (<>).\n Proof.\n inv STEP; inv MATCH; inv MATCHST; try (by inv CONT; esplits; try refl; do 3 (econs; eauto)).\n - cinv MWF. exploit eval_expr_inject; eauto. i. des.\n exploit eval_lvalue_inject; eauto. i. des.\n exploit sem_cast_inject; eauto. i. des.\n exploit assign_loc_inject; eauto. i. des.\n rewrite CENV in *. esplits; eauto; econs; eauto. cinv MLE. econs; eauto.\n + eapply match_env_incr; eauto.\n + eapply match_temp_env_incr; eauto.\n + eapply match_cont_incr; eauto.\n\n - cinv MWF. exploit eval_expr_inject; eauto. i. des. esplits; try refl; econs; eauto.\n econs; eauto. eapply set_match_temp_env; eauto.\n\n - cinv MWF. exploit eval_exprlist_inject; eauto. i. des.\n exploit eval_expr_inject; eauto. i. des. esplits; try refl; do 3 (econs; eauto).\n\n - cinv MWF. exploit eval_exprlist_inject; eauto. i. des.\n exploit external_call_mem_inject_gen; eauto. i. des.\n exploit SimMemInjC.parallel_gen; eauto.\n { ii. eapply external_call_max_perm; eauto. }\n { ii. eapply external_call_max_perm; eauto. }\n i. des. esplits; eauto.\n + econs 4; eauto.\n + cinv MLE. econs; eauto. econs; eauto.\n * eapply match_env_incr; eauto.\n * unfold set_opttemp. des_ifs.\n { eapply set_match_temp_env; eauto. eapply match_temp_env_incr; eauto. }\n { eapply match_temp_env_incr; eauto. }\n * eapply match_cont_incr; eauto.\n\n - esplits; try refl; do 3 (econs; eauto).\n\n - cinv MWF. exploit eval_expr_inject; eauto. i. des.\n exploit bool_val_inject; eauto. i. esplits; try refl; do 2 (econs; eauto).\n\n - esplits; try refl; do 3 (econs; eauto).\n\n - exploit free_list_inject_parallel; eauto.\n { eapply blocks_of_env_match; eauto. } i. des.\n esplits; try econs 15; eauto. econs; eauto. clarify. econs; eauto. eapply call_cont_match; eauto.\n cinv MLE. eapply match_cont_incr; eauto.\n\n - cinv MWF. exploit eval_expr_inject; eauto. i. des.\n exploit sem_cast_inject; eauto. i. des.\n exploit free_list_inject_parallel; eauto.\n { eapply blocks_of_env_match; eauto. } i. des.\n esplits; try econs 16; eauto. econs; eauto. clarify. econs; eauto.\n + cinv MLE. eapply val_inject_incr; eauto.\n + eapply call_cont_match; eauto. cinv MLE. eapply match_cont_incr; eauto.\n\n - cinv MWF. exploit free_list_inject_parallel; eauto.\n { eapply blocks_of_env_match; eauto. } i. des.\n esplits; eauto.\n + econs 17; eauto. unfold is_call_cont in *. destruct CONT; clarify.\n + econs; eauto. clarify. econs; eauto. cinv MLE. eapply match_cont_incr; eauto.\n\n - cinv MWF. exploit eval_expr_inject; eauto. i. des.\n assert (SWITCH: sem_switch_arg v_tgt (typeof a) = Some n).\n { unfold sem_switch_arg in *. inv INJ; ss; clarify; des_ifs. }\n esplits; try refl; do 3 (econs; eauto).\n\n - exploit find_label_match; eauto.\n { eapply call_cont_match; eauto. } i. des.\n esplits; try refl; do 2 (econs; eauto).\n\n - exploit match_globals_find_funct; eauto. intros FPTRTGT.\n exploit FUNCTIONENTRY; eauto. i. des.\n esplits; try econs 23; eauto. econs; eauto. clarify. econs; eauto.\n cinv MLE. eapply match_cont_incr; eauto.\n\n - cinv MWF. exploit match_globals_find_funct; eauto. intros FPTRTGT.\n exploit external_call_mem_inject_gen; eauto. i. des.\n exploit SimMemInjC.parallel_gen; eauto.\n { ii. eapply external_call_max_perm; eauto. }\n { ii. eapply external_call_max_perm; eauto. }\n i. des. esplits; try econs 24; eauto.\n cinv MLE. econs; eauto. econs; eauto. eapply match_cont_incr; eauto.\n\n - inv CONT. esplits; try refl; econs; eauto. clarify. econs; eauto. destruct optid; ss.\n eapply set_match_temp_env; eauto.\n Qed.\n\n Lemma clight_step_preserve_injection2\n st_src0 st_tgt0 st_src1 j0 m_src0 m_tgt0 tr\n (SYMBOLS: symbols_inject j0 se_src se_tgt)\n (GENV: meminj_match_globals eq ge_src ge_tgt j0)\n (INJECT: Mem.inject j0 m_src0 m_tgt0)\n (MATCH: match_states_clight_internal st_src0 st_tgt0 j0 m_src0 m_tgt0)\n (STEP: step se_src ge_src (function_entry ge_src) st_src0 tr st_src1):\n exists st_tgt1 m_src1 m_tgt1 j1 ,\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<>) /\\\n (<> >>) /\\\n (<> >>).\n Proof.\n set (sm:=SimMemInj.mk\n m_src0 m_tgt0 j0\n (loc_unmapped j0 /2\\ SimMemInj.valid_blocks m_src0)\n (loc_out_of_reach j0 m_src0 /2\\ SimMemInj.valid_blocks m_tgt0)\n (Mem.nextblock m_src0)\n (Mem.nextblock m_tgt0) 1%positive 1%positive).\n assert (SYMBINJ: symbols_inject (SimMemInj.inj sm) se_src se_tgt) by eauto.\n exploit clight_step_preserve_injection; eauto; ss.\n - econs; eauto. econs; ss; eauto; try refl; try xomega.\n - i. des. destruct sm1.\n inv MATCH0. inv MLE. inv MWF. ss. esplits; eauto; try (eapply Mem.unchanged_on_implies; eauto; ii; ss).\n + inv FROZEN. ii. exploit NEW_IMPLIES_OUTSIDE; eauto. i. des.\n unfold Mem.valid_block. clear - OUTSIDE_SRC OUTSIDE_TGT. xomega.\n Qed.\n\nEnd CLIGHTINJ.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/selfsim/ClightStepInj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2018132270610754, "lm_q1q2_score": 0.10720507788564947}} {"text": "(** * Induction: Proof by Induction *)\n \n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export begriffs_Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n \n Here are two ways to compile your code:\n \n - CoqIDE:\n \n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n \n - Command line:\n \n Run [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic. *)\n\n(* [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- here *)\n reflexivity.\n Case \"b = false\". (* <---- and here *)\n rewrite <- H.\n reflexivity.\nQed.\n\n(** [Case] does something very straightforward: It simply adds a\n string that we choose (tagged with the identifier \"Case\") to the\n context for the current goal. When subgoals are generated, this\n string is carried over into their contexts. When the last of\n these subgoals is finally proved and the next top-level goal\n becomes active, this string will no longer appear in the context\n and we will be able to see that the case where we introduced it is\n complete. Also, as a sanity check, if we try to execute a new\n [Case] tactic while the string left by the previous one is still\n in the context, we get a nice clear error message.\n\n For nested case analyses (e.g., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c H.\n destruct c.\n Case \"c = true\".\n reflexivity.\n Case \"c = false\".\n rewrite <- H.\n destruct b.\n SCase \"b = true\".\n reflexivity.\n SCase \"b = false\".\n reflexivity.\nQed.\n\n\n(** [] *)\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left using a simple argument. The fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on like this we'll never be done. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAbort.\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (basic_induction) *)\n\n(** Prove the following lemmas using induction. You might need\n previously proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n S (n + m) = n + (S m).\nProof. \n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n intros m. simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. intros m. rewrite plus_0_r. reflexivity.\n Case \"n = S n'\".\n intros m. rewrite <- plus_n_Sm.\n simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n intros m p.\n simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (double_plus) *)\n\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | 0 => 0\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite IHn'.\n rewrite plus_n_Sm. reflexivity.\nQed.\n\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction]. \n\n(* FILL IN HERE *)\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n).\n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n\n assert (H: n + m = m + n).\n rewrite -> plus_comm. reflexivity.\n rewrite H. reflexivity.\nQed.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n intros m n p.\n assert (H: n + (m + p) = (n + m) + p).\n rewrite plus_assoc. reflexivity.\n assert (K: m + (n + p) = (m + n) + p).\n rewrite plus_assoc. reflexivity.\n rewrite H. rewrite K.\n assert (L: m + n = n + m).\n rewrite plus_comm. reflexivity.\n rewrite L. reflexivity.\nQed.\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\n\nTheorem mult_1_r : forall n : nat,\n n * 1 = n.\nProof.\n induction n as [| n'].\n Case \"base\". simpl. reflexivity.\n Case \"step\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem mult_Sm : forall m n : nat,\n n * S m = n + n * m.\nProof.\n intros m n.\n induction n as [| n'].\n Case \"base\". simpl. reflexivity.\n Case \"step\". simpl. rewrite IHn'.\n rewrite plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros m n.\n induction m as [| m'].\n Case \"base\". rewrite mult_0_r. simpl. reflexivity.\n Case \"step\". simpl. rewrite mult_Sm. rewrite IHm'.\n reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\n\n(** Prove the following simple fact: *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n intros n.\n induction n as [| n'].\n Case \"base\". simpl. reflexivity.\n Case \"step\". simpl.\n rewrite IHn'. rewrite negb_involutive.\n\n destruct n' as [| c].\n SCase \"n' = 0\". simpl. reflexivity.\n SCase \"n' = S c\". simpl. reflexivity.\nQed.\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n intros n.\n induction n as [| n'].\n Case \"base\". simpl. reflexivity.\n Case \"step\". simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n intros n.\n destruct n as [| n'].\n Case \"0\". simpl. reflexivity.\n Case \"S n'\". simpl. reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\n(** Prove the following theorem. Putting [true] on the left-hand side\nof the equality may seem odd, but this is how the theorem is stated in\nthe standard library, so we follow suit. Since rewriting \nworks equally well in either direction, we will have no \nproblem using the theorem no matter which way we state it. *)\n\nTheorem beq_nat_refl : forall n : nat, \n true = beq_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal. \n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. \n*)\n\nTheorem plus_swap' : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (binary_commute) *)\n(** Recall the [increment] and [binary-to-unary] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that these functions commute -- that is, incrementing a binary\n number and then converting it to unary yields the same result as\n first converting it to unary and then incrementing.\n\n (Before you start working on this exercise, please copy the\n definitions from your solution to the [binary] exercise here so\n that this file can be graded on its own. If you find yourself\n wanting to change your original definitions to make the property\n easier to prove, feel free to do so.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n\n Again, feel free to change your earlier definitions if this helps\n here. \n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Advanced Material *)\n\n(** ** Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millenia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity. \n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician might write it something like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show \n 0 + (m + p) = (0 + m) + p. \n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident: Coq has been designed so that its [induction] tactic\n generates the same sub-goals, in the same order, as the bullet\n points that a mathematician would write. But there are\n significant differences of detail: the formal proof is much more\n explicit in some ways (e.g., the use of [reflexivity]) but much\n less explicit in others (in particular, the \"proof state\" at any\n given point in the Coq proof is completely implicit, whereas the\n informal proof reminds the reader several times where things\n stand). *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n']. \n Case \"n = 0\".\n reflexivity. \n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n \n Proof: (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n \n Theorem: [true = beq_nat n n] for any [n].\n \n Proof: (* FILL IN HERE *)\n[]\n *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "sftypes", "repo": "software-foundations", "sha": "6d3754608420aeb5dfe8abfe2275a623f0083459", "save_path": "github-repos/coq/sftypes-software-foundations", "path": "github-repos/coq/sftypes-software-foundations/software-foundations-6d3754608420aeb5dfe8abfe2275a623f0083459/begriffs_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.10706425693868046}} {"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableWalk.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n Definition data_create_spec (g_rd: Pointer) (data_addr: Z64) (map_addr: Z64) (g_data': Pointer) (g_src: Pointer) (adt: RData) : option (RData * Z64) :=\n match map_addr, data_addr with\n | VZ64 map_addr, VZ64 data_addr =>\n rely is_int64 map_addr; rely is_int64 data_addr;\n let idx0 := __addr_to_idx map_addr 0 in\n let idx1 := __addr_to_idx map_addr 1 in\n let idx2 := __addr_to_idx map_addr 2 in\n let idx3 := __addr_to_idx map_addr 3 in\n let ret_idx := idx3 in\n rely (peq (base g_rd) ginfo_loc);\n rely (peq (base g_data') ginfo_loc);\n rely (peq (base g_src) ginfo_loc);\n rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n rely prop_dec ((buffer (priv adt)) @ SLOT_NS = None);\n let rd_gidx := (offset g_rd) in\n let data_gidx := offset g_data' in\n let src_gidx := offset g_src in\n let grd := (gs (share adt)) @ rd_gidx in\n rely prop_dec (__addr_to_gidx data_addr = data_gidx);\n rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n rely prop_dec (glock grd = Some CPU_ID);\n let root_gidx := (g_rtt (gnorm grd)) in\n rely is_gidx rd_gidx; rely is_gidx root_gidx; rely is_gidx src_gidx; rely is_gidx data_gidx;\n when adt == query_oracle adt;\n (* hold root lock *)\n let adt := adt {log: EVT CPU_ID (ACQ root_gidx) :: log adt} in\n let groot := (gs (share adt)) @ root_gidx in\n rely (tbl_level (gaux groot) =? 0);\n rely prop_dec (glock groot = None);\n rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n rely (gtype groot =? GRANULE_STATE_TABLE);\n (* walk deeper root *)\n let entry0 := (g_data (gnorm groot)) @ idx0 in\n rely is_int64 entry0;\n let phys0 := __entry_to_phys entry0 3 in\n let lv1_gidx := __addr_to_gidx phys0 in\n if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n (* level 1 valid, hold level 1 lock *)\n let adt := adt {log: EVT CPU_ID (REL root_gidx groot {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv1_gidx) :: log adt} in\n let glv1 := (gs (share adt)) @ lv1_gidx in\n rely prop_dec (glock glv1 = None);\n rely (tbl_level (gaux glv1) =? 1);\n (* walk deeper level 1 *)\n rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n rely (gtype glv1 =? GRANULE_STATE_TABLE);\n let entry1 := (g_data (gnorm glv1)) @ idx1 in\n rely is_int64 entry1;\n let phys1 := __entry_to_phys entry1 3 in\n let lv2_gidx := __addr_to_gidx phys1 in\n if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n (* level 2 valid, hold level 2 lock *)\n when adt == query_oracle adt;\n let adt := adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv2_gidx) :: log adt} in\n let glv2 := (gs (share adt)) @ lv2_gidx in\n rely (tbl_level (gaux glv2) =? 2);\n rely prop_dec (glock glv2 = None);\n (* walk deeper level 2 *)\n rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);\n rely (gtype glv2 =? GRANULE_STATE_TABLE);\n let entry2 := (g_data (gnorm glv2)) @ idx2 in\n rely is_int64 entry2;\n let phys2 := __entry_to_phys entry2 3 in\n let lv3_gidx := __addr_to_gidx phys2 in\n if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then\n (* level 2 valid, hold level 2 lock *)\n when adt == query_oracle adt;\n let adt := adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv3_gidx) :: log adt} in\n let glv3 := (gs (share adt)) @ lv3_gidx in\n rely prop_dec (glock glv3 = None);\n rely (tbl_level (gaux glv3) =? 3);\n let adt := adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in\n (* create data *)\n let llt_gidx := lv3_gidx in\n let idx := idx3 in\n let gn_llt := (gs (share adt)) @ llt_gidx in\n let gn_data := (gs (share adt)) @ data_gidx in\n let gn_src := (gs (share adt)) @ src_gidx in\n rely (g_tag (ginfo gn_llt) =? GRANULE_STATE_TABLE);\n rely (gtype gn_llt =? GRANULE_STATE_TABLE);\n rely (gtype gn_data =? GRANULE_STATE_DELEGATED);\n rely (g_tag (ginfo gn_src) =? GRANULE_STATE_NS);\n rely (gtype gn_src =? GRANULE_STATE_NS);\n rely prop_dec (glock gn_data = Some CPU_ID);\n rely (tbl_level (gaux gn_data) =? 0);\n let llt_pte := (g_data (gnorm gn_llt)) @ idx in\n rely is_int64 llt_pte;\n if PTE_TO_IPA_STATE llt_pte =? IPA_STATE_VACANT then\n let e := EVT CPU_ID (COPY_NS src_gidx (READ_DATA data_gidx)) in\n let gdata' := gn_data {gnorm: (gnorm gn_data) {g_data: g_data (gnorm gn_src)}}\n {gaux: mkAuxillaryVars 0 0 map_addr} in\n let pte_val := Z.lor (IPA_STATE_TO_PTE IPA_STATE_ABSENT) data_addr in\n let llt' := (g_data (gnorm gn_llt)) # idx == pte_val in\n let gllt' := gn_llt {ginfo : (ginfo gn_llt) {g_refcount : g_refcount (ginfo gn_llt) + 1}}\n {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n let cp := EVT CPU_ID (COPY_NS src_gidx (READ_DATA data_gidx)) in\n Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: cp :: log adt}\n {share : (share adt) {gs : ((gs (share adt)) # data_gidx == gdata') # llt_gidx == gllt'}},\n VZ64 0)\n else Some (adt {log: EVT CPU_ID (REL llt_gidx gn_llt {glock: Some CPU_ID}) :: log adt}, VZ64 1)\n else\n (* level 3 invalid *)\n Some (adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: log adt}\n {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n else\n (* level 2 invalid *)\n Some (adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: log adt}\n {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n else\n (* level 1 invalid *)\n Some (adt {log: EVT CPU_ID (REL root_gidx groot {glock: Some CPU_ID}) :: log adt}\n {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsIntro/Specs/data_create.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.20689404148054266, "lm_q1q2_score": 0.10425518414774498}} {"text": "Require Import OptionSumbool.\nRequire Import Morphisms.\nRequire Import AccessRights.\nRequire Import References.\nRequire Import Capabilities.\nRequire Import Indices.\nRequire Import Objects.\nRequire Import ObjectLabels.\nRequire Import SystemState.\nRequire Import SemanticsDefinitions.\nRequire Import Semantics.\nRequire Import Semantics_Conv.\nRequire Import AccessRightSets.\nRequire Import Execution.\nRequire Import RefSets.\nRequire Import Basics.\nRequire Import Attenuation.\nRequire Import OptionMap2.\nRequire Import RelationClasses.\nRequire Import Iff_Equiv.\nRequire Import AccessEdge.\nRequire Import AccessGraphs.\nRequire Import SequentialAccess.\n\n\nModule MakeAccessExecution (Ref:ReferenceType) (RefS: RefSetType Ref) (Edges: AccessEdgeType Ref) (AccessGraph:AccessGraphType Ref Edges) (Seq:SeqAccType Ref RefS Edges AccessGraph) (Cap:CapabilityType Ref) (Ind:IndexType) (Obj:ObjectType Ref Cap Ind) (Sys:SystemStateType Ref Cap Ind Obj) (SemDefns: SemanticsDefinitionsType Ref Cap Ind Obj Sys) (Sem: SemanticsType Ref RefS Cap Ind Obj Sys SemDefns) (Exe: ExecutionType Ref RefS Cap Ind Obj Sys SemDefns Sem).\n\n Module DT := MakeAttenuation Ref RefS Edges AccessGraph Seq Cap Ind Obj Sys SemDefns Sem.\n Import DT.\n Export DT.\n\n(* Import Seq.RefSet_Mod. *)\n Import RefS.\n\n Theorem ag_objs_spec_subset: forall a b Na Nb, AG.Subset a b -> \n Seq.ag_objs_spec a Na -> Seq.ag_objs_spec b Nb -> RefSet.Subset Na Nb.\n Proof.\n unfold Seq.ag_objs_spec; red. intros a b Na Nb Hsub Hobjs_a Hobjs_b x Hx.\n apply Hobjs_a in Hx; destruct Hx as [obj [rgt [Hedge | Hedge]]]; eapply Hsub in Hedge;\n apply Hobjs_b; do 2 eapply ex_intro; [left|right];apply Hedge.\n Qed.\n\n Theorem dirAcc_dep_compose : forall Fs, Proper (Sys.eq ==> Sys.eq) Fs ->\n forall Fsa, dirAcc_approx_dep Fs Fsa -> forall Fs' Fsa', dirAcc_approx_dep Fs' Fsa' ->\n dirAcc_approx_dep (compose Fs' Fs) (fun s => (compose (Fsa' (Fs s)) (Fsa s))).\n Proof.\n unfold dirAcc_approx_dep; unfold compose; \n intros Fs HeqF Fsa Hdep Fs' Fsa' Hdep' s s' ag ag' ag2 Hda Hda2 Hsub Heq.\n (* apply Hdep' over subset, but instantiate dirAcc first *)\n generalize (exists_dirAcc_spec (Fs s)); intros [daF' HdaF'].\n eapply Hdep'; [apply HdaF'| apply Hda2| | apply HeqF; apply Heq].\n eapply Hdep; [ apply Hda | apply HdaF' | apply Hsub | apply Heq].\n Qed.\n\n Implicit Arguments dirAcc_dep_compose [Fs Fsa Fs' Fsa'].\n\n Theorem potAcc_eq_iff: forall i p, Seq.potAcc i p -> \n forall i', AG.eq i i' -> forall p', AG.eq p p' -> Seq.potAcc i' p'.\n Proof.\n intros i p Hpa i' Heq p' Heq'.\n destruct Hpa as [Htrans Hmax]. \n split;\n [ eapply Seq.potTransfer_eq; [apply Heq| apply Heq' | auto]\n | red; intros a Htrans';\n eapply AG.eq_trans; [apply AG.eq_sym; apply Heq' | ]; apply Hmax;\n eapply Seq.potTransfer_eq; [apply AG.eq_sym; apply Heq'| apply AG.eq_refl | auto]\n ].\n Qed.\n\n \n Theorem potAcc_approx_dirAcc_dep_compose: forall Fs, Proper (Sys.eq ==> Sys.eq) Fs ->\n forall Fsa, dirAcc_approx_dep Fs Fsa -> Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa -> \n forall Fp, potAcc_approx_dirAcc_dep Fsa Fp -> \n forall (Fs':Sys.t->Sys.t) Fsa', Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa' ->\n forall Fp', potAcc_approx_dirAcc_dep Fsa' Fp' -> \n potAcc_approx_dirAcc_dep (fun s => (compose (Fsa' (Fs s)) (Fsa s))) (fun s => (compose (Fp' (Fs s)) (Fp s))).\n Proof.\n intros Fs HeqF Fsa HdaX HeqFsa Fp HpaX Fs' Fsa' HeqFsa' Fp' HpaX' \n i i' p p' p2 s s' s'' Heq Heq' Hda Hsub Hpa Hpa' Hsub'.\n generalize (exists_dirAcc_spec (Fs s)); intros [i3 Hda3].\n generalize (HdaX _ _ _ _ _ Hda Hda3 Hsub (Sys.eq_refl _)); intros HdaXi.\n generalize (Seq.exists_potAcc (Fsa s i')); intros [p3 Hpa3].\n eapply HpaX'; \n [ apply Sys.eq_refl\n | apply HeqF; eapply Sys.eq_trans; [apply Heq| apply Heq']\n | apply Hda3\n | apply HdaXi\n | apply Hpa3\n | eapply potAcc_eq_iff in Hpa'; [ apply Hpa'| | apply AG.eq_refl];\n eapply HeqFsa';\n [eapply HeqF; auto\n | eapply HeqFsa; [auto |apply AG.eq_refl]]\n | eapply HpaX; \n [ apply Sys.eq_refl\n | eapply Sys.eq_trans; [apply Heq | apply Heq']\n | apply Hda \n | apply Hsub\n | apply Hpa\n | apply Hpa3\n | apply Hsub'\n ]\n ].\n Qed.\n\n\n(* This needs to change to capture s in the function *)\n(* Perhaps this fixpoint will work better? *)\n \n(* not efficient, but closer to inductive *)\n Fixpoint dirAcc_execute op_list s : (AG.t -> AG.t) :=\n match op_list with\n | nil => id_ag\n | cons op tail => compose (dirAcc_op op (Exe.execute s tail)) (dirAcc_execute tail s)\n end.\n \n Inductive dirAcc_execute_spec : list Sem.operation -> (Sys.t -> AG.t -> AG.t) -> Prop:=\n | dirAcc_execute_spec_nil : dirAcc_execute_spec nil (fun (s:Sys.t) (a:AG.t)=> a)\n | dirAcc_execute_spec_cons : forall op op_list Fp, dirAcc_execute_spec op_list Fp ->\n dirAcc_execute_spec (cons op op_list) (fun s => compose (dirAcc_op op (Exe.execute s op_list)) (Fp s)).\n \n Theorem dirAcc_execute_spec_dirAcc_execute: forall op_list,\n dirAcc_execute_spec op_list (dirAcc_execute op_list).\n Proof.\n intros.\n induction op_list; simpl.\n (* base *)\n apply dirAcc_execute_spec_nil.\n (* step *)\n apply dirAcc_execute_spec_cons; auto.\n Qed.\n\n Theorem dirAcc_execute_spec_eq_iff: forall opList Fsa,\n dirAcc_execute_spec opList Fsa <-> Fsa = (dirAcc_execute opList).\n Proof.\n intros opList.\n induction opList.\n intros; split; intros.\n inversion H.\n simpl in *.\n eauto.\n \n rewrite H; eapply dirAcc_execute_spec_dirAcc_execute.\n \n intros; split; intros.\n inversion H.\n eapply IHopList in H3.\n unfold dirAcc_execute in *.\n rewrite <- H3. auto.\n\n rewrite H; eapply dirAcc_execute_spec_dirAcc_execute.\n \n Qed.\n\n Fixpoint potAcc_execute op_list s : (AG.t -> AG.t) := \n match op_list with\n | nil => id_ag\n | cons op tail => compose (potAcc_op op (Exe.execute s tail)) (potAcc_execute tail s)\n end.\n\n Inductive potAcc_execute_spec : list Sem.operation -> (Sys.t -> AG.t -> AG.t) -> Prop:=\n | potAcc_execute_spec_nil : potAcc_execute_spec nil (fun (s:Sys.t) (a:AG.t)=> a)\n | potAcc_execute_spec_cons : forall op op_list Fp, potAcc_execute_spec op_list Fp ->\n potAcc_execute_spec (cons op op_list) (fun s => compose (potAcc_op op (Exe.execute s op_list)) (Fp s)).\n \n Theorem potAcc_execute_spec_potAcc_execute: forall op_list,\n potAcc_execute_spec op_list (potAcc_execute op_list).\n Proof.\n intros.\n induction op_list; simpl.\n (* base *)\n apply potAcc_execute_spec_nil.\n (* step *)\n apply potAcc_execute_spec_cons; auto.\n Qed.\n\n Theorem potAcc_execute_spec_eq_iff: forall opList Fsa,\n potAcc_execute_spec opList Fsa <-> Fsa = (potAcc_execute opList).\n Proof.\n intros opList.\n induction opList.\n intros; split; intros.\n inversion H.\n simpl in *.\n eauto.\n \n rewrite H; eapply potAcc_execute_spec_potAcc_execute.\n \n intros; split; intros.\n inversion H.\n eapply IHopList in H3.\n unfold potAcc_execute in *.\n rewrite <- H3. auto.\n\n rewrite H; eapply potAcc_execute_spec_potAcc_execute.\n \n Qed.\n\n\n (* Inductive potAcc_execute_spec :(list Sem.operation) -> Sys.t -> (AG.t -> AG.t) -> Prop := *)\n (* | potAcc_execute_spec_nil : forall s, potAcc_execute_spec nil s id_ag *)\n (* | potAcc_execute_spec_cons: forall l s Fp, potAcc_execute_spec l s Fp -> *)\n (* forall op, potAcc_execute_spec (cons op l) (Sem.do_op op s) (compose (potAcc_op op s) Fp). *)\n\n(* First, demonstrate that execution is approximated by potAcc_execute_spec *)\n\n (* I didn't write an operation_eq relation, so we will use eq and hope this doesn't hurt us in the long run *)\n Theorem execute_proper_1 : Proper (Sys.eq ==> eq ==> Sys.eq) Exe.execute.\n Proof.\n unfold Proper; unfold respectful; intros.\n rewrite H0; clear H0; clear x0.\n induction y0; simpl in *; [| apply SemConv.do_op_eq]; auto.\n Qed.\n\n Theorem dirAcc_execute_approx : \n forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->\n dirAcc_approx_dep (fun s => (Exe.execute s op_list)) Fsa.\n Proof.\n \n intros; induction H.\n (* base *)\n unfold dirAcc_approx_dep in *; simpl in *; intros.\n eapply AGProps.subset_trans;\n [apply AGProps.subset_equal;\n eapply dirAcc_spec_eq;\n [apply Sys.eq_refl\n |apply H0\n |apply H\n ]\n |auto\n ].\n (* step *)\n eapply dirAcc_dep_compose; auto; try apply dirAcc_approx_dep_op.\n (* Execute is proper *)\n unfold Proper; unfold respectful; intros; eapply execute_proper_1; auto.\n Qed.\n\n Theorem proper_dirAcc_op: forall op,\n Proper (Sys.eq ==> AG.eq ==> AG.eq) (dirAcc_op op).\n Proof.\n unfold dirAcc_op; unfold Proper; unfold respectful; intros.\n destruct op; simpl; auto.\n (* id_ag cases solved , 4 cases remain*)\n\n (* fetch *)\n case (SemDefns.fetch_preReq_dec t t0 x);\n case (SemDefns.fetch_preReq_dec t t0 y); intros; eauto;\n (* eauto handles the no_op case. Solve portion handles contradiciton cases. *)\n try solve [eapply SemDefns.fetch_preReq_eq_iff in f; try apply Ref.eq_refl;\n try apply Ind.eq_refl; eauto; contradiction].\n\n eapply ag_add_cap_by_indirect_index_equiv; eauto; try apply Ref.eq_refl.\n case ( SemDefns.option_hasRight_dec (SC.getCap t0 t x));\n case ( SemDefns.option_hasRight_dec (SC.getCap t0 t y)); intros; auto;\n (* auto handles the two easy cases, this handles the contradictory cases *)\n eapply SemDefns.option_hasRight_eq in o; solve \n [apply n in o; contradiction\n | auto\n | apply Ref.eq_refl\n | apply AccessRight.eq_refl\n ].\n \n (* store *)\n case (SemDefns.store_preReq_dec t t0 x);\n case (SemDefns.store_preReq_dec t t0 y); intros; eauto;\n (* eauto handles the no_op case. Solve portion handles contradiciton cases. *)\n try solve [eapply SemDefns.store_preReq_eq_iff in s; try apply Ref.eq_refl;\n try apply Ind.eq_refl; eauto; contradiction].\n eapply ag_push_cap_by_indices_equiv; eauto; try apply Ref.eq_refl.\n\n (* send *)\n case (SemDefns.send_preReq_dec t t0 x);\n case (SemDefns.send_preReq_dec t t0 y); intros; eauto;\n (* eauto handles the no_op case. Solve portion handles contradiciton cases. *)\n try solve [eapply SemDefns.send_preReq_eq_iff in s; try apply Ref.eq_refl;\n try apply Ind.eq_refl; eauto; contradiction].\n unfold send_dep_ag.\n destruct s as [s_1 s_2]; destruct s0 as [s0_1 s0_2].\n unfold SemDefns.option_hasRight in *.\n (case (option_sumbool (SC.getCap t0 t x)); intros opt1; [|destruct opt1 as [v1 opt1]]; try rewrite opt1 in *;\n (case (option_sumbool (SC.getCap t0 t y)); intros opt2; [|destruct opt2 as [v2 opt2]]; try rewrite opt2 in *);\n simpl in *; try contradiction).\n generalize H; intros H'.\n eapply SC.getCap_eq with (i:=t0) (o:=t) in H'; [ | apply Ind.eq_refl | apply Ref.eq_refl ].\n rewrite opt1 in H'; rewrite opt2 in H'; simpl in H'.\n eapply Cap.target_eq in H'.\n \n case (option_map1_eq_tgt_dec t0 t x);\n case (option_map1_eq_tgt_dec t0 t y); intros; eauto;\n try rewrite opt1 in *; try rewrite opt2 in *; simpl in *;\n try solve [rewrite H' in *; contradiction\n | eapply ag_add_caps_reply_equiv; eauto; try apply Ref.eq_refl\n | eapply ag_add_caps_send_equiv; eauto; try apply Ref.eq_refl; try apply CIL_Facts.cil_Equiv\n ].\n\n (* allocate *)\n unfold allocate_dep_ag.\n case (SemDefns.allocate_preReq_dec t t0 x);\n case (SemDefns.allocate_preReq_dec t t0 y); intros; eauto;\n (* eauto handles the no_op case. Solve portion handles contradiciton cases. *)\n try solve [eapply SemDefns.allocate_preReq_eq_iff in a; try apply Ref.eq_refl;\n try apply Ind.eq_refl; eauto; contradiction].\n eapply ag_add_caps_allocate_equiv; eauto; try apply Ref.eq_refl; try apply CIL_Facts.cil_Equiv.\n Qed.\n\n\n Theorem dirAcc_execute_spec_proper : forall op_list Fsa,\n dirAcc_execute_spec op_list Fsa -> Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa.\n Proof.\n intros op_list Fsa H.\n induction H; auto.\n (* step *)\n unfold Proper; unfold respectful; intros.\n eapply proper_dirAcc_op.\n eapply execute_proper_1; auto.\n eapply IHdirAcc_execute_spec; auto.\n Qed.\n \n Hint Resolve proper_dirAcc_op dirAcc_execute_spec_proper.\n\n\n Theorem potAcc_execute_approx :\n forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->\n forall Fp, potAcc_execute_spec op_list Fp ->\n potAcc_approx_dirAcc_dep Fsa Fp.\n Proof.\n intros. revert H. revert Fsa.\n induction H0.\n (* base *)\n unfold potAcc_approx_dirAcc_dep. intros.\n inversion H. rewrite <- H8 in H5.\n eapply AGProps.subset_trans; [ | apply H6].\n apply AGProps.subset_equal.\n eapply potAcc_equiv; try apply AG.eq_refl; eauto.\n (* step *)\n intros. inversion H.\n eapply potAcc_approx_dirAcc_dep_compose; \n try solve \n [auto \n | (* execute is proper *)\n unfold Proper; unfold respectful; intros; eapply execute_proper_1; auto\n | (* dirAcc_approx_dep *)\n apply dirAcc_execute_approx; auto\n | (* potAcc_approx_dirAcc_dep (dirAcc_op op) (potAcc_op op) *)\n apply potAcc_approx_dirAcc_dep_op; auto\n | eauto\n ].\n Qed.\n\n(* Second, demonstrate that such approximation is reducing over the existing objs *)\n\n\n Theorem Proper_AG_attenuating :\n Proper (RefSet.eq ==> AG.eq ==> AG.eq ==> iff) AG_attenuating.\n Proof.\n unfold Proper. unfold respectful. unfold AG_attenuating; intros.\n split; intros;\n \n (case (Ref.eq_dec src tgt); intros Heq;\n [intuition eauto \n | right; edestruct H2; \n [ eapply H; apply H3 \n | eapply H; apply H4 \n | intro Hnot; apply H5; apply H0; apply Hnot\n | contradiction \n | intro Hnot; apply H6; apply H1; apply Hnot\n ]\n ]). \n\n Qed.\n\n Theorem Proper_AG_attenuating_2 :\n Proper (RefSet.eq ==> AG.eq ==> AG.Subset --> impl) AG_attenuating.\n Proof.\n unfold Proper. unfold respectful. unfold impl. unfold flip; unfold AG_attenuating; intros.\n \n case (Ref.eq_dec src tgt); intros Heq; [intuition eauto | ].\n right; edestruct H2;\n [eapply H; apply H3\n | eapply H; apply H4\n | intro Hnot; apply H5; apply H0; apply Hnot\n | contradiction\n | intro Hnot; apply H6; apply H1; apply Hnot].\n\n Qed.\n\n Theorem Proper_AG_attenuating_3:\n Proper (RefSet.Subset --> AG.eq ==> AG.Subset --> impl) AG_attenuating.\n Proof.\n unfold Proper; unfold respectful; unfold impl; unfold flip; intros.\n eapply AG_attenuating_subset_objs; [ | apply H].\n eapply Proper_AG_attenuating_2; eauto. apply RefSet.eq_refl.\n Qed.\n\n Theorem Proper_AG_attenuating_4:\n Proper (RefSet.Subset --> AG.Subset ==> AG.Subset --> impl) AG_attenuating.\n Proof.\n unfold Proper; unfold respectful; unfold impl; unfold flip; intros. \n unfold AG_attenuating in *; intros.\n case (Ref.eq_dec src tgt); try solve [intuition auto]; right.\n edestruct H2;\n [ eapply H; apply H3\n | eapply H; apply H4\n | intro Hnot; apply H5; apply H0; apply Hnot\n | contradiction\n | intro Hnot; apply H6; apply H1; apply Hnot].\n Qed.\n\n (* Helper functions for objs_not_unborn *)\n \n Theorem is_label_id: forall s s', Sys.eq s s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros s s' Heq o lbl; split; intros Hlbl;\n (eapply SC.isLabel_eq;\n [eapply Ref.eq_refl\n |eapply ObjectLabel.eq_refl\n |eauto\n |auto]).\n Qed.\n Theorem is_label_read: forall a t s s', Sys.eq (Sem.do_read a t s) s' -> \n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t s s' Heq;\n eapply Sys.eq_trans in Heq; \n [eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.read_spec].\n Qed.\n\n Theorem is_label_write: forall a t s s', Sys.eq (Sem.do_write a t s) s' -> \n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t s s' Heq;\n eapply Sys.eq_trans in Heq; \n [eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.write_spec].\n Qed.\n\n Theorem is_label_fetch_invalid: forall a t c i s s', Sys.eq (Sem.do_fetch a t c i s) s' ->\n ~ SemDefns.fetch_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.fetch_invalid; eauto].\n Qed.\n\n Theorem is_label_copyCap: forall c t i a s s', Sys.eq (SemDefns.SC.copyCap c t i a s) s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros c t i a s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;\n \n (* first case *)\n (case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]]; \n try rewrite Hcase in *; simpl in *; try solve [contradiction];\n (* second case *)\n (case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']]; \n try rewrite Hcase' in *; simpl in *; try solve [contradiction];\n (* getLabel equiv and solv *)\n (eapply SC.getLabel_copyCap_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;\n try solve \n [contradiction \n | eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).\n Qed.\n\n\n (* move the next two Theorems to systemstate_convimpl *)\n Theorem getLabel_weakCopyCap_map_eq: forall s i o i' o' i_src opt_i_lbl opt_i_lbl',\n SC.getLabel i_src s = opt_i_lbl ->\n SC.getLabel i_src (SC.weakCopyCap i o i' o' s) = opt_i_lbl' ->\n option_map_eq ObjectLabel.eq opt_i_lbl opt_i_lbl'.\n Proof.\n intros s i o i' o' i_src opt_i_lbl opt_i_lbl' Hi_lbl Hi_lbl'.\n unfold SC.weakCopyCap in *; unfold SC.getCap in *; unfold SC.getObj in *.\n\n case (option_sumbool (SC.getObjTuple o s)); intros Hopt1;\n [| destruct Hopt1 as [o'_tuple Hopt1]]; rewrite Hopt1 in *; simpl in *; auto;\n try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].\n destruct_tuple o'_tuple o'_obj o'_lbl o'_type o'_sched; simpl in *.\n\n case (option_sumbool (OC.getCap i o'_obj)); intros Hopt2;\n [| destruct Hopt2 as [copied_cap Hopt2]]; rewrite Hopt2 in *; simpl in *; auto;\n try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].\n\n unfold SC.addCap in *; unfold SC.getLabel in *;\n unfold SC.getObj in *; unfold SC.updateObj in *.\n\n case (option_sumbool (SC.getObjTuple o' s)); intros Hopt3;\n [|destruct Hopt3 as [t_tuple Hopt3]; destruct_tuple t_tuple t_obj t_lbl t_type t_sched];\n rewrite Hopt3 in *; simpl in *;\n try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto]. \n\n unfold SC.addObjTuple in *; unfold SC.getObjTuple in *; unfold OC.addCap in *.\n \n case (Ref.eq_dec o' i_src ); intros Heq1.\n (* i_src [=] o' *)\n rewrite Sys_Facts.add_eq_o in Hi_lbl'; simpl in *; auto.\n unfold SC.tupleGetLabel in *.\n rewrite Heq1 in *; rewrite Hopt3 in *; simpl in *;\n try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].\n\n (* i_src [<>] o' *)\n rewrite Sys_Facts.add_neq_o in Hi_lbl'; simpl in *; auto;\n try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].\n Qed.\n\n Theorem getLabel_weakCopyCap_map_eq_equiv: forall s i o i' o' i_src s' opt_i_lbl opt_i_lbl',\n Sys.eq (SC.weakCopyCap i o i' o' s) s' ->\n SC.getLabel i_src s = opt_i_lbl ->\n SC.getLabel i_src s' = opt_i_lbl' ->\n option_map_eq ObjectLabel.eq opt_i_lbl opt_i_lbl'.\n Proof.\n intros.\n eapply option_map_eq_transitive; \n [eauto\n |\n |rewrite <- H1; eapply SC.getLabel_eq; [eapply Ref.eq_refl| eapply H]].\n \n rewrite <- H0.\n eapply getLabel_weakCopyCap_map_eq; eapply eq_refl.\n Qed.\n\n\n Theorem is_label_weakCopyCap: forall c t i a s s', Sys.eq (SemDefns.SC.weakCopyCap c t i a s) s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros c t i a s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;\n \n (* first case *)\n (case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]]; \n try rewrite Hcase in *; simpl in *; try solve [contradiction];\n (* second case *)\n (case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']]; \n try rewrite Hcase' in *; simpl in *; try solve [contradiction];\n (* getLabel equiv and solv *)\n (eapply getLabel_weakCopyCap_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;\n try solve \n [contradiction \n | eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).\n Qed.\n\n Theorem is_label_fetch_valid: forall a t c i s s', Sys.eq (Sem.do_fetch a t c i s) s' ->\n SemDefns.fetch_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hfetch_prereq.\n case (SemDefns.option_hasRight_dec (SemDefns.SC.getCap t a s) rd); intros Hread'.\n\n\n generalize Hfetch_prereq; intros [Hprereq Hopt];\n eapply Sys.eq_trans in Heq;\n [ \n | eapply Sys.eq_sym; eapply Sem.fetch_read; eauto].\n (* has read *)\n destruct Hprereq as [[Halive Hactive] Htarget_alive].\n unfold SemDefns.target_is_alive in *.\n case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];\n rewrite Hcap in *; simpl in *; try contradiction.\n eapply is_label_copyCap; eauto.\n (* no read *)\n generalize Hfetch_prereq; intros [Hprereq [Hread | Hweak]]; try contradiction.\n eapply Sys.eq_trans in Heq;\n [ \n | eapply Sys.eq_sym; eapply Sem.fetch_weak; eauto].\n destruct Hprereq as [[Halive Hactive] Htarget_alive].\n unfold SemDefns.target_is_alive in *.\n case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];\n rewrite Hcap in *; simpl in *; try contradiction.\n unfold SC.weakCopyCap in *.\n eapply is_label_weakCopyCap; eauto.\n Qed.\n\n Theorem is_label_store_invalid: forall a t c i s s', Sys.eq (Sem.do_store a t c i s) s' ->\n ~ SemDefns.store_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.store_invalid; eauto].\n Qed.\n \n Theorem is_label_store_valid: forall a t c i s s', Sys.eq (Sem.do_store a t c i s) s' ->\n SemDefns.store_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hstore_prereq.\n\n generalize Hstore_prereq; intros [Hprereq Hright];\n eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.store_valid; eauto].\n\n destruct Hprereq as [[Halive Hactive] Htarget_alive].\n unfold SemDefns.target_is_alive in *.\n case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];\n rewrite Hcap in *; simpl in *; try contradiction.\n eapply is_label_copyCap; eauto.\n Qed.\n\n Theorem is_label_revoke_invalid: forall a t c s s', Sys.eq (Sem.do_revoke a t c s) s' ->\n ~ SemDefns.revoke_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.revoke_invalid; eauto].\n Qed.\n \n Theorem getLabel_updateObj_equiv: forall n o s s',\n Sys.eq (SC.updateObj n o s) s' -> forall a,\n SC.getLabel a s = SC.getLabel a s'.\n Proof.\n unfold SC.updateObj.\n unfold SC.getLabel.\n unfold SC.getObj.\n unfold SC.addObjTuple.\n unfold SC.getObjTuple.\n intros.\n case (option_sumbool (Sys.MapS.find n s)); intros Hcase; [|destruct Hcase as [[[[o' l'] t'] d'] Hcase]]; \n rewrite Hcase in *; simpl in *; auto.\n\n (* equiv *)\n \n generalize (Sys_MapEquiv.find_eq a _ _ _ (Ref.eq_refl _) H); intros Heq.\n \n case (option_sumbool (Sys.MapS.find a s));intros Hcase1; \n [|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;\n (case (option_sumbool (Sys.MapS.find a s'));intros Hcase2; \n [|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);\n try contradiction; auto.\n unfold SC.tupleGetLabel. \n destruct tup1 as [[[obj1 lbl1] sch1] typ1];\n destruct tup2 as [[[obj2 lbl2] sch2] typ2];\n destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *.\n rewrite Heq2 in *; auto.\n\n\n (* not equiv *)\n\n generalize (Sys_MapEquiv.find_eq a _ _ _ (Ref.eq_refl _) H); intros Heq.\n\n case (Ref.eq_dec a n); intros Heq_r.\n\n \n\n\n rewrite Sys_Facts.add_eq_o in Heq; simpl in *; auto; try contradiction.\n unfold Sys.P.t in *.\n case (option_sumbool (Sys.MapS.find a s));intros Hcase1; \n [|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;\n (case (option_sumbool (Sys.MapS.find a s'));intros Hcase2; \n [|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);\n try contradiction; auto; simpl in *;\n\n (try destruct tup1 as [[[obj1 lbl1] sch1] typ1];\n destruct tup2 as [[[obj2 lbl2] sch2] typ2];\n destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *;\n rewrite Heq2 in *; auto;\n rewrite Heq_r in *;\n rewrite Hcase in *;\n try solve [discriminate | injection Hcase1; intros H1 H2 H3 H4; rewrite H3; auto]).\n\n rewrite Sys_Facts.add_neq_o in Heq; simpl in *; auto; try contradiction.\n unfold Sys.P.t in *.\n case (option_sumbool (Sys.MapS.find a s));intros Hcase1; \n [|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;\n (case (option_sumbool (Sys.MapS.find a s'));intros Hcase2; \n [|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);\n try contradiction; auto; simpl in *.\n\n try destruct tup1 as [[[obj1 lbl1] sch1] typ1];\n destruct tup2 as [[[obj2 lbl2] sch2] typ2];\n destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *.\n \n rewrite Heq2; auto.\n Qed.\n Implicit Arguments getLabel_updateObj_equiv [n o s s'].\n\n Theorem is_label_rmCap: forall c t s s', Sys.eq (SC.rmCap c t s) s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros c t s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;\n unfold SC.rmCap in *;\n\n (case (option_sumbool (SC.getObj t s)); intros Hcase2; [| destruct Hcase2 as [obj Hcase2]];\n try rewrite Hcase2 in *; simpl in *; try contradiction);\n\n solve [\n (* equiv case *)\n case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']]; \n try rewrite Hcase' in *; simpl in *; try solve [contradiction];\n (case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]]; \n try rewrite Hcase in *; simpl in *; try solve [contradiction];\n (eapply SC.getLabel_eq with (r:=o) in Heq; [| eapply Ref.eq_refl];\n rewrite Hcase in Heq; rewrite Hcase' in Heq; simpl in *; \n solve [contradiction\n | eapply ObjectLabel.eq_trans; solve [eapply Sys.eq_sym; eauto | eauto]]))\n|\n (* second *)\n\n generalize (getLabel_updateObj_equiv Heq); intros Hrw;\n rewrite Hrw in *; auto].\n Qed.\n\n Theorem is_label_revoke_valid: forall a t c s s', Sys.eq (Sem.do_revoke a t c s) s' ->\n SemDefns.revoke_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c s s' Heq Hrevoke_prereq.\n\n generalize Hrevoke_prereq; intros [Hprereq Hright];\n eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.revoke_valid; eauto].\n\n destruct Hprereq as [[Halive Hactive] Htarget_alive].\n unfold SemDefns.target_is_alive in *.\n case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];\n rewrite Hcap in *; simpl in *; try contradiction.\n eapply is_label_rmCap; eauto.\n Qed.\n\n Theorem is_label_copyCapList: forall c t ixi_list s s', Sys.eq (SC.copyCapList c t ixi_list s) s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros c t ixi_list s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;\n \n (* first case *)\n (case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]]; \n try rewrite Hcase in *; simpl in *; try solve [contradiction];\n (* second case *)\n (case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']]; \n try rewrite Hcase' in *; simpl in *; try solve [contradiction];\n (* getLabel equiv and solv *)\n (eapply SC.getLabel_copyCapList_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;\n try solve \n [contradiction \n | eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).\n Qed.\n\n Theorem is_label_addCap: forall c a cap s s', Sys.eq (SC.addCap c cap a s) s' ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros c a cap s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;\n unfold SC.addCap in *; unfold SC.getObj in *;\n (case (option_sumbool (SC.getObjTuple a s)); intros Htuple; [| destruct Htuple as [[[[obj1 lbl1] typ1] schd1] Htuple]];\n rewrite Htuple in *; simpl in *; try contradiction;\n (case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]]; \n try rewrite Hcase in *; simpl in *; try solve [contradiction];\n (case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']]; \n try rewrite Hcase' in *; simpl in *; try solve [contradiction])));\n try solve [\n (* Solve s [=] s' cases *)\n first \n [ generalize (getLabel_updateObj_equiv Heq o); intros Hlbl_eq\n | generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl o) Heq); intros Hlbl_eq\n ];\n try rewrite Hcase' in Hlbl_eq; try rewrite Hcase in Hlbl_eq; try rewrite Hlbl_eq in *; simpl in *; \n (* attempt solutions *)\n try contradiction; try discriminate; auto;\n try solve [injection Hlbl_eq; intros Hlbl_eq'; rewrite Hlbl_eq' in *; auto]].\n Qed.\n\n Theorem is_label_send_valid: forall a t c i s s', Sys.eq (Sem.do_send a t c i s) s' ->\n SemDefns.send_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hsend_prereq.\n\n generalize Hsend_prereq; intros [Hprereq Hright];\n eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.send_valid; eauto].\n\n destruct Hprereq as [[Halive Hactive] Htarget_alive].\n unfold SemDefns.target_is_alive in *.\n case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];\n rewrite Hcap in *; simpl in *; try contradiction.\n case (option_sumbool i); intros Hi; [|destruct Hi as [i' Hi]]; rewrite Hi in *; simpl in *.\n (* no reply *)\n eapply is_label_copyCapList; eauto.\n (* has reply *)\n intros o lbl.\n\n eapply Sys.eq_trans in Heq; \n [|eapply SC.copyCapList_eq; [ eapply Ref.eq_refl | apply Ref.eq_refl | eapply CIL_Facts.cil_Equiv| ]].\n eapply iff_sym; eapply iff_trans; eapply iff_sym.\n eapply is_label_copyCapList; apply Heq.\n 2:apply Sys.eq_refl.\n eapply is_label_addCap; eapply Sys.eq_refl.\n Qed.\n\n Theorem is_label_send_invalid: forall a t c i s s', Sys.eq (Sem.do_send a t c i s) s' ->\n ~ SemDefns.send_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.send_invalid; eauto].\n Qed.\n\n Theorem is_label_allocate_invalid: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->\n ~ SemDefns.allocate_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t c i s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.allocate_invalid; eauto].\n Qed.\n\n Theorem is_label_allocate_valid: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->\n SemDefns.allocate_preReq a t s ->\n forall o lbl, (if (Ref.eq_dec o t) then \n SC.is_label o s unborn /\\ ObjectLabel.eq lbl alive \n else SC.is_label o s lbl) <-> \n SC.is_label o s' lbl.\n Proof.\n intros a t c i s s' Heq Hallocate_prereq o lbl.\n\n generalize Hallocate_prereq; intros [Halive Hunborn];\n eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.allocate_valid; eauto].\n\n generalize Hunborn; intros Hunborn'; eapply SC.is_label_iff_getLabel in Hunborn.\n\n eapply Sys.eq_trans in Heq.\n 2:eapply SC.addCap_eq; [ eapply Ind.eq_refl| eapply Cap.eq_refl | eapply Ref.eq_refl| ].\n eapply iff_trans.\n 2:eapply is_label_addCap; apply Heq.\n 2:apply Sys.eq_refl.\n\n clear Heq.\n \n eapply iff_trans.\n 2:eapply is_label_copyCapList;eapply Sys.eq_refl.\n\n (* cases of o [=] t *)\n case (Ref.eq_dec o t); intros Href_case.\n (* o [=] t *) \n rewrite Href_case in *.\n\n unfold SC.set_alive.\n unfold SC.is_label in *.\n unfold SC.is_unborn in *.\n\n rewrite SC.getLabel_set_label_eq_o; simpl; try apply Ref.eq_refl.\n rewrite SC.getLabel_updateObj_o.\n rewrite SC.getLabel_rmCapsByTarget_o.\n rewrite Hunborn in *; simpl.\n intuition (eauto; try apply ObjectLabel.eq_sym; auto).\n\n (* o [<>] t *)\n unfold SC.set_alive in *.\n unfold SC.is_label in *.\n unfold SC.is_unborn in *.\n\n rewrite SC.getLabel_set_label_neq_o; auto.\n rewrite SC.getLabel_updateObj_o.\n rewrite SC.getLabel_rmCapsByTarget_o; auto.\n eapply iff_refl.\n Qed.\n Implicit Arguments is_label_allocate_valid [a t c i s s' o lbl].\n\n Theorem is_label_allocate_valid_unborn: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->\n SemDefns.allocate_preReq a t s ->\n forall lbl, ObjectLabel.eq lbl unborn ->\n forall o, SC.is_label o s' lbl -> SC.is_label o s lbl.\n Proof.\n intros.\n eapply is_label_allocate_valid in H2; try eauto 1.\n revert H2; case (Ref.eq_dec o t); intros Hcase H2; intuition.\n eapply ObjectLabel.eq_trans in H1; [|apply ObjectLabel.eq_sym; apply H4]; discriminate H1.\n Qed.\n \n Require Import OptionMap2.\n\n\n \n\n Theorem is_label_destroy_valid: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->\n SemDefns.destroy_preReq a t s ->\n forall o lbl, (if (option_map_eq_dec Ref.eq_dec (Some o) (SemDefns.option_target (SC.getCap t a s))) then \n SC.is_label o s alive /\\ ObjectLabel.eq lbl dead \n else SC.is_label o s lbl) <-> \n SC.is_label o s' lbl.\n Proof.\n intros a t s s' Heq Hdestroy_prereq o lbl.\n\n generalize Hdestroy_prereq; intros [[[Halive Hactive] Htarget_alive] Hwrite];\n eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.destroy_valid; eauto].\n\n unfold SemDefns.target_is_alive in *.\n unfold SC.getCap in *.\n unfold SC.getObj in *.\n \n case (option_sumbool (SC.getObjTuple a s)) as [Hcase | [[[[obj1 lbl1] typ1] sch1] Hcase]];\n rewrite Hcase in *; simpl in *; try contradiction;\n (case (option_sumbool (OC.getCap t obj1)) as [Hcase2 | [cap Hcase2]];\n rewrite Hcase2 in *; simpl in*; try contradiction).\n\n unfold SC.is_alive in *.\n clear Hcase Hcase2 Hwrite.\n revert Heq Htarget_alive. generalize (Cap.target cap). intros target Heq Htarget_alive.\n clear obj1 lbl1 typ1 sch1. clear cap.\n clear Hactive.\n unfold SC.set_dead in *.\n\n\n idtac.\n eapply iff_trans; [ clear Heq |\n apply SC.is_label_eq_iff; [ apply Ref.eq_refl| apply Heq | apply ObjectLabel.eq_refl]].\n \n case (option_map_eq_dec Ref.eq_dec (Some o) (Some target)) as [Heq_t|Heq_t]; simpl in *.\n unfold Ref.eq in Heq_t; rewrite Heq_t in *.\n\n\n (* target [=] o] *)\n rewrite SC.is_label_set_label_eq_o; [| apply Ref.eq_sym; auto].\n generalize Htarget_alive; intros Htarget_alive'.\n eapply SC.is_label_iff_getLabel in Htarget_alive.\n rewrite Htarget_alive.\n intuition.\n\n (* target [<>] o *)\n rewrite SC.is_label_set_label_neq_o; [apply iff_refl| intro; apply Heq_t; apply Ref.eq_sym; auto].\n Qed.\n Implicit Arguments is_label_destroy_valid [a t s s' o lbl].\n\n Theorem is_label_destroy_valid_unborn: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->\n SemDefns.destroy_preReq a t s ->\n forall lbl, ObjectLabel.eq lbl unborn ->\n forall o, SC.is_label o s' lbl -> SC.is_label o s lbl.\n Proof.\n intros.\n eapply is_label_destroy_valid in H2; try eauto 1.\n revert H2; case (option_map_eq_dec Ref.eq_dec (Some o) (SemDefns.option_target (SC.getCap t a s)));\n intros Hcase H2; intuition.\n eapply ObjectLabel.eq_trans in H1; [|apply ObjectLabel.eq_sym; apply H4]; discriminate H1.\n Qed.\n \n\n\n\n\n\n Theorem is_label_destroy_invalid: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->\n ~ SemDefns.destroy_preReq a t s ->\n forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).\n Proof.\n intros a t s s' Heq Hprereq.\n eapply Sys.eq_trans in Heq; \n [ eapply is_label_id; eauto\n | eapply Sys.eq_sym; eapply Sem.destroy_invalid; eauto].\n Qed.\n\n Theorem set_label_eq: forall t t', Ref.eq t t' ->\n forall l l', ObjectLabel.eq l l' ->\n forall s s', Sys.eq s s' ->\n Sys.eq (SC.set_label t s l) (SC.set_label t' s' l').\n Proof.\n intros.\n unfold SC.set_label in *.\n generalize (SC.getObjTuple_eq _ _ _ _ H H1); intros Heq_tuple.\n case (option_sumbool (SC.getObjTuple t s)) as [Hcase | [[[[obj lbl] sch] typ] Hcase]]; \n rewrite Hcase in *; simpl in *; \n (case (option_sumbool (SC.getObjTuple t' s')) as [Hcase' | [[[[obj' lbl'] sch'] typ'] Hcase']]; \n rewrite Hcase' in *; simpl in *; try contradiction; eauto). \n destruct Heq_tuple as [[[Hobj Hlbl] Hsch] Htyp]; simpl in *.\n eapply SC.addObjTuple_eq; eauto; try apply Ref.eq_refl.\n unfold ObjectLabel.eq in *. rewrite H0; rewrite Hsch; rewrite Hobj; rewrite Htyp.\n eapply Sys.P.eq_refl.\n Qed.\n\n\n\n\n\n (* we need a theorem about objs_not_unborn n s -> Exe.execute_def s list s' -> objs_not_unborn n s' *)\n\n\n Theorem objs_not_unborn_op: forall n s, objs_not_unborn n s ->\n forall op s', Sys.eq (Sem.do_op op s) s' -> objs_not_unborn n s'.\n Proof.\n intros n s Hobjs op s' H.\n unfold objs_not_unborn in *.\n intros x Hx Hnot.\n eapply Hobjs.\n apply Hx.\n\n\n unfold SC.is_unborn in *.\n (* cases *)\n destruct op. simpl in *.\n (* read *)\n eapply is_label_read; eauto.\n (* write *)\n eapply is_label_write; eauto.\n (* fetch *)\n case (SemDefns.fetch_preReq_dec t t0 s); intros Hcase;\n solve [ eapply is_label_fetch_valid; eauto | eapply is_label_fetch_invalid; eauto].\n (* store *)\n case (SemDefns.store_preReq_dec t t0 s); intros Hcase;\n solve [ eapply is_label_store_valid; eauto | eapply is_label_store_invalid; eauto].\n (* revoke *)\n case (SemDefns.revoke_preReq_dec t t0 s); intros Hcase;\n solve [ eapply is_label_revoke_valid; eauto | eapply is_label_revoke_invalid; eauto].\n (* send *)\n case (SemDefns.send_preReq_dec t t0 s); intros Hcase;\n solve [ eapply is_label_send_valid; eauto | eapply is_label_send_invalid; eauto].\n (* allocate *)\n case (SemDefns.allocate_preReq_dec t t0 s); intros Hcase;\n solve \n [ eapply is_label_allocate_valid_unborn; solve [eauto; apply ObjectLabel.eq_refl] \n | eapply is_label_allocate_invalid; eauto\n ].\n (* destroy *)\n case (SemDefns.destroy_preReq_dec t t0 s); intros Hcase;\n solve \n [ eapply is_label_destroy_valid_unborn; solve [eauto; apply ObjectLabel.eq_refl] \n | eapply is_label_destroy_invalid; eauto\n ]. \n Qed.\n\n Theorem objs_not_unborn_oplist : forall n s, objs_not_unborn n s ->\n forall opL s', Exe.execute_def s opL s' -> objs_not_unborn n s'.\n Proof.\n intros n s Hobjs opL s' Hexe.\n induction Hexe.\n (* base *)\n unfold objs_not_unborn in *.\n intros x Hx Hnot.\n eapply Hobjs.\n apply Hx.\n unfold SC.is_unborn in *.\n eapply SC.isLabel_eq in Hnot.\n apply Hnot.\n apply Ref.eq_refl.\n apply ObjectLabel.eq_refl.\n apply Sys.eq_sym; apply H.\n (* step *)\n eapply objs_not_unborn_op; eauto.\n Qed.\n\n\n Theorem Proper_objs_not_unborn : \n Proper (RefSet.Subset --> Sys.eq ==> impl) objs_not_unborn.\n Proof.\n unfold Proper; unfold respectful; unfold impl; unfold flip; intros.\n unfold objs_not_unborn in *.\n intros e Hin.\n eapply H in Hin. \n generalize (H1 e Hin); clear H1; intros H1.\n intro Hnot. apply H1.\n eapply SC.isLabel_eq; \n [ apply Ref.eq_refl | apply ObjectLabel.eq_refl | apply Sys.eq_sym; apply H0 | apply Hnot].\n Qed.\n\n Ltac try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2:=\n let Heq := fresh \"Heq\" in\n try solve [ generalize (ag_objs_spec_equiv _ _ _ _ Hp_objs Hp'_objs (AG.eq_refl _)); intros Heq;\n eapply Proper_objs_not_unborn; unfold flip; \n [ apply RefSetProps.subset_equal; apply RefSet.eq_sym; apply Heq\n | apply Sys.eq_refl | apply Hunborn2]].\n\n Theorem ag_objs_spec_insert: forall p p_objs, Seq.ag_objs_spec p p_objs ->\n forall a n p'_objs, Seq.ag_objs_spec (insert a n p) p'_objs ->\n RefSet.eq p'_objs (RefSet.add a (RefSet.add n p_objs)).\n Proof.\n intros.\n unfold insert in *.\n\n generalize (Seq.ag_objs_spec_ag_objs (ag_add_cap a (Cap.mkCap n all_rights) p)).\n generalize (Seq.ag_objs (ag_add_cap a (Cap.mkCap n all_rights) p)).\n intros mid_objs Hmid_objs.\n\n rewrite ag_objs_spec_add_cap_equiv_nonempty with (objs':=p'_objs); \n [ rewrite CC.mkCap_target\n | apply Hmid_objs\n | rewrite CC.mkCap_rights; intro Hnot; apply Hnot with tx; eapply in_all_rights\n | apply H0\n ].\n\n rewrite ag_objs_spec_add_cap_equiv_nonempty with (objs':=mid_objs); \n [ rewrite CC.mkCap_target\n | apply H\n | rewrite CC.mkCap_rights; intro Hnot; apply Hnot with tx; eapply in_all_rights\n | apply Hmid_objs\n ].\n\n rewrite RefSetAddEq.double_add;\n rewrite RefSetProps.add_add;\n rewrite RefSetAddEq.double_add.\n eapply RefSet.eq_refl.\n Qed.\n\n Theorem ag_objs_spec_endow: forall p p_objs, Seq.ag_objs_spec p p_objs ->\n forall a n p'_objs, Seq.ag_objs_spec (endow a n p) p'_objs ->\n RefSet.eq p'_objs (RefSet.add a (RefSet.add n p_objs)).\n Proof.\n intros. unfold endow in *.\n generalize (Seq.potAcc_potAcc_fun (insert a n p)); intros Hpa.\n destruct Hpa as [Htrans _].\n eapply ag_objs_spec_potTransfer in Htrans; eauto. \n eapply ag_objs_spec_equiv in H0; [ | apply Htrans | apply AG.eq_refl].\n rewrite <- H0 in *.\n clear H0 Htrans; clear p'_objs.\n eapply ag_objs_spec_insert; eauto.\n Qed.\n\n\n Theorem getLabel_addCap_map_eq_inline: forall r i c o s,\n option_map_eq ObjectLabel.eq (SC.getLabel r (SC.addCap i c o s)) (SC.getLabel r s).\n Proof.\n intros.\n generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].\n eapply EQ_sym.\n eapply SC.getLabel_addCap_map_eq; eapply eq_refl.\n Qed.\n\n Theorem getLabel_copyCapList_map_eq_inline: forall s o t ixi_list i_src,\n option_map_eq ObjectLabel.eq (SC.getLabel i_src (SC.copyCapList o t ixi_list s)) (SC.getLabel i_src s).\n Proof.\n intros.\n generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].\n eapply EQ_sym; eapply SC.getLabel_copyCapList_map_eq; eapply eq_refl.\n Qed.\n\n Theorem is_label_allocate_not_unborn : forall lbl, ~ ObjectLabel.eq lbl unborn ->\n forall x s, SC.is_label x s lbl ->\n forall a t t' l s', Sys.eq (Sem.do_allocate a t t' l s) s' ->\n SC.is_label x s' lbl.\n Proof.\n intros.\n case (SemDefns.allocate_preReq_dec a t s); intros Hcase;\n (eapply Sys.eq_trans in H1; \n [ \n | eapply Sys.eq_sym; solve \n [eapply Sem.allocate_valid; eauto \n | eapply Sem.allocate_invalid; eauto]]);\n try solve[ eapply SC.isLabel_eq; [ apply Ref.eq_refl| apply ObjectLabel.eq_refl | apply H1 | apply H0]].\n (* allocate occrus*)\n generalize Hcase; intros [[Halive Hactive] Hunborn].\n eapply SC.is_label_iff_getLabel in Halive.\n eapply SC.is_label_iff_getLabel in Hunborn.\n eapply SC.is_label_iff_getLabel in H0.\n unfold SC.is_label.\n generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl x) H1); intros Heq; clear H1.\n\n (* this the main theorem what we want, how do we instantiate EQ options, playing with ones I can find*)\n\n generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].\n unfold Transitive in *.\n eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_addCap_map_eq_inline].\n eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_copyCapList_map_eq_inline].\n unfold SC.set_alive in *.\n\n case (Ref.eq_dec x t); intros Hcase2; [unfold Ref.eq in Hcase2; rewrite Hcase2 in *|].\n (* x = t *)\n rewrite SC.getLabel_set_label_eq_o in Heq; try apply Ref.eq_refl.\n rewrite SC.getLabel_updateObj_o in Heq.\n rewrite SC.getLabel_rmCapsByTarget_o in Heq.\n rewrite H0 in *.\n inversion Hunborn as [Hlbl].\n rewrite Hlbl in H.\n generalize (H (ObjectLabel.eq_refl _)); intros; contradiction.\n (* x <> t *)\n rewrite SC.getLabel_set_label_neq_o in Heq; auto.\n rewrite SC.getLabel_updateObj_o in Heq.\n rewrite SC.getLabel_rmCapsByTarget_o in Heq.\n \n (* there should really be a theorem for this *)\n rewrite H0 in *.\n case (option_sumbool (SC.getLabel x s')) as [Hcase3 | [lbl' Hcase3]]; \n rewrite Hcase3 in *; simpl in *; auto.\n rewrite Heq. apply ObjectLabel.eq_refl.\n Qed.\n\n Theorem is_label_allocate_new_label : forall a t s, SemDefns.allocate_preReq a t s ->\n forall t2 l s', Sys.eq (Sem.do_allocate a t t2 l s) s' ->\n SC.is_label t s' alive.\n Proof.\n intros a t s Hprereq t2 l s' Heq.\n generalize Hprereq; intros [[Halive Hactive] Hunborn].\n eapply SC.is_label_iff_getLabel in Halive.\n eapply SC.is_label_iff_getLabel in Hunborn.\n eapply SC.is_label_iff_getLabel.\n eapply Sys.eq_trans in Heq; [|eapply Sys.eq_sym; eapply Sem.allocate_valid; auto].\n generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl t) Heq); clear Heq; intros Heq.\n\n generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].\n unfold Transitive in *.\n\n eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_addCap_map_eq_inline].\n eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_copyCapList_map_eq_inline].\n unfold SC.set_alive in *.\n\n rewrite SC.getLabel_set_label_eq_o in Heq; try apply Ref.eq_refl.\n rewrite SC.getLabel_updateObj_o in Heq.\n rewrite SC.getLabel_rmCapsByTarget_o in Heq.\n rewrite Hunborn in *.\n\n case (option_sumbool (SC.getLabel t s')) as [Hcase3 | [lbl' Hcase3]]; \n rewrite Hcase3 in *; simpl in *; auto; try contradiction.\n rewrite Heq. apply eq_refl.\n Qed.\n\n Theorem objs_not_unborn_potAcc_op: forall p p_objs, Seq.ag_objs_spec p p_objs ->\n forall s, objs_not_unborn p_objs s ->\n forall op p'_objs, Seq.ag_objs_spec (potAcc_op op s p) p'_objs ->\n forall s', Sys.eq (Sem.do_op op s) s' ->\n objs_not_unborn p'_objs s'.\n Proof.\n intros p p_objs Hp_objs s Hp_objs_unborn op p'_objs Hp'_objs s' Hsys_eq.\n generalize (objs_not_unborn_op _ _ Hp_objs_unborn _ _ Hsys_eq); intros Hunborn2.\n\n destruct op; simpl in *; unfold id_ag in *;\n try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2.\n unfold endow_dep in *.\n revert Hp'_objs; case (SemDefns.allocate_preReq_dec t t0 s); intros Hcase Hp'_objs;\n try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2.\n\n eapply Proper_objs_not_unborn; unfold flip; \n [ eapply RefSetProps.subset_equal; eapply ag_objs_spec_endow; [apply Hp_objs | apply Hp'_objs ]\n | eapply Sys.eq_refl\n |].\n clear Hp'_objs Hp_objs_unborn Hp_objs.\n unfold objs_not_unborn in *.\n intros x Hin.\n eapply RefSetProps.Add_add in Hin.\n destruct Hin as [Hin | Hin].\n (* t = x *)\n rewrite Hin in *.\n generalize Hcase; intros [[Halive Hactive] Hunborn].\n\n eapply is_label_allocate_not_unborn in Halive; [ | intro Hnot; discriminate Hnot| apply Hsys_eq].\n intro Hnot.\n unfold SC.is_unborn in *.\n eapply SC.is_label_iff_getLabel in Hnot.\n eapply SC.is_label_iff_getLabel in Halive.\n rewrite Halive in Hnot.\n discriminate.\n\n eapply RefSetProps.Add_add in Hin.\n destruct Hin as [Hin|Hin].\n (* t0 = x *)\n rewrite Hin in *.\n generalize Hcase; intros [[Halive Hactive] Hunborn].\n\n idtac.\n generalize Hcase; intros Halive'.\n eapply is_label_allocate_new_label in Halive'; [ | eapply Hsys_eq].\n eapply SC.is_label_iff_getLabel in Halive'. unfold SC.is_unborn. intro Hnot. \n eapply SC.is_label_iff_getLabel in Hnot.\n rewrite Halive' in Hnot.\n discriminate Hnot.\n\n (* induction hypothesis *)\n eapply Hunborn2; eauto.\n Qed.\n\n\n Theorem objs_not_unborn_potAcc_execute_spec: forall p p_objs, Seq.ag_objs_spec p p_objs ->\n forall s, objs_not_unborn p_objs s ->\n forall op_list Fp', potAcc_execute_spec op_list Fp' -> \n forall Fp'_objs, Seq.ag_objs_spec (Fp' s p) Fp'_objs ->\n forall s', Exe.execute_def s op_list s' ->\n objs_not_unborn Fp'_objs s'.\n Proof.\n intros p p_objs Hp_objs s Hp_objs_unborn op_list Fp' Hpax.\n induction Hpax; intros Fp'_objs HFp'_objs s' Hexe.\n eapply ag_objs_spec_equiv in Hp_objs; [ | apply HFp'_objs | apply AG.eq_refl ].\n inversion Hexe.\n red; intros. eapply Hp_objs in H0. eapply Hp_objs_unborn in H0.\n intros Hnot; apply H0.\n eapply SC.isLabel_eq;\n [ eapply Ref.eq_refl | eapply ObjectLabel.eq_refl | eapply Sys.eq_sym; eapply H | eapply Hnot].\n (* step *)\n unfold compose in *.\n inversion Hexe.\n generalize (Seq.ag_objs_spec_ag_objs (Fp s p)); generalize (Seq.ag_objs (Fp s p)); intros ag_objs' Hag_objs'.\n eapply objs_not_unborn_potAcc_op; \n [apply Hag_objs'\n | \n | apply HFp'_objs\n |\n ]; [eapply IHHpax; eauto; eapply Exe.execute_spec; eapply Sys.eq_refl|].\n \n inversion Hexe.\n eapply Exe.execute_spec in H6.\n eapply Sys.eq_trans; [ | eapply H8].\n eapply SemConv.do_op_eq.\n eapply H6.\n Qed.\n\n\n Theorem potAcc_execute_spec_potAcc: forall p, Seq.maxTransfer p ->\n forall op_list Fp', potAcc_execute_spec op_list Fp' -> forall s, Seq.maxTransfer (Fp' s p).\n Proof.\n intros p Hmax op_list Fp' Hpax s.\n induction Hpax; eauto.\n (* step *)\n unfold compose.\n unfold potAcc_op.\n destruct op; unfold id_ag; simpl;\n (* eliminate 7 cases of identity transformation *) auto.\n\n unfold endow_dep.\n case (SemDefns.allocate_preReq_dec t t0 (Exe.execute s op_list)); intros Hcase; \n (* eliminate 1/2 case of id_ag *) auto.\n unfold endow.\n generalize Seq.potAcc_potAcc_fun; intros Hpa.\n edestruct Hpa as [Htrasn Hmax']. eapply Seq.maxTransfer_maxPotTransfer in Hmax'. apply Hmax'.\n Qed.\n\n Theorem objs_not_unborn_dirAcc_spec: forall s i, dirAcc_spec s i ->\n forall objs, Seq.ag_objs_spec i objs -> objs_not_unborn objs s.\n Proof.\n intros.\n (* introduce contradiciton *)\n unfold objs_not_unborn; intros n Hin Hunborn.\n (* work through objs_spec *)\n eapply H0 in Hin; clear H0; destruct Hin as [obj [rgt [HinE | HinE ]]];\n (* cases *)\n (* apply dirAcc in HinE and destruct*)\n eapply H in HinE;\n destruct_dirAcc HinE s'' HeqS src_ref src lbl srcType srcSched HmapS \n src' lbl' srcType' srcSched' HeqP Halive ind cap HmapSrc'\n cap_obj cap_lbl cap_type cap_sched HmapScap cap_obj' cap_lbl' cap_type' cap_sched' \n HeqPcap HaliveCap rgt' HinR HeqEdge;\n (* simplify edge equality *)\n generalize (Edges.eq_source _ _ HeqEdge); intros HeqEdgeS; \n repeat progress rewrite Edges.source_rewrite in HeqEdgeS;\n generalize (Edges.eq_target _ _ HeqEdge); intros HeqEdgeT;\n repeat progress rewrite Edges.target_rewrite in HeqEdgeT;\n generalize (Edges.eq_right _ _ HeqEdge); intros HeqEdgeR;\n repeat progress rewrite Edges.right_rewrite in HeqEdgeR;\n (* simplify tuple equality *)\n destruct_tuple HeqP Hsrc Hlbl HsrcT HsrcS; simpl in *;\n destruct_tuple HeqPcap Hsrc_cap Hlbl_cap HsrcT_cap HsrcS_cap; simpl in *;\n (* rewrite everything through to show that n is alive in hyp HmapS | HmapScap. *)\n rewrite HeqEdgeS in *;\n rewrite HeqEdgeT in *;\n rewrite Hlbl in *;\n rewrite Hlbl_cap in *;\n unfold ObjectLabel.eq in *;\n rewrite <- Halive in *;\n rewrite <- HaliveCap in *.\n\n (* use HmapS to find an equivelent label in s *)\n eapply Sys_MapEquiv.exists_mapsTo_eq in HmapS;\n [ | apply Sys.eq_sym; apply HeqS | apply Ref.eq_refl].\n destruct HmapS as [tuple [Htuple HmapS]].\n destruct_tuple tuple t_obj t_lbl t_schd t_typ; simpl in *.\n destruct_tuple Htuple Ht_obj Ht_lbl Ht_schd Ht_typ.\n rewrite <- Ht_lbl in *.\n (* prove contradiciton by discrimination *)\n unfold SC.is_unborn in Hunborn.\n unfold SC.is_label in Hunborn.\n unfold SC.getLabel in Hunborn.\n unfold SC.getObjTuple in Hunborn.\n eapply Sys.MapS.find_1 in HmapS.\n rewrite HmapS in Hunborn.\n simpl in Hunborn.\n discriminate.\n\n (* other case *)\n\n (* use HmapScap to find an equivelent label in s *)\n eapply Sys_MapEquiv.exists_mapsTo_eq in HmapScap;\n [ | apply Sys.eq_sym; apply HeqS | apply Ref.eq_refl].\n destruct HmapScap as [tuple [Htuple HmapScap]].\n destruct_tuple tuple t_obj t_lbl t_schd t_typ; simpl in *.\n destruct_tuple Htuple Ht_obj Ht_lbl Ht_schd Ht_typ.\n rewrite <- Ht_lbl in *.\n (* prove contradiciton by discrimination *)\n unfold SC.is_unborn in Hunborn.\n unfold SC.is_label in Hunborn.\n unfold SC.getLabel in Hunborn.\n unfold SC.getObjTuple in Hunborn.\n eapply Sys.MapS.find_1 in HmapScap.\n rewrite HmapScap in Hunborn.\n simpl in Hunborn.\n discriminate.\n Qed.\n\n\n (* throw into sequential access *)\n Theorem maxTransfer_potAcc_refl : forall p, Seq.maxTransfer p -> Seq.potAcc p p.\n Proof.\n intros; split.\n eapply Seq.potTransfer_base; apply AG.eq_refl.\n eapply Seq.maxTransfer_maxPotTransfer; auto.\n Qed.\n\n\nTheorem AG_attenuating_potAcc_op_2: forall objs s, objs_not_unborn objs s -> \n forall i p, Seq.potAcc i p -> \n forall ag_N, Seq.ag_objs_spec p ag_N -> objs_not_unborn ag_N s ->\n forall op, AG_attenuating objs p (potAcc_op op s p).\nProof.\n intros objs s Hobjs i p Hpa ag_N Hag_objs Hag_objs_unborn op.\n destruct op; simpl; try unfold id_ag; try solve [apply AG_attenuating_eq; apply AG.eq_refl].\n unfold endow_dep.\n case (SemDefns.allocate_preReq_dec t t0 s); intros H'; try solve [apply AG_attenuating_eq; apply AG.eq_refl].\n destruct H'.\n eapply AG_attenuating_endow; try solve [ apply Hag_objs | apply Hpa\n| intro Hnot; first [apply Hobjs in Hnot|apply Hag_objs_unborn in Hnot]; apply Hnot; auto].\nQed.\n\n Theorem AG_attenuating_compose: forall objs p Fp1, AG_attenuating objs p (Fp1 p) ->\n forall Fp2, AG_attenuating objs (Fp1 p) (compose Fp2 Fp1 p) ->\n AG_attenuating objs p (compose Fp2 Fp1 p).\n Proof.\n intros.\n eapply AG_attenuating_trans; [ apply H | apply H0].\n Qed.\n\n\n(* This theorem states that the function Fp, which conservatively approximates the execution\n of op_list on s, is AG_attenuating-ing on its input provided all objs are unborn. *)\n\nTheorem execute_potAcc_attenuating: \n forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->\n forall Fp, potAcc_execute_spec op_list Fp ->\n forall s i, dirAcc_spec s i -> forall p, Seq.potAcc i p ->\n forall objs, objs_not_unborn objs s ->\n AG_attenuating objs p (Fp s p).\nProof.\n intros op_list Fsa Hdax Fp Hpax s i Hda p Hpa objs Hobjs.\n revert Hdax Hpax; revert Fsa Fp.\n induction op_list; intros Fsa Fp Hdax Hpax.\n\n (* base *)\n \n inversion Hpax; eauto.\n\n (* step *)\n\n rename a into op.\n inversion Hdax. rename Fp0 into Fsa'. clear H H1. clear op0 op_list0.\n inversion Hpax. rename Fp0 into Fp'. clear H H3. clear op0 op_list0.\n\n generalize (IHop_list _ _ H2 H4); intros IHreduce; clear IHop_list.\n\n apply AG_attenuating_compose; [apply IHreduce|].\n unfold compose.\n\n (* generalize (exists_dirAcc_spec (Exe.execute s op_list)); intros [i' Hda']. *)\n (* generalize (Seq.exists_potAcc i'); intros [p' Hpa']. *)\n (* generalize (Seq.ag_objs_spec_ag_objs p'); intros Hagobjs. *)\n (* generalize (objs_not_unborn_oplist _ _ Hobjs op_list _ (Exe.execute_spec_2 s op_list _ (Sys.eq_refl _))); intros Hobjsunborn. *)\n\n(* okay, aside from the potAcc property, all of these subgoals are about the objs_not_unborn invariants *)\n(* first, we need to know that objs not unborn remain not unborn over execution.\n second, we need to know that no objs produced by a potAcc_execute_spec funcitons also preserve \n objs_obj_unborn *)\n\neapply AG_attenuating_potAcc_op_2.\n(* objs unborn in Exe.execute s op_list *) \n eapply objs_not_unborn_oplist; [apply Hobjs| eapply Exe.execute_spec_2; apply Sys.eq_refl].\n(* potAcc_execute_spec op_list Fp' -> exists da, Seq.potAcc da (Fp' s p) *)\n eapply maxTransfer_potAcc_refl; eapply potAcc_execute_spec_potAcc; [ | eauto];\n destruct Hpa as [HpotTrans Hmax]; eapply Seq.maxTransfer_maxPotTransfer in Hmax; auto.\n(* ag_objs_spec *)\neapply Seq.ag_objs_spec_ag_objs.\n(* potAcc_execute_spec op_list Fp' -> objs_not_unborn (Seq.ag_objs (Fp' s p)) (Exe.execute s op_list) *)\neapply objs_not_unborn_potAcc_execute_spec; eauto; [|apply Exe.execute_spec; eapply Sys.eq_refl].\ngeneralize (Seq.ag_objs_spec_ag_objs p); intros Hp_objs.\neapply ag_objs_spec_potTransfer_2 in Hp_objs; [ | eapply Hpa].\neapply objs_not_unborn_dirAcc_spec; eauto.\nQed.\n\n(* Given execute_potAcc_attenuating, we can now turn to execute_attenuatinge *)\n\n Theorem execute_attenuating : forall s i, dirAcc_spec s i -> forall p, Seq.potAcc i p ->\n forall op_list s', Exe.execute_def s op_list s' -> forall i', dirAcc_spec s' i' ->\n forall p', Seq.potAcc i' p' -> forall objs, objs_not_unborn objs s ->\n AG_attenuating objs p p'.\n Proof.\n intros s i Hda p Hpa op_list s' Hexe i' Hda' p' Hpa' objs HnAlive.\n (* proof sketch *)\n (* by dirAcc_execute_spec_dirAcc_execute and potAcc_execute_spec_potAcc_execute, we know that we can\n instantiate execute_potAcc_attenuating*)\n generalize (execute_potAcc_attenuating\n op_list \n _ (dirAcc_execute_spec_dirAcc_execute _)\n _ (potAcc_execute_spec_potAcc_execute _)\n _ _ Hda\n _ Hpa\n _ HnAlive); intros Hreduce.\n\n \n eapply Proper_AG_attenuating_4; unfold flip;\n [ apply RefSetProps.subset_equal; apply RefSet.eq_refl\n | apply AGProps.subset_equal; apply AG.eq_refl\n |\n | apply Hreduce\n ].\n\n (* all that remains is to show that potAcc_execute conservatively approximates potAcc *) \n generalize (potAcc_execute_approx \n op_list\n _ (dirAcc_execute_spec_dirAcc_execute _)\n _ (potAcc_execute_spec_potAcc_execute _)); intros HPAapprox.\n generalize (dirAcc_execute_approx\n op_list\n _ (dirAcc_execute_spec_dirAcc_execute _)); intros HDAapprox.\n unfold dirAcc_approx_dep in *.\n unfold potAcc_approx_dirAcc_dep in *.\n eapply Exe.execute_spec in Hexe.\n eapply dirAcc_spec_iff in Hda'; [ | apply Hexe| apply AG.eq_refl].\n \n generalize (HDAapprox _ _ _ _ _ \n Hda Hda' (AGProps.subset_equal (AG.eq_refl _)) (Sys.eq_refl _)); \n clear HDAapprox; intros HDAapprox.\n generalize (Seq.exists_potAcc (dirAcc_execute op_list s i)); intros [p2 Hpa2].\n generalize (HPAapprox _ _ _ _ _ _ _ _ \n (Sys.eq_refl _) (Sys.eq_refl _)\n Hda (AGProps.subset_equal (AG.eq_refl _))\n Hpa Hpa2\n (AGProps.subset_equal (AG.eq_refl _)));\n clear HPAapprox; intros HPAapprox.\n \n eapply AGProps.subset_trans;[|eapply HPAapprox].\n\n eapply Seq.potAcc_monotonic; [ apply HDAapprox | apply Hpa'| apply Hpa2].\n Qed.\n\n\n\n\n\n\n\nEnd MakeAccessExecution.\n\n", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/AccessExecutionImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.20434190235957034, "lm_q1q2_score": 0.10296914549663837}} {"text": "(***Zhaoguo Wang, Homework #2 Induction ***)\n\n(** * Induction: Proof by Induction *)\n \n\n(** The next line imports all of our definitions from the\n previous chapter. *)\n\nRequire Export Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n into [Basics.vo]. (This is like making a .class file from a .java\n file, or a .o file from a .c file.)\n \n Here are two ways to compile your code:\n \n - CoqIDE:\n \n Open [Basics.v].\n In the \"Compile\" menu, click on \"Compile Buffer\".\n \n - Command line:\n \n Run [coqc Basics.v]\n\n *)\n\n(* ###################################################################### *)\n(** * Naming Cases *)\n\n(** The fact that there is no explicit command for moving from\n one branch of a case analysis to the next can make proof scripts\n rather hard to read. In larger proofs, with nested case analyses,\n it can even become hard to stay oriented when you're sitting with\n Coq and stepping through the proof. (Imagine trying to remember\n that the first five subgoals belong to the inner case analysis and\n the remaining seven cases are what remains of the outer one...)\n Disciplined use of indentation and comments can help, but a better\n way is to use the [Case] tactic. *)\n\n(* [Case] is not built into Coq: we need to define it ourselves.\n There is no need to understand how it works -- you can just skip\n over the definition to the example that follows. It uses some\n facilities of Coq that we have not discussed -- the string\n library (just for the concrete syntax of quoted strings) and the\n [Ltac] command, which allows us to declare custom tactics. Kudos\n to Aaron Bohannon for this nice hack! *)\n\nRequire String. Open Scope string_scope.\n\nLtac move_to_top x :=\n match reverse goal with\n | H : _ |- _ => try move x after H\n end.\n\nTactic Notation \"assert_eq\" ident(x) constr(v) :=\n let H := fresh in\n assert (x = v) as H by reflexivity;\n clear H.\n\nTactic Notation \"Case_aux\" ident(x) constr(name) :=\n first [\n set (x := name); move_to_top x\n | assert_eq x name; move_to_top x\n | fail 1 \"because we are working on a different case\" ].\n\nTactic Notation \"Case\" constr(name) := Case_aux Case name.\nTactic Notation \"SCase\" constr(name) := Case_aux SCase name.\nTactic Notation \"SSCase\" constr(name) := Case_aux SSCase name.\nTactic Notation \"SSSCase\" constr(name) := Case_aux SSSCase name.\nTactic Notation \"SSSSCase\" constr(name) := Case_aux SSSSCase name.\nTactic Notation \"SSSSSCase\" constr(name) := Case_aux SSSSSCase name.\nTactic Notation \"SSSSSSCase\" constr(name) := Case_aux SSSSSSCase name.\nTactic Notation \"SSSSSSSCase\" constr(name) := Case_aux SSSSSSSCase name.\n(** Here's an example of how [Case] is used. Step through the\n following proof and observe how the context changes. *)\n\nTheorem andb_true_elim1 : forall b c : bool,\n andb b c = true -> b = true.\nProof.\n intros b c H.\n destruct b.\n Case \"b = true\". (* <----- here *)\n reflexivity.\n Case \"b = false\". (* <---- and here *)\n rewrite <- H. \n reflexivity. \nQed.\n\n(** [Case] does something very straightforward: It simply adds a\n string that we choose (tagged with the identifier \"Case\") to the\n context for the current goal. When subgoals are generated, this\n string is carried over into their contexts. When the last of\n these subgoals is finally proved and the next top-level goal\n becomes active, this string will no longer appear in the context\n and we will be able to see that the case where we introduced it is\n complete. Also, as a sanity check, if we try to execute a new\n [Case] tactic while the string left by the previous one is still\n in the context, we get a nice clear error message.\n\n For nested case analyses (e.g., when we want to use a [destruct]\n to solve a goal that has itself been generated by a [destruct]),\n there is an [SCase] (\"subcase\") tactic. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2) *)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n andb b c = true -> c = true.\nProof.\n intros b c H.\n destruct c.\n Case \"c = true\".\n reflexivity.\n Case \"c = false\".\n destruct b.\n rewrite <- H.\n SCase \"b = true\".\n reflexivity.\n SCase \"b = false\".\n rewrite <- H.\n reflexivity.\n Qed.\n\n(** There are no hard and fast rules for how proofs should be\n formatted in Coq -- in particular, where lines should be broken\n and how sections of the proof should be indented to indicate their\n nested structure. However, if the places where multiple subgoals\n are generated are marked with explicit [Case] tactics placed at\n the beginning of lines, then the proof will be readable almost no\n matter what choices are made about other aspects of layout.\n\n This is a good place to mention one other piece of (possibly\n obvious) advice about line lengths. Beginning Coq users sometimes\n tend to the extremes, either writing each tactic on its own line\n or entire proofs on one line. Good style lies somewhere in the\n middle. In particular, one reasonable convention is to limit\n yourself to 80-character lines. Lines longer than this are hard\n to read and can be inconvenient to display and print. Many\n editors have features that help enforce this. *)\n\n(* ###################################################################### *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n for [+] on the left using a simple argument. The fact that it is\n also a neutral element on the _right_... *)\n\nTheorem plus_0_r_firsttry : forall n:nat,\n n + 0 = n.\n\n(** ... cannot be proved in the same simple way. Just applying\n [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary\n unknown number, so the [match] in the definition of [+] can't be\n simplified. *)\n\nProof.\n intros n.\n simpl. (* Does nothing! *)\nAdmitted.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n further: the branch of the case analysis where we assume [n = 0]\n goes through, but in the branch where [n = S n'] for some [n'] we\n get stuck in exactly the same way. We could use [destruct n'] to\n get one step further, but since [n] can be arbitrarily large, if we\n try to keep on like this we'll never be done. *)\n\nTheorem plus_0_r_secondtry : forall n:nat,\n n + 0 = n.\nProof.\n intros n. destruct n as [| n'].\n Case \"n = 0\".\n reflexivity. (* so far so good... *)\n Case \"n = S n'\".\n simpl. (* ...but here we are stuck again *)\nAdmitted.\n\n(** To prove such facts -- indeed, to prove most interesting\n facts about numbers, lists, and other inductively defined sets --\n we need a more powerful reasoning principle: _induction_.\n\n Recall (from high school) the principle of induction over natural\n numbers: If [P(n)] is some proposition involving a natural number\n [n] and we want to show that P holds for _all_ numbers [n], we can\n reason like this:\n - show that [P(O)] holds;\n - show that, for any [n'], if [P(n')] holds, then so does\n [P(S n')];\n - conclude that [P(n)] holds for all [n].\n\n In Coq, the steps are the same but the order is backwards: we\n begin with the goal of proving [P(n)] for all [n] and break it\n down (by applying the [induction] tactic) into two separate\n subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n n')]. Here's how this works for the theorem we are trying to\n prove at the moment: *)\n\nTheorem plus_0_r : forall n:nat, n + 0 = n.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\". reflexivity.\n Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Like [destruct], the [induction] tactic takes an [as...]\n clause that specifies the names of the variables to be introduced\n in the subgoals. In the first branch, [n] is replaced by [0] and\n the goal becomes [0 + 0 = 0], which follows by simplification. In\n the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n n'] is added to the context (with the name [IHn'], i.e., the\n Induction Hypothesis for [n']). The goal in this case becomes [(S\n n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in\n turn follows from the induction hypothesis. *)\n\nTheorem minus_diag : forall n,\n minus n n = 0.\nProof.\n (* WORKED IN CLASS *)\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (basic_induction) *)\n\n(** Prove the following lemmas using induction. You might need\n previously proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n n * 0 = 0.\nProof.\n intros n. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat, \n S (n + m) = n + (S m).\nProof. \n intros n m. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n n + m = m + n.\nProof.\n intros n m. induction n as [| n'].\n simpl.\n rewrite -> plus_0_r.\n reflexivity.\n rewrite <- plus_n_Sm.\n simpl.\n rewrite IHn'. reflexivity. Qed.\n\n\n\nTheorem plus_assoc : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed. \n\n\n(** **** Exercise: 2 stars (double_plus) *)\n\n(** Consider the following function, which doubles its argument: *)\n\nFixpoint double (n:nat) :=\n match n with\n | O => O\n | S n' => S (S (double n'))\n end.\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof. \n intros n. induction n as [|n'].\n Case \"n = 0\".\n simpl. reflexivity.\n Case \"n = S n'\".\n simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed. \n\n\n\n(** **** Exercise: 1 star (destruct_induction) *)\n(** Briefly explain the difference between the tactics\n [destruct] and [induction]. \n\n(* The destruct and induction both can get n' a step further at a time;\nhowever, n can be an arbitrary unknow number: instruct can prove P (O) \nholds and P(S n')holds for any n' when P(n') holds by introducing and \napplying hypothesis, then come to the conclusion P(n) holds for all n; \ndestruct cannot.*)\n\n*)\n(** [] *)\n\n\n(* ###################################################################### *)\n(** * Proofs Within Proofs *)\n\n\n(** In Coq, as in informal mathematics, large proofs are very\n often broken into a sequence of theorems, with later proofs\n referring to earlier theorems. Occasionally, however, a proof\n will need some miscellaneous fact that is too trivial (and of too\n little general interest) to bother giving it its own top-level\n name. In such cases, it is convenient to be able to simply state\n and prove the needed \"sub-theorem\" right at the point where it is\n used. The [assert] tactic allows us to do this. For example, our\n earlier proof of the [mult_0_plus] theorem referred to a previous\n theorem named [plus_O_n]. We can also use [assert] to state and\n prove [plus_O_n] in-line: *)\n\nTheorem mult_0_plus' : forall n m : nat,\n (0 + n) * m = n * m.\nProof.\n intros n m.\n assert (H: 0 + n = n). \n Case \"Proof of assertion\". reflexivity.\n rewrite -> H.\n reflexivity. Qed.\n\n(** The [assert] tactic introduces two sub-goals. The first is\n the assertion itself; by prefixing it with [H:] we name the\n assertion [H]. (Note that we could also name the assertion with\n [as] just as we did above with [destruct] and [induction], i.e.,\n [assert (0 + n = n) as H]. Also note that we mark the proof of\n this assertion with a [Case], both for readability and so that,\n when using Coq interactively, we can see when we're finished\n proving the assertion by observing when the [\"Proof of assertion\"]\n string disappears from the context.) The second goal is the same\n as the one at the point where we invoke [assert], except that, in\n the context, we have the assumption [H] that [0 + n = n]. That\n is, [assert] generates one subgoal where we must prove the\n asserted fact and a second subgoal where we can use the asserted\n fact to make progress on whatever we were trying to prove in the\n first place. *)\n\n(** Actually, [assert] will turn out to be handy in many sorts of\n situations. For example, suppose we want to prove that [(n + m)\n + (p + q) = (m + n) + (p + q)]. The only difference between the\n two sides of the [=] is that the arguments [m] and [n] to the\n first inner [+] are swapped, so it seems we should be able to\n use the commutativity of addition ([plus_comm]) to rewrite one\n into the other. However, the [rewrite] tactic is a little stupid\n about _where_ it applies the rewrite. There are three uses of\n [+] here, and it turns out that doing [rewrite -> plus_comm]\n will affect only the _outer_ one. *)\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n (* We just need to swap (n + m) for (m + n)...\n it seems like plus_comm should do the trick! *)\n rewrite -> plus_comm.\n (* Doesn't work...Coq rewrote the wrong plus! *)\nAdmitted.\n\n(** To get [plus_comm] to apply at the point where we want it, we can\n introduce a local lemma stating that [n + m = m + n] (for\n the particular [m] and [n] that we are talking about here), prove\n this lemma using [plus_comm], and then use this lemma to do the\n desired rewrite. *)\n\nTheorem plus_rearrange : forall n m p q : nat,\n (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n intros n m p q.\n assert (H: n + m = m + n).\n Case \"Proof of assertion\".\n rewrite -> plus_comm. reflexivity.\n rewrite -> H. reflexivity. Qed.\n\n(** **** Exercise: 4 stars (mult_comm) *)\n(** Use [assert] to help prove this theorem. You shouldn't need to\n use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n intros n m p.\n rewrite plus_assoc.\n assert (H: n + m = m + n).\n rewrite -> plus_comm.\n reflexivity.\n rewrite -> H. \n rewrite <- plus_assoc. reflexivity. Qed.\n\n\n\n\n(** Now prove commutativity of multiplication. (You will probably\n need to define and prove a separate subsidiary theorem to be used\n in the proof of this one.) You may find that [plus_swap] comes in\n handy. *)\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n intros n m. induction m.\n simpl.\n rewrite mult_0_r.\n reflexivity.\n simpl.\n rewrite <- mult_n_Sm.\n rewrite plus_comm.\n rewrite IHm.\n reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)\n\n(** Prove the following simple fact: *)\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n evenb n = negb (evenb (S n)).\nProof.\n intros n.\n induction n as [|n'].\n reflexivity.\n simpl. rewrite -> IHn'.\n assert (H: forall x, x = negb (negb x)).\n Case \"Proof of assertion\".\n intro x.\n induction x.\n reflexivity.\n reflexivity.\n rewrite <- H. simpl. reflexivity.\n Qed.\n\n\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, optional (more_exercises) *)\n(** Take a piece of paper. For each of the following theorems, first\n _think_ about whether (a) it can be proved using only\n simplification and rewriting, (b) it also requires case\n analysis ([destruct]), or (c) it also requires induction. Write\n down your prediction. Then fill in the proof. (There is no need\n to turn in your piece of paper; this is just to encourage you to\n reflect before hacking!) *)\n\nTheorem ble_nat_refl : forall n:nat,\n true = ble_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n beq_nat 0 (S n) = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n andb b false = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat, \n ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n beq_nat (S n) 0 = false.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem all3_spec : forall b c : bool,\n orb\n (andb b c)\n (orb (negb b)\n (negb c))\n = true.\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n (n + m) * p = (n * p) + (m * p).\nProof.\n (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n n * (m * p) = (n * m) * p.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl) *)\nTheorem beq_nat_refl : forall n : nat, \n true = beq_nat n n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap') *)\n(** The [replace] tactic allows you to specify a particular subterm to\n rewrite and what you want it rewritten to. More precisely,\n [replace (t) with (u)] replaces (all copies of) expression [t] in\n the goal by expression [u], and generates [t = u] as an additional\n subgoal. This is often useful when a plain [rewrite] acts on the wrong\n part of the goal. \n\n Use the [replace] tactic to do a proof of [plus_swap'], just like\n [plus_swap] but without needing [assert (n + m = m + n)]. \n*)\n\nTheorem plus_swap' : forall n m p : nat, \n n + (m + p) = m + (n + p).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars (binary_commute) *)\n(** Recall the [increment] and [binary-to-unary] functions that you\n wrote for the [binary] exercise in the [Basics] chapter. Prove\n that these functions commute -- that is, incrementing a binary\n number and then converting it to unary yields the same result as\n first converting it to unary and then incrementing.\n\n (Before you start working on this exercise, please copy the\n definitions from your solution to the [binary] exercise here so\n that this file can be graded on its own. If you find yourself\n wanting to change your original definitions to make the property\n easier to prove, feel free to do so.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 5 stars, advanced (binary_inverse) *)\n(** This exercise is a continuation of the previous exercise about\n binary numbers. You will need your definitions and theorems from\n the previous exercise to complete this one.\n\n (a) First, write a function to convert natural numbers to binary\n numbers. Then prove that starting with any natural number,\n converting to binary, then converting back yields the same\n natural number you started with.\n\n (b) You might naturally think that we should also prove the\n opposite direction: that starting with a binary number,\n converting to a natural, and then back to binary yields the\n same number we started with. However, it is not true!\n Explain what the problem is.\n\n (c) Define a function [normalize] from binary numbers to binary\n numbers such that for any binary number b, converting to a\n natural and then back to binary yields [(normalize b)]. Prove\n it.\n\n Again, feel free to change your earlier definitions if this helps\n here. \n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Advanced Material *)\n\n(** ** Formal vs. Informal Proof *)\n\n(** \"Informal proofs are algorithms; formal proofs are code.\" *)\n\n(** The question of what, exactly, constitutes a \"proof\" of a\n mathematical claim has challenged philosophers for millenia. A\n rough and ready definition, though, could be this: a proof of a\n mathematical proposition [P] is a written (or spoken) text that\n instills in the reader or hearer the certainty that [P] is true.\n That is, a proof is an act of communication.\n\n Now, acts of communication may involve different sorts of readers.\n On one hand, the \"reader\" can be a program like Coq, in which case\n the \"belief\" that is instilled is a simple mechanical check that\n [P] can be derived from a certain set of formal logical rules, and\n the proof is a recipe that guides the program in performing this\n check. Such recipes are _formal_ proofs.\n\n Alternatively, the reader can be a human being, in which case the\n proof will be written in English or some other natural language,\n thus necessarily _informal_. Here, the criteria for success are\n less clearly specified. A \"good\" proof is one that makes the\n reader believe [P]. But the same proof may be read by many\n different readers, some of whom may be convinced by a particular\n way of phrasing the argument, while others may not be. One reader\n may be particularly pedantic, inexperienced, or just plain\n thick-headed; the only way to convince them will be to make the\n argument in painstaking detail. But another reader, more familiar\n in the area, may find all this detail so overwhelming that they\n lose the overall thread. All they want is to be told the main\n ideas, because it is easier to fill in the details for themselves.\n Ultimately, there is no universal standard, because there is no\n single way of writing an informal proof that is guaranteed to\n convince every conceivable reader. In practice, however,\n mathematicians have developed a rich set of conventions and idioms\n for writing about complex mathematical objects that, within a\n certain community, make communication fairly reliable. The\n conventions of this stylized form of communication give a fairly\n clear standard for judging proofs good or bad.\n\n Because we are using Coq in this course, we will be working\n heavily with formal proofs. But this doesn't mean we can ignore\n the informal ones! Formal proofs are useful in many ways, but\n they are _not_ very efficient ways of communicating ideas between\n human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\n\nTheorem plus_assoc' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity. \n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** Coq is perfectly happy with this as a proof. For a human,\n however, it is difficult to make much sense of it. If you're used\n to Coq you can probably step through the tactics one after the\n other in your mind and imagine the state of the context and goal\n stack at each point, but if the proof were even a little bit more\n complicated this would be next to impossible. Instead, a\n mathematician might write it something like this: *)\n(** - _Theorem_: For any [n], [m] and [p],\n n + (m + p) = (n + m) + p.\n _Proof_: By induction on [n].\n\n - First, suppose [n = 0]. We must show \n 0 + (m + p) = (0 + m) + p. \n This follows directly from the definition of [+].\n\n - Next, suppose [n = S n'], where\n n' + (m + p) = (n' + m) + p.\n We must show\n (S n') + (m + p) = ((S n') + m) + p.\n By the definition of [+], this follows from\n S (n' + (m + p)) = S ((n' + m) + p),\n which is immediate from the induction hypothesis. [] *)\n\n(** The overall form of the proof is basically similar. This is\n no accident: Coq has been designed so that its [induction] tactic\n generates the same sub-goals, in the same order, as the bullet\n points that a mathematician would write. But there are\n significant differences of detail: the formal proof is much more\n explicit in some ways (e.g., the use of [reflexivity]) but much\n less explicit in others (in particular, the \"proof state\" at any\n given point in the Coq proof is completely implicit, whereas the\n informal proof reminds the reader several times where things\n stand). *)\n\n(** Here is a formal proof that shows the structure more\n clearly: *)\n\nTheorem plus_assoc'' : forall n m p : nat,\n n + (m + p) = (n + m) + p.\nProof.\n intros n m p. induction n as [| n']. \n Case \"n = 0\".\n reflexivity. \n Case \"n = S n'\".\n simpl. rewrite -> IHn'. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n \n Proof: (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)\n(** Write an informal proof of the following theorem, using the\n informal proof of [plus_assoc] as a model. Don't just\n paraphrase the Coq tactics into English!\n \n Theorem: [true = beq_nat n n] for any [n].\n \n Proof: (* FILL IN HERE *)\n[]\n *)\n\n(* $Date: 2013-01-30 09:21:23 -0500 (Wed, 30 Jan 2013) $ *)\n", "meta": {"author": "randywse", "repo": "541", "sha": "eae3a7e9f16ee8cbaa6f7a79682b318360d057bf", "save_path": "github-repos/coq/randywse-541", "path": "github-repos/coq/randywse-541/541-eae3a7e9f16ee8cbaa6f7a79682b318360d057bf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869692386284973, "lm_q2_score": 0.2450850131323717, "lm_q1q2_score": 0.10261634108341015}} {"text": "(** * Auto: More Automation *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import omega.Omega.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Imp.\n\n(** Up to now, we've used the more manual part of Coq's tactic\n facilities. In this chapter, we'll learn more about some of Coq's\n powerful automation features: proof search via the [auto] tactic,\n automated forward reasoning via the [Ltac] hypothesis matching\n machinery, and deferred instantiation of existential variables\n using [eapply] and [eauto]. Using these features together with\n Ltac's scripting facilities will enable us to make our proofs\n startlingly short! Used properly, they can also make proofs more\n maintainable and robust to changes in underlying definitions. A\n deeper treatment of [auto] and [eauto] can be found in the\n [UseAuto] chapter in _Programming Language Foundations_.\n\n There's another major category of automation we haven't discussed\n much yet, namely built-in decision procedures for specific kinds\n of problems: [omega] is one example, but there are others. This\n topic will be deferred for a while longer.\n\n Our motivating example will be this proof, repeated with just a\n few small changes from the [Imp] chapter. We will simplify\n this proof in several stages. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2;\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst.\n - (* E_Skip *) reflexivity.\n - (* E_Ass *) reflexivity.\n - (* E_Seq *)\n assert (st' = st'0) as EQ1.\n { (* Proof of assertion *) apply IHE1_1; apply H1. }\n subst st'0.\n apply IHE1_2. assumption.\n (* E_IfTrue *)\n - (* b evaluates to true *)\n apply IHE1. assumption.\n - (* b evaluates to false (contradiction) *)\n rewrite H in H5. discriminate.\n (* E_IfFalse *)\n - (* b evaluates to true (contradiction) *)\n rewrite H in H5. discriminate.\n - (* b evaluates to false *)\n apply IHE1. assumption.\n (* E_WhileFalse *)\n - (* b evaluates to false *)\n reflexivity.\n - (* b evaluates to true (contradiction) *)\n rewrite H in H2. discriminate.\n (* E_WhileTrue *)\n - (* b evaluates to false (contradiction) *)\n rewrite H in H4. discriminate.\n - (* b evaluates to true *)\n assert (st' = st'0) as EQ1.\n { (* Proof of assertion *) apply IHE1_1; assumption. }\n subst st'0.\n apply IHE1_2. assumption. Qed.\n\n(* ################################################################# *)\n(** * The [auto] Tactic *)\n\n(** Thus far, our proof scripts mostly apply relevant hypotheses or\n lemmas by name, and one at a time. *)\n\nExample auto_example_1 : forall (P Q R: Prop),\n (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n intros P Q R H1 H2 H3.\n apply H2. apply H1. assumption.\nQed.\n\n(** The [auto] tactic frees us from this drudgery by _searching_ for a\n sequence of applications that will prove the goal: *)\n\nExample auto_example_1' : forall (P Q R: Prop),\n (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n auto.\nQed.\n\n(** The [auto] tactic solves goals that are solvable by any combination of\n - [intros] and\n - [apply] (of hypotheses from the local context, by default). *)\n\n(** Using [auto] is always \"safe\" in the sense that it will never fail\n and will never change the proof state: either it completely solves\n the current goal, or it does nothing. *)\n\n(** Here is a larger example showing [auto]'s power: *)\n\nExample auto_example_2 : forall P Q R S T U : Prop,\n (P -> Q) ->\n (P -> R) ->\n (T -> R) ->\n (S -> T -> U) ->\n ((P->Q) -> (P->S)) ->\n T ->\n P ->\n U.\nProof. auto. Qed.\n\n(** Proof search could, in principle, take an arbitrarily long time,\n so there are limits to how far [auto] will search by default. *)\n\nExample auto_example_3 : forall (P Q R S T U: Prop),\n (P -> Q) ->\n (Q -> R) ->\n (R -> S) ->\n (S -> T) ->\n (T -> U) ->\n P ->\n U.\nProof.\n (* When it cannot solve the goal, [auto] does nothing *)\n auto.\n (* Optional argument says how deep to search (default is 5) *)\n auto 6.\nQed.\n\n(** When searching for potential proofs of the current goal,\n [auto] considers the hypotheses in the current context together\n with a _hint database_ of other lemmas and constructors. Some\n common lemmas about equality and logical operators are installed\n in this hint database by default. *)\n\nExample auto_example_4 : forall P Q R : Prop,\n Q ->\n (Q -> R) ->\n P \\/ (Q /\\ R).\nProof. auto. Qed.\n\n(** If we want to see which facts [auto] is using, we can use\n [info_auto] instead. *)\n\nExample auto_example_5: 2 = 2.\nProof.\n info_auto.\nQed.\n\n(** We can extend the hint database just for the purposes of one\n application of [auto] by writing \"[auto using ...]\". *)\n\nLemma le_antisym : forall n m: nat, (n <= m /\\ m <= n) -> n = m.\nProof. intros. omega. Qed.\n\nExample auto_example_6 : forall n m p : nat,\n (n <= p -> (n <= m /\\ m <= n)) ->\n n <= p ->\n n = m.\nProof.\n auto using le_antisym.\nQed.\n\n(** Of course, in any given development there will probably be\n some specific constructors and lemmas that are used very often in\n proofs. We can add these to the global hint database by writing\n\n Hint Resolve T.\n\n at the top level, where [T] is a top-level theorem or a\n constructor of an inductively defined proposition (i.e., anything\n whose type is an implication). As a shorthand, we can write\n\n Hint Constructors c.\n\n to tell Coq to do a [Hint Resolve] for _all_ of the constructors\n from the inductive definition of [c].\n\n It is also sometimes necessary to add\n\n Hint Unfold d.\n\n where [d] is a defined symbol, so that [auto] knows to expand uses\n of [d], thus enabling further possibilities for applying lemmas that\n it knows about. *)\n\n(** It is also possible to define specialized hint databases that can\n be activated only when needed. See the Coq reference manual for\n details. *)\n\nHint Resolve le_antisym.\n\nExample auto_example_6' : forall n m p : nat,\n (n<= p -> (n <= m /\\ m <= n)) ->\n n <= p ->\n n = m.\nProof.\n auto. (* picks up hint from database *)\nQed.\n\nDefinition is_fortytwo x := (x = 42).\n\nExample auto_example_7: forall x,\n (x <= 42 /\\ 42 <= x) -> is_fortytwo x.\nProof.\n auto. (* does nothing *)\nAbort.\n\nHint Unfold is_fortytwo.\n\nExample auto_example_7' : forall x,\n (x <= 42 /\\ 42 <= x) -> is_fortytwo x.\nProof.\n auto. (* try also: info_auto. *)\nQed.\n\n(** Let's take a first pass over [ceval_deterministic] to simplify the\n proof script. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst; auto.\n - (* E_Seq *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto.\n - (* E_IfTrue *)\n + (* b evaluates to false (contradiction) *)\n rewrite H in H5. discriminate.\n - (* E_IfFalse *)\n + (* b evaluates to true (contradiction) *)\n rewrite H in H5. discriminate.\n - (* E_WhileFalse *)\n + (* b evaluates to true (contradiction) *)\n rewrite H in H2. discriminate.\n (* E_WhileTrue *)\n - (* b evaluates to false (contradiction) *)\n rewrite H in H4. discriminate.\n - (* b evaluates to true *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto.\nQed.\n\n(** When we are using a particular tactic many times in a proof, we\n can use a variant of the [Proof] command to make that tactic into\n a default within the proof. Saying [Proof with t] (where [t] is\n an arbitrary tactic) allows us to use [t1...] as a shorthand for\n [t1;t] within the proof. As an illustration, here is an alternate\n version of the previous proof, using [Proof with auto]. *)\n\nTheorem ceval_deterministic'_alt: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof with auto.\n intros c st st1 st2 E1 E2;\n generalize dependent st2;\n induction E1;\n intros st2 E2; inversion E2; subst...\n - (* E_Seq *)\n assert (st' = st'0) as EQ1...\n subst st'0...\n - (* E_IfTrue *)\n + (* b evaluates to false (contradiction) *)\n rewrite H in H5. discriminate.\n - (* E_IfFalse *)\n + (* b evaluates to true (contradiction) *)\n rewrite H in H5. discriminate.\n - (* E_WhileFalse *)\n + (* b evaluates to true (contradiction) *)\n rewrite H in H2. discriminate.\n (* E_WhileTrue *)\n - (* b evaluates to false (contradiction) *)\n rewrite H in H4. discriminate.\n - (* b evaluates to true *)\n assert (st' = st'0) as EQ1...\n subst st'0...\nQed.\n\n(* ################################################################# *)\n(** * Searching For Hypotheses *)\n\n(** The proof has become simpler, but there is still an annoying\n amount of repetition. Let's start by tackling the contradiction\n cases. Each of them occurs in a situation where we have both\n\n H1: beval st b = false\n\n and\n\n H2: beval st b = true\n\n as hypotheses. The contradiction is evident, but demonstrating it\n is a little complicated: we have to locate the two hypotheses [H1]\n and [H2] and do a [rewrite] following by a [discriminate]. We'd\n like to automate this process.\n\n (In fact, Coq has a built-in tactic [congruence] that will do the\n job in this case. But we'll ignore the existence of this tactic\n for now, in order to demonstrate how to build forward search\n tactics by hand.)\n\n As a first step, we can abstract out the piece of script in\n question by writing a little function in Ltac. *)\n\nLtac rwd H1 H2 := rewrite H1 in H2; discriminate.\n\nTheorem ceval_deterministic'': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst; auto.\n - (* E_Seq *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto.\n - (* E_IfTrue *)\n + (* b evaluates to false (contradiction) *)\n rwd H H5.\n - (* E_IfFalse *)\n + (* b evaluates to true (contradiction) *)\n rwd H H5.\n - (* E_WhileFalse *)\n + (* b evaluates to true (contradiction) *)\n rwd H H2.\n (* E_WhileTrue *)\n - (* b evaluates to false (contradiction) *)\n rwd H H4.\n - (* b evaluates to true *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto. Qed.\n\n(** That was a bit better, but we really want Coq to discover the\n relevant hypotheses for us. We can do this by using the [match\n goal] facility of Ltac. *)\n\nLtac find_rwd :=\n match goal with\n H1: ?E = true,\n H2: ?E = false\n |- _ => rwd H1 H2\n end.\n\n(** This [match goal] looks for two distinct hypotheses that\n have the form of equalities, with the same arbitrary expression\n [E] on the left and with conflicting boolean values on the right.\n If such hypotheses are found, it binds [H1] and [H2] to their\n names and applies the [rwd] tactic to [H1] and [H2].\n\n Adding this tactic to the ones that we invoke in each case of the\n induction handles all of the contradictory cases. *)\n\nTheorem ceval_deterministic''': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst; try find_rwd; auto.\n - (* E_Seq *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto.\n - (* E_WhileTrue *)\n + (* b evaluates to true *)\n assert (st' = st'0) as EQ1 by auto.\n subst st'0.\n auto. Qed.\n\n(** Let's see about the remaining cases. Each of them involves\n applying a conditional hypothesis to extract an equality.\n Currently we have phrased these as assertions, so that we have to\n predict what the resulting equality will be (although we can then\n use [auto] to prove it). An alternative is to pick the relevant\n hypotheses to use and then [rewrite] with them, as follows: *)\n\nTheorem ceval_deterministic'''': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst; try find_rwd; auto.\n - (* E_Seq *)\n rewrite (IHE1_1 st'0 H1) in *. auto.\n - (* E_WhileTrue *)\n + (* b evaluates to true *)\n rewrite (IHE1_1 st'0 H3) in *. auto. Qed.\n\n(** Now we can automate the task of finding the relevant hypotheses to\n rewrite with. *)\n\nLtac find_eqn :=\n match goal with\n H1: forall x, ?P x -> ?L = ?R,\n H2: ?P ?X\n |- _ => rewrite (H1 X H2) in *\n end.\n\n(** The pattern [forall x, ?P x -> ?L = ?R] matches any hypothesis of\n the form \"for all [x], _some property of [x]_ implies _some\n equality_.\" The property of [x] is bound to the pattern variable\n [P], and the left- and right-hand sides of the equality are bound\n to [L] and [R]. The name of this hypothesis is bound to [H1].\n Then the pattern [?P ?X] matches any hypothesis that provides\n evidence that [P] holds for some concrete [X]. If both patterns\n succeed, we apply the [rewrite] tactic (instantiating the\n quantified [x] with [X] and providing [H2] as the required\n evidence for [P X]) in all hypotheses and the goal. *)\n\n\n\nTheorem ceval_deterministic''''': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1; intros st2 E2; inversion E2; subst; try find_rwd;\n try find_eqn; auto.\nQed.\n\n(** The big payoff in this approach is that our proof script should be\n more robust in the face of modest changes to our language. To\n test this, let's try adding a [REPEAT] command to the language. *)\n\nModule Repeat.\n\nInductive com : Type :=\n | CSkip\n | CAss (x : string) (a : aexp)\n | CSeq (c1 c2 : com)\n | CIf (b : bexp) (c1 c2 : com)\n | CWhile (b : bexp) (c : com)\n | CRepeat (c : com) (b : bexp).\n\n(** [REPEAT] behaves like [WHILE], except that the loop guard is\n checked _after_ each execution of the body, with the loop\n repeating as long as the guard stays _false_. Because of this,\n the body will always execute at least once. *)\n\nNotation \"'SKIP'\" :=\n CSkip.\nNotation \"x '::=' a\" :=\n (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" :=\n (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n (CWhile b c) (at level 80, right associativity).\nNotation \"'TEST' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n (CIf c1 c2 c3) (at level 80, right associativity).\nNotation \"'REPEAT' c 'UNTIL' b 'END'\" :=\n (CRepeat c b) (at level 80, right associativity).\n\nReserved Notation \"st '=[' c ']=>' st'\"\n (at level 40).\n\nInductive ceval : com -> state -> state -> Prop :=\n | E_Skip : forall st,\n st =[ SKIP ]=> st\n | E_Ass : forall st a1 n x,\n aeval st a1 = n ->\n st =[ x ::= a1 ]=> (x !-> n ; st)\n | E_Seq : forall c1 c2 st st' st'',\n st =[ c1 ]=> st' ->\n st' =[ c2 ]=> st'' ->\n st =[ c1 ;; c2 ]=> st''\n | E_IfTrue : forall st st' b c1 c2,\n beval st b = true ->\n st =[ c1 ]=> st' ->\n st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n | E_IfFalse : forall st st' b c1 c2,\n beval st b = false ->\n st =[ c2 ]=> st' ->\n st =[ TEST b THEN c1 ELSE c2 FI ]=> st'\n | E_WhileFalse : forall b st c,\n beval st b = false ->\n st =[ WHILE b DO c END ]=> st\n | E_WhileTrue : forall st st' st'' b c,\n beval st b = true ->\n st =[ c ]=> st' ->\n st' =[ WHILE b DO c END ]=> st'' ->\n st =[ WHILE b DO c END ]=> st''\n | E_RepeatEnd : forall st st' b c,\n st =[ c ]=> st' ->\n beval st' b = true ->\n st =[ REPEAT c UNTIL b END ]=> st'\n | E_RepeatLoop : forall st st' st'' b c,\n st =[ c ]=> st' ->\n beval st' b = false ->\n st' =[ REPEAT c UNTIL b END ]=> st'' ->\n st =[ REPEAT c UNTIL b END ]=> st''\n\n where \"st =[ c ]=> st'\" := (ceval c st st').\n\n(** Our first attempt at the determinacy proof does not quite succeed:\n the [E_RepeatEnd] and [E_RepeatLoop] cases are not handled by our\n previous automation. *)\n\nTheorem ceval_deterministic: forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1;\n intros st2 E2; inversion E2; subst; try find_rwd; try find_eqn; auto.\n - (* E_RepeatEnd *)\n + (* b evaluates to false (contradiction) *)\n find_rwd.\n (* oops: why didn't [find_rwd] solve this for us already?\n answer: we did things in the wrong order. *)\n - (* E_RepeatLoop *)\n + (* b evaluates to true (contradiction) *)\n find_rwd.\nQed.\n\n(** Fortunately, to fix this, we just have to swap the invocations of\n [find_eqn] and [find_rwd]. *)\n\nTheorem ceval_deterministic': forall c st st1 st2,\n st =[ c ]=> st1 ->\n st =[ c ]=> st2 ->\n st1 = st2.\nProof.\n intros c st st1 st2 E1 E2.\n generalize dependent st2;\n induction E1;\n intros st2 E2; inversion E2; subst; try find_eqn; try find_rwd; auto.\nQed.\n\nEnd Repeat.\n\n(** These examples just give a flavor of what \"hyper-automation\"\n can achieve in Coq. The details of [match goal] are a bit\n tricky (and debugging scripts using it is, frankly, not very\n pleasant). But it is well worth adding at least simple uses to\n your proofs, both to avoid tedium and to \"future proof\" them. *)\n\n(* ================================================================= *)\n(** ** The [eapply] and [eauto] variants *)\n\n(** To close the chapter, we'll introduce one more convenient feature\n of Coq: its ability to delay instantiation of quantifiers. To\n motivate this feature, recall this example from the [Imp]\n chapter: *)\n\nExample ceval_example1:\n empty_st =[\n X ::= 2;;\n TEST X <= 1\n THEN Y ::= 3\n ELSE Z ::= 4\n FI\n ]=> (Z !-> 4 ; X !-> 2).\nProof.\n (* We supply the intermediate state [st']... *)\n apply E_Seq with (X !-> 2).\n - apply E_Ass. reflexivity.\n - apply E_IfFalse. reflexivity. apply E_Ass. reflexivity.\nQed.\n\n(** In the first step of the proof, we had to explicitly provide a\n longish expression to help Coq instantiate a \"hidden\" argument to\n the [E_Seq] constructor. This was needed because the definition\n of [E_Seq]...\n\n E_Seq : forall c1 c2 st st' st'',\n st =[ c1 ]=> st' ->\n st' =[ c2 ]=> st'' ->\n st =[ c1 ;; c2 ]=> st''\n\n is quantified over a variable, [st'], that does not appear in its\n conclusion, so unifying its conclusion with the goal state doesn't\n help Coq find a suitable value for this variable. If we leave\n out the [with], this step fails (\"Error: Unable to find an\n instance for the variable [st']\").\n\n What's silly about this error is that the appropriate value for [st']\n will actually become obvious in the very next step, where we apply\n [E_Ass]. If Coq could just wait until we get to this step, there\n would be no need to give the value explicitly. This is exactly what\n the [eapply] tactic gives us: *)\n\nExample ceval'_example1:\n empty_st =[\n X ::= 2;;\n TEST X <= 1\n THEN Y ::= 3\n ELSE Z ::= 4\n FI\n ]=> (Z !-> 4 ; X !-> 2).\nProof.\n eapply E_Seq. (* 1 *)\n - apply E_Ass. (* 2 *)\n reflexivity. (* 3 *)\n - (* 4 *) apply E_IfFalse. reflexivity. apply E_Ass. reflexivity.\nQed.\n\n(** The [eapply H] tactic behaves just like [apply H] except\n that, after it finishes unifying the goal state with the\n conclusion of [H], it does not bother to check whether all the\n variables that were introduced in the process have been given\n concrete values during unification.\n\n If you step through the proof above, you'll see that the goal\n state at position [1] mentions the _existential variable_ [?st']\n in both of the generated subgoals. The next step (which gets us\n to position [2]) replaces [?st'] with a concrete value. This new\n value contains a new existential variable [?n], which is\n instantiated in its turn by the following [reflexivity] step,\n position [3]. When we start working on the second\n subgoal (position [4]), we observe that the occurrence of [?st']\n in this subgoal has been replaced by the value that it was given\n during the first subgoal. *)\n\n(** Several of the tactics that we've seen so far, including [exists],\n [constructor], and [auto], have similar variants. For example,\n here's a proof using [eauto]: *)\n\nHint Constructors ceval.\nHint Transparent state.\nHint Transparent total_map.\n\nDefinition st12 := (Y !-> 2 ; X !-> 1).\nDefinition st21 := (Y !-> 1 ; X !-> 2).\n\nExample eauto_example : exists s',\n st21 =[\n TEST X <= Y\n THEN Z ::= Y - X\n ELSE Y ::= X + Z\n FI\n ]=> s'.\nProof. info_eauto. Qed.\n\n(** The [eauto] tactic works just like [auto], except that it uses\n [eapply] instead of [apply]; [info_eauto] shows us which facts\n [auto] uses. *)\n\n(** Pro tip: One might think that, since [eapply] and [eauto] are more\n powerful than [apply] and [auto], we should just use them all the\n time. Unfortunately, they are also significantly slower --\n especially [eauto]. Coq experts tend to use [apply] and [auto]\n most of the time, only switching to the [e] variants when the\n ordinary variants don't do the job. *)\n\n\n(* 06 Apr 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/a8src/Auto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.20946967639529512, "lm_q1q2_score": 0.10064571320553428}}