text
stringlengths 938
1.05M
|
---|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_MS__NAND4B_4_V
`define SKY130_FD_SC_MS__NAND4B_4_V
/**
* nand4b: 4-input NAND, first input inverted.
*
* Verilog wrapper for nand4b with size of 4 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_ms__nand4b.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_ms__nand4b_4 (
Y ,
A_N ,
B ,
C ,
D ,
VPWR,
VGND,
VPB ,
VNB
);
output Y ;
input A_N ;
input B ;
input C ;
input D ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
sky130_fd_sc_ms__nand4b base (
.Y(Y),
.A_N(A_N),
.B(B),
.C(C),
.D(D),
.VPWR(VPWR),
.VGND(VGND),
.VPB(VPB),
.VNB(VNB)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_ms__nand4b_4 (
Y ,
A_N,
B ,
C ,
D
);
output Y ;
input A_N;
input B ;
input C ;
input D ;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
sky130_fd_sc_ms__nand4b base (
.Y(Y),
.A_N(A_N),
.B(B),
.C(C),
.D(D)
);
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_MS__NAND4B_4_V
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__A41O_FUNCTIONAL_PP_V
`define SKY130_FD_SC_LP__A41O_FUNCTIONAL_PP_V
/**
* a41o: 4-input AND into first input of 2-input OR.
*
* X = ((A1 & A2 & A3 & A4) | B1)
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_lp__udp_pwrgood_pp_pg.v"
`celldefine
module sky130_fd_sc_lp__a41o (
X ,
A1 ,
A2 ,
A3 ,
A4 ,
B1 ,
VPWR,
VGND,
VPB ,
VNB
);
// Module ports
output X ;
input A1 ;
input A2 ;
input A3 ;
input A4 ;
input B1 ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
// Local signals
wire and0_out ;
wire or0_out_X ;
wire pwrgood_pp0_out_X;
// Name Output Other arguments
and and0 (and0_out , A1, A2, A3, A4 );
or or0 (or0_out_X , and0_out, B1 );
sky130_fd_sc_lp__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_X, or0_out_X, VPWR, VGND);
buf buf0 (X , pwrgood_pp0_out_X );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_LP__A41O_FUNCTIONAL_PP_V |
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HD__LPFLOW_INPUTISO0N_BEHAVIORAL_PP_V
`define SKY130_FD_SC_HD__LPFLOW_INPUTISO0N_BEHAVIORAL_PP_V
/**
* lpflow_inputiso0n: Input isolator with inverted enable.
*
* X = (A & SLEEP_B)
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_l_pp_pg/sky130_fd_sc_hd__udp_pwrgood_l_pp_pg.v"
`celldefine
module sky130_fd_sc_hd__lpflow_inputiso0n (
X ,
A ,
SLEEP_B,
VPWR ,
VGND ,
VPB ,
VNB
);
// Module ports
output X ;
input A ;
input SLEEP_B;
input VPWR ;
input VGND ;
input VPB ;
input VNB ;
// Local signals
wire and0_out_X;
// Name Output Other arguments
and and0 (and0_out_X, A, SLEEP_B );
sky130_fd_sc_hd__udp_pwrgood$l_pp$PG pwrgood0 (X , and0_out_X, VPWR, VGND);
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_HD__LPFLOW_INPUTISO0N_BEHAVIORAL_PP_V |
`timescale 1ns / 1ps
`include "riffa.vh"
module pcie_data_sender #(parameter C_PCI_DATA_WIDTH = 128, INPUT_DATA_WIDTH = 8, NUM_PES = 8) (
input clk,
input rst,
//Collector Interface
output coll_ready,
input coll_data_valid,
input[INPUT_DATA_WIDTH - 1:0] coll_data,
//RIFFA TX Interface
output CHNL_TX,
input CHNL_TX_ACK,
output CHNL_TX_LAST,
output[`SIG_CHNL_LENGTH_W - 1:0] CHNL_TX_LEN,
output[30:0] CHNL_TX_OFF,
output[C_PCI_DATA_WIDTH - 1:0] CHNL_TX_DATA,
output reg CHNL_TX_DATA_VALID,
input CHNL_TX_DATA_REN,
input[`SIG_CHNL_LENGTH_W - 1:0] dna_len,
output idle,
input en
);
localparam DATA_PER_TX = C_PCI_DATA_WIDTH/INPUT_DATA_WIDTH; //number of data chunks that can fit with in C_PCI_DATA_WIDTH
parameter IT_BITS = $clog2(DATA_PER_TX);
reg state = STATE_IDLE;
localparam STATE_IDLE = 1'b0;
localparam STATE_SENDING = 1'b1;
reg[`SIG_CHNL_LENGTH_W - 1:0] dna_len_r, send_len;
reg tx_issued;
//state transition logic
always@(posedge clk) begin
if(rst) begin
state <= STATE_IDLE;
dna_len_r <= 0;
send_len <= 0;
end
else begin
case(state)
STATE_IDLE: begin
if(en) begin
dna_len_r <= (dna_len - NUM_PES)*NUM_PES >> 7 /*to 128-bit chunks*/ ; // excluding reference dna reads
send_len <= (dna_len - NUM_PES)*NUM_PES >> 5/*to 32-bit words*/; // excluding reference dna reads
state <= STATE_SENDING;
end
end //STATE_IDLE
STATE_SENDING: begin
if(tx_issued) begin
dna_len_r <= dna_len_r - 1;
if(dna_len_r == 1) begin
state <= STATE_IDLE;
end
end
end //STATE_SENDING
endcase
end
end
assign idle = (state == STATE_IDLE);
//Register Input Data
reg[INPUT_DATA_WIDTH - 1:0] data_r;
reg data_valid_r;
wire fetch_input = coll_ready;
always@(posedge clk) begin
if(rst) begin
data_r <= 0;
data_valid_r <= 0;
end
else begin
if(fetch_input) begin
data_r <= coll_data;
data_valid_r <= coll_data_valid;
end
end
end
//Put data chuck in tx buffer
reg[IT_BITS - 1:0] iter = 0;
reg[C_PCI_DATA_WIDTH - 1:0] tx_buffer;
reg tx_buffer_valid = 0;
always@(posedge clk) begin
if(rst) begin
tx_buffer <= 0;
tx_buffer_valid <= 0;
end
else begin
if(data_valid_r && coll_ready) begin
tx_buffer[iter*INPUT_DATA_WIDTH +:INPUT_DATA_WIDTH] <= data_r;
iter <= iter + 1'b1;
tx_buffer_valid <= &iter;
end
else if(tx_issued) begin
tx_buffer_valid <= 1'b0;
end
end
end
//TODO: consider adding one more register stage for better timing
//Send tx buffer to RIFFA
assign CHNL_TX_LEN = send_len; //C_PCI_DATA_WIDTH/32;
assign CHNL_TX_LAST = 1'b1; //(dna_len_r == 1);
assign CHNL_TX_OFF = 0;
assign CHNL_TX_DATA = tx_buffer;
assign CHNL_TX = (state == STATE_SENDING);
always@* begin
tx_issued = 1'b0;
CHNL_TX_DATA_VALID = 1'b0;
if(state == STATE_SENDING) begin
if(tx_buffer_valid) begin
CHNL_TX_DATA_VALID = 1'b1;
if(CHNL_TX_DATA_REN) begin
tx_issued = 1'b1;
end
end //tx_buffer_valid
end
end
assign coll_ready = ~tx_buffer_valid || (tx_buffer_valid && tx_issued);
endmodule
|
Require Export PredMonad.Reflection.OrderedType.
Require Export Coq.Logic.ProofIrrelevance.
Import EqNotations.
Import ListNotations.
Import ProofIrrelevanceTheory.
(***
*** Pairs of Types + Relations
***)
(* Shorthand for type + relation *)
Notation "'TpRel'" := (sigT OTRelation).
(* Shorthand for building type + relation pairs *)
Notation "'mkTpRel' A" := (existT OTRelation A _)
(left associativity, at level 20).
(* Shorthand for equalities on types + relations *)
Notation "A =t= B" := (existT OTRelation A%type _ = existT OTRelation B%type _)
(no associativity, at level 70).
(* OTRelation instance for the first projection of a type + relation pair *)
Instance OTRelation_projT1 (tprel:TpRel) : OTRelation (projT1 tprel) :=
projT2 tprel.
(* A pfun that converts from an otype to an equal one *)
Definition eq_pfun A B {RA:OTRelation A} {RB:OTRelation B} (e:A =t= B) :
A -o> B :=
match e in _ = existT _ B _ with
| eq_refl => id_pfun
end.
Arguments eq_pfun {_ _ _ _} !e.
(* Composing two eq_pfuns composes the equality proofs *)
Lemma compose_eq_pfun {A B C}
{RA:OTRelation A} {RB:OTRelation B} {RC:OTRelation C}
(e1:A =t= B) (e2:B =t= C) (e3:A =t= C) :
compose_pfun (eq_pfun e1) (eq_pfun e2) =o= eq_pfun e3.
Proof.
assert (A =t= B) as e1'; [ assumption | ].
assert (B =t= C) as e2'; [ assumption | ].
revert e1 e2 e3; dependent rewrite e1'; dependent rewrite e2'; intros.
repeat (rewrite (UIP_refl _ _ _); simpl).
split; intros c1 c2 Rc; apply Rc.
Qed.
(* An eq_pfun on two equal types simplifies to the identity *)
Lemma eq_pfun_refl {A} {RA:OTRelation A} (e:A =t= A) : eq_pfun e = id_pfun.
Proof.
rewrite (UIP_refl _ _ e). reflexivity.
Qed.
Lemma eqTpTupleR {A B C} {RA:OTRelation A} {RB:OTRelation B} {RC:OTRelation C} :
A =t= B -> A*C =t= B*C.
Proof.
intro e; dependent rewrite e; reflexivity.
Defined.
(* commute eq_pfun before a pfun_curry inside it *)
Lemma commute_eq_curry_pfun {A1 A2 B C}
`{OType A1} `{OType A2} `{OTRelation B} `{OTRelation C}
(e:A1 =t= A2) (f : (A2 * B) -o> C) :
compose_pfun (eq_pfun e) (pfun_curry f) =o=
pfun_curry (compose_pfun (eq_pfun (eqTpTupleR e)) f).
Proof.
assert (A1 =t= A2) as e'; try assumption.
revert H e f; dependent rewrite e'; intros.
rewrite (UIP_refl _ _ e). simpl.
split; intros x1 x2 Rx y1 y2 Ry; simpl; apply pfun_Proper; split; assumption.
Qed.
(* commute eq_pfun inside a pfun_apply *)
Lemma commute_eq_apply_pfun {A1 A2 B C}
`{OTRelation A1} `{OTRelation A2} `{OTRelation B} `{OTRelation C}
(e:A1 =t= A2) (f: A2 -o> B -o> C) g :
compose_pfun (eq_pfun e) (pfun_apply f g) =o=
pfun_apply (compose_pfun (eq_pfun e) f) (compose_pfun (eq_pfun e) g).
Proof.
assert (A1 =t= A2) as e'; try assumption.
revert e f g; dependent rewrite e'; intros. rewrite (UIP_refl _ _ _). simpl.
split; intros x1 x2 Rx; simpl;
assert (f @o@ x1 <o= f @o@ x2) as Rfx;
try (apply pfun_Proper; assumption);
apply Rfx; apply pfun_Proper; assumption.
Qed.
Lemma eq_pfun_adjoint_l {A1 A2 B}
`{OTRelation A1} `{OTRelation A2} `{OTRelation B}
(e12:A1 =t= A2) (e21:A2 =t= A1) f g :
compose_pfun (eq_pfun e12) f =o= g <-> f =o= compose_pfun (eq_pfun e21) g.
Proof.
assert (A1 =t= A2) as e'; try assumption.
revert f g e12 e21; dependent rewrite <- e'; intros.
rewrite (UIP_refl _ _ e12); rewrite (UIP_refl _ _ e21); simpl.
split; intros [Rfg Rgf]; split; intros x y Rxy; simpl;
first [ apply Rfg | apply Rgf ]; assumption.
Qed.
Lemma eq_pfun_adjoint_r {A1 A2 B}
`{OTRelation A1} `{OTRelation A2} `{OTRelation B}
(e12:A1 =t= A2) (e21:A2 =t= A1) f g :
compose_pfun f (eq_pfun e12) =o= g <-> f =o= compose_pfun g (eq_pfun e21).
Proof.
assert (A1 =t= A2) as e'; try assumption.
revert f g e12 e21; dependent rewrite <- e'; intros.
rewrite (UIP_refl _ _ e12); rewrite (UIP_refl _ _ e21); simpl.
split; intros [Rfg Rgf]; split; intros x y Rxy; simpl;
first [ apply Rfg | apply Rgf ]; assumption.
Qed.
(***
*** Ordered Type Contexts
***)
(* A context here is just a list of types *)
Inductive Ctx : Type :=
| CtxNil
| CtxCons A `{OTRelation A} (ctx:Ctx)
.
(* An element of a context is a nested tuple of elements of its types *)
Fixpoint CtxElem (ctx:Ctx) : Type :=
match ctx with
| CtxNil => unit
| CtxCons A ctx' => CtxElem ctx' * A
end.
(* OTRelation instance for any CtxElem type *)
Instance OTRelation_CtxElem ctx : OTRelation (CtxElem ctx).
Proof.
induction ctx.
- apply OTunit_R.
- apply OTpair_R; assumption.
Defined.
(* A context is valid iff each ordered type in it is valid *)
Fixpoint ValidCtxF ctx : Prop :=
match ctx with
| CtxNil => True
| CtxCons A ctx' =>
OType A /\ ValidCtxF ctx'
end.
(* Typeclass version of ValidCtxF *)
Class ValidCtx ctx : Prop := validCtx : ValidCtxF ctx.
(* Instances for building ValidCtx proofs *)
Instance ValidCtx_Nil : ValidCtx CtxNil := I.
Instance ValidCtx_Cons A `{OType A} ctx (vc:ValidCtx ctx) :
ValidCtx (CtxCons A ctx) := conj _ vc.
(* OType instance of CtxElem of a valid context *)
Instance OType_CtxElem ctx (valid:ValidCtx ctx) : OType (CtxElem ctx).
Proof.
induction ctx; [ | destruct valid ]; typeclasses eauto.
Qed.
(* Convert an equality on context to one on CtxElems *)
Definition eqCtxElem {ctx1 ctx2} (e:ctx1=ctx2) :
(CtxElem ctx1) =t= (CtxElem ctx2) :=
match e in _ = ctx2 with
| eq_refl => eq_refl
end.
(* Helper pfun that converts between equal contexts *)
Definition eq_ctx_pfun {ctx1 ctx2} e : CtxElem ctx1 -o> CtxElem ctx2 :=
eq_pfun (eqCtxElem e).
Arguments eq_ctx_pfun {_ _ } e /.
(* Get the head type of a context, defaulting to unit *)
Definition ctxHead ctx : Type :=
match ctx with
| CtxNil => unit
| CtxCons A _ => A
end.
Instance OTRelation_ctxHead ctx : OTRelation (ctxHead ctx) :=
match ctx with
| CtxNil => _
| CtxCons _ _ => _
end.
Instance OType_ctxHead ctx `{valid:ValidCtx ctx} : OType (ctxHead ctx).
Proof.
destruct ctx.
- typeclasses eauto.
- exact (proj1 valid).
Defined.
(* Get the tail of a context, defaulting to the empty context *)
Definition ctxTail ctx :=
match ctx with
| CtxNil => CtxNil
| CtxCons _ ctx' => ctx'
end.
Instance ValidCtx_ctxTail ctx `{valid:ValidCtx ctx} : ValidCtx (ctxTail ctx).
Proof.
destruct ctx.
- typeclasses eauto.
- exact (proj2 valid).
Defined.
(* Non-nil contexts equal cons of their heads and tails *)
Lemma ctx_eq_head_tail ctx :
ctx <> CtxNil -> ctx = CtxCons (ctxHead ctx) (ctxTail ctx).
destruct ctx; intro e.
elimtype False; apply e; reflexivity.
reflexivity.
Qed.
(* Look up the nth type in a Ctx, returning the unit type as a default *)
Fixpoint ctxNth n ctx {struct ctx} : Type :=
match ctx with
| CtxNil => unit
| CtxCons A ctx' =>
match n with
| 0 => A
| S n' => ctxNth n' ctx'
end
end.
Arguments ctxNth !n !ctx.
(* The OTRelation for the nth type in a context *)
Instance OTRelation_ctxNth n ctx : OTRelation (ctxNth n ctx).
Proof.
revert n; induction ctx; intros; simpl; try typeclasses eauto.
destruct n; simpl; typeclasses eauto.
Defined.
Arguments OTRelation_ctxNth !n !ctx.
(* For valid contexts, the nth element is a valid OType *)
Instance OType_ctxNth n ctx `{valid:ValidCtx ctx} : OType (ctxNth n ctx).
Proof.
revert n valid; induction ctx; intros; simpl; try typeclasses eauto.
destruct valid. destruct n; try assumption. apply IHctx; apply H1.
Defined.
(* The ctxNth of nil is always unit *)
Lemma ctxNth_nil n : ctxNth n CtxNil =t= unit.
Proof.
induction n; reflexivity.
Qed.
(* Pfun to extract the nth element of a context *)
Fixpoint nth_pfun ctx n : CtxElem ctx -o> ctxNth n ctx :=
match ctx return CtxElem ctx -o> ctxNth n ctx with
| CtxNil => const_pfun tt
| CtxCons A ctx' =>
match n return CtxElem (CtxCons A ctx') -o> ctxNth n (CtxCons A ctx') with
| 0 => snd_pfun
| S n' => compose_pfun fst_pfun (nth_pfun ctx' n')
end
end.
Arguments nth_pfun !ctx !n.
(* Appending contexts *)
(* FIXME: is this needed? *)
Fixpoint appendCtx ctx1 ctx2 : Ctx :=
match ctx1 with
| CtxNil => ctx2
| CtxCons A ctx1' =>
CtxCons A (appendCtx ctx1' ctx2)
end.
(* Context length *)
(* FIXME: is this needed? *)
Fixpoint ctxLen ctx :=
match ctx with
| CtxNil => 0
| CtxCons A ctx' => S (ctxLen ctx')
end.
(***
*** Context Insertion, aka Weakening
***)
(* Weaken a context by inserting a type at point w *)
Fixpoint ctxInsert w W {RW:OTRelation W} ctx : Ctx :=
match w with
| 0 => CtxCons W ctx
| S w' =>
match ctx with
| CtxNil => CtxCons unit (ctxInsert w' W CtxNil)
| CtxCons B ctx' => CtxCons B (ctxInsert w' W ctx')
end
end.
Arguments ctxInsert !w W {RW} !ctx.
(* FIXME: move these somewhere sensible! *)
Ltac destruct_ands :=
repeat (lazymatch goal with | H:_ /\ _ |- _ => destruct H | _ => idtac end).
Ltac split_ands :=
repeat (lazymatch goal with | |- _ /\ _ => split | _ => idtac end).
(* A context is valid iff its weakening with a valid OType is *)
Lemma ValidCtx_ctxInsert_iff n W `{OTRelation W} ctx :
(OType W /\ ValidCtx ctx) <-> ValidCtx (ctxInsert n W ctx).
Proof.
split; revert ctx; induction n; intro ctx; destruct ctx; simpl; intro valid;
destruct_ands; split_ands;
try typeclasses eauto; try apply I.
- apply IHn; split; auto.
- apply IHn; split; assumption.
- apply (proj1 (IHn CtxNil H1)).
- apply (proj1 (IHn _ H2)).
- apply (proj2 (IHn _ H2)).
Qed.
(* Weakening preserves validity *)
Instance ValidCtx_ctxInsert w W `{OType W} ctx {valid:ValidCtx ctx} :
ValidCtx (ctxInsert w W ctx).
Proof.
apply ValidCtx_ctxInsert_iff; split; assumption.
Defined.
Lemma OType_ctxInsert n W `{OTRelation W} ctx `{ValidCtx (ctxInsert n W ctx)} :
OType W.
Proof.
exact (proj1 ((proj2 (ValidCtx_ctxInsert_iff n W ctx)) H0)).
Qed.
(* ctxInsert commutes with ctxTail by incrementing the weakening position *)
Lemma ctxInsert_ctxTail n A {RA:OTRelation A} ctx :
ctxInsert n A (ctxTail ctx) = ctxTail (ctxInsert (S n) A ctx).
Proof.
revert ctx; induction n; intros; destruct ctx; reflexivity.
Qed.
(* The head of a weakened context at non-zero position is just the head of the
original context *)
Lemma ctxHead_ctxInsert_S n A {RA:OTRelation A} ctx :
ctxHead (ctxInsert (S n) A ctx) =t= ctxHead ctx.
Proof.
destruct ctx; reflexivity.
Qed.
(* Map from a weaker to a stronger context, by dropping the new element *)
Fixpoint weaken_pfun w W {RW:OTRelation W} ctx :
CtxElem (ctxInsert w W ctx) -o> CtxElem ctx :=
match w return CtxElem (ctxInsert w W ctx) -o> CtxElem ctx with
| 0 => fst_pfun (H:=OTRelation_CtxElem _)
| S w' =>
match ctx return CtxElem (ctxInsert (S w') W ctx) -o> CtxElem ctx with
| CtxNil => const_pfun tt
| CtxCons B ctx' =>
pair_pfun (compose_pfun fst_pfun (weaken_pfun w' W ctx')) snd_pfun
end
end.
Arguments weaken_pfun !w W {RW} !ctx.
(* Weaken an index in a context, to make ctxNth commute with ctxInsert *)
Fixpoint weakenIndex w (n:nat) {struct w} : nat :=
match w with
| 0 => S n
| S w' =>
match n with
| 0 => 0
| S n' => S (weakenIndex w' n')
end
end.
Arguments weakenIndex !w !n.
(* Weakening commutes with ctxNth *)
Lemma weaken_ctxNth w W {RW:OTRelation W} ctx n :
ctxNth (weakenIndex w n) (ctxInsert w W ctx) =t= ctxNth n ctx.
Proof.
revert ctx n; induction w; intros; destruct ctx; simpl.
- reflexivity.
- reflexivity.
- destruct n; simpl; try reflexivity. rewrite <- (ctxNth_nil n). apply IHw.
- destruct n; simpl; try reflexivity. apply IHw.
Qed.
(* FIXME: put this somewhere more appropriate *)
Lemma unit_eq_tt (x:unit) : x =o= tt.
Proof.
destruct x; reflexivity.
Qed.
(* FIXME: put this somewhere more appropriate *)
Definition pfun_unit_eq_tt {A} {RA:OTRelation A} (f g: A -o> unit) : f =o= g.
(* FIXME: why doesn't unit_eq_tt work without an arg on both sides? *)
split; intros x y Rxy; repeat rewrite (unit_eq_tt (_ @o@ _));
reflexivity.
Qed.
(* Weakening followed by nth is just the extended nth *)
Lemma weaken_nth_pfun w W `{OType W} ctx {valid:ValidCtx ctx} n :
compose_pfun (weaken_pfun w W ctx) (nth_pfun ctx n)
=o= compose_pfun (nth_pfun (ctxInsert w W ctx) (weakenIndex w n))
(eq_pfun (weaken_ctxNth w W ctx n)).
Proof.
revert ctx valid n; induction w; intros; destruct ctx; destruct n; simpl;
try apply pfun_unit_eq_tt; destruct valid.
- rewrite eq_pfun_refl. rewrite compose_id_pfun. reflexivity.
- rewrite eq_pfun_refl. rewrite compose_id_pfun. reflexivity.
- rewrite eq_pfun_refl. rewrite compose_pair_snd.
rewrite compose_id_pfun. reflexivity.
- rewrite compose_compose_pfun. rewrite compose_pair_fst.
rewrite <- compose_compose_pfun. rewrite IHw; try assumption.
rewrite compose_compose_pfun. f_equiv. f_equiv. apply proof_irrelevance.
Qed.
(***
*** Context Deletion, aka Substitution
***)
(* Delete the nth element of a context *)
Fixpoint ctxDelete n ctx {struct ctx} : Ctx :=
match ctx with
| CtxNil => CtxNil
| CtxCons A ctx' =>
match n with
| 0 => ctx'
| S n' => CtxCons A (ctxDelete n' ctx')
end
end.
Arguments ctxDelete !n !ctx.
Instance ValidCtx_ctxDelete n ctx {valid:ValidCtx ctx} :
ValidCtx (ctxDelete n ctx).
Proof.
revert n valid; induction ctx; intros n valid;
[ | destruct n; destruct valid ]; simpl.
- apply I.
- assumption.
- split; [ | apply IHctx ]; assumption.
Defined.
(* The the n+1-th suffix of a context *)
Fixpoint ctxSuffix n ctx {struct ctx} : Ctx :=
match ctx with
| CtxNil => CtxNil
| CtxCons A ctx' =>
match n with
| 0 => ctx'
| S n' => ctxSuffix n' ctx'
end
end.
(* ctxSuffix preserves ValidCtx *)
Instance ValidCtx_ctxSuffix n ctx {valid:ValidCtx ctx} :
ValidCtx (ctxSuffix n ctx).
Proof.
revert n valid; induction ctx; intros n valid;
[ | destruct n; destruct valid ]; simpl.
- apply I.
- assumption.
- apply IHctx; assumption.
Defined.
(* Substitute into a context by providing a pfun for the nth value *)
Fixpoint subst_pfun ctx n :
(CtxElem (ctxSuffix n ctx) -o> ctxNth n ctx) ->
CtxElem (ctxDelete n ctx) -o> CtxElem ctx :=
match ctx return
(CtxElem (ctxSuffix n ctx) -o> ctxNth n ctx) ->
CtxElem (ctxDelete n ctx) -o> CtxElem ctx with
| CtxNil => fun s => const_pfun tt
| CtxCons A ctx' =>
match n return
(CtxElem (ctxSuffix n (CtxCons A ctx')) -o> ctxNth n (CtxCons A ctx')) ->
CtxElem (ctxDelete n (CtxCons A ctx')) -o> CtxElem (CtxCons A ctx')
with
| 0 => fun s => pair_pfun id_pfun s
| S n' =>
fun s =>
pair_pfun (compose_pfun fst_pfun (subst_pfun ctx' n' s)) snd_pfun
end
end.
(* Proper-ness of subst_pfun *)
Instance Proper_subst_pfun ctx n : Proper (ot_R ==> ot_R) (subst_pfun ctx n).
Proof.
revert n; induction ctx; intros; [ | destruct n ]; simpl; intros s1 s2 Rs.
- reflexivity.
- intros c1 c2 Rc; simpl. split; [ | apply Rs ]; assumption.
- intros c1 c2 Rc; simpl.
split; destruct Rc; [ apply IHctx | ]; assumption.
Qed.
(* Proper-ness of subst_pfun w.r.t equivalence *)
Instance Proper_subst_pfun_equiv ctx n :
Proper (ot_equiv ==> ot_equiv) (subst_pfun ctx n).
Proof.
intros s1 s2 Rs; destruct Rs; split; apply Proper_subst_pfun; assumption.
Qed.
(* FIXME HERE: delete subst_var_pfun? *)
(* Helper shortcut for the repeated types in subst_var_pfun *)
Definition subst_var_tp ctx n v :=
(CtxElem (ctxSuffix n ctx) -o> ctxNth n ctx) ->
CtxElem (ctxDelete n ctx) -o> ctxNth v ctx.
(* Substitute into a variable v, which may or may not equal n *)
Fixpoint subst_var_pfun ctx n v {struct ctx} :
(CtxElem (ctxSuffix n ctx) -o> ctxNth n ctx) ->
CtxElem (ctxDelete n ctx) -o> ctxNth v ctx :=
match ctx return subst_var_tp ctx n v with
| CtxNil => fun s => const_pfun tt
| CtxCons A ctx' =>
match n return subst_var_tp (CtxCons A ctx') n v with
| 0 =>
match v return subst_var_tp (CtxCons A ctx') 0 v with
| 0 => fun s => s
| S v' => fun _ => nth_pfun ctx' v'
end
| S n' =>
match v return subst_var_tp (CtxCons A ctx') (S n') v with
| 0 => fun _ => snd_pfun
| S v' =>
fun s => compose_pfun fst_pfun (subst_var_pfun ctx' n' v' s)
end
end
end.
Lemma subst_nth_pfun ctx n v s {valid:ValidCtx ctx} :
compose_pfun (subst_pfun ctx n s) (nth_pfun ctx v) =o=
subst_var_pfun ctx n v s.
Proof.
revert n v s valid; induction ctx; intros;
[ | destruct n; destruct v; destruct valid ]; simpl.
- rewrite compose_const_pfun_f. reflexivity.
- apply compose_pair_snd.
- rewrite compose_compose_pfun. rewrite compose_pair_fst.
rewrite id_compose_pfun. reflexivity.
- apply compose_pair_snd.
- rewrite compose_compose_pfun. rewrite compose_pair_fst.
rewrite <- compose_compose_pfun. f_equiv. apply IHctx. assumption.
Qed.
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_MS__NAND2B_BLACKBOX_V
`define SKY130_FD_SC_MS__NAND2B_BLACKBOX_V
/**
* nand2b: 2-input NAND, first input inverted.
*
* Verilog stub definition (black box without power pins).
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_ms__nand2b (
Y ,
A_N,
B
);
output Y ;
input A_N;
input B ;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_MS__NAND2B_BLACKBOX_V
|
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: xilinx.com:ip:axi_crossbar:2.1
// IP Revision: 1
`timescale 1ns/1ps
(* DowngradeIPIdentifiedWarnings = "yes" *)
module ZynqDesign_xbar_1 (
aclk,
aresetn,
s_axi_awaddr,
s_axi_awprot,
s_axi_awvalid,
s_axi_awready,
s_axi_wdata,
s_axi_wstrb,
s_axi_wvalid,
s_axi_wready,
s_axi_bresp,
s_axi_bvalid,
s_axi_bready,
s_axi_araddr,
s_axi_arprot,
s_axi_arvalid,
s_axi_arready,
s_axi_rdata,
s_axi_rresp,
s_axi_rvalid,
s_axi_rready,
m_axi_awaddr,
m_axi_awprot,
m_axi_awvalid,
m_axi_awready,
m_axi_wdata,
m_axi_wstrb,
m_axi_wvalid,
m_axi_wready,
m_axi_bresp,
m_axi_bvalid,
m_axi_bready,
m_axi_araddr,
m_axi_arprot,
m_axi_arvalid,
m_axi_arready,
m_axi_rdata,
m_axi_rresp,
m_axi_rvalid,
m_axi_rready
);
(* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 CLKIF CLK" *)
input wire aclk;
(* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 RSTIF RST" *)
input wire aresetn;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI AWADDR" *)
input wire [31 : 0] s_axi_awaddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI AWPROT" *)
input wire [2 : 0] s_axi_awprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI AWVALID" *)
input wire [0 : 0] s_axi_awvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI AWREADY" *)
output wire [0 : 0] s_axi_awready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI WDATA" *)
input wire [31 : 0] s_axi_wdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI WSTRB" *)
input wire [3 : 0] s_axi_wstrb;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI WVALID" *)
input wire [0 : 0] s_axi_wvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI WREADY" *)
output wire [0 : 0] s_axi_wready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI BRESP" *)
output wire [1 : 0] s_axi_bresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI BVALID" *)
output wire [0 : 0] s_axi_bvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI BREADY" *)
input wire [0 : 0] s_axi_bready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI ARADDR" *)
input wire [31 : 0] s_axi_araddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI ARPROT" *)
input wire [2 : 0] s_axi_arprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI ARVALID" *)
input wire [0 : 0] s_axi_arvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI ARREADY" *)
output wire [0 : 0] s_axi_arready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI RDATA" *)
output wire [31 : 0] s_axi_rdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI RRESP" *)
output wire [1 : 0] s_axi_rresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI RVALID" *)
output wire [0 : 0] s_axi_rvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S00_AXI RREADY" *)
input wire [0 : 0] s_axi_rready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI AWADDR [31:0] [31:0], xilinx.com:interface:aximm:1.0 M01_AXI AWADDR [31:0] [63:32], xilinx.com:interface:aximm:1.0 M02_AXI AWADDR [31:0] [95:64]" *)
output wire [95 : 0] m_axi_awaddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI AWPROT [2:0] [2:0], xilinx.com:interface:aximm:1.0 M01_AXI AWPROT [2:0] [5:3], xilinx.com:interface:aximm:1.0 M02_AXI AWPROT [2:0] [8:6]" *)
output wire [8 : 0] m_axi_awprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI AWVALID [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI AWVALID [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI AWVALID [0:0] [2:2]" *)
output wire [2 : 0] m_axi_awvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI AWREADY [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI AWREADY [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI AWREADY [0:0] [2:2]" *)
input wire [2 : 0] m_axi_awready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI WDATA [31:0] [31:0], xilinx.com:interface:aximm:1.0 M01_AXI WDATA [31:0] [63:32], xilinx.com:interface:aximm:1.0 M02_AXI WDATA [31:0] [95:64]" *)
output wire [95 : 0] m_axi_wdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI WSTRB [3:0] [3:0], xilinx.com:interface:aximm:1.0 M01_AXI WSTRB [3:0] [7:4], xilinx.com:interface:aximm:1.0 M02_AXI WSTRB [3:0] [11:8]" *)
output wire [11 : 0] m_axi_wstrb;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI WVALID [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI WVALID [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI WVALID [0:0] [2:2]" *)
output wire [2 : 0] m_axi_wvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI WREADY [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI WREADY [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI WREADY [0:0] [2:2]" *)
input wire [2 : 0] m_axi_wready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI BRESP [1:0] [1:0], xilinx.com:interface:aximm:1.0 M01_AXI BRESP [1:0] [3:2], xilinx.com:interface:aximm:1.0 M02_AXI BRESP [1:0] [5:4]" *)
input wire [5 : 0] m_axi_bresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI BVALID [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI BVALID [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI BVALID [0:0] [2:2]" *)
input wire [2 : 0] m_axi_bvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI BREADY [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI BREADY [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI BREADY [0:0] [2:2]" *)
output wire [2 : 0] m_axi_bready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI ARADDR [31:0] [31:0], xilinx.com:interface:aximm:1.0 M01_AXI ARADDR [31:0] [63:32], xilinx.com:interface:aximm:1.0 M02_AXI ARADDR [31:0] [95:64]" *)
output wire [95 : 0] m_axi_araddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI ARPROT [2:0] [2:0], xilinx.com:interface:aximm:1.0 M01_AXI ARPROT [2:0] [5:3], xilinx.com:interface:aximm:1.0 M02_AXI ARPROT [2:0] [8:6]" *)
output wire [8 : 0] m_axi_arprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI ARVALID [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI ARVALID [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI ARVALID [0:0] [2:2]" *)
output wire [2 : 0] m_axi_arvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI ARREADY [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI ARREADY [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI ARREADY [0:0] [2:2]" *)
input wire [2 : 0] m_axi_arready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI RDATA [31:0] [31:0], xilinx.com:interface:aximm:1.0 M01_AXI RDATA [31:0] [63:32], xilinx.com:interface:aximm:1.0 M02_AXI RDATA [31:0] [95:64]" *)
input wire [95 : 0] m_axi_rdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI RRESP [1:0] [1:0], xilinx.com:interface:aximm:1.0 M01_AXI RRESP [1:0] [3:2], xilinx.com:interface:aximm:1.0 M02_AXI RRESP [1:0] [5:4]" *)
input wire [5 : 0] m_axi_rresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI RVALID [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI RVALID [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI RVALID [0:0] [2:2]" *)
input wire [2 : 0] m_axi_rvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M00_AXI RREADY [0:0] [0:0], xilinx.com:interface:aximm:1.0 M01_AXI RREADY [0:0] [1:1], xilinx.com:interface:aximm:1.0 M02_AXI RREADY [0:0] [2:2]" *)
output wire [2 : 0] m_axi_rready;
axi_crossbar_v2_1_axi_crossbar #(
.C_FAMILY("zynq"),
.C_NUM_SLAVE_SLOTS(1),
.C_NUM_MASTER_SLOTS(3),
.C_AXI_ID_WIDTH(1),
.C_AXI_ADDR_WIDTH(32),
.C_AXI_DATA_WIDTH(32),
.C_AXI_PROTOCOL(2),
.C_NUM_ADDR_RANGES(1),
.C_M_AXI_BASE_ADDR(192'H00000000412100000000000043c000000000000041200000),
.C_M_AXI_ADDR_WIDTH(96'H000000100000001000000010),
.C_S_AXI_BASE_ID(32'H00000000),
.C_S_AXI_THREAD_ID_WIDTH(32'H00000000),
.C_AXI_SUPPORTS_USER_SIGNALS(0),
.C_AXI_AWUSER_WIDTH(1),
.C_AXI_ARUSER_WIDTH(1),
.C_AXI_WUSER_WIDTH(1),
.C_AXI_RUSER_WIDTH(1),
.C_AXI_BUSER_WIDTH(1),
.C_M_AXI_WRITE_CONNECTIVITY(96'H000000010000000100000001),
.C_M_AXI_READ_CONNECTIVITY(96'H000000010000000100000001),
.C_R_REGISTER(1),
.C_S_AXI_SINGLE_THREAD(32'H00000001),
.C_S_AXI_WRITE_ACCEPTANCE(32'H00000001),
.C_S_AXI_READ_ACCEPTANCE(32'H00000001),
.C_M_AXI_WRITE_ISSUING(96'H000000010000000100000001),
.C_M_AXI_READ_ISSUING(96'H000000010000000100000001),
.C_S_AXI_ARB_PRIORITY(32'H00000000),
.C_M_AXI_SECURE(96'H000000000000000000000000),
.C_CONNECTIVITY_MODE(0)
) inst (
.aclk(aclk),
.aresetn(aresetn),
.s_axi_awid(1'H0),
.s_axi_awaddr(s_axi_awaddr),
.s_axi_awlen(8'H00),
.s_axi_awsize(3'H0),
.s_axi_awburst(2'H0),
.s_axi_awlock(1'H0),
.s_axi_awcache(4'H0),
.s_axi_awprot(s_axi_awprot),
.s_axi_awqos(4'H0),
.s_axi_awuser(1'H0),
.s_axi_awvalid(s_axi_awvalid),
.s_axi_awready(s_axi_awready),
.s_axi_wid(1'H0),
.s_axi_wdata(s_axi_wdata),
.s_axi_wstrb(s_axi_wstrb),
.s_axi_wlast(1'H1),
.s_axi_wuser(1'H0),
.s_axi_wvalid(s_axi_wvalid),
.s_axi_wready(s_axi_wready),
.s_axi_bid(),
.s_axi_bresp(s_axi_bresp),
.s_axi_buser(),
.s_axi_bvalid(s_axi_bvalid),
.s_axi_bready(s_axi_bready),
.s_axi_arid(1'H0),
.s_axi_araddr(s_axi_araddr),
.s_axi_arlen(8'H00),
.s_axi_arsize(3'H0),
.s_axi_arburst(2'H0),
.s_axi_arlock(1'H0),
.s_axi_arcache(4'H0),
.s_axi_arprot(s_axi_arprot),
.s_axi_arqos(4'H0),
.s_axi_aruser(1'H0),
.s_axi_arvalid(s_axi_arvalid),
.s_axi_arready(s_axi_arready),
.s_axi_rid(),
.s_axi_rdata(s_axi_rdata),
.s_axi_rresp(s_axi_rresp),
.s_axi_rlast(),
.s_axi_ruser(),
.s_axi_rvalid(s_axi_rvalid),
.s_axi_rready(s_axi_rready),
.m_axi_awid(),
.m_axi_awaddr(m_axi_awaddr),
.m_axi_awlen(),
.m_axi_awsize(),
.m_axi_awburst(),
.m_axi_awlock(),
.m_axi_awcache(),
.m_axi_awprot(m_axi_awprot),
.m_axi_awregion(),
.m_axi_awqos(),
.m_axi_awuser(),
.m_axi_awvalid(m_axi_awvalid),
.m_axi_awready(m_axi_awready),
.m_axi_wid(),
.m_axi_wdata(m_axi_wdata),
.m_axi_wstrb(m_axi_wstrb),
.m_axi_wlast(),
.m_axi_wuser(),
.m_axi_wvalid(m_axi_wvalid),
.m_axi_wready(m_axi_wready),
.m_axi_bid(3'H0),
.m_axi_bresp(m_axi_bresp),
.m_axi_buser(3'H0),
.m_axi_bvalid(m_axi_bvalid),
.m_axi_bready(m_axi_bready),
.m_axi_arid(),
.m_axi_araddr(m_axi_araddr),
.m_axi_arlen(),
.m_axi_arsize(),
.m_axi_arburst(),
.m_axi_arlock(),
.m_axi_arcache(),
.m_axi_arprot(m_axi_arprot),
.m_axi_arregion(),
.m_axi_arqos(),
.m_axi_aruser(),
.m_axi_arvalid(m_axi_arvalid),
.m_axi_arready(m_axi_arready),
.m_axi_rid(3'H0),
.m_axi_rdata(m_axi_rdata),
.m_axi_rresp(m_axi_rresp),
.m_axi_rlast(3'H7),
.m_axi_ruser(3'H0),
.m_axi_rvalid(m_axi_rvalid),
.m_axi_rready(m_axi_rready)
);
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__UDP_DLATCH_PR_PP_PKG_SN_SYMBOL_V
`define SKY130_FD_SC_LP__UDP_DLATCH_PR_PP_PKG_SN_SYMBOL_V
/**
* udp_dlatch$PR_pp$PKG$sN: D-latch, gated clear direct / gate active
* high (Q output UDP)
*
* Verilog stub (with power pins) for graphical symbol definition
* generation.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_lp__udp_dlatch$PR_pp$PKG$sN (
//# {{data|Data Signals}}
input D ,
output Q ,
//# {{control|Control Signals}}
input RESET ,
//# {{clocks|Clocking}}
input GATE ,
//# {{power|Power}}
input SLEEP_B ,
input KAPWR ,
input NOTIFIER,
input VPWR ,
input VGND
);
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_LP__UDP_DLATCH_PR_PP_PKG_SN_SYMBOL_V
|
// Copyright 1986-2016 Xilinx, Inc. All Rights Reserved.
// --------------------------------------------------------------------------------
// Tool Version: Vivado v.2016.4 (win64) Build 1733598 Wed Dec 14 22:35:39 MST 2016
// Date : Wed May 31 20:17:20 2017
// Host : GILAMONSTER running 64-bit major release (build 9200)
// Command : write_verilog -force -mode synth_stub
// c:/ZyboIP/examples/dma_example/dma_example.srcs/sources_1/bd/system/ip/system_auto_us_2/system_auto_us_2_stub.v
// Design : system_auto_us_2
// Purpose : Stub declaration of top-level module interface
// Device : xc7z020clg484-1
// --------------------------------------------------------------------------------
// This empty module with port declaration file causes synthesis tools to infer a black box for IP.
// The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion.
// Please paste the declaration into a Verilog source file or add the file as an additional source.
(* X_CORE_INFO = "axi_dwidth_converter_v2_1_11_top,Vivado 2016.4" *)
module system_auto_us_2(s_axi_aclk, s_axi_aresetn, s_axi_awaddr,
s_axi_awlen, s_axi_awsize, s_axi_awburst, s_axi_awlock, s_axi_awcache, s_axi_awprot,
s_axi_awregion, s_axi_awqos, s_axi_awvalid, s_axi_awready, s_axi_wdata, s_axi_wstrb,
s_axi_wlast, s_axi_wvalid, s_axi_wready, s_axi_bresp, s_axi_bvalid, s_axi_bready,
m_axi_awaddr, m_axi_awlen, m_axi_awsize, m_axi_awburst, m_axi_awlock, m_axi_awcache,
m_axi_awprot, m_axi_awregion, m_axi_awqos, m_axi_awvalid, m_axi_awready, m_axi_wdata,
m_axi_wstrb, m_axi_wlast, m_axi_wvalid, m_axi_wready, m_axi_bresp, m_axi_bvalid,
m_axi_bready)
/* synthesis syn_black_box black_box_pad_pin="s_axi_aclk,s_axi_aresetn,s_axi_awaddr[31:0],s_axi_awlen[7:0],s_axi_awsize[2:0],s_axi_awburst[1:0],s_axi_awlock[0:0],s_axi_awcache[3:0],s_axi_awprot[2:0],s_axi_awregion[3:0],s_axi_awqos[3:0],s_axi_awvalid,s_axi_awready,s_axi_wdata[31:0],s_axi_wstrb[3:0],s_axi_wlast,s_axi_wvalid,s_axi_wready,s_axi_bresp[1:0],s_axi_bvalid,s_axi_bready,m_axi_awaddr[31:0],m_axi_awlen[7:0],m_axi_awsize[2:0],m_axi_awburst[1:0],m_axi_awlock[0:0],m_axi_awcache[3:0],m_axi_awprot[2:0],m_axi_awregion[3:0],m_axi_awqos[3:0],m_axi_awvalid,m_axi_awready,m_axi_wdata[63:0],m_axi_wstrb[7:0],m_axi_wlast,m_axi_wvalid,m_axi_wready,m_axi_bresp[1:0],m_axi_bvalid,m_axi_bready" */;
input s_axi_aclk;
input s_axi_aresetn;
input [31:0]s_axi_awaddr;
input [7:0]s_axi_awlen;
input [2:0]s_axi_awsize;
input [1:0]s_axi_awburst;
input [0:0]s_axi_awlock;
input [3:0]s_axi_awcache;
input [2:0]s_axi_awprot;
input [3:0]s_axi_awregion;
input [3:0]s_axi_awqos;
input s_axi_awvalid;
output s_axi_awready;
input [31:0]s_axi_wdata;
input [3:0]s_axi_wstrb;
input s_axi_wlast;
input s_axi_wvalid;
output s_axi_wready;
output [1:0]s_axi_bresp;
output s_axi_bvalid;
input s_axi_bready;
output [31:0]m_axi_awaddr;
output [7:0]m_axi_awlen;
output [2:0]m_axi_awsize;
output [1:0]m_axi_awburst;
output [0:0]m_axi_awlock;
output [3:0]m_axi_awcache;
output [2:0]m_axi_awprot;
output [3:0]m_axi_awregion;
output [3:0]m_axi_awqos;
output m_axi_awvalid;
input m_axi_awready;
output [63:0]m_axi_wdata;
output [7:0]m_axi_wstrb;
output m_axi_wlast;
output m_axi_wvalid;
input m_axi_wready;
input [1:0]m_axi_bresp;
input m_axi_bvalid;
output m_axi_bready;
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HD__TAP_1_V
`define SKY130_FD_SC_HD__TAP_1_V
/**
* tap: Tap cell with no tap connections (no contacts on metal1).
*
* Verilog wrapper for tap with size of 1 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_hd__tap.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hd__tap_1 (
VPWR,
VGND,
VPB ,
VNB
);
input VPWR;
input VGND;
input VPB ;
input VNB ;
sky130_fd_sc_hd__tap base (
.VPWR(VPWR),
.VGND(VGND),
.VPB(VPB),
.VNB(VNB)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hd__tap_1 ();
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
sky130_fd_sc_hd__tap base ();
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_HD__TAP_1_V
|
module busInterface (
input wire [31:0] mem_addr,
input wire [31:0] mem_rdata_gpio,
input wire [31:0] mem_rdata_uart,
input wire [31:0] mem_rdata_uartRx,
input wire [31:0] mem_rdata_timer,
input wire [31:0] mem_rdata_prng,
input wire [31:0] mem_rdata_memory,
input wire mem_ready_gpio,
input wire mem_ready_uart,
input wire mem_ready_uartRx,
input wire mem_ready_timer,
input wire mem_ready_prng,
input wire mem_ready_memory,
output wire mem_ready,
output wire [31:0] mem_rdata,
output wire [7:0] enables
);
always @(*) begin
enables = 0;
case (mem_addr[31:4])
28'hffff000: enables[0] = 1'd1;
28'hffff001: enables[1] = 1'd1;
28'hffff002: enables[2] = 1'd1;
28'hffff003: enables[3] = 1'd1;
28'hffff004: enables[4] = 1'd1;
28'hffff005: enables[5] = 1'd1;
28'hffff006: enables[6] = 1'd1;
default: enables[7] = 1;
endcase
case (mem_addr[31:4])
28'hffff000: mem_ready = mem_ready_memory;
28'hffff001: mem_ready = mem_ready_memory;
28'hffff002: mem_ready = mem_ready_uartRx;
28'hffff003: mem_ready = mem_ready_timer;
28'hffff004: mem_ready = mem_ready_uart;
28'hffff005: mem_ready = mem_ready_prng;
28'hffff006: mem_ready = mem_ready_gpio;
default: mem_ready = mem_ready_memory;
endcase
case (mem_addr[31:4])
28'hffff000: mem_rdata = mem_rdata_memory;
28'hffff001: mem_rdata = mem_rdata_memory;
28'hffff002: mem_rdata = mem_rdata_uartRx;
28'hffff003: mem_rdata = mem_rdata_timer;
28'hffff004: mem_rdata = mem_rdata_uart;
28'hffff005: mem_rdata = mem_rdata_prng;
28'hffff006: mem_rdata = mem_rdata_gpio;
default: mem_rdata = mem_rdata_memory;
endcase
end
endmodule
|
module game_top_final
(
input wire clk, reset,
input wire [1:0] btn,
input wire [1:0] sw,
// btn for the bar, sw for the gun
// you should modify the sw (by de-bouncing)
output wire hsync, vsync,
output wire [2:0] rgb
// this should be directed to the UCF file
);
// symbolic state declaration
localparam [1:0]
newgame = 2'b00,
play = 2'b01,
newball = 2'b10,
over = 2'b11;
// same as the previous simpler one
// signal declaration
reg [1:0] state_reg, state_next;
// state machine transfer (two always)
wire [9:0] pixel_x, pixel_y;
wire video_on, pixel_tick, graph_on, hit, miss, kill;
// same as the name defined in sub-module
wire [3:0] text_on;
// for mux (with graph_ojn)
wire [2:0] graph_rgb, text_rgb;
reg [2:0] rgb_reg, rgb_next;
wire [3:0] dig0, dig1;
reg gra_still, d_inc, d_dec, d_clr, timer_start;
// for the auxiliary timer and counter (not the one linked with LCD or second timer)
wire timer_tick, timer_up;
reg boo_live;
// tell the second timer (cpp) that the player is still live or not
reg [1:0] ball_reg, ball_next;
// number of balls remained
//=======================================================
// instantiation
//=======================================================
// instantiate video synchronization unit
vga_sync vsync_unit
(.clk(clk), .reset(reset), .hsync(hsync), .vsync(vsync),
.video_on(video_on), .p_tick(pixel_tick),
.pixel_x(pixel_x), .pixel_y(pixel_y));
// instantiate text module
game_text game_text_unit
(.clk(clk),
.pix_x(pixel_x), .pix_y(pixel_y),
.dig0(dig0), .dig1(dig1), .ball(ball_reg),
.text_on(text_on), .text_rgb(text_rgb));
// eliminate the video_on signal if you wish
// instantiate graph module
game_graph graph_unit
(.clk(clk), .reset(reset), .btn(btn), .sw(sw), .video_on(video_on),
.pix_x(pixel_x), .pix_y(pixel_y),
.gra_still(gra_still), .hit(hit), .miss(miss), .kill(kill),
.graph_on(graph_on), .graph_rgb(graph_rgb));
// instantiate 2 sec timer
// 60 Hz tick (refresh rate)
assign timer_tick = (pixel_x==0) && (pixel_y==0);
// anyway, you can use the refr_tick if you wish
vga_timer vga_timer_unit
(.clk(clk), .reset(reset), .timer_tick(timer_tick),
.timer_start(timer_start), .timer_up(timer_up));
// instantiate 2-digit decade counter
score_counter score_counter_unit
(.clk(clk), .reset(reset), .d_inc(d_inc), .d_dec(d_dec), .d_clr(d_clr),
.dig0(dig0), .dig1(dig1));
// with this, text module can work normally
//=======================================================
// FSMD
//=======================================================
// FSMD state & data registers
always @(posedge clk, posedge reset)
if (reset)
begin
state_reg <= newgame;
ball_reg <= 0;
rgb_reg <= 0;
end
else
begin
state_reg <= state_next;
ball_reg <= ball_next;
if (pixel_tick)
rgb_reg <= rgb_next;
end
// FSMD next-state logic
always @*
begin
gra_still = 1'b1;
timer_start = 1'b0;
d_inc = 1'b0;
d_dec = 1'b0;
d_clr = 1'b0;
state_next = state_reg;
ball_next = ball_reg;
case (state_reg)
newgame:
begin
boo_live = 1'b1;
ball_next = 2'b11; // three balls
d_clr = 1'b1; // clear score
if (btn != 2'b00) // button pressed
// you can not attack before the game start, okay?
begin
state_next = play;
ball_next = ball_reg - 1;
end
end
play:
begin
gra_still = 1'b0; // animated screen
boo_live = 1'b1; // still live I assume
if (hit)
d_inc = 1'b1; // increment score
else if (kill)
// kill only decrease the score
// kill do not terminate player's life
d_dec = 1'b1; // decrease the score (by two)
else if (miss)
begin
if (ball_reg==0)
state_next = over;
else
state_next = newball;
timer_start = 1'b1; // 2 sec timer
ball_next = ball_reg - 1;
end
end
newball:
begin
boo_live = 1'b1;
// wait for 2 sec and until button pressed
if (timer_up && (btn != 2'b00))
state_next = play;
end
over:
begin
boo_live = 1'b0;
// now the player is dead
// finally
// wait for 2 sec to display game over
if (timer_up)
// you don't need to press the button I assume
state_next = newgame;
end
endcase
end
//=======================================================
// rgb multiplexing circuit
//=======================================================
always @*
if (~video_on)
rgb_next = "000"; // blank the edge/retrace
// because of that command, actually I don't need to input the video_on
// signal into the game_graph module
else
// display score, rule, or game over
if (text_on[3] ||
((state_reg==newgame) && text_on[1]) || // rule
((state_reg==over) && text_on[0]))
rgb_next = text_rgb;
else if (graph_on) // display graph
rgb_next = graph_rgb;
else if (text_on[2]) // display logo
rgb_next = text_rgb;
// logo should not cover the ball I assume
// but, who cares
else
rgb_next = 3'b110; // yellow background
// output
assign rgb = rgb_reg;
endmodule
|
`timescale 1ns / 1ps
////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 14:00:47 10/13/2014
// Design Name: uart_rx
// Module Name: C:/ece4743/projects/lab9_solution/tb_uart_rx.v
// Project Name: lab9_solution
// Target Device:
// Tool versions:
// Description:
//
// Verilog Test Fixture created by ISE for module: uart_rx
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
////////////////////////////////////////////////////////////////////////////////
module tb_uart_rx;
// Inputs
reg clk;
reg reset;
reg wren;
reg rden;
reg [7:0] din;
reg rxin;
reg [2:0] addr;
// Outputs
wire [8:0] dout;
parameter CLK_PERIOD=20; //clock period in ns. 20 ns = 50 MHZ
//parameter UUT_PERIOD=8'h1A; //57600 baudrate
parameter UUT_PERIOD=8'h0C; //115200 baudrate
parameter CLK16X_PERIOD=(CLK_PERIOD*(UUT_PERIOD+1)*2);
parameter CHARACTER_PERIOD = (CLK16X_PERIOD * 16 * 10);
// Instantiate the Unit Under Test (UUT)
uart_rx uut (
.clk(clk),
.reset(reset),
.wren(wren),
.rden(rden),
.din(din),
.dout(dout),
.rxin(rxin),
.addr(addr)
);
`define FSIZE 1024
integer infifo[(`FSIZE-1):0];
integer head,tail;
integer errors;
initial begin
clk = 0;
#100 //reset delay
forever #10 clk = ~clk;
end
//timeout process
initial begin
#(CHARACTER_PERIOD*35); //wait 35 characters
if (head != tail) begin
$display("%t: TIMEOUT, not all characters processed.",$time);
$display("The timeout is probably due to the DATARDY bit never going high.");
end
end
reg [9:0] shiftdata;
integer i;
task putserialdata;
input [8:0] outdata;
begin
infifo[head] = outdata;
head = head + 1;
if (head == `FSIZE) head = 0;
shiftdata ={1'b1,outdata[7:0],1'b0};
i = 0;
while (i != 10) begin
rxin = shiftdata[0];
#(CLK16X_PERIOD*16) //wait one bit time
i = i + 1;
shiftdata = {1'b1,shiftdata[9:1]};
end
end
endtask
task putserialdata_badstop;
input [8:0] outdata;
begin
infifo[head] = outdata;
head = head + 1;
if (head == `FSIZE) head = 0;
shiftdata ={1'b1,outdata[7:0],1'b0};
i = 0;
while (i != 10) begin
if (i == 9) rxin = 0;
else rxin = shiftdata[0];
#(CLK16X_PERIOD*16) //wait one bit time
i = i + 1;
shiftdata = {1'b1,shiftdata[9:1]};
end
end
endtask
task putserialdata_badstart;
input [8:0] outdata;
begin
infifo[head] = outdata;
head = head + 1;
if (head == `FSIZE) head = 0;
shiftdata ={1'b1,outdata[7:0],1'b0};
i = 0;
while (i != 10) begin
if (i == 0) begin
rxin = 0;
#(CLK16X_PERIOD*2);
rxin = 1; //bad start
#(CLK16X_PERIOD*14);
end else begin
rxin = shiftdata[0];
#(CLK16X_PERIOD*16); //wait one bit time
end
i = i + 1;
shiftdata = {1'b1,shiftdata[9:1]};
end
end
endtask
reg [8:0] expecteddata;
task readdata;
begin
//read status register, wait for TXDONE bit to be set
@(negedge clk);
rden = 1;
addr = 7; //status register
@(negedge clk);
while (dout[1] == 0) begin
@(negedge clk); //wait for DataRdy bit
end
addr = 5; //FIFO register
@(posedge clk); //must latch FIFO out data on posedge
if (expecteddata[8] == 1) begin
//expected framing error, just check ferr bit
if (dout[8] != 1) begin
errors = errors + 1;
$display("%t: FAIL,did not receive expected framing error",$time);
end else begin
$display("%t: PASS,received expected framing error",$time);
end
end else begin
//no expected framing error
if (expecteddata != dout) begin
errors = errors + 1;
$display("%t: FAIL,expected serial out of %h, found: %h",$time,expecteddata,dout);
end else begin
$display("%t: PASS,got expected serial out of %h",$time,expecteddata);
end
end
addr = 7;
rden = 0;
@(negedge clk);
end
endtask
task checkdata;
begin
while (head != tail) begin
expecteddata = infifo[tail];
tail = tail + 1;
if (tail == `FSIZE) tail = 0;
readdata();
end
end
endtask
task writerxen; //this writes a 'expectedbit' to the EN bit of the control register
input expectedbit;
begin
@(negedge clk);
din = {7'b0000000,expectedbit};
wren = 1;
addr = 7;
@(negedge clk);
wren = 0;
rden = 1;
@(negedge clk);
@(negedge clk);
if (dout[0] != expectedbit) begin
errors = errors + 1;
$display("%t: FAIL, writing UART RXEN bit = %h failed.",$time,expectedbit);
end else begin
$display("%t: PASS, writing UART RXEN bit = %h.",$time, expectedbit);
end
rden = 0;
@(negedge clk);
end
endtask
task rdoverrun; //read the overrun flag
input expectedbit;
begin
@(negedge clk);
addr = 7;
rden = 1;
@(negedge clk);
if (dout[2] != expectedbit) begin
errors = errors + 1;
$display("%t: FAIL, reading UART OVERRUN bit, expected: %h, actual: %h.",$time,expectedbit,dout[2]);
end else begin
$display("%t: PASS, reading UART OVERRUN bit: %h.",$time, expectedbit);
end
rden = 0;
end
endtask
task rddatardy; //read the data rdy flag
input expectedbit;
begin
@(negedge clk);
addr = 7;
rden = 1;
@(negedge clk);
if (dout[1] != expectedbit) begin
errors = errors + 1;
$display("%t: FAIL, reading UART DATARDY bit, expected: %h, actual: %h.",$time,expectedbit,dout[1]);
end else begin
$display("%t: PASS, reading UART DATARDY bit.",$time);
end
rden = 0;
end
endtask
integer j;
initial begin
// Initialize Inputs
#1
clk = 0;
reset = 1;
wren = 0;
rden = 0;
din = 0;
rxin = 1;
addr = 0;
errors = 0;
head = 0;
tail = 0;
// Wait 100 ns for global reset to finish
#100;
// Add stimulus here
reset = 0;
// Add stimulus here
@(negedge clk);
@(negedge clk);
@(negedge clk);
@(negedge clk);
@(negedge clk);
//first need to write the period register
din = UUT_PERIOD;
wren = 1;
addr = 4;
@(negedge clk);
wren = 0;
rden = 1;
@(negedge clk);
@(negedge clk);
if (dout != UUT_PERIOD) begin
errors = errors + 1;
$display("%t: FAIL, PERIOD register write/read failed: %h, expected: %h",$time,UUT_PERIOD,dout);
end else begin
$display("%t: PASS, Period register read/write",$time);
end
rden = 0;
@(negedge clk);
writerxen(1); //write a '1' to UART to get it started
putserialdata(9'h039);
checkdata();
putserialdata(9'h012);
putserialdata(9'h0D3);
putserialdata(9'h0B7);
#(CHARACTER_PERIOD*3)
#(CLK16X_PERIOD*16)
checkdata();
$display("Testing bad stop bit");
putserialdata_badstop(9'h155); //test bad stop bit
checkdata();
$display("Testing bad start bit");
putserialdata_badstop(9'h1AA); //test bad stop bit
checkdata();
putserialdata(9'h084);
checkdata();
//now test overrun
j = 0;
while (j != 18) begin
putserialdata(j+ 9'h030);
j = j + 1;
end
//check the overrun bit
@(negedge clk);
@(negedge clk);
@(negedge clk);
rdoverrun(0);
//send one more character, will set the overrun bit.
putserialdata(j+ 9'h030);
@(negedge clk);
@(negedge clk);
@(negedge clk);
rdoverrun(1);
//now reset the uart
writerxen(0); //write a '0' to UART RXEN to reset it.
//overrun should now be 0.
@(negedge clk);
@(negedge clk);
rdoverrun(0);
//data avaialble bit should be 0 as well
rddatardy(0);
//re-enable the modem
writerxen(1); //write a '1' to UART RXEN to enable it.
//we need flush our internal FIFO
head = 0; tail = 0;
//write one more datum to verify FIFO is restarted
putserialdata(9'h0A7);
checkdata();
$display("%t: All vectors done.",$time);
if (errors != 0)
$display("%t: FAIL, had %d errors during simulation.",$time,errors);
else
$display("%t: PASS, no errors during simulation.",$time);
end
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HDLL__AND3_1_V
`define SKY130_FD_SC_HDLL__AND3_1_V
/**
* and3: 3-input AND.
*
* Verilog wrapper for and3 with size of 1 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_hdll__and3.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hdll__and3_1 (
X ,
A ,
B ,
C ,
VPWR,
VGND,
VPB ,
VNB
);
output X ;
input A ;
input B ;
input C ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
sky130_fd_sc_hdll__and3 base (
.X(X),
.A(A),
.B(B),
.C(C),
.VPWR(VPWR),
.VGND(VGND),
.VPB(VPB),
.VNB(VNB)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hdll__and3_1 (
X,
A,
B,
C
);
output X;
input A;
input B;
input C;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
sky130_fd_sc_hdll__and3 base (
.X(X),
.A(A),
.B(B),
.C(C)
);
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_HDLL__AND3_1_V
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Francis Bruno, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, see <http://www.gnu.org/licenses>.
//
// This code is available under licenses for commercial use. Please contact
// Francis Bruno for more information.
//
// http://www.gplgpu.com
// http://www.asicsolutions.com
//
// Title : Write Buffer Registers
// File : hbi_wcregs.v
// Author : Frank Bruno
// Created : 30-Dec-2005
// RCS File : $Source:$
// Status : $Id:$
//
//
///////////////////////////////////////////////////////////////////////////////
//
// Description :
// Infer the registers that make up the hbi write buffer (cache). The
// "cache" consists of two buffers for data and two buffers for the
// memory controller mask (byte enables). The data and mask relate as
// follows:
//
// Buf 0:
// mc page 0 buff0 mask0
// mc page 1 buff1 mask1
// Buf 1:
// mc page 0 buff2 mask2
// mc page 1 buff3 mask3
//
// For each buffer, mc pages 0,1 are contiguous, with mc page 0 having
// the lower address.
//
// The output stage is simply a 4:1 mux, that selects the mc page and
// mask to be sent to the memory controller.
//
//////////////////////////////////////////////////////////////////////////////
//
// Modules Instantiated:
//
///////////////////////////////////////////////////////////////////////////////
//
// Modification History:
//
// $Log:$
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
`timescale 1ns/10ps
module hbi_wcregs
(
input hb_clk, // pci clock
input mclock, // MC clock
input hb_soft_reset_n, // reset
input [31:0] pci_data, // pci data, raw or converted from yuv
input [3:0] wc_be, // byte enables
input [3:0] wc_be_d, // byte enables
input clr_wc0, // clear cache0
input clr_wc1, // clear cache1
input ld_wc0, // load cache0
input ld_wc1, // load cache1
input wcregs_addr, // bit one of the RAM addr
input wcregs_we, // Write enable for the RAM
input [2:0] sub_buf_sel, // 1 of 4 "half buffers" for writing
input hst_push,
input hst_pop,
input [1:0] hst_mw_addr,
input select,
output [127:0] hb_pdo, // "write" pixel data to mc
output reg [15:0] hst_md, // byte mask data to mc
output reg mc_done,
output reg [1:0] push_count
);
reg [3:0] mask0; // byte enables buffers
reg [3:0] mask1;
reg [3:0] mask2;
reg [3:0] mask3;
reg [3:0] mask4; // byte enables buffers
reg [3:0] mask5;
reg [3:0] mask6;
reg [3:0] mask7;
reg [3:0] mask8; // byte enables buffers
reg [3:0] mask9;
reg [3:0] maska;
reg [3:0] maskb;
reg [3:0] maskc; // byte enables buffers
reg [3:0] maskd;
reg [3:0] maske;
reg [3:0] maskf;
reg [3:0] wc_be_i; // byte enables
reg [3:0] wc_be_di, wc_be_dii; // byte enables
reg clr_wc0_i; // clear cache0
reg clr_wc1_i; // clear cache1
reg ld_wc0_i; // load cache0
reg ld_wc1_i; // load cache1
reg [2:0] sub_buf_sel_i; // 1 of 4 "half buffers" for writing
reg [3:0] waddr;
reg we;
reg [1:0] pop_count;
wire [127:0] data_in;
// Technically agp data should be delayed one cycle. However, since I am not
// using it, it is sort of a place holder for DMA, I am leaving it as is
always @(posedge hb_clk) begin
waddr <= {wcregs_addr, sub_buf_sel} | select;
we <= wcregs_we;
wc_be_i <= select ? wc_be_di : wc_be;
wc_be_di <= wc_be_d;
clr_wc0_i <= clr_wc0;
clr_wc1_i <= clr_wc1;
ld_wc0_i <= ld_wc0;
ld_wc1_i <= ld_wc1;
sub_buf_sel_i <= sub_buf_sel | select;
end
dpram_32_128x16 U_MW_RAM
(
.data (pci_data),
.wren (we),
.wraddress (waddr),
.rdaddress (hst_mw_addr),
.byteena_a (~wc_be_i),
.wrclock (hb_clk),
.rdclock (mclock),
.q (hb_pdo)
);
// Mask (byte enable) buffer
// loads have precedence over clears. when a clear is received, every
// mask for that buffer is cleared, except for the selected mask being loaded
always @(posedge hb_clk) begin
case (sub_buf_sel_i) //synopsys full_case parallel_case
3'd0: begin
// Mask for Buffer 0
if (ld_wc0_i) mask0 <= mask0 & wc_be_i;
else if (clr_wc0_i) mask0 <= 4'hF;
if (clr_wc0_i) begin
mask1 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) mask8 <= mask8 & wc_be_i;
else if (clr_wc1_i) mask8 <= 4'hF;
if (clr_wc1_i) begin
mask9 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd1: begin
// Mask for Buffer 0
if (ld_wc0_i) mask1 <= mask1 & wc_be_i;
else if (clr_wc0_i) mask1 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) mask9 <= mask9 & wc_be_i;
else if (clr_wc1_i) mask9 <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd2: begin
// Mask for Buffer 0
if (ld_wc0_i) mask2 <= mask2 & wc_be_i;
else if (clr_wc0_i) mask2 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maska <= maska & wc_be_i;
else if (clr_wc1_i) maska <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd3: begin
// Mask for Buffer 0
if (ld_wc0_i) mask3 <= mask3 & wc_be_i;
else if (clr_wc0_i) mask3 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask2 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maskb <= maskb & wc_be_i;
else if (clr_wc1_i) maskb <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maska <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd4: begin
// Mask for Buffer 0
if (ld_wc0_i) mask4 <= mask4 & wc_be_i;
else if (clr_wc0_i) mask4 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maskc <= maskc & wc_be_i;
else if (clr_wc1_i) maskc <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd5: begin
// Mask for Buffer 0
if (ld_wc0_i) mask5 <= mask5 & wc_be_i;
else if (clr_wc0_i) mask5 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask6 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maskd <= maskd & wc_be_i;
else if (clr_wc1_i) maskd <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maske <= 4'hF;
maskf <= 4'hF;
end
end
3'd6: begin
// Mask for Buffer 0
if (ld_wc0_i) mask6 <= mask6 & wc_be_i;
else if (clr_wc0_i) mask6 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask7 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maske <= maske & wc_be_i;
else if (clr_wc1_i) maske <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maskf <= 4'hF;
end
end
3'd7: begin
// Mask for Buffer 0
if (ld_wc0_i) mask7 <= mask7 & wc_be_i;
else if (clr_wc0_i) mask7 <= 4'hF;
if (clr_wc0_i) begin
mask0 <= 4'hF;
mask1 <= 4'hF;
mask2 <= 4'hF;
mask3 <= 4'hF;
mask4 <= 4'hF;
mask5 <= 4'hF;
mask6 <= 4'hF;
end
// Mask for buffer 1
if (ld_wc1_i) maskf <= maskf & wc_be_i;
else if (clr_wc1_i) maskf <= 4'hF;
if (clr_wc1_i) begin
mask8 <= 4'hF;
mask9 <= 4'hF;
maska <= 4'hF;
maskb <= 4'hF;
maskc <= 4'hF;
maskd <= 4'hF;
maske <= 4'hF;
end
end
endcase // case(sub_buf_sel_i)
end // always @ (posedge hb_clk)
// pop, push counters, and done flag
always @(posedge mclock or negedge hb_soft_reset_n) begin
if (!hb_soft_reset_n) begin
push_count <= 2'b00;
pop_count <= 2'b00;
mc_done <= 1'b0;
end else begin
// push counter. It is used to tell when MC is done
if (hst_push) push_count <= push_count + 2'b01;
if (hst_pop) pop_count <= pop_count + 2'b01;
// Done flop. This toggles when MC is done. Writes are always 8 cycles,
// reads are always 16 cycles.
if ((hst_pop && pop_count[0]) || (hst_push && (push_count == 2'b11)))
mc_done <= ~mc_done;
end // else: !if(!hb_soft_reset_n)
end // always @ (posedge mclock or negedge hb_soft_reset_n)
// output mux
always @* begin
case (pop_count)
2'h3: hst_md = {maskf, maske, maskd, maskc};
2'h2: hst_md = {maskb, maska, mask9, mask8};
2'h1: hst_md = {mask7, mask6, mask5, mask4};
2'h0: hst_md = {mask3, mask2, mask1, mask0};
endcase // case(pop_count)
end // always @ (pop_count or...
endmodule // HBI_WCREGS
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/13/2016 05:51:29 PM
// Design Name:
// Module Name: Testbench_Barrel_Shifter
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Testbench_Barrel_Shifter ();
parameter PERIOD = 10;
parameter EWR=5;
parameter SWR=26;
//inputs
reg clk;
reg rst;
reg load_i;
reg [EWR-1:0] Shift_Value_i;
reg [SWR-1:0] Shift_Data_i;
reg Left_Right_i;
reg Bit_Shift_i;
///////////////////OUTPUT//////////////////////////7
wire [SWR-1:0] N_mant_o;
Mux_Array_DW #(
.SWR(SWR),
.EWR(EWR)
) inst_Mux_Array (
.clk(clk),
.rst(rst),
.load_i(load_i),
.Data_i (Shift_Data_i),
.FSM_left_right_i (Left_Right_i),
.Shift_Value_i (Shift_Value_i),
.bit_shift_i (Bit_Shift_i),
.Data_o (N_mant_o)
);
integer Contador_shiftvalue = 0;
always begin
#(8*PERIOD/2) Contador_shiftvalue = Contador_shiftvalue + 1;
Shift_Value_i = Contador_shiftvalue;
Left_Right_i = ~Left_Right_i;
#(8*PERIOD/2);
end
always @ (N_mant_o )
begin
$monitor($time,"REA Salida = %b Entrada = %b Numero de Corrimiento: %d",N_mant_o,Shift_Data_i, Shift_Value_i);
$display($time,"TEO Salida = %b Entrada = %b Numero de Corrimiento: %d",(Shift_Data_i>>Shift_Value_i),Shift_Data_i,Shift_Value_i);
end
initial begin
// Initialize Input
rst = 1;
clk = 0;
load_i = 0;
Shift_Value_i = 0;
Shift_Data_i = $random;
Left_Right_i = 0;
Bit_Shift_i = 0;
#40 rst = 0;
load_i = 1;
end
initial begin
#(PERIOD * 1024);
$finish;
end
initial begin
clk = 1'b0;
#(PERIOD/2);
forever
#(PERIOD/2) clk = ~clk;
end
endmodule
|
// ========== Copyright Header Begin ==========================================
//
// OpenSPARC T1 Processor File: tlu_misctl.v
// Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
//
// The above named program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License version 2 as published by the Free Software Foundation.
//
// The above named program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this work; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// ========== Copyright Header End ============================================
////////////////////////////////////////////////////////////////////////
/*
// Description: Block that contain most of miscellaneous
// control and datapath components
// to alleviate tdp and tcp congestions
*/
////////////////////////////////////////////////////////////////////////
// Global header file includes
////////////////////////////////////////////////////////////////////////
`include "sys.h" // system level definition file which contains the
// time scale definition
`include "tlu.h"
////////////////////////////////////////////////////////////////////////
// Local header file includes / local defines
////////////////////////////////////////////////////////////////////////
module tlu_misctl (/*AUTOARG*/
// outputs
tlu_exu_cwp_m, tlu_exu_ccr_m, tlu_lsu_asi_m, tlu_cwp_no_change_m,
tlu_sscan_misctl_data, tlu_ifu_trappc_w2, tlu_ifu_trapnpc_w2,
tlu_pc_new_w, tlu_npc_new_w, so,
// PIC experiment
tlu_exu_pic_onebelow_m, tlu_exu_pic_twobelow_m,
// inputs
ctu_sscan_tid, ifu_tlu_pc_m, exu_tlu_cwp0, exu_tlu_cwp1, exu_tlu_cwp2,
exu_tlu_cwp3, tlu_final_ttype_w2, tsa_wr_tid, tlu_true_pc_sel_w,
tsa1_wr_vld, tsa_ttype_en, tsa_rd_vld_e, tsa0_rdata_cwp, tsa0_rdata_pstate,
tsa0_rdata_asi, tsa0_rdata_ccr, tsa0_rdata_gl, tsa0_rdata_pc, tsa1_rdata_ttype,
tsa1_rdata_npc, tsa1_rdata_htstate, tlu_thrd_rsel_e, tlu_final_offset_w1,
tlu_partial_trap_pc_w1, tlu_restore_pc_w1, tlu_restore_npc_w1,
ifu_npc_w, tlu_restore_pc_sel_w1, tlu_pic_cnt_en_m, tlu_pic_onebelow_e,
tlu_pic_twobelow_e, tlu_rst, si, se, rclk);
// pich_threebelow_flg, pich_twobelow_flg, pich_onebelow_flg,
//=================================================
// output
//=================================================
output [`TSA_CCR_WIDTH-1:0] tlu_exu_ccr_m; // restored ccr
output [`TSA_CWP_WIDTH-1:0] tlu_exu_cwp_m; // restored cwp
output [`TLU_ASI_STATE_WIDTH-1:0] tlu_lsu_asi_m; // restored asi
output tlu_cwp_no_change_m; // cwp change indicator
//
// sscan output
output [`MISCTL_SSCAN_WIDTH-1:0] tlu_sscan_misctl_data;
//
// trap pc and npc
output [48:0] tlu_ifu_trappc_w2, tlu_ifu_trapnpc_w2;
output [48:0] tlu_pc_new_w, tlu_npc_new_w;
// global nets
output so;
// PIC experiment
output tlu_exu_pic_onebelow_m; // local traps send to exu
output tlu_exu_pic_twobelow_m; // local traps send to exu
//=================================================
// input
//=================================================
// sscan related inputs
input [`TLU_THRD_NUM-1:0] ctu_sscan_tid;
input [`TSA_TTYPE_WIDTH-1:0] tlu_final_ttype_w2;
input [1:0] tsa_wr_tid;
input tsa1_wr_vld, tsa_rd_vld_e;
input tsa_ttype_en;
//
// current cwp value from exu
input [2:0] exu_tlu_cwp0; // cwp - thread0
input [2:0] exu_tlu_cwp1; // cwp - thread1
input [2:0] exu_tlu_cwp2; // cwp - thread2
input [2:0] exu_tlu_cwp3; // cwp - thread3
//
// componets from trap stack arrays (tsas)
input [`TSA_CWP_WIDTH-1:0] tsa0_rdata_cwp;
input [`TSA_PSTATE_WIDTH-1:0] tsa0_rdata_pstate;
input [`TSA_CCR_WIDTH-1:0] tsa0_rdata_ccr;
input [`TLU_ASI_STATE_WIDTH-1:0] tsa0_rdata_asi;
input [`TSA_GLOBAL_WIDTH-1:0] tsa0_rdata_gl;
input [46:0] tsa0_rdata_pc;
input [`TSA_TTYPE_WIDTH-1:0] tsa1_rdata_ttype;
input [46:0] tsa1_rdata_npc;
input [`TSA_HTSTATE_WIDTH-1:0] tsa1_rdata_htstate;
//
// trap pc calculations signals
input [48:0] ifu_tlu_pc_m; // pc
// input [48:0] ifu_tlu_npc_m; // npc
input [`TSA_TTYPE_WIDTH-1:0] tlu_final_offset_w1;
input [33:0] tlu_partial_trap_pc_w1;
input [48:0] tlu_restore_pc_w1;
input [48:0] tlu_restore_npc_w1;
// input [48:0] ifu_pc_w;
input [48:0] ifu_npc_w;
input tlu_restore_pc_sel_w1;
//
// modified due to timing fix
input [2:0] tlu_true_pc_sel_w;
// input tlu_retry_inst_m;
// input tlu_done_inst_m;
// input tlu_dnrtry_inst_m_l;
//
input [`TLU_THRD_NUM-1:0] tlu_thrd_rsel_e;
// global nets
input si, se;
//
//clk
input rclk;
//
// PIC trap experiment
// input [`TLU_THRD_NUM-1:0] tlu_thread_inst_vld_w2; // valid inst for a thread
// input [`TLU_THRD_NUM-1:0] pich_threebelow_flg;
// input [`TLU_THRD_NUM-1:0] pich_twobelow_flg;
// input [`TLU_THRD_NUM-1:0] pich_onebelow_flg;
input tlu_pic_onebelow_e;
input tlu_pic_twobelow_e;
input tlu_pic_cnt_en_m;
input tlu_rst;
//=================================================
// local wires
//=================================================
// local clock
wire clk;
//
// staged thread id
wire [`TLU_THRD_NUM-1:0] thrd_sel_m;
wire [`TLU_THRD_NUM-1:0] tsa_wsel_thrd_w2;
//
// staged tsa_controls
wire tsa_rd_vld_m; // tsa_rd_vld_e,
//
// components from tsas
// tsa0
wire [`TLU_ASI_STATE_WIDTH-1:0] tsa0_asi_m;
wire [`TSA_CWP_WIDTH-1:0] tsa0_cwp_m;
wire [`TSA_CCR_WIDTH-1:0] tsa0_ccr_m;
wire [`TSA_PSTATE_WIDTH-1:0] tsa0_pstate_m;
wire [`TSA_GLOBAL_WIDTH-1:0] tsa0_gl_m;
wire [46:0] tsa0_pc_m;
// tsa1
wire [`TSA_TTYPE_WIDTH-1:0] tsa1_ttype_m;
wire [`TSA_HTSTATE_WIDTH-1:0] tsa1_htstate_m;
wire [46:0] tsa1_npc_m;
//
// modified for timing
// wire [48:0] pc_new_m, npc_new_m;
wire [48:0] pc_new_w, npc_new_w, ifu_pc_w;
wire [46:0] tsa0_pc_w, tsa1_npc_w;
//
// sscan related signals
wire [`TLU_THRD_NUM-1:0] sscan_tid_sel;
wire [`TLU_THRD_NUM-1:0] sscan_ttype_en;
wire [`TLU_THRD_NUM-1:0] sscan_tt_rd_sel;
wire [`TLU_THRD_NUM-1:0] sscan_tt_wr_sel;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt0_data;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt1_data;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt2_data;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt3_data;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt0_din;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt1_din;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt2_din;
wire [`TSA_TTYPE_WIDTH-1:0] sscan_tt3_din;
wire [`MISCTL_SSCAN_WIDTH-1:0] misctl_sscan_test_data;
//
// cwp logic
wire cwp_no_change_m;
wire [`TSA_CWP_WIDTH-1:0] cwp_xor_m, trap_old_cwp_m;
wire [48:0] normal_trap_pc_w1, normal_trap_npc_w1;
wire [48:0] trap_pc_w1, trap_npc_w1;
wire [48:0] trap_pc_w2, trap_npc_w2;
//
// PIC experiment
wire tlu_pic_onebelow_m, tlu_pic_twobelow_m;
// wire [`TLU_THRD_NUM-1:0] pic_onebelow_e, pic_twobelow_e;
wire local_rst;
//
//=========================================================================================
// local clock
//=========================================================================================
assign clk = rclk;
//=========================================================================================
// TSA data capture
//=========================================================================================
dff_s #(`TSA_CCR_WIDTH) dff_tsa0_ccr_m (
.din (tsa0_rdata_ccr[`TSA_CCR_WIDTH-1:0]),
.q (tsa0_ccr_m[`TSA_CCR_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TSA_CWP_WIDTH) dff_tsa0_cwp_m (
.din (tsa0_rdata_cwp[`TSA_CWP_WIDTH-1:0]),
.q (tsa0_cwp_m[`TSA_CWP_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TLU_ASI_STATE_WIDTH) dff_lsu_asi_m (
.din (tsa0_rdata_asi[`TLU_ASI_STATE_WIDTH-1:0]),
.q (tsa0_asi_m[`TLU_ASI_STATE_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TSA_PSTATE_WIDTH) dff_tsa0_pstate_m (
.din (tsa0_rdata_pstate[`TSA_CCR_WIDTH-1:0]),
.q (tsa0_pstate_m[`TSA_PSTATE_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TSA_GLOBAL_WIDTH) dff_tsa0_gl_m (
.din (tsa0_rdata_gl[`TSA_GLOBAL_WIDTH-1:0]),
.q (tsa0_gl_m[`TSA_GLOBAL_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(47) dff_tsa0_pc_m (
.din (tsa0_rdata_pc[46:0]),
.q (tsa0_pc_m[46:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TSA_TTYPE_WIDTH) dff_tsa1_ttype_m (
.din (tsa1_rdata_ttype[`TSA_TTYPE_WIDTH-1:0]),
.q (tsa1_ttype_m[`TSA_TTYPE_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(`TSA_HTSTATE_WIDTH) dff_tsa1_htstate_m (
.din (tsa1_rdata_htstate[`TSA_HTSTATE_WIDTH-1:0]),
.q (tsa1_htstate_m[`TSA_HTSTATE_WIDTH-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(47) dff_tsa1_npc_m (
.din (tsa1_rdata_npc[46:0]),
.q (tsa1_npc_m[46:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
//
//=========================================================================================
// CWP/CCR restoration
//=========================================================================================
assign tlu_exu_ccr_m[`TSA_CCR_WIDTH-1:0] =
tsa0_ccr_m[`TSA_CCR_WIDTH-1:0];
assign tlu_exu_cwp_m[`TSA_CWP_WIDTH-1:0] =
tsa0_cwp_m[`TSA_CWP_WIDTH-1:0];
assign tlu_lsu_asi_m[`TLU_ASI_STATE_WIDTH-1:0] =
tsa0_asi_m[`TLU_ASI_STATE_WIDTH-1:0];
// modified/added for timing violations
// moved the logic from exu to tlu due to timing violations
dff_s #(`TLU_THRD_NUM) dff_thrd_sel_m (
.din (tlu_thrd_rsel_e[`TLU_THRD_NUM-1:0]),
.q (thrd_sel_m[`TLU_THRD_NUM-1:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
mux4ds #(`TSA_CWP_WIDTH) mux_trap_old_cwp_m(
.in0(exu_tlu_cwp0[`TSA_CWP_WIDTH-1:0]),
.in1(exu_tlu_cwp1[`TSA_CWP_WIDTH-1:0]),
.in2(exu_tlu_cwp2[`TSA_CWP_WIDTH-1:0]),
.in3(exu_tlu_cwp3[`TSA_CWP_WIDTH-1:0]),
.sel0(thrd_sel_m[0]),
.sel1(thrd_sel_m[1]),
.sel2(thrd_sel_m[2]),
.sel3(thrd_sel_m[3]),
.dout(trap_old_cwp_m[`TSA_CWP_WIDTH-1:0])
);
assign cwp_xor_m[`TSA_CWP_WIDTH-1:0] =
trap_old_cwp_m[`TSA_CWP_WIDTH-1:0] ^ tlu_exu_cwp_m[`TSA_CWP_WIDTH-1:0];
assign cwp_no_change_m = ~|(cwp_xor_m[`TSA_CWP_WIDTH-1:0]);
assign tlu_cwp_no_change_m = cwp_no_change_m;
//=========================================================================================
// Generate TTYPE SSCAN data
//=========================================================================================
//
// staging the tsa_rd_vld signal
// moved to tlu_tcl for timing
/*
dff_s dff_tsa_rd_vld_e (
.din (tsa_rd_vld),
.q (tsa_rd_vld_e),
.clk (clk),
.se (se),
.si (),
.so ()
);
*/
dff_s dff_tsa_rd_vld_m (
.din (tsa_rd_vld_e),
.q (tsa_rd_vld_m),
.clk (clk),
.se (se),
.si (),
.so ()
);
assign tsa_wsel_thrd_w2[0] = ~tsa_wr_tid[1] & ~tsa_wr_tid[0];
assign tsa_wsel_thrd_w2[1] = ~tsa_wr_tid[1] & tsa_wr_tid[0];
assign tsa_wsel_thrd_w2[2]= tsa_wr_tid[1] & ~tsa_wr_tid[0];
assign tsa_wsel_thrd_w2[3] = tsa_wr_tid[1] & tsa_wr_tid[0];
// generating write indicators of ttype to the tsa
assign sscan_tt_wr_sel[0] =
tsa_ttype_en & tsa1_wr_vld & tsa_wsel_thrd_w2[0];
assign sscan_tt_wr_sel[1] =
tsa_ttype_en & tsa1_wr_vld & tsa_wsel_thrd_w2[1];
assign sscan_tt_wr_sel[2] =
tsa_ttype_en & tsa1_wr_vld & tsa_wsel_thrd_w2[2];
assign sscan_tt_wr_sel[3] =
tsa_ttype_en & tsa1_wr_vld & tsa_wsel_thrd_w2[3];
//
// generating read indicators of ttype from the tsa
assign sscan_tt_rd_sel[0] =
tsa_rd_vld_m & thrd_sel_m[0];
assign sscan_tt_rd_sel[1] =
tsa_rd_vld_m & thrd_sel_m[1];
assign sscan_tt_rd_sel[2] =
tsa_rd_vld_m & thrd_sel_m[2];
assign sscan_tt_rd_sel[3] =
tsa_rd_vld_m & thrd_sel_m[3];
assign sscan_ttype_en[0] =
sscan_tt_rd_sel[0] | sscan_tt_wr_sel[0];
assign sscan_ttype_en[1] =
sscan_tt_rd_sel[1] | sscan_tt_wr_sel[1];
assign sscan_ttype_en[2] =
sscan_tt_rd_sel[2] | sscan_tt_wr_sel[2];
assign sscan_ttype_en[3] =
sscan_tt_rd_sel[3] | sscan_tt_wr_sel[3];
//
assign sscan_tt0_din[`TSA_TTYPE_WIDTH-1:0] =
(sscan_tt_wr_sel[0]) ?
tlu_final_ttype_w2[`TSA_TTYPE_WIDTH-1:0] :
tsa1_ttype_m[`TSA_TTYPE_WIDTH-1:0];
assign sscan_tt1_din[`TSA_TTYPE_WIDTH-1:0] =
(sscan_tt_wr_sel[1]) ?
tlu_final_ttype_w2[`TSA_TTYPE_WIDTH-1:0] :
tsa1_ttype_m[`TSA_TTYPE_WIDTH-1:0];
assign sscan_tt2_din[`TSA_TTYPE_WIDTH-1:0] =
(sscan_tt_wr_sel[2]) ?
tlu_final_ttype_w2[`TSA_TTYPE_WIDTH-1:0] :
tsa1_ttype_m[`TSA_TTYPE_WIDTH-1:0];
assign sscan_tt3_din[`TSA_TTYPE_WIDTH-1:0] =
(sscan_tt_wr_sel[3]) ?
tlu_final_ttype_w2[`TSA_TTYPE_WIDTH-1:0] :
tsa1_ttype_m[`TSA_TTYPE_WIDTH-1:0];
//
dffe_s #(`TSA_TTYPE_WIDTH) dffe_sscan_tt0_data (
.din (sscan_tt0_din[`TSA_TTYPE_WIDTH-1:0]),
.q (sscan_tt0_data[`TSA_TTYPE_WIDTH-1:0]),
.en (sscan_ttype_en[0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dffe_s #(`TSA_TTYPE_WIDTH) dffe_sscan_tt1_data (
.din (sscan_tt1_din[`TSA_TTYPE_WIDTH-1:0]),
.q (sscan_tt1_data[`TSA_TTYPE_WIDTH-1:0]),
.en (sscan_ttype_en[1]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dffe_s #(`TSA_TTYPE_WIDTH) dffe_sscan_tt2_data (
.din (sscan_tt2_din[`TSA_TTYPE_WIDTH-1:0]),
.q (sscan_tt2_data[`TSA_TTYPE_WIDTH-1:0]),
.en (sscan_ttype_en[2]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dffe_s #(`TSA_TTYPE_WIDTH) dffe_sscan_tt3_data (
.din (sscan_tt3_din[`TSA_TTYPE_WIDTH-1:0]),
.q (sscan_tt3_data[`TSA_TTYPE_WIDTH-1:0]),
.en (sscan_ttype_en[3]),
.clk (clk),
.se (se),
.si (),
.so ()
);
assign sscan_tid_sel[`TLU_THRD_NUM-1:0] =
ctu_sscan_tid[`TLU_THRD_NUM-1:0];
mux4ds #(`MISCTL_SSCAN_WIDTH) mx_sscan_test_data (
.in0 (sscan_tt0_data[`TSA_TTYPE_WIDTH-1:0]),
.in1 (sscan_tt1_data[`TSA_TTYPE_WIDTH-1:0]),
.in2 (sscan_tt2_data[`TSA_TTYPE_WIDTH-1:0]),
.in3 (sscan_tt3_data[`TSA_TTYPE_WIDTH-1:0]),
.sel0 (sscan_tid_sel[0]),
.sel1 (sscan_tid_sel[1]),
.sel2 (sscan_tid_sel[2]),
.sel3 (sscan_tid_sel[3]),
.dout (misctl_sscan_test_data[`MISCTL_SSCAN_WIDTH-1:0])
);
assign tlu_sscan_misctl_data[`MISCTL_SSCAN_WIDTH-1:0] =
misctl_sscan_test_data[`MISCTL_SSCAN_WIDTH-1:0];
//
// code moved from tlu_tcl - trap pc delivery logic
//
assign normal_trap_pc_w1[48:0] =
{1'b0, tlu_partial_trap_pc_w1[33:0],
tlu_final_offset_w1[`TSA_TTYPE_WIDTH-1:0], 5'b00000};
assign normal_trap_npc_w1[48:0] =
{1'b0, tlu_partial_trap_pc_w1[33:0],
tlu_final_offset_w1[`TSA_TTYPE_WIDTH-1:0], 5'b00100};
//
// code moved from tlu_tdp
mux2ds #(49) mx_trap_pc_w1 (
.in0 (normal_trap_pc_w1[48:0]),
.in1 (tlu_restore_pc_w1[48:0]),
.sel0 (~tlu_restore_pc_sel_w1),
.sel1 (tlu_restore_pc_sel_w1),
.dout (trap_pc_w1[48:0])
);
//
dff_s #(49) dff_trap_pc_w2 (
.din (trap_pc_w1[48:0]),
.q (trap_pc_w2[48:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
assign tlu_ifu_trappc_w2[48:0] = trap_pc_w2[48:0];
mux2ds #(49) mx_trap_npc_w1 (
.in0 (normal_trap_npc_w1[48:0]),
.in1 (tlu_restore_npc_w1[48:0]),
.sel0 (~tlu_restore_pc_sel_w1),
.sel1 (tlu_restore_pc_sel_w1),
.dout (trap_npc_w1[48:0])
);
//
dff_s #(49) dff_trap_npc_w2 (
.din (trap_npc_w1[48:0]),
.q (trap_npc_w2[48:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
assign tlu_ifu_trapnpc_w2[48:0] = trap_npc_w2[48:0];
//--------------------------------------------------------------------------------
// Recovery PC and NPC selection
//--------------------------------------------------------------------------------
// On done, npc will become pc.
// modified for timing
//
dff_s #(47) dff_tsa0_pc_w (
.din (tsa0_pc_m[46:0]),
.q (tsa0_pc_w[46:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
dff_s #(49) dff_ifu_pc_w (
.din (ifu_tlu_pc_m[48:0]),
.q (ifu_pc_w[48:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
mux3ds #(49) mux_pc_new_w (
.in0 ({tsa0_pc_w[46:0], 2'b00}),
.in1 ({tsa1_npc_w[46:0], 2'b00}),
.in2 (ifu_pc_w[48:0]),
.sel0 (tlu_true_pc_sel_w[0]),
.sel1 (tlu_true_pc_sel_w[1]),
.sel2 (tlu_true_pc_sel_w[2]),
.dout (pc_new_w[48:0])
);
assign tlu_pc_new_w[48:0] = pc_new_w[48:0];
//
// On done, npc will become pc.
// On done, npc will stay npc. The valid to the IFU will
// not be signaled along with npc for a done.
// modified for timing
dff_s #(47) dff_tsa1_npc_w (
.din (tsa1_npc_m[46:0]),
.q (tsa1_npc_w[46:0]),
.clk (clk),
.se (se),
.si (),
.so ()
);
mux2ds #(49) mux_npc_new_w (
.in0 ({tsa1_npc_w[46:0],2'b00}),
.in1 (ifu_npc_w[48:0]),
.sel0 (~tlu_true_pc_sel_w[2]),
.sel1 (tlu_true_pc_sel_w[2]),
.dout (npc_new_w[48:0])
);
assign tlu_npc_new_w[48:0] = npc_new_w[48:0];
//--------------------------------------------------------------------------------
// PIC trap experiment
//--------------------------------------------------------------------------------
// added for bug 4785
assign local_rst = tlu_rst;
dffr_s dffr_tlu_exu_pic_onebelow_m (
.din (tlu_pic_onebelow_e),
.q (tlu_pic_onebelow_m),
.rst (local_rst),
.clk (clk),
.se (se),
.si (),
.so ()
);
dffr_s dffr_tlu_exu_pic_twobelow_m (
.din (tlu_pic_twobelow_e),
.q (tlu_pic_twobelow_m),
.rst (local_rst),
.clk (clk),
.se (se),
.si (),
.so ()
);
assign tlu_exu_pic_onebelow_m =
tlu_pic_onebelow_m & tlu_pic_cnt_en_m;
assign tlu_exu_pic_twobelow_m =
tlu_pic_twobelow_m & tlu_pic_cnt_en_m;
/*
assign pic_onebelow_e[0] =
tlu_thread_inst_vld_w2[0]? pich_twobelow_flg[0]: pich_onebelow_flg[0];
assign pic_onebelow_e[1] =
tlu_thread_inst_vld_w2[1]? pich_twobelow_flg[1]: pich_onebelow_flg[1];
assign pic_onebelow_e[2] =
tlu_thread_inst_vld_w2[2]? pich_twobelow_flg[2]: pich_onebelow_flg[2];
assign pic_onebelow_e[3] =
tlu_thread_inst_vld_w2[3]? pich_twobelow_flg[3]: pich_onebelow_flg[3];
assign tlu_pic_onebelow_e =
(tlu_thrd_rsel_e[0]) ? pic_onebelow_e[0]:
(tlu_thrd_rsel_e[1]) ? pic_onebelow_e[1]:
(tlu_thrd_rsel_e[2]) ? pic_onebelow_e[2]:
pic_onebelow_e[3];
assign pic_twobelow_e[0] =
tlu_thread_inst_vld_w2[0]? pich_threebelow_flg[0]: pich_twobelow_flg[0];
assign pic_twobelow_e[1] =
tlu_thread_inst_vld_w2[1]? pich_threebelow_flg[1]: pich_twobelow_flg[1];
assign pic_twobelow_e[2] =
tlu_thread_inst_vld_w2[2]? pich_threebelow_flg[2]: pich_twobelow_flg[2];
assign pic_twobelow_e[3] =
tlu_thread_inst_vld_w2[3]? pich_threebelow_flg[3]: pich_twobelow_flg[3];
assign tlu_pic_twobelow_e =
(tlu_thrd_rsel_e[0]) ? pic_twobelow_e[0]:
(tlu_thrd_rsel_e[1]) ? pic_twobelow_e[1]:
(tlu_thrd_rsel_e[2]) ? pic_twobelow_e[2]:
pic_twobelow_e[3];
*/
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HDLL__OR2B_BEHAVIORAL_PP_V
`define SKY130_FD_SC_HDLL__OR2B_BEHAVIORAL_PP_V
/**
* or2b: 2-input OR, first input inverted.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_hdll__udp_pwrgood_pp_pg.v"
`celldefine
module sky130_fd_sc_hdll__or2b (
X ,
A ,
B_N ,
VPWR,
VGND,
VPB ,
VNB
);
// Module ports
output X ;
input A ;
input B_N ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
// Local signals
wire not0_out ;
wire or0_out_X ;
wire pwrgood_pp0_out_X;
// Name Output Other arguments
not not0 (not0_out , B_N );
or or0 (or0_out_X , not0_out, A );
sky130_fd_sc_hdll__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_X, or0_out_X, VPWR, VGND);
buf buf0 (X , pwrgood_pp0_out_X );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_HDLL__OR2B_BEHAVIORAL_PP_V |
module var24_multi (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, valid);
input A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X;
output valid;
wire [8:0] min_value = 9'd120;
wire [8:0] max_weight = 9'd60;
wire [8:0] max_volume = 9'd60;
wire [8:0] total_value =
A * 9'd4
+ B * 9'd8
+ C * 9'd0
+ D * 9'd20
+ E * 9'd10
+ F * 9'd12
+ G * 9'd18
+ H * 9'd14
+ I * 9'd6
+ J * 9'd15
+ K * 9'd30
+ L * 9'd8
+ M * 9'd16
+ N * 9'd18
+ O * 9'd18
+ P * 9'd14
+ Q * 9'd7
+ R * 9'd7
+ S * 9'd29
+ T * 9'd23
+ U * 9'd24
+ V * 9'd3
+ W * 9'd18
+ X * 9'd5;
wire [8:0] total_weight =
A * 9'd28
+ B * 9'd8
+ C * 9'd27
+ D * 9'd18
+ E * 9'd27
+ F * 9'd28
+ G * 9'd6
+ H * 9'd1
+ I * 9'd20
+ J * 9'd0
+ K * 9'd5
+ L * 9'd13
+ M * 9'd8
+ N * 9'd14
+ O * 9'd22
+ P * 9'd12
+ Q * 9'd23
+ R * 9'd26
+ S * 9'd1
+ T * 9'd22
+ U * 9'd26
+ V * 9'd15
+ W * 9'd0
+ X * 9'd21;
wire [8:0] total_volume =
A * 9'd27
+ B * 9'd27
+ C * 9'd4
+ D * 9'd4
+ E * 9'd0
+ F * 9'd24
+ G * 9'd4
+ H * 9'd20
+ I * 9'd12
+ J * 9'd15
+ K * 9'd5
+ L * 9'd2
+ M * 9'd9
+ N * 9'd28
+ O * 9'd19
+ P * 9'd18
+ Q * 9'd30
+ R * 9'd12
+ S * 9'd28
+ T * 9'd13
+ U * 9'd18
+ V * 9'd16
+ W * 9'd26
+ X * 9'd3;
assign valid = ((total_value >= min_value) && (total_weight <= max_weight) && (total_volume <= max_volume));
endmodule
|
// Copyright 1986-2016 Xilinx, Inc. All Rights Reserved.
// --------------------------------------------------------------------------------
// Tool Version: Vivado v.2016.4 (win64) Build 1733598 Wed Dec 14 22:35:39 MST 2016
// Date : Thu Feb 02 02:49:15 2017
// Host : TheMosass-PC running 64-bit major release (build 9200)
// Command : write_verilog -force -mode synth_stub -rename_top decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix -prefix
// decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix_ design_1_processing_system7_0_0_stub.v
// Design : design_1_processing_system7_0_0
// Purpose : Stub declaration of top-level module interface
// Device : xc7z010clg400-1
// --------------------------------------------------------------------------------
// This empty module with port declaration file causes synthesis tools to infer a black box for IP.
// The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion.
// Please paste the declaration into a Verilog source file or add the file as an additional source.
(* X_CORE_INFO = "processing_system7_v5_5_processing_system7,Vivado 2016.4" *)
module decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix(I2C0_SDA_I, I2C0_SDA_O, I2C0_SDA_T, I2C0_SCL_I,
I2C0_SCL_O, I2C0_SCL_T, SDIO0_WP, UART0_TX, UART0_RX, TTC0_WAVE0_OUT, TTC0_WAVE1_OUT,
TTC0_WAVE2_OUT, USB0_PORT_INDCTL, USB0_VBUS_PWRSELECT, USB0_VBUS_PWRFAULT,
M_AXI_GP0_ARVALID, M_AXI_GP0_AWVALID, M_AXI_GP0_BREADY, M_AXI_GP0_RREADY,
M_AXI_GP0_WLAST, M_AXI_GP0_WVALID, M_AXI_GP0_ARID, M_AXI_GP0_AWID, M_AXI_GP0_WID,
M_AXI_GP0_ARBURST, M_AXI_GP0_ARLOCK, M_AXI_GP0_ARSIZE, M_AXI_GP0_AWBURST,
M_AXI_GP0_AWLOCK, M_AXI_GP0_AWSIZE, M_AXI_GP0_ARPROT, M_AXI_GP0_AWPROT, M_AXI_GP0_ARADDR,
M_AXI_GP0_AWADDR, M_AXI_GP0_WDATA, M_AXI_GP0_ARCACHE, M_AXI_GP0_ARLEN, M_AXI_GP0_ARQOS,
M_AXI_GP0_AWCACHE, M_AXI_GP0_AWLEN, M_AXI_GP0_AWQOS, M_AXI_GP0_WSTRB, M_AXI_GP0_ACLK,
M_AXI_GP0_ARREADY, M_AXI_GP0_AWREADY, M_AXI_GP0_BVALID, M_AXI_GP0_RLAST,
M_AXI_GP0_RVALID, M_AXI_GP0_WREADY, M_AXI_GP0_BID, M_AXI_GP0_RID, M_AXI_GP0_BRESP,
M_AXI_GP0_RRESP, M_AXI_GP0_RDATA, IRQ_F2P, FCLK_CLK0, FCLK_RESET0_N, MIO, DDR_CAS_n, DDR_CKE,
DDR_Clk_n, DDR_Clk, DDR_CS_n, DDR_DRSTB, DDR_ODT, DDR_RAS_n, DDR_WEB, DDR_BankAddr, DDR_Addr,
DDR_VRN, DDR_VRP, DDR_DM, DDR_DQ, DDR_DQS_n, DDR_DQS, PS_SRSTB, PS_CLK, PS_PORB)
/* synthesis syn_black_box black_box_pad_pin="I2C0_SDA_I,I2C0_SDA_O,I2C0_SDA_T,I2C0_SCL_I,I2C0_SCL_O,I2C0_SCL_T,SDIO0_WP,UART0_TX,UART0_RX,TTC0_WAVE0_OUT,TTC0_WAVE1_OUT,TTC0_WAVE2_OUT,USB0_PORT_INDCTL[1:0],USB0_VBUS_PWRSELECT,USB0_VBUS_PWRFAULT,M_AXI_GP0_ARVALID,M_AXI_GP0_AWVALID,M_AXI_GP0_BREADY,M_AXI_GP0_RREADY,M_AXI_GP0_WLAST,M_AXI_GP0_WVALID,M_AXI_GP0_ARID[11:0],M_AXI_GP0_AWID[11:0],M_AXI_GP0_WID[11:0],M_AXI_GP0_ARBURST[1:0],M_AXI_GP0_ARLOCK[1:0],M_AXI_GP0_ARSIZE[2:0],M_AXI_GP0_AWBURST[1:0],M_AXI_GP0_AWLOCK[1:0],M_AXI_GP0_AWSIZE[2:0],M_AXI_GP0_ARPROT[2:0],M_AXI_GP0_AWPROT[2:0],M_AXI_GP0_ARADDR[31:0],M_AXI_GP0_AWADDR[31:0],M_AXI_GP0_WDATA[31:0],M_AXI_GP0_ARCACHE[3:0],M_AXI_GP0_ARLEN[3:0],M_AXI_GP0_ARQOS[3:0],M_AXI_GP0_AWCACHE[3:0],M_AXI_GP0_AWLEN[3:0],M_AXI_GP0_AWQOS[3:0],M_AXI_GP0_WSTRB[3:0],M_AXI_GP0_ACLK,M_AXI_GP0_ARREADY,M_AXI_GP0_AWREADY,M_AXI_GP0_BVALID,M_AXI_GP0_RLAST,M_AXI_GP0_RVALID,M_AXI_GP0_WREADY,M_AXI_GP0_BID[11:0],M_AXI_GP0_RID[11:0],M_AXI_GP0_BRESP[1:0],M_AXI_GP0_RRESP[1:0],M_AXI_GP0_RDATA[31:0],IRQ_F2P[0:0],FCLK_CLK0,FCLK_RESET0_N,MIO[53:0],DDR_CAS_n,DDR_CKE,DDR_Clk_n,DDR_Clk,DDR_CS_n,DDR_DRSTB,DDR_ODT,DDR_RAS_n,DDR_WEB,DDR_BankAddr[2:0],DDR_Addr[14:0],DDR_VRN,DDR_VRP,DDR_DM[3:0],DDR_DQ[31:0],DDR_DQS_n[3:0],DDR_DQS[3:0],PS_SRSTB,PS_CLK,PS_PORB" */;
input I2C0_SDA_I;
output I2C0_SDA_O;
output I2C0_SDA_T;
input I2C0_SCL_I;
output I2C0_SCL_O;
output I2C0_SCL_T;
input SDIO0_WP;
output UART0_TX;
input UART0_RX;
output TTC0_WAVE0_OUT;
output TTC0_WAVE1_OUT;
output TTC0_WAVE2_OUT;
output [1:0]USB0_PORT_INDCTL;
output USB0_VBUS_PWRSELECT;
input USB0_VBUS_PWRFAULT;
output M_AXI_GP0_ARVALID;
output M_AXI_GP0_AWVALID;
output M_AXI_GP0_BREADY;
output M_AXI_GP0_RREADY;
output M_AXI_GP0_WLAST;
output M_AXI_GP0_WVALID;
output [11:0]M_AXI_GP0_ARID;
output [11:0]M_AXI_GP0_AWID;
output [11:0]M_AXI_GP0_WID;
output [1:0]M_AXI_GP0_ARBURST;
output [1:0]M_AXI_GP0_ARLOCK;
output [2:0]M_AXI_GP0_ARSIZE;
output [1:0]M_AXI_GP0_AWBURST;
output [1:0]M_AXI_GP0_AWLOCK;
output [2:0]M_AXI_GP0_AWSIZE;
output [2:0]M_AXI_GP0_ARPROT;
output [2:0]M_AXI_GP0_AWPROT;
output [31:0]M_AXI_GP0_ARADDR;
output [31:0]M_AXI_GP0_AWADDR;
output [31:0]M_AXI_GP0_WDATA;
output [3:0]M_AXI_GP0_ARCACHE;
output [3:0]M_AXI_GP0_ARLEN;
output [3:0]M_AXI_GP0_ARQOS;
output [3:0]M_AXI_GP0_AWCACHE;
output [3:0]M_AXI_GP0_AWLEN;
output [3:0]M_AXI_GP0_AWQOS;
output [3:0]M_AXI_GP0_WSTRB;
input M_AXI_GP0_ACLK;
input M_AXI_GP0_ARREADY;
input M_AXI_GP0_AWREADY;
input M_AXI_GP0_BVALID;
input M_AXI_GP0_RLAST;
input M_AXI_GP0_RVALID;
input M_AXI_GP0_WREADY;
input [11:0]M_AXI_GP0_BID;
input [11:0]M_AXI_GP0_RID;
input [1:0]M_AXI_GP0_BRESP;
input [1:0]M_AXI_GP0_RRESP;
input [31:0]M_AXI_GP0_RDATA;
input [0:0]IRQ_F2P;
output FCLK_CLK0;
output FCLK_RESET0_N;
inout [53:0]MIO;
inout DDR_CAS_n;
inout DDR_CKE;
inout DDR_Clk_n;
inout DDR_Clk;
inout DDR_CS_n;
inout DDR_DRSTB;
inout DDR_ODT;
inout DDR_RAS_n;
inout DDR_WEB;
inout [2:0]DDR_BankAddr;
inout [14:0]DDR_Addr;
inout DDR_VRN;
inout DDR_VRP;
inout [3:0]DDR_DM;
inout [31:0]DDR_DQ;
inout [3:0]DDR_DQS_n;
inout [3:0]DDR_DQS;
inout PS_SRSTB;
inout PS_CLK;
inout PS_PORB;
endmodule
|
//-----------------------------------------------------------------------------------
//--TestInitRam.v----------------------------------------------------------------------------
//--By Kyle Williams, 11/20/2012-----------------------------------------------------
//--MODULE DESCRIPTION---------------------------------------------------------------
//----------------Loads Memory With Dummy Data---------------------------------------
module TestInitRam
#(
parameter ADDR_WIDTH = 4,
parameter DATA_WIDTH = 8,
parameter MEM_DEPTH = 64
)(
//------------Input Ports------------
input clk,
input rst,
//------------Output Ports-----------
output reg[DATA_WIDTH-1:0] key,
output reg finished,
output reg [ADDR_WIDTH-1:0] addrA,
output reg [ADDR_WIDTH-1:0] addrB,
output reg wr_enaA,
output reg wr_enaB,
output reg[DATA_WIDTH-1:0] data_outA,
output reg[DATA_WIDTH-1:0] data_outB
);
//------------Reg/ Wires-------------
reg [DATA_WIDTH-1:0] tempMem [0:MEM_DEPTH-1];
reg [ADDR_WIDTH-1:0] addr;
always@(posedge clk)//we don't care about synthesizable change whenever clk changes
begin:TransferData
if(tempMem[addr][DATA_WIDTH-1]==1'b1 || tempMem[addr][DATA_WIDTH-1]==1'b0)begin
wr_enaA <= 1'b1;
wr_enaB <= 1'b1;
addrA <= addr;
addrB <= addr+1;
data_outA <= tempMem[addr];
data_outB <= tempMem[addr+1];
addr <= addr+2;//increment address by two we have two ports lets use them both
end else begin
finished <= 1'b1;
wr_enaA <= 1'b0;
wr_enaB <= 1'b0;
addrA <= 0;
addrB <= 0;
wr_enaA<=0;
wr_enaB<=0;
data_outA<=0;
data_outB<=0;
end
end
always@(posedge clk)
begin:Reset
if(rst)
begin
addr <= 0;
addrA <= 0;
addrB <= 0;
wr_enaA<=0;
wr_enaB<=0;
finished<=0;
data_outA<=0;
data_outB<=0;
end
end
integer r1,c1;
initial
begin
r1 = $fopen("Input","rb");
c1 = $fread(tempMem,r1);
$fclose(r1);
end
initial
begin
key = "PASS";
end
endmodule
|
(* Copyright (c) 2008-2012, 2015, Adam Chlipala
*
* This work is licensed under a
* Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
* Unported License.
* The license text is available at:
* http://creativecommons.org/licenses/by-nc-nd/3.0/
*)
(** %\chapter{いくつかの手短かな例}% *)
(**
(** I will start off by jumping right in to a fully worked set of examples, building certified compilers from increasingly complicated source languages to stack machines. We will meet a few useful tactics and see how they can be used in manual proofs, and we will also see how easily these proofs can be automated instead. This chapter is not meant to give full explanations of the features that are employed. Rather, it is meant more as an advertisement of what is possible. Later chapters will introduce all of the concepts in bottom-up fashion. In other words, it is expected that most readers will not understand what exactly is going on here, but I hope this demo will whet your appetite for the remaining chapters!
As always, you can step through the source file <<StackMachine.v>> for this chapter interactively in Proof General. Alternatively, to get a feel for the whole lifecycle of creating a Coq development, you can enter the pieces of source code in this chapter in a new <<.v>> file in an Emacs buffer. If you do the latter, include these three lines at the start of the file. *)
*)
(**
まずは実際に動く例として、ソース言語からスタックマシンを生成する証明付きコンパイラの構成から始めましょう。単純なソース言語をコンパイルできる状態から始めて、少しずつ複雑なソース言語に対応できるようにしていきます。証明に関しては、便利なタクティクをいくつか紹介し、それらが手動の証明でどう使えるかを見ます。さらに、どれくらい簡単に自動化できるかも見ます。本章では利用する機能の完全な説明を与えるつもりはありません。むしろ本章の狙いは、Coqで何ができるのかを見てもらうことです。後の章ですべての概念をボトムアップに紹介していきます。言い換えれば、ほとんどの読者にとって本章の内容を完璧に理解するのは難しいかもしれません。ここで紹介するデモが残りの章への興味に繋がればそれで十分です!
本章についても、Proof Generalを使うことで、ソースファイルである<<StackMachine.v>>を対話的に1ステップずつ実行していけます。Coqによる開発の工程を肌で感じたければ、本章に出てくるソースコードをEmacsバッファ内で新規の<<.v>>ファイルに1つずつ書き込んでいってもよいでしょう。後者の方法を取るなら、ファイルの先頭に以下の三行をコピーしてください。
*)
Require Import Bool Arith List Cpdt.CpdtTactics.
Set Implicit Arguments.
Set Asymmetric Patterns.
(* begin hide *)
(* begin thide *)
Definition bleh := app_assoc.
(* end thide *)
(* end hide *)
(**
(** In general, similar commands will be hidden in the book rendering of each chapter's source code, so you will need to insert them in from-scratch replayings of the code that is presented. To be more specific, every chapter begins with the above three lines, with the import list tweaked as appropriate, considering which definitions the chapter uses. The second command above affects the default behavior of definitions regarding type inference, and the third allows for more concise pattern-matching syntax in Coq versions 8.5 and higher (having no effect in earlier versions). *)
*)
(**
以降、本書では、各章のソースコード内の似通ったコマンドを省略します。省略されている部分については、前を同じものをコピー&ペーストする必要があります。具体的には、どの章も先頭には上記の三行が挿入されています。ただし、[Require Import]の後ろの部分は、章ごとに必要な定義に書き換える必要があります。二行めのコマンドは、型推論に関する定義の標準的なふるまいに影響します。三行めは、より簡潔なパターンマッチングの機能を利用できるようにするためのものです(Coqのバージョン8.5以降のコマンドであり、バージョン8.5未満に対する影響はありません)。*)
(** * 自然数の算術式 *)
(** (* We will begin with that staple of compiler textbooks, arithmetic expressions over a single type of numbers. *)
コンパイラの教科書ではおなじみの、数値型の上での算術式から始めましょう。*)
(** ** ソース言語 *)
(**
(** We begin with the syntax of the source language.%\index{Vernacular commands!Inductive}% *)
*)
(**
ソース言語のシンタックスから始めます。%\index{Vernacular commands!Inductive}% *)
Inductive binop : Set := Plus | Times.
(**
(** Our first line of Coq code should be unsurprising to ML and Haskell programmers. We define an %\index{algebraic datatypes}%algebraic datatype [binop] to stand for the binary operators of our source language. There are just two wrinkles compared to ML and Haskell. First, we use the keyword [Inductive], in place of <<data>>, <<datatype>>, or <<type>>. This is not just a trivial surface syntax difference; inductive types in Coq are much more expressive than garden variety algebraic datatypes, essentially enabling us to encode all of mathematics, though we begin humbly in this chapter. Second, there is the %\index{Gallina terms!Set}%[: Set] fragment, which declares that we are defining a datatype that should be thought of as a constituent of programs. Later, we will see other options for defining datatypes in the universe of proofs or in an infinite hierarchy of universes, encompassing both programs and proofs, that is useful in higher-order constructions. *)
*)
(**
はじめてのCoqコードとなるこの一行は、MLやHaskellのプログラマにとっては意外なものではないでしょう。ソース言語の二項演算子を表すために、[binop]という%\index{代数的データ型}%代数的データ型(algebraic datatype)を定義しています。MLやHaskellと異なる点は二つだけです。一つめは、Coqでは<<data>>や<<datatype>>、<<type>>の代わりに、[Inductive]を使うことです。これは単なる表面的なシンタックスの違いではありません。本章ではあまり威力を発揮しませんが、Coqの帰納的データ型(inductive data types)にはありふれた代数的データ型よりもずっと豊かな表現力があり、とくに数学のすべてを表現できます。二つめは%\index{Gallina terms!Set}%[: Set]の存在です。これは、プログラムの構成要素として考えられるべきデータ型を定義することを宣言するものです。のちほど、証明の世界のデータ型や、プログラムと証明の両方を包含する無限の階層を持った世界のデータ型(高階の構成で役立ちます)といった、他のデータ型を定義するときのキーワードも登場します。*)
Inductive exp : Set :=
| Const : nat -> exp
| Binop : binop -> exp -> exp -> exp.
(**
(** Now we define the type of arithmetic expressions. We write that a constant may be built from one argument, a natural number; and a binary operation may be built from a choice of operator and two operand expressions.
A note for readers following along in the PDF version: %\index{coqdoc}%coqdoc supports pretty-printing of tokens in %\LaTeX{}%#LaTeX# or HTML. Where you see a right arrow character, the source contains the ASCII text <<->>>. Other examples of this substitution appearing in this chapter are a double right arrow for <<=>>>, the inverted %`%#'#A' symbol for <<forall>>, and the Cartesian product %`%#'#X' for <<*>>. When in doubt about the ASCII version of a symbol, you can consult the chapter source code.
%\medskip%
Now we are ready to say what programs in our expression language mean. We will do this by writing an %\index{interpreters}%interpreter that can be thought of as a trivial operational or denotational semantics. (If you are not familiar with these semantic techniques, no need to worry: we will stick to "common sense" constructions.)%\index{Vernacular commands!Definition}% *)
*)
(**
次は算術式の型の定義です。定数[Const]は一つの自然数値の引数から作られること、二項演算子[Binop]は一つの演算子と二つのオペランド式から作られることを、それぞれ書き下してあります。
ここで、本書をPDF版で読んでいる読者に注意があります。本書に出てくるCoqのソースコードは、coqdoc%\index{coqdoc}%により、%\LaTeX{}%#LaTeX#やHTML形式に変換されています。PDF上の右矢印「→」は、ソース上ではASCIIテキストの<<->>>です。ほかにも、二重の右矢印「⇒」は<<=>>>に、記号「∀」は<<forall>>に、デカルト積「×」は<<*>>に置き換えが必要です。ASCIIテキストでどう書くのかが分からなくなったら、本書のソースコードを参照してください。
%\medskip%
ソース言語を定義したところで、この言語で表現されるプログラムの意味を与えましょう。ここでは、%\index{インタプリタ}%インタプリタを書くことにより、プログラムの意味を与えます。これはごく単純な操作的意味論と表示的意味論として考えられます(これらの意味論の手法に不慣れでも心配いりません。「常識的」な構成をするという程度の話です)。%\index{Vernacular commands!Definition}% *)
Definition binopDenote (b : binop) : nat -> nat -> nat :=
match b with
| Plus => plus
| Times => mult
end.
(**
(** The meaning of a binary operator is a binary function over naturals, defined with pattern-matching notation analogous to the <<case>> and <<match>> of ML and Haskell, and referring to the functions [plus] and [mult] from the Coq standard library. The keyword [Definition] is Coq's all-purpose notation for binding a term of the programming language to a name, with some associated syntactic sugar, like the notation we see here for defining a function. That sugar could be expanded to yield this definition:
[[
Definition binopDenote : binop -> nat -> nat -> nat := fun (b : binop) =>
match b with
| Plus => plus
| Times => mult
end.
]]
In this example, we could also omit all of the type annotations, arriving at:
[[
Definition binopDenote := fun b =>
match b with
| Plus => plus
| Times => mult
end.
]]
Languages like Haskell and ML have a convenient%\index{principal types}\index{type inference}% _principal types_ property, which gives us strong guarantees about how effective type inference will be. Unfortunately, Coq's type system is so expressive that any kind of "complete" type inference is impossible, and the task even seems to be hard in practice. Nonetheless, Coq includes some very helpful heuristics, many of them copying the workings of Haskell and ML type-checkers for programs that fall in simple fragments of Coq's language.
This is as good a time as any to mention the profusion of different languages associated with Coq. The theoretical foundation of Coq is a formal system called the%\index{Calculus of Inductive Constructions}\index{CIC|see{Calculus of Inductive Constructions}}% _Calculus of Inductive Constructions_ (CIC)%~\cite{CIC}%, which is an extension of the older%\index{Calculus of Constructions}\index{CoC|see{Calculus of Constructions}}% _Calculus of Constructions_ (CoC)%~\cite{CoC}%. CIC is quite a spartan foundation, which is helpful for proving metatheory but not so helpful for real development. Still, it is nice to know that it has been proved that CIC enjoys properties like%\index{strong normalization}% _strong normalization_ %\cite{CIC}%, meaning that every program (and, more importantly, every proof term) terminates; and%\index{relative consistency}% _relative consistency_ %\cite{SetsInTypes}% with systems like versions of %\index{Zermelo-Fraenkel set theory}%Zermelo-Fraenkel set theory, which roughly means that you can believe that Coq proofs mean that the corresponding propositions are "really true," if you believe in set theory.
Coq is actually based on an extension of CIC called %\index{Gallina}%Gallina. The text after the [:=] and before the period in the last code example is a term of Gallina. Gallina includes several useful features that must be considered as extensions to CIC. The important metatheorems about CIC have not been extended to the full breadth of the features that go beyond the formalized language, but most Coq users do not seem to lose much sleep over this omission.
Next, there is %\index{Ltac}%Ltac, Coq's domain-specific language for writing proofs and decision procedures. We will see some basic examples of Ltac later in this chapter, and much of this book is devoted to more involved Ltac examples.
Finally, commands like [Inductive] and [Definition] are part of %\index{Vernacular commands}%the Vernacular, which includes all sorts of useful queries and requests to the Coq system. Every Coq source file is a series of vernacular commands, where many command forms take arguments that are Gallina or Ltac programs. (Actually, Coq source files are more like _trees_ of vernacular commands, thanks to various nested scoping constructs.)
%\medskip%
We can give a simple definition of the meaning of an expression:%\index{Vernacular commands!Fixpoint}% *)
*)
(**
二項演算子の意味は、自然数の上の二引数関数です。この関数は、MLやHaskellにおける<<match>>や<<case>>のようなパターンマッチングを使って定義し、Coqの標準ライブラリ内の関数[plus]と[mult]を参照しています。[Definition]というキーワードは、Coqの項を名前に束縛する汎用の記法です。さまざまな目的に応じた構文糖衣が用意されており、この例では関数定義のための構文糖衣を使っています。この構文糖衣を展開すると以下のようになります。
[[
Definition binopDenote : binop -> nat -> nat -> nat := fun (b : binop) =>
match b with
| Plus => plus
| Times => mult
end.
]]
この例では、次のように、型注釈をすべて外してもかまいません。
[[
Definition binopDenote := fun b =>
match b with
| Plus => plus
| Times => mult
end.
]]
MLやHaskellのような言語には、_[主要型]_(principal type)%\index{principal types}\index{type inference}%を求められるという有用な性質があります。この性質は、型推論の効果に対し、強い保証を与えてくれるものです。残念ながら、Coqの型システムは表現力がとても豊かであるがために、あらゆる意味で「完全」な型推論は不可能であり、実際に主要型を求めることは困難にさえ思えます。とはいえCoqには、そのためのヒューリスティックな仕組みがいくつか含まれています。それらの仕組みの多くは、Coqの単純なコードに落ちるようなプログラムに対するMLやHaskellの型検査器の仕組みから移植されたものです。
いい機会なので、ここでCoqに付随する複数の言語について触れておきましょう。Coqの理論的な基礎は、_[Calculus of Inductive Constructions]_ %\index{Calculs of Inductive Constructions}\index{CIC|see{Calculus of Inductive Constructions}}% (CIC) %~\cite{CIC}%と呼ばれる形式システムにあります。そのCICは、それ以前にあった_[Calculus of Constructions]_ %\index{Calculus of Constructions}\index{CoC|see{Calculus of Constructions}}%(CoC)%~\cite{CoC}%という型システムの拡張です。CICは、メタ理論の証明には有用ですが、現場の開発に使うには厳格すぎるシステムです。それでも、CICには%\index{強正規化性}%_[強正規化性]_(strong normalizaiton)や、%\index{Zermelo-Fraenkel集合論}%Zermelo-Fraenkel集合論に類似した系に対する%\index{相対無矛盾性}%_[相対無矛盾性]_(relative consistency)といった性質があると証明されていることは知っておくとよいでしょう。強正規化性とは、すべてのプログラム(さらにはすべての証明項も)が停止するという性質です。相対無矛盾性とは、簡単に言うと、Coqで書かれた証明に対応する数学的命題が「本当に正しい」ことを、集合論を信じるならば信じてよい、という性質です。
Coqは、実際には%\index{Gallina}%Gallinaと呼ばれるCICの拡張に基いています。上記のコードのうち、「[:=]」から「[.]」までの中身は、Gallinaの項です。Gallinaには、CICの拡張として考えるべき有用な特徴が含まれています。形式言語の範囲を越える全機能に至るまでCICに関する重要なメタ定理が拡張されているわけではありませんが、それを気に病んでいるCoqユーザはほとんどいません。
Coqに付随する次の言語は、証明を書いたり手続きを決定したりするためのドメイン固有言語である%\index{Ltac}%Ltacです。本章の後半では、基本的なLtacの例をいくつか紹介します。本書全体では、もっとたくさんのLtacの例を紹介していきます。
最後は、[Inductive]や[Definition]のようなコマンドを含む%\index{Vernacularコマンド}%Vernacularです。Vernacularには、Coqシステムに対するあらゆる種類の有用な要求や命令が含まれます。Coqのソースファイルは、いずれもVernacularコマンドの列であり、それらのコマンドの多くは引数としてGallinaやLtacのプログラムを取ります(ネストされたスコープを持つさまざまな構造の影響で、Coqのソースファイルは実際には列ではなく_[木]_に近い形をしています)。
%\medskip%
式の意味の簡単な定義を与えましょう。%\index{Vernacular commands!Fixpoint}% *)
Fixpoint expDenote (e : exp) : nat :=
match e with
| Const n => n
| Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
end.
(**
(** We declare explicitly that this is a recursive definition, using the keyword [Fixpoint]. The rest should be old hat for functional programmers. *)
*)
(**
これが再帰的な定義であることを、[Fixpoint]キーワードを使って明示的に宣言しています。それ以外の部分は、関数型プログラマにとっては目新しいものではないでしょう。 *)
(**
(** It is convenient to be able to test definitions before starting to prove things about them. We can verify that our semantics is sensible by evaluating some sample uses, using the command %\index{Vernacular commands!Eval}%[Eval]. This command takes an argument expressing a%\index{reduction strategy}% _reduction strategy_, or an "order of evaluation." Unlike with ML, which hardcodes an _eager_ reduction strategy, or Haskell, which hardcodes a _lazy_ strategy, in Coq we are free to choose between these and many other orders of evaluation, because all Coq programs terminate. In fact, Coq silently checked %\index{termination checking}%termination of our [Fixpoint] definition above, using a simple heuristic based on monotonically decreasing size of arguments across recursive calls. Specifically, recursive calls must be made on arguments that were pulled out of the original recursive argument with [match] expressions. (In Chapter 7, we will see some ways of getting around this restriction, though simply removing the restriction would leave Coq useless as a theorem proving tool, for reasons we will start to learn about in the next chapter.)
To return to our test evaluations, we run the [Eval] command using the [simpl] evaluation strategy, whose definition is best postponed until we have learned more about Coq's foundations, but which usually gets the job done. *)
*)
(**
これらの定義について何かしら証明を始める前に、定義をテストできると好都合です。これまでに定義したセマンティクスがもっともらしいことを、コマンド%\index{Vernacular commands!Eval}%[Eval]で用例をいくつか評価することにより確かめてみましょう。[Eval]コマンドは、%\index{簡約戦略}%_[簡約戦略]_(reduction strategy)もしくは_[評価順序]_(order of evaluation)と呼ばれるものを表す引数を取ります。_[先行評価]_が前提のMLや、_[遅延評価]_が前提のHaskellとは違い、Coqではさまざまな評価順序を選べます。これが可能なのは、すべてのCoqプログラムが停止するからです。実を言うと、Coqの内部では、上記の[Fixpoint]で定義した関数の%\index{termination checking}%停止性が確認されています。この確認では、再帰が呼び出されるたびに引数のサイズが単調に減少することに基づいた単純なヒューリスティクスにより、停止性を判断しています。この場合には、[match]式によって分割された元の再帰的な引数に対して再帰呼び出しが作られていなければなりません。(この制限を単純に削除すると、Coqは定理証明のための道具として役に立たないものになってしまうでしょう。その理由は次章から学びます。第7章では、[Fixpoint]の制限に対処するためのいくつかの方法を見ます。)
評価を試してみる前に、[simpl]という評価戦略を使って[Eval]コマンドを実行しましょう。[simpl]の定義はCoqの基礎をもっと学んでから示しますが、通常は[simpl]を使えばいいでしょう。 *)
Eval simpl in expDenote (Const 42).
(** [= 42 : nat] *)
Eval simpl in expDenote (Binop Plus (Const 2) (Const 2)).
(** [= 4 : nat] *)
Eval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
(** [= 28 : nat] *)
(**
(** %\smallskip{}%Nothing too surprising goes on here, so we are ready to move on to the target language of our compiler. *)
*)
(**
%\smallskip{}%どれも自然な結果です。今度はコンパイラのターゲット言語を定義することにしましょう。 *)
(** ** ターゲット言語 *)
(**
(** We will compile our source programs onto a simple stack machine, whose syntax is: *)
*)
(**
前項で定義したソース言語によるプログラムを、単純なスタックマシンへとコンパイルします。コンパイラのターゲット言語は次のようなシンタックスで与えます。 *)
Inductive instr : Set :=
| iConst : nat -> instr
| iBinop : binop -> instr.
Definition prog := list instr.
Definition stack := list nat.
(**
(** An instruction either pushes a constant onto the stack or pops two arguments, applies a binary operator to them, and pushes the result onto the stack. A program is a list of instructions, and a stack is a list of natural numbers.
We can give instructions meanings as functions from stacks to optional stacks, where running an instruction results in [None] in case of a stack underflow and results in [Some s'] when the result of execution is the new stack [s']. %\index{Gallina operators!::}%The infix operator [::] is "list cons" from the Coq standard library.%\index{Gallina terms!option}% *)
*)
(**
[instr]は命令で、スタックの先頭に定数をプッシュする[iConst]か、引数を二つポップして二項演算子に適用したあとで結果をスタックにプッシュする[iBinon]のいずれかです。プログラム([prog])は命令([instr])のリストであり、スタック([stack])は自然数のリストです。
命令には、スタックからスタックのオプション型への関数として意味を与えましょう。命令を実行した結果がスタックアンダーフローに陥る場合は[None]、結果として新たなスタック[s']を得る場合は[Some s']を返すものとします。%\index{Gallina operators!::}%中置演算子「[::]」はリストのconsです。Coqの標準ライブラリで定義されています。%\index{Gallina terms!option}% *)
Definition instrDenote (i : instr) (s : stack) : option stack :=
match i with
| iConst n => Some (n :: s)
| iBinop b =>
match s with
| arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')
| _ => None
end
end.
(**
(** With [instrDenote] defined, it is easy to define a function [progDenote], which iterates application of [instrDenote] through a whole program. *)
*)
(**
[instrDenote]が定義できたので、プログラム全体を通して[instrDenote]を繰り返し適用する関数[progDenote]も簡単に定義できます。 *)
Fixpoint progDenote (p : prog) (s : stack) : option stack :=
match p with
| nil => Some s
| i :: p' =>
match instrDenote i s with
| None => None
| Some s' => progDenote p' s'
end
end.
(**
(** With the two programming languages defined, we can turn to the compiler definition. *)
*)
(**
二つのプログラミング言語が定義できたところで、コンパイラの定義に移りましょう。 *)
(** ** 変換 *)
(**
(** Our compiler itself is now unsurprising. The list concatenation operator %\index{Gallina operators!++}\coqdocnotation{%#<tt>#++#</tt>#%}% comes from the Coq standard library. *)
*)
(**
コンパイラは自然に定義できます。リストの結合には、Coqの標準ライブラリにある%\index{Gallina operators!++}\coqdocnotation{%#<tt>#++#</tt>#%}%を使います。 *)
Fixpoint compile (e : exp) : prog :=
match e with
| Const n => iConst n :: nil
| Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil
end.
(** (* Before we set about proving that this compiler is correct, we can try a few test runs, using our sample programs from earlier. *)
このコンパイラが正しいことを証明する前に、先ほど実行したサンプルプログラムを試しに走らせてみましょう。 *)
Eval simpl in compile (Const 42).
(** [= iConst 42 :: nil : prog] *)
Eval simpl in compile (Binop Plus (Const 2) (Const 2)).
(** [= iConst 2 :: iConst 2 :: iBinop Plus :: nil : prog] *)
Eval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
(** [= iConst 7 :: iConst 2 :: iConst 2 :: iBinop Plus :: iBinop Times :: nil : prog] *)
(** (* %\smallskip{}%We can also run our compiled programs and check that they give the right results. *)
%\smallskip{}%コンパイルされたプログラムを実行して正しい結果を返すことも確かめてみます。 *)
Eval simpl in progDenote (compile (Const 42)) nil.
(** [= Some (42 :: nil) : option stack] *)
Eval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.
(** [= Some (4 :: nil) : option stack] *)
Eval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2))
(Const 7))) nil.
(** [= Some (28 :: nil) : option stack] *)
(** (* %\smallskip{}%So far so good, but how can we be sure the compiler operates correctly for _all_ input programs? *)
%\smallskip{}%今のところうまくいっています。でも、どうすれば_[すべて]_の入力プログラムに対してコンパイラが正しく動作することを確かめられるでしょうか。 *)
(** ** 変換の正しさ *)
(**
(** We are ready to prove that our compiler is implemented correctly. We can use a new vernacular command [Theorem] to start a correctness proof, in terms of the semantics we defined earlier:%\index{Vernacular commands!Theorem}% *)
*)
(**
コンパイラが正しく実装されたことを証明しましょう。先ほど定義したセマンティクスの観点から証明を始めるために、[Theorem]という新たなVernacularコマンドを使います。%\index{Vernacular commands!Theorem}% *)
Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
(* begin thide *)
(**
(** Though a pencil-and-paper proof might clock out at this point, writing "by a routine induction on [e]," it turns out not to make sense to attack this proof directly. We need to use the standard trick of%\index{strengthening the induction hypothesis}% _strengthening the induction hypothesis_. We do that by proving an auxiliary lemma, using the command [Lemma] that is a synonym for [Theorem], conventionally used for less important theorems that appear in the proofs of primary theorems.%\index{Vernacular commands!Lemma}% *)
*)
(**
紙と鉛筆による証明なら、ここで「[e]に関する帰納法より」と書いて終了できるかもしれませんが、この証明に直接取り組むのは実は懸命ではありません。ここでは、基本的な手法である%\index{帰納法の仮定の強化}%_[帰納法の仮定の強化]_が必要になります。そのために[Lemma]コマンドを使って補題を示しましょう。[Lemma]コマンドは[Theorem]のシノニムで、慣習的に主定理の証明に必要となる補助的な定理に対して使います。%\index{Vernacular commands!Lemma}% *)
Abort.
Lemma compile_correct' : forall e p s,
progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).
(**
(** After the period in the [Lemma] command, we are in%\index{interactive proof-editing mode}% _the interactive proof-editing mode_. We find ourselves staring at this ominous screen of text:
[[
1 subgoal
============================
forall (e : exp) (p : list instr) (s : stack),
progDenote (compile e ++ p) s = progDenote p (expDenote e :: s)
]]
Coq seems to be restating the lemma for us. What we are seeing is a limited case of a more general protocol for describing where we are in a proof. We are told that we have a single subgoal. In general, during a proof, we can have many pending %\index{subgoals}%subgoals, each of which is a logical proposition to prove. Subgoals can be proved in any order, but it usually works best to prove them in the order that Coq chooses.
Next in the output, we see our single subgoal described in full detail. There is a double-dashed line, above which would be our free variables and %\index{hypotheses}%hypotheses, if we had any. Below the line is the %\index{conclusion}%conclusion, which, in general, is to be proved from the hypotheses.
We manipulate the proof state by running commands called%\index{tactics}% _tactics_. Let us start out by running one of the most important tactics:%\index{tactics!induction}%
*)
*)
(**
[Lemma]コマンドのピリオドを読み込むと、%\index{対話的証明モード}%_[対話的証明モード]_(interactive proof-editing mode)に入ります。スクリーンに何やら新しいテキストが表示されるのが見えるでしょう。
[[
1 subgoal
============================
forall (e : exp) (p : list instr) (s : stack),
progDenote (compile e ++ p) s = progDenote p (expDenote e :: s)
]]
Coqが補題を再掲してくれたように見えます。これは、私たちが証明のどこにいるのかを示す一般的なやり方で、今はその特別な場合です。一行めの表示は、サブゴールが一つある、と読めます。一般に、証明の途中には証明すべき論理命題がいくつも出てきます。それら未証明の部分的な論理命題が、%\index{サブゴール}%サブゴールです。複数のサブゴールはどんな順番で証明してもかまいませんが、通常はCoqが提示してくれた順番で証明するのがよいでしょう。
上記の出力では、その下に一つのサブゴールの詳細が完全に示されています。二重線の上側には、自由変数や%\index{仮定}%仮定が(もしあれば)示されます。二重線の下側は%\index{結論}%結論で、一般には仮定を使って証明されるべきものが示されます。
証明の状態は、%\index{タクティク}%_[タクティク]_と呼ばれるコマンドを実行することで操作します。もっとも重要なタクティクの一つである%\index{tactics!induction}%[induction]から始めましょう。
*)
induction e.
(**
(** We declare that this proof will proceed by induction on the structure of the expression [e]. This swaps out our initial subgoal for two new subgoals, one for each case of the inductive proof:
[[
2 subgoals
n : nat
============================
forall (s : stack) (p : list instr),
progDenote (compile (Const n) ++ p) s =
progDenote p (expDenote (Const n) :: s)
subgoal 2 is
forall (s : stack) (p : list instr),
progDenote (compile (Binop b e1 e2) ++ p) s =
progDenote p (expDenote (Binop b e1 e2) :: s)
]]
The first and current subgoal is displayed with the double-dashed line below free variables and hypotheses, while later subgoals are only summarized with their conclusions. We see an example of a %\index{free variable}%free variable in the first subgoal; [n] is a free variable of type [nat]. The conclusion is the original theorem statement where [e] has been replaced by [Const n]. In a similar manner, the second case has [e] replaced by a generalized invocation of the [Binop] expression constructor. We can see that proving both cases corresponds to a standard proof by %\index{structural induction}%structural induction.
We begin the first case with another very common tactic.%\index{tactics!intros}%
*)
*)
(**
この証明を式[e]の構造に対する帰納法によって進める、と宣言しています。これにより、元のサブゴールが、帰納法による証明の場合分けに対応する二つの新しいサブゴールに変わります。
[[
2 subgoals
n : nat
============================
forall (s : stack) (p : list instr),
progDenote (compile (Const n) ++ p) s =
progDenote p (expDenote (Const n) :: s)
subgoal 2 is
forall (s : stack) (p : list instr),
progDenote (compile (Binop b e1 e2) ++ p) s =
progDenote p (expDenote (Binop b e1 e2) :: s)
]]
一つめのサブゴール(現在のサブゴールでもあります)には、二重線とその上の自由変数や仮定が表示されますが、それ以降のサブゴールには結論だけが表示されます。一つめのサブゴールには%\index{自由変数}%自由変数がありますね。[nat]型の自由変数[n]です。このサブゴールの結論は、元の定理の主張で[e]が[Const n]に置き換えられてものです。同様に、二つめのサブゴールの[e]は、コンストラクタ[Binop]の一般的な形に置き換えられています。場合分けの両方のサブゴールの証明が、%\index{構造的帰納法}%構造的帰納法による標準的な証明に対応していることがわかります。
前に使った[induction]とはまた別の、やはりよく利用する[intros]というタクティクを使って、一つめのサブゴールを証明するところから始めましょう。%\index{tactics!intros}% *)
intros.
(**
(** The current subgoal changes to:
[[
n : nat
s : stack
p : list instr
============================
progDenote (compile (Const n) ++ p) s =
progDenote p (expDenote (Const n) :: s)
]]
We see that [intros] changes [forall]-bound variables at the beginning of a goal into free variables.
To progress further, we need to use the definitions of some of the functions appearing in the goal. The [unfold] tactic replaces an identifier with its definition.%\index{tactics!unfold}%
*)
*)
(**
サブゴールは次のように変わります。
[[
n : nat
s : stack
p : list instr
============================
progDenote (compile (Const n) ++ p) s =
progDenote p (expDenote (Const n) :: s)
]]
[intros]により、先頭にあった[forall]で束縛された変数が自由変数に変わりました。
さらに証明を進めるためには、ゴール内にあるいくつかの関数の定義を使う必要があります。[unfold]タクティクを使うと、識別子がその定義に置き換わります。%\index{tactics!unfold}%
*)
unfold compile.
(** [[
n : nat
s : stack
p : list instr
============================
progDenote ((iConst n :: nil) ++ p) s =
progDenote p (expDenote (Const n) :: s)
]]
*)
unfold expDenote.
(**
(** [[
n : nat
s : stack
p : list instr
============================
progDenote ((iConst n :: nil) ++ p) s = progDenote p (n :: s)
]]
We only need to unfold the first occurrence of [progDenote] to prove the goal. An [at] clause used with [unfold] specifies a particular occurrence of an identifier to unfold, where we count occurrences from left to right.%\index{tactics!unfold}% *)
*)
(**
[[
n : nat
s : stack
p : list instr
============================
progDenote ((iConst n :: nil) ++ p) s = progDenote p (n :: s)
]]
ゴールを証明するのに展開が必要なのは、一つめの[progDenote]だけです。[unfold]と一緒に[at]節を使うことで、展開したい特定の識別子の出現場所を指定できます。出現場所は左から右に数えます。%\index{tactics!unfold}% *)
unfold progDenote at 1.
(**
(** [[
n : nat
s : stack
p : list instr
============================
(fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
option stack :=
match p0 with
| nil => Some s0
| i :: p' =>
match instrDenote i s0 with
| Some s' => progDenote p' s'
| None => None (A:=stack)
end
end) ((iConst n :: nil) ++ p) s =
progDenote p (n :: s)
]]
This last [unfold] has left us with an anonymous recursive definition of [progDenote] (similarly to how [fun] or "lambda" constructs in general allow anonymous non-recursive functions), which will generally happen when unfolding recursive definitions. Note that Coq has automatically renamed the [fix] arguments [p] and [s] to [p0] and [s0], to avoid clashes with our local free variables. There is also a subterm [None (A:=stack)], which has an annotation specifying that the type of the term ought to be [option stack]. This is phrased as an explicit instantiation of a named type parameter [A] from the definition of [option].
Fortunately, in this case, we can eliminate the complications of anonymous recursion right away, since the structure of the argument ([iConst n :: nil) ++ p] is known, allowing us to simplify the internal pattern match with the [simpl] tactic, which applies the same reduction strategy that we used earlier with [Eval] (and whose details we still postpone).%\index{tactics!simpl}%
*)
*)
(**
[[
n : nat
s : stack
p : list instr
============================
(fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
option stack :=
match p0 with
| nil => Some s0
| i :: p' =>
match instrDenote i s0 with
| Some s' => progDenote p' s'
| None => None (A:=stack)
end
end) ((iConst n :: nil) ++ p) s =
progDenote p (n :: s)
]]
この[unfold]により、[progDenote]が無名の再帰関数に変わります(一般に[fun]や「lambda」で再帰しない無名関数が得られるのに似ています)。再帰的な定義を展開すると、通常はこのようなことが起こります。ここで、Coqが引数[p]と[s]を、それぞれ[p0]および[s0]へと自動的に変えたことに注意してください。これは、局所的な自由変数と名前の衝突を避けるためです。[None (A:=stack)]という部分項もありますね。この項には、この項が[option stack]型を持つということを指示する注釈が含まれています。このことを、「名前付きの型変数[A]を[option]の定義から明示的に具体化する」と表現します。
幸いなことに、今の例ではこの複雑な無名の再帰関数をすぐに取り除けます。これは、引数である[(iConst n :: nil) ++ p]の構造が、[simpl]タクティクを使って内部のパターンマッチを簡約することで明らかになるからです。[simpl]タクティクは、先ほど[Eval]で使ったのと同じ簡約戦略を適用します(詳細については今はまだ触れません)。%\index{tactics!simpl}%
*)
simpl.
(**
(** [[
n : nat
s : stack
p : list instr
============================
(fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
option stack :=
match p0 with
| nil => Some s0
| i :: p' =>
match instrDenote i s0 with
| Some s' => progDenote p' s'
| None => None (A:=stack)
end
end) p (n :: s) = progDenote p (n :: s)
]]
Now we can unexpand the definition of [progDenote]:%\index{tactics!fold}%
*)
*)
(**
[[
n : nat
s : stack
p : list instr
============================
(fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
option stack :=
match p0 with
| nil => Some s0
| i :: p' =>
match instrDenote i s0 with
| Some s' => progDenote p' s'
| None => None (A:=stack)
end
end) p (n :: s) = progDenote p (n :: s)
]]
これで[progDenote]の定義を折り畳むことができます。%\index{tactics!fold}%
*)
fold progDenote.
(**
(** [[
n : nat
s : stack
p : list instr
============================
progDenote p (n :: s) = progDenote p (n :: s)
]]
It looks like we are at the end of this case, since we have a trivial equality. Indeed, a single tactic finishes us off:%\index{tactics!reflexivity}%
*)
*)
(**
[[
n : nat
s : stack
p : list instr
============================
progDenote p (n :: s) = progDenote p (n :: s)
]]
自明な等式になったので、このケースの証明はこれで終わりのように見えます。実際、次のタクティクを使えば証明は終わりです。%\index{tactics!reflexivity}%
*)
reflexivity.
(**
(** On to the second inductive case:
[[
b : binop
e1 : exp
IHe1 : forall (s : stack) (p : list instr),
progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
e2 : exp
IHe2 : forall (s : stack) (p : list instr),
progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
============================
forall (s : stack) (p : list instr),
progDenote (compile (Binop b e1 e2) ++ p) s =
progDenote p (expDenote (Binop b e1 e2) :: s)
]]
We see our first example of %\index{hypotheses}%hypotheses above the double-dashed line. They are the inductive hypotheses [IHe1] and [IHe2] corresponding to the subterms [e1] and [e2], respectively.
We start out the same way as before, introducing new free variables and unfolding and folding the appropriate definitions. The seemingly frivolous [unfold]/[fold] pairs are actually accomplishing useful work, because [unfold] will sometimes perform easy simplifications. %\index{tactics!intros}\index{tactics!unfold}\index{tactics!fold}% *)
*)
(**
二つめのサブゴールに入ります。
[[
b : binop
e1 : exp
IHe1 : forall (s : stack) (p : list instr),
progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
e2 : exp
IHe2 : forall (s : stack) (p : list instr),
progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
============================
forall (s : stack) (p : list instr),
progDenote (compile (Binop b e1 e2) ++ p) s =
progDenote p (expDenote (Binop b e1 e2) :: s)
]]
二重線の上に%\index{仮定}%「仮定」が登場する最初の例です。部分項[e1]および[e2]に対応する帰納法の仮定は、それぞれ[IHe1]および[IHe2]です。
前回と同じように、自由変数を導入([intro]duce)し、適切な定義を展開([unfold])して、折り畳み([fold])ます。一見すると、[unfold]して[fold]するのは無駄に見えるかもしれませんが、[unfold]が簡単な簡約を実施する場合があるので、実際には有益な仕事が成し遂げられています。%\index{tactics!intros}\index{tactics!unfold}\index{tactics!fold}% *)
intros.
unfold compile.
fold compile.
unfold expDenote.
fold expDenote.
(**
(** Now we arrive at a point where the tactics we have seen so far are insufficient. No further definition unfoldings get us anywhere, so we will need to try something different.
[[
b : binop
e1 : exp
IHe1 : forall (s : stack) (p : list instr),
progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
e2 : exp
IHe2 : forall (s : stack) (p : list instr),
progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
s : stack
p : list instr
============================
progDenote ((compile e2 ++ compile e1 ++ iBinop b :: nil) ++ p) s =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
What we need is the associative law of list concatenation, which is available as a theorem [app_assoc_reverse] in the standard library.%\index{Vernacular commands!Check}% (Here and elsewhere, it is possible to tell the difference between inputs and outputs to Coq by periods at the ends of the inputs.) *)
*)
(**
これは、これまでに使ったタクティクだけでは不十分な状況です。定義の展開をこれ以上しても何も得られないので、何か別のことを試す必要があります。
[[
b : binop
e1 : exp
IHe1 : forall (s : stack) (p : list instr),
progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
e2 : exp
IHe2 : forall (s : stack) (p : list instr),
progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
s : stack
p : list instr
============================
progDenote ((compile e2 ++ compile e1 ++ iBinop b :: nil) ++ p) s =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
必要なのは、リストの結合に関する結合律(associative law)です。これは標準ライブラリにある[app_assoc_reverse]という定理として利用できます。%\index{Vernacular commands!Check}%(ここに限らず、説明に出てくる記述がCoqに対する入力なのか、それとも出力結果なのかは、末尾にピリオドがあるかどうかで見分けられます。)
*)
Check app_assoc_reverse.
(**
(** %\vspace{-.15in}%[[
app_assoc_reverse
: forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
]]
If we did not already know the name of the theorem, we could use the %\index{Vernacular commands!SearchRewrite}%[SearchRewrite] command to find it, based on a pattern that we would like to rewrite: *)
*)
(**
%\vspace{-.15in}%[[
app_assoc_reverse
: forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
]]
もし使いたい定理の名前がわからなければ、%\index{Vernacular commands!SearchRewrite}%[SearchRewrite]コマンドを使って検索できます。[SearchRewrite]には、以下のように、書き換えたいパターンを指定します。 *)
SearchRewrite ((_ ++ _) ++ _).
(**
(**%\vspace{-.15in}%[[
app_assoc_reverse:
forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
]]
%\vspace{-.25in}%
[[
app_assoc: forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n
]]
We use [app_assoc_reverse] to perform a rewrite: %\index{tactics!rewrite}% *)
*)
(**
%\vspace{-.15in}%[[
app_assoc_reverse:
forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
]]
%\vspace{-.25in}%
[[
app_assoc: forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n
]]
書き換えに[app_assoc_reverse]を使いましょう。 %\index{tactics!rewrite}% *)
rewrite app_assoc_reverse.
(** (* %\noindent{}%changing the conclusion to:
[[
progDenote (compile e2 ++ (compile e1 ++ iBinop b :: nil) ++ p) s =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
Now we can notice that the lefthand side of the equality matches the lefthand side of the second inductive hypothesis, so we can rewrite with that hypothesis, too.%\index{tactics!rewrite}% *)
%\noindent{}%結論は以下のように変わります。
[[
progDenote (compile e2 ++ (compile e1 ++ iBinop b :: nil) ++ p) s =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
この等式の左辺は、二つめの帰納法の仮定に出てくる等式の左辺に一致しています。よって、その仮定も書き換えに使えます。%\index{tactics!rewrite}% *)
rewrite IHe2.
(**
(** [[
progDenote ((compile e1 ++ iBinop b :: nil) ++ p) (expDenote e2 :: s) =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
The same process lets us apply the remaining hypothesis.%\index{tactics!rewrite}% *)
*)
(**
[[
progDenote ((compile e1 ++ iBinop b :: nil) ++ p) (expDenote e2 :: s) =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
同様にして残りの仮定も適用できます。%\index{tactics!rewrite}% *)
rewrite app_assoc_reverse.
rewrite IHe1.
(**
(** [[
progDenote ((iBinop b :: nil) ++ p) (expDenote e1 :: expDenote e2 :: s) =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
Now we can apply a similar sequence of tactics to the one that ended the proof of the first case.%\index{tactics!unfold}\index{tactics!simpl}\index{tactics!fold}\index{tactics!reflexivity}%
*)
*)
(**
[[
progDenote ((iBinop b :: nil) ++ p) (expDenote e1 :: expDenote e2 :: s) =
progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
]]
これで、先ほど終わらせた一つめの証明と同様のタクティクを適用していくことができます。%\index{tactics!unfold}\index{tactics!simpl}\index{tactics!fold}\index{tactics!reflexivity}%
*)
unfold progDenote at 1.
simpl.
fold progDenote.
reflexivity.
(** (* And the proof is completed, as indicated by the message: *)
次のようなメッセージが出て、証明完了です。 *)
(**
<<
Proof completed.
>>
*)
(**
(** And there lies our first proof. Already, even for simple theorems like this, the final proof script is unstructured and not very enlightening to readers. If we extend this approach to more serious theorems, we arrive at the unreadable proof scripts that are the favorite complaints of opponents of tactic-based proving. Fortunately, Coq has rich support for scripted automation, and we can take advantage of such a scripted tactic (defined elsewhere) to make short work of this lemma. We abort the old proof attempt and start again.%\index{Vernacular commands!Abort}%
*)
*)
(**
これが本書の最初の証明です。このような単純な定理ですら、最終的に得られる証明のスクリプトは構造化されておらず、読み手にとってあまり教育的ではありません。もっと本格的な定理を同じ方針で証明すれば、タクティクを使った証明を批判するのに好都合な、可読性が低い証明のスクリプトになってしまいます。幸いなことに、Coqはスクリプトによる高機能な自動化に対応しています。別の場所でスクリプトとして定義した自動化のタクティクを利用することで、この補題に対する短い証明を与えることが可能です。これまでの証明を[Abort]で中止し、はじめからやり直してみましょう。%\index{Vernacular commands!Abort}%
*)
Abort.
(** %\index{tactics!induction}\index{tactics!crush}% *)
Lemma compile_correct' : forall e s p, progDenote (compile e ++ p) s =
progDenote p (expDenote e :: s).
induction e; crush.
Qed.
(**
(** We need only to state the basic inductive proof scheme and call a tactic that automates the tedious reasoning in between. In contrast to the period tactic terminator from our last proof, the %\index{tactics!semicolon}%semicolon tactic separator supports structured, compositional proofs. The tactic [t1; t2] has the effect of running [t1] and then running [t2] on each remaining subgoal. The semicolon is one of the most fundamental building blocks of effective proof automation. The period terminator is very useful for exploratory proving, where you need to see intermediate proof states, but final proofs of any serious complexity should have just one period, terminating a single compound tactic that probably uses semicolons.
The [crush] tactic comes from the library associated with this book and is not part of the Coq standard library. The book's library contains a number of other tactics that are especially helpful in highly automated proofs.
The %\index{Vernacular commands!Qed}%[Qed] command checks that the proof is finished and, if so, saves it. The tactic commands we have written above are an example of a _proof script_, or a series of Ltac programs; while [Qed] uses the result of the script to generate a _proof term_, a well-typed term of Gallina. To believe that a theorem is true, we only need to trust that the (relatively simple) checker for proof terms is correct; the use of proof scripts is immaterial. Part I of this book will introduce the principles behind encoding all proofs as terms of Gallina.
The proof of our main theorem is now easy. We prove it with four period-terminated tactics, though separating them with semicolons would work as well; the version here is easier to step through.%\index{tactics!intros}% *)
*)
(**
必要なのは、まず帰納法による証明における決まり文句を書き、中間の長々しい推論を自動化するタクティクを呼ぶことだけです。前回の証明ではタクティクの末尾にピリオドを置きましたが、今回の証明ではピリオドの代わりに%\index{tactics!semicolon}%セミコロンを使います。セミコロンは二つのタクティクを切り離し、証明を構造化して組み合わせられるようにしてくれます。タクティク[t1; t2]には、[t1]を適用してから残りの各サブゴールに対して[t2]を適用する、という効果があります。セミコロンは、証明を効果的に自動化するための基本的な構成要素の一つです。ピリオドは、途中の状態を確認しながら探索的に証明をしていくときは便利に使えます。しかし、それなりに複雑な証明は、最終的にすべて、セミコロンを使って合成した一つのタクティクの末尾にピリオドが一つだけある状態にすべきです。
[crush]は、本書に付随するライブラリで用意しているタクティクであり、Coqの標準ライブラリにはありません。ほかにも本書のライブラリには証明の高度な自動化にとても役立つタクティクがいくつも含まれています。
%\index{Vernacular commands!Qed}%[Qed]コマンドは、証明が実際に完了していることを確認し、そうであればその証明を保存します。これまで書いてきたタクティクたちは_[証明スクリプト]_、別の言い方をするとLtacプログラムの列であり、正しく型付けされたGallinaの項です。証明スクリプトそのものは、定理が正しいことを信じる根拠にはなりません。定理が正しいことを信じるのに必要なのは、証明項の(比較的単純な)検査器が正しいことを信頼することだけです。本書の第1部では、あらゆる証明をGallinaの項として表現することの背景にある原理について説明します。
今、主定理は容易に証明できます。ここではピリオドで終端した四つのタクティクにより証明します。セミコロン区切りにしても同じことですが、証明を順番に進めるには、このやり方のほうが簡単だからです。%\index{tactics!intros}% *)
Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
intros.
(**
(** [[
e : exp
============================
progDenote (compile e) nil = Some (expDenote e :: nil)
]]
At this point, we want to massage the lefthand side to match the statement of [compile_correct']. A theorem from the standard library is useful: *)
*)
(**
[[
e : exp
============================
progDenote (compile e) nil = Some (expDenote e :: nil)
]]
ここで、左辺を[compile_correct']の主張に合うように書き換えましょう。標準ライブラリの以下の定理が使えます。 *)
Check app_nil_end.
(** [[
app_nil_end
: forall (A : Type) (l : list A), l = l ++ nil
]]
%\index{tactics!rewrite}% *)
rewrite (app_nil_end (compile e)).
(**
(** This time, we explicitly specify the value of the variable [l] from the theorem statement, since multiple expressions of list type appear in the conclusion. The [rewrite] tactic might choose the wrong place to rewrite if we did not specify which we want.
[[
e : exp
============================
progDenote (compile e ++ nil) nil = Some (expDenote e :: nil)
]]
Now we can apply the lemma.%\index{tactics!rewrite}% *)
*)
(**
今度は結論に複数のリストが現れているので、定理内の変数[l]の値を明示しています。[rewrite]タクティクは、書き換えたいものを明示しないと、別の場所を選んで書き換えてしまうことがあります。
[[
e : exp
============================
progDenote (compile e ++ nil) nil = Some (expDenote e :: nil)
]]
これで補題が適用できます。%\index{tactics!rewrite}% *)
rewrite compile_correct'.
(**
(** [[
e : exp
============================
progDenote nil (expDenote e :: nil) = Some (expDenote e :: nil)
]]
We are almost done. The lefthand and righthand sides can be seen to match by simple symbolic evaluation. That means we are in luck, because Coq identifies any pair of terms as equal whenever they normalize to the same result by symbolic evaluation. By the definition of [progDenote], that is the case here, but we do not need to worry about such details. A simple invocation of %\index{tactics!reflexivity}%[reflexivity] does the normalization and checks that the two results are syntactically equal.%\index{tactics!reflexivity}% *)
*)
(**
[[
e : exp
============================
progDenote nil (expDenote e :: nil) = Some (expDenote e :: nil)
]]
これでもうほとんど終わりです。左辺と右辺は単純な記号的評価によって一致しそうに見えます。ありがたいことに、記号的評価によって同じ結果に正規化されるものは、Coqによって同じ項とみなされます。この場合に左辺と右辺が同じ項に評価されるのは[progDenote]の定義によるわけですが、そのような詳細を気にする必要はありません。%\index{tactics!reflexivity}%[reflexivity]タクティクを呼び出すだけで、正規化および左辺と右辺の構文的な等しさの確認を実施してくれます。%\index{tactics!reflexivity}% *)
reflexivity.
Qed.
(* end thide *)
(**
(** This proof can be shortened and automated, but we leave that task as an exercise for the reader. *)
*)
(**
この証明は、もっと短く、さらに自動化できますが、これは読者への演習問題としましょう。 *)
(** * 型付き式 *)
(**
(** In this section, we will build on the initial example by adding additional expression forms that depend on static typing of terms for safety. *)
*)
(**
この節では、項が静的型付けを持つような安全な式の構造を付け足すことで、最初の例を拡充していきます。 *)
(** ** ソース言語 *)
(**
(** We define a trivial language of types to classify our expressions: *)
*)
(**
式を区別するために、自明な型の言語を定義します。 *)
Inductive type : Set := Nat | Bool.
(**
(** Like most programming languages, Coq uses case-sensitive variable names, so that our user-defined type [type] is distinct from the [Type] keyword that we have already seen appear in the statement of a polymorphic theorem (and that we will meet in more detail later), and our constructor names [Nat] and [Bool] are distinct from the types [nat] and [bool] in the standard library.
Now we define an expanded set of binary operators. *)
*)
(**
多くのプログラミング言語と同様に、Coqでは変数名の大文字と小文字に区別があるので、ここで定義した型[type]は、先ほど多相的な定理の主張の中に登場した[Type]キーワード(詳細は後で説明します)とは区別されます。コンストラクタである[Nat]と[Bool]も、標準ライブラリ内にある型[nat]および[bool]とは異なります。
二項演算子についても拡張したものを定義しましょう。 *)
Inductive tbinop : type -> type -> type -> Set :=
| TPlus : tbinop Nat Nat Nat
| TTimes : tbinop Nat Nat Nat
| TEq : forall t, tbinop t t Bool
| TLt : tbinop Nat Nat Bool.
(**
(** The definition of [tbinop] is different from [binop] in an important way. Where we declared that [binop] has type [Set], here we declare that [tbinop] has type [type -> type -> type -> Set]. We define [tbinop] as an _indexed type family_. Indexed inductive types are at the heart of Coq's expressive power; almost everything else of interest is defined in terms of them.
The intuitive explanation of [tbinop] is that a [tbinop t1 t2 t] is a binary operator whose operands should have types [t1] and [t2], and whose result has type [t]. For instance, constructor [TLt] (for less-than comparison of numbers) is assigned type [tbinop Nat Nat Bool], meaning the operator's arguments are naturals and its result is Boolean. The type of [TEq] introduces a small bit of additional complication via polymorphism: we want to allow equality comparison of any two values of any type, as long as they have the _same_ type.
ML and Haskell have indexed algebraic datatypes. For instance, their list types are indexed by the type of data that the list carries. However, compared to Coq, ML and Haskell 98 place two important restrictions on datatype definitions.
First, the indices of the range of each data constructor must be type variables bound at the top level of the datatype definition. There is no way to do what we did here, where we, for instance, say that [TPlus] is a constructor building a [tbinop] whose indices are all fixed at [Nat]. %\index{generalized algebraic datatypes}\index{GADTs|see{generalized algebraic datatypes}}% _Generalized algebraic datatypes_ (GADTs)%~\cite{GADT}% are a popular feature in %\index{GHC Haskell}%GHC Haskell, OCaml 4, and other languages that removes this first restriction.
The second restriction is not lifted by GADTs. In ML and Haskell, indices of types must be types and may not be _expressions_. In Coq, types may be indexed by arbitrary Gallina terms. Type indices can live in the same universe as programs, and we can compute with them just like regular programs. Haskell supports a hobbled form of computation in type indices based on %\index{Haskell}%multi-parameter type classes, and recent extensions like type functions bring Haskell programming even closer to "real" functional programming with types, but, without dependent typing, there must always be a gap between how one programs with types and how one programs normally.
*)
*)
(**
[tbinop]の定義には、[binop]の定義とは大きく異なる点があります。[binop]は[Set]型であると宣言しましたが、[tbinop]は[type -> type -> type -> Set]型であると宣言しています。これは、_[添字付けされた型の族]_(indexed type family)として[tbinop]を定義しているということです。添字付けされた型の族は、Coqの表現力の根幹です。実際、それ以外の興味深いものは、ほとんどすべて添字付けされた型の族によって定義されます。
[tbinop]の直観的な説明は、「[tbinop t1 t2 t]は、型[t1]と[t2]のオペランドを取って型[t]の結果を返す二項演算子である」というものです。たとえばコンストラクタ[TLt](自然数の順序$\leq$#≦#)は、引数が自然数、結果がブール値であることを意味する型[tbinop Nat Nat Bool]を持ちます。[TEq]の型は、多相性によって少し複雑になっています。具体的には、等値の比較である[TEq]では、_[同じ]_型を持つ値を任意に取れるようにしてあります。
MLやHaskellには添字付けされた代数的データ型があります。たとえば、MLやHaskellのリスト型は、リストの要素の型によって添字付けられています。ただし、MLやHaskelll 98は、Coqに比べるとデータ型の定義に関して二つの大きな制限があります。
まず、各データコンストラクタの添字が、そのデータ型の定義のトップレベルで束縛された型変数でなければいけません。
たとえば、[TPlus]はすべての添字が[Nat]に固定された[tbinop]を構成するコンストラクタですが、MLやHaskellではそのような定義をする手段はありません。
%\index{generalized algebraic datatypes}\index{GADTs|see{generalized algebraic datatypes}}%_一般化代数データ型_(Generalized algebraic datatypes、GADTs)%~\cite{GADT}%は、%\index{GHC Haskell}%GHC Haskell、OCaml 4など、この制限が取り除かれている言語で広く採用されている機能です。
二つめの制限はGADTsでは対処できません。MLやHaskellでは、型の添字は必ず型であり、[式]であってはいけません。Coqでは、型は任意のGallina項により添字付けできます。型の添字はプログラムと同じ領域に属することができ、それらは通常のプログラムと同様に計算できます。
Haskellは、%\index{Haskell}multi-parameter type classに基いた型の添字計算に制限付きで対応しています。また、型関数(type function)のような近年の拡張により、Haskellプログラミングは「本物」の型付き関数型プログラミングにだいぶ近づきました。しかし、依存型なしでは、型を使ってプログラミングすることと、普通にプログラミングすることとの間に、必ずギャップが生じます。
*)
(**
(** We can define a similar type family for typed expressions, where a term of type [texp t] can be assigned object language type [t]. (It is conventional in the world of interactive theorem proving to call the language of the proof assistant the%\index{meta language}% _meta language_ and a language being formalized the%\index{object language}% _object language_.) *)
*)
(**
型付きの式に対しても、同じように型族を定義できます。型[texp t]を持つ項には、対象言語の型[t]が割り当てられます。(対話的定理証明の分野では、慣習的に、証明支援器の言語を%\index{メタ言語}%[メタ言語]と呼び、形式化の対象になっている言語を%\index{対象言語}%[対象言語]と呼びます。)*)
Inductive texp : type -> Set :=
| TNConst : nat -> texp Nat
| TBConst : bool -> texp Bool
| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.
(** (* Thanks to our use of dependent types, every well-typed [texp] represents a well-typed source expression, by construction. This turns out to be very convenient for many things we might want to do with expressions. For instance, it is easy to adapt our interpreter approach to defining semantics. We start by defining a function mapping the types of our object language into Coq types: *)
依存型を利用することで、すべてのwell-typedな[texp]は、その構成によりwell-typedなソース言語の式を表すことになります。式を使って何かをしたい場合、これがとても便利なことが多いのです。たとえば、インタプリタのときの手法をセマンティクスの定義にも簡単に適用できます。対象言語の型をCoqの型に移す写像の定義から始めましょう。 *)
Definition typeDenote (t : type) : Set :=
match t with
| Nat => nat
| Bool => bool
end.
(**
(** It can take a few moments to come to terms with the fact that [Set], the type of types of programs, is itself a first-class type, and that we can write functions that return [Set]s. Past that wrinkle, the definition of [typeDenote] is trivial, relying on the [nat] and [bool] types from the Coq standard library. We can interpret binary operators by relying on standard-library equality test functions [eqb] and [beq_nat] for Booleans and naturals, respectively, along with a less-than test [leb]: *)
*)
(**
「プログラムの型」の型である[Set]は、それ自身がファーストクラスの型なので、[Set]を返す関数が書けます。この事実を受け入れるには少し時間がかかるかもしれませんね。それさえ納得できれば、[typeDenote]の定義ではCoqの標準ライブラリの型である[nat]と[bool]をそのまま使っているだけです。二項演算子の定義では、標準ライブラリの比較関数である[eqb](ブール値間の等値性)、[beq_nat](自然数値間の等値性)、[leb](自然数の$\leq$#≦#)をそのまま使います。*)
Definition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)
: typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
match b with
| TPlus => plus
| TTimes => mult
| TEq Nat => beq_nat
| TEq Bool => eqb
| TLt => leb
end.
(**
(** This function has just a few differences from the denotation functions we saw earlier. First, [tbinop] is an indexed type, so its indices become additional arguments to [tbinopDenote]. Second, we need to perform a genuine%\index{dependent pattern matching}% _dependent pattern match_, where the necessary _type_ of each case body depends on the _value_ that has been matched. At this early stage, we will not go into detail on the many subtle aspects of Gallina that support dependent pattern-matching, but the subject is central to Part II of the book.
The same tricks suffice to define an expression denotation function in an unsurprising way. Note that the [type] arguments to the [TBinop] constructor must be included explicitly in pattern-matching, but here we write underscores because we do not need to refer to those arguments directly. *)
*)
(**
この関数は、前に定義した[binopDenote]関数とそれほど大きく違うわけではありません。まず、[tbinop]は添字付けされた型なので、その添字が[tbinopDenote]の追加の引数になります。
次に、場合分けの本体における_[型]_がマッチした_[値]_に依存する場合には、正真正銘の%\index{依存パターンマッチ}%_[依存パターンマッチ]_が必要です。
Gallinaには、依存パターンマッチを支援する面がたくさんありますが、ここでは詳細には踏み込みません。これは本書の第2部の中心テーマです。
同じ仕組みにより、式に対する[texpDenote]関数も自然に定義できます。
コンストラクタ[TBinop]に対する[type]型の引数を明示的にパターンマッチに含めなければなりませんが、これらの引数を直接参照する必要はないので、ここではアンダースコアを書いています。
*)
Fixpoint texpDenote t (e : texp t) : typeDenote t :=
match e with
| TNConst n => n
| TBConst b => b
| TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)
end.
(**
(** We can evaluate a few example programs to convince ourselves that this semantics is correct. *)
*)
(**
このセマンティクスが正しいことを確かめるために、プログラムをいくつか試しに評価してみましょう。*)
Eval simpl in texpDenote (TNConst 42).
(** [= 42 : typeDenote Nat] *)
(* begin hide *)
Eval simpl in texpDenote (TBConst false).
(* end hide *)
Eval simpl in texpDenote (TBConst true).
(** [= true : typeDenote Bool] *)
Eval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2))
(TNConst 7)).
(** [= 28 : typeDenote Nat] *)
Eval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2))
(TNConst 7)).
(** [= false : typeDenote Bool] *)
Eval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))
(TNConst 7)).
(** [= true : typeDenote Bool] *)
(**
(** %\smallskip{}%Now we are ready to define a suitable stack machine target for compilation. *)
*)
(**
%\smallskip{}%これでコンパイルに適したスタックマシンのターゲットを定義する準備ができました。*)
(** ** ターゲット言語 *)
(**
(** In the example of the untyped language, stack machine programs could encounter stack underflows and "get stuck." This was unfortunate, since we had to deal with this complication even though we proved that our compiler never produced underflowing programs. We could have used dependent types to force all stack machine programs to be underflow-free.
For our new languages, besides underflow, we also have the problem of stack slots with naturals instead of bools or vice versa. This time, we will use indexed typed families to avoid the need to reason about potential failures.
We start by defining stack types, which classify sets of possible stacks. *)
*)
(**
言語に型がなかったときは、スタックマシーンのプログラムがスタックアンダーフローを起こして動かなくなる可能性がありました。アンダーフローするプログラムをコンパイラは生成しない、と証明したのに、そのような事態への対処が必要になるというのでは、残念すぎます。
依存型を使えば、すべてのスタックマシーンのプログラムがアンダーフローを起こさないことが強制できたでしょう。
新しい言語には、アンダーフロー以外にも、ブール値ではなく自然数がスタックに入ったり、その逆の状況が起きたりするという問題があります。ここでは、起こりうる障害を推論しなくて済むように、添字付けられた型の族を使うことにします。
まずはスタック型を定義し、起こりうるスタックの状態を分類できるようにしましょう。
*)
Definition tstack := list type.
(**
(** Any stack classified by a [tstack] must have exactly as many elements, and each stack element must have the type found in the same position of the stack type.
We can define instructions in terms of stack types, where every instruction's type tells us what initial stack type it expects and what final stack type it will produce. *)
*)
(**
ある[tstack]によって分類されるスタックは、いずれも要素の数が同じでなければなりません。また、各スタックの要素の型は、スタック型における同じ位置の型でなければなりません。
スタック型を利用して命令を定義しましょう。いずれの命令も、命令が最初に期待しているスタック型と命令によって生成される最終的なスタック型とがわかるような型を持ちます。
*)
Inductive tinstr : tstack -> tstack -> Set :=
| TiNConst : forall s, nat -> tinstr s (Nat :: s)
| TiBConst : forall s, bool -> tinstr s (Bool :: s)
| TiBinop : forall arg1 arg2 res s,
tbinop arg1 arg2 res
-> tinstr (arg1 :: arg2 :: s) (res :: s).
(** (** Stack machine programs must be a similar inductive family, since, if we again used the [list] type family, we would not be able to guarantee that intermediate stack types match within a program. *)*)
(**
スタックマシーンのプログラムも、同様な帰納的な族にしなければなりません。
もしここで前のように[list]型の族を使ったら、プログラム内部で中間的なスタック型がマッチするかどうかを保証する手立てがなくなってしまうからです。
*)
Inductive tprog : tstack -> tstack -> Set :=
| TNil : forall s, tprog s s
| TCons : forall s1 s2 s3,
tinstr s1 s2
-> tprog s2 s3
-> tprog s1 s3.
(**
(** Now, to define the semantics of our new target language, we need a representation for stacks at runtime. We will again take advantage of type information to define types of value stacks that, by construction, contain the right number and types of elements. *)
*)
(**
次は、新しいターゲット言語のセマンティクスを定義するために、実行時のスタックの表現を決める必要があります。構成の仕方から要素の個数と型が正しい値について、スタックの型を定義するのにも、型の情報が役立ちます。
*)
Fixpoint vstack (ts : tstack) : Set :=
match ts with
| nil => unit
| t :: ts' => typeDenote t * vstack ts'
end%type.
(**
(** This is another [Set]-valued function. This time it is recursive, which is perfectly valid, since [Set] is not treated specially in determining which functions may be written. We say that the value stack of an empty stack type is any value of type [unit], which has just a single value, [tt]. A nonempty stack type leads to a value stack that is a pair, whose first element has the proper type and whose second element follows the representation for the remainder of the stack type. We write [%]%\index{notation scopes}\coqdocvar{%#<tt>#type#</tt>#%}% as an instruction to Coq's extensible parser. In particular, this directive applies to the whole [match] expression, which we ask to be parsed as though it were a type, so that the operator [*] is interpreted as Cartesian product instead of, say, multiplication. (Note that this use of %\coqdocvar{%#<tt>#type#</tt>#%}% has no connection to the inductive type [type] that we have defined.)
This idea of programming with types can take a while to internalize, but it enables a very simple definition of instruction denotation. Our definition is like what you might expect from a Lisp-like version of ML that ignored type information. Nonetheless, the fact that [tinstrDenote] passes the type-checker guarantees that our stack machine programs can never go wrong. We use a special form of [let] to destructure a multi-level tuple. *)
*)
(**
[Set]値の関数がまた出てきました。
今回は再帰関数です。書かれる可能性がある関数を決める際に[Set]が特別扱いされることはないので、再帰関数でも完全に妥当です。
この関数は、空のスタック型の値を表すスタックは[unit]型の任意の値である、と言っています。
[unit]は、唯一の値[tt]を持つ型です。
空でないスタック型は、ペアの値を表すスタックになります。そのペアは、一つめの要素が適切な型で、二つめの要素が残りのスタック型の表現に従うようなものです。
[%]%\index{notation scopes}\coqdocvar{%#<tt>#type#</tt>#%}%は、Coqの拡張可能なパーサへの、ある指示になります。
この場合は[match]式全体に適用される指示で、その[match]式が型としてパースされるようにし、演算子[*]が乗算ではなく直積として解釈されるようにします。
(この場合の%\coqdocvar{%#<tt>#type#</tt>#%}%は、先ほど定義した帰納的データ型[type]には関係ありません。)
型を使ったプログラミングの概念を習得するには時間がかかるかもしれませんが、おかげで命令の表示的意味論がとてもシンプルに定義できます。
ここで得られた定義は、型情報が無視されたLispふうのMLによる定義にも似ています。
にもかかわらず、[tinstrDenote]が型検査を通るという事実により、このスタックマシーンのプログラムで障害が発生することがありえないと保証されるのです。
多重タプルを分解するには特殊な形式の[let]を使います。
*)
Definition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=
match i with
| TiNConst _ n => fun s => (n, s)
| TiBConst _ b => fun s => (b, s)
| TiBinop _ _ _ _ b => fun s =>
let '(arg1, (arg2, s')) := s in
((tbinopDenote b) arg1 arg2, s')
end.
(**
(** Why do we choose to use an anonymous function to bind the initial stack in every case of the [match]? Consider this well-intentioned but invalid alternative version:
[[
Definition tinstrDenote ts ts' (i : tinstr ts ts') (s : vstack ts) : vstack ts' :=
match i with
| TiNConst _ n => (n, s)
| TiBConst _ b => (b, s)
| TiBinop _ _ _ _ b =>
let '(arg1, (arg2, s')) := s in
((tbinopDenote b) arg1 arg2, s')
end.
]]
The Coq type checker complains that:
<<
The term "(n, s)" has type "(nat * vstack ts)%type"
while it is expected to have type "vstack ?119".
>>
This and other mysteries of Coq dependent typing we postpone until Part II of the book. The upshot of our later discussion is that it is often useful to push inside of [match] branches those function parameters whose types depend on the type of the value being matched. Our later, more complete treatment of Gallina's typing rules will explain why this helps.
*)
*)
(**
[match]の場合分けで、初期スタックの束縛に無名関数を使ったのはなぜでしょうか。次のように書くと意図がはっきりしますが、これは正しくありません。
[[
Definition tinstrDenote ts ts' (i : tinstr ts ts') (s : vstack ts) : vstack ts' :=
match i with
| TiNConst _ n => (n, s)
| TiBConst _ b => (b, s)
| TiBinop _ _ _ _ b =>
let '(arg1, (arg2, s')) := s in
((tbinopDenote b) arg1 arg2, s')
end.
]]
Coqの型検査器は以下のようなエラーを出力します。
<<
The term "(n, s)" has type "(nat * vstack ts)%type"
while it is expected to have type "vstack ?119".
>>
Coqの依存型における型付けの深淵な部分については第2部で述べます。関数の引数のうち、マッチさせる値の型に依存するような型を持つものは、[match]の分岐の中に押し込めるとうまくいく場合が多い、というのが上記の議論の要点です。それでうまくいく理由は、のちほどGallinaの型付け規則についてもっときちんと扱うときに説明します。
*)
(**
(** We finish the semantics with a straightforward definition of program denotation. *)
*)
(**
最後に、プログラムの表示的意味論を直接定義します。
*)
Fixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=
match p with
| TNil _ => fun s => s
| TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)
end.
(**
(** The same argument-postponing trick is crucial for this definition. *)
*)
(**
この定義でも引数を[match]の中に入れるテクニックが重要です。
*)
(** ** 翻訳 *)
(**
(** To define our compilation, it is useful to have an auxiliary function for concatenating two stack machine programs. *)
*)
(**
コンパイルを定義するために、スタックマシーンの二つのプログラムを結合する補助関数を用意しましょう。
*)
Fixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=
match p with
| TNil _ => fun p' => p'
| TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')
end.
(**
(** With that function in place, the compilation is defined very similarly to how it was before, modulo the use of dependent typing. *)
*)
(**
スタックマシーンの結合処理をこの関数で置き換えれば、前とよく似た形でコンパイルの関数を定義できます(依存型を使っていることを除く)。
*)
Fixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=
match e with
| TNConst n => TCons (TiNConst _ n) (TNil _)
| TBConst b => TCons (TiBConst _ b) (TNil _)
| TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)
(tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))
end.
(**
(** One interesting feature of the definition is the underscores appearing to the right of [=>] arrows. Haskell and ML programmers are quite familiar with compilers that infer type parameters to polymorphic values. In Coq, it is possible to go even further and ask the system to infer arbitrary terms, by writing underscores in place of specific values. You may have noticed that we have been calling functions without specifying all of their arguments. For instance, the recursive calls here to [tcompile] omit the [t] argument. Coq's _implicit argument_ mechanism automatically inserts underscores for arguments that it will probably be able to infer. Inference of such values is far from complete, though; generally, it only works in cases similar to those encountered with polymorphic type instantiation in Haskell and ML.
The underscores here are being filled in with stack types. That is, the Coq type inferencer is, in a sense, inferring something about the flow of control in the translated programs. We can take a look at exactly which values are filled in: *)
*)
(**
この定義で面白いのは、矢印[=>]の右側にアンダースコアがあることです。
型パラメータから多相的な値を推論するコンパイラは、HaskellやMLのプログラマにはお馴染みでしょう。
Coqではさらに踏み込んで、特定の値の位置にアンダースコアを書くことで、任意の項に対する値の推論をシステムに任せることが可能です。
これまでも引数をすべて与えずに関数を呼び出していたことに気付いている読者もいるかもしれません。
たとえば、[tcompile]の再帰呼び出しでは引数[t]を省略しています。
Coqには_[暗黙引数]_(implicit argument)という仕組みがあり、推論ができるかもしれない引数に対して自動でアンダースコアを挿入します。
しかし、そのような値の推論を完全にするのは、到底無理な話です。
一般には、HaskellやMLにおいて多相型の具体化ができるような場面でしか機能しません。
この場合、アンダースコアにはスタック型が入ります。
つまり、Coqの型推論器は、翻訳されたプログラムの制御フローについて何かしら推論していると言えます。
何の値が入っているかは、以下のようにして確認できます。
*)
Print tcompile.
(** %\vspace{-.15in}%[[
tcompile =
fix tcompile (t : type) (e : texp t) (ts : tstack) {struct e} :
tprog ts (t :: ts) :=
match e in (texp t0) return (tprog ts (t0 :: ts)) with
| TNConst n => TCons (TiNConst ts n) (TNil (Nat :: ts))
| TBConst b => TCons (TiBConst ts b) (TNil (Bool :: ts))
| TBinop arg1 arg2 res b e1 e2 =>
tconcat (tcompile arg2 e2 ts)
(tconcat (tcompile arg1 e1 (arg2 :: ts))
(TCons (TiBinop ts b) (TNil (res :: ts))))
end
: forall t : type, texp t -> forall ts : tstack, tprog ts (t :: ts)
]]
*)
(**(** We can check that the compiler generates programs that behave appropriately on our sample programs from above: *)*)
(**
このコンパイラでも、前に利用したサンプルプログラムに対して適切に動作するプログラムが生成されることを確認しましょう。
*)
Eval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.
(** [= (42, tt) : vstack (Nat :: nil)] *)
Eval simpl in tprogDenote (tcompile (TBConst true) nil) tt.
(** [= (true, tt) : vstack (Bool :: nil)] *)
Eval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2)
(TNConst 2)) (TNConst 7)) nil) tt.
(** [= (28, tt) : vstack (Nat :: nil)] *)
Eval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2)
(TNConst 2)) (TNConst 7)) nil) tt.
(** [= (false, tt) : vstack (Bool :: nil)] *)
Eval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))
(TNConst 7)) nil) tt.
(** [= (true, tt) : vstack (Bool :: nil)] *)
(**(** %\smallskip{}%The compiler seems to be working, so let us turn to proving that it _always_ works. *)*)
(** %\smallskip{}%うまくコンパイラが動いているように見えるので、これが_[常に]_正しく動くことを証明しましょう。 *)
(** ** 翻訳の正しさ *)
(** (** We can state a correctness theorem similar to the last one. *)*)
(** 正しさについての定理を前回と同様に主張します。 *)
Theorem tcompile_correct : forall t (e : texp t),
tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
(* begin hide *)
Abort.
(* end hide *)
(* begin thide *)
(**(** Again, we need to strengthen the theorem statement so that the induction will go through. This time, to provide an excuse to demonstrate different tactics, I will develop an alternative approach to this kind of proof, stating the key lemma as: *)*)
(**
帰納法がうまくいくように、今回も定理の主張を強める必要があります。
新しいタクティクを使って見せたいので、今回は前とは違う手法で証明を開発することにします。
次の重要な補題を用意することから始めましょう。
*)
Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
tprogDenote (tcompile e ts) s = (texpDenote e, s).
(**(** While lemma [compile_correct'] quantified over a program that is the "continuation"%~\cite{continuations}% for the expression we are considering, here we avoid drawing in any extra syntactic elements. In addition to the source expression and its type, we also quantify over an initial stack type and a stack compatible with it. Running the compilation of the program starting from that stack, we should arrive at a stack that differs only in having the program's denotation pushed onto it.
Let us try to prove this theorem in the same way that we settled on in the last section. *)*)
(**
[compile_correct']は、考慮している式への「継続」%~\cite{continuations}%であるようなプログラムについて量化された補題になっていますが、構文上の要素は増やさないようにしています。
ソース言語の式とその型に加えて、最初のスタック型と、そのスタック型に適合するスタックについても量化されています。
そのようなスタックからプログラムのコンパイルを始めると、その上にプログラムの表示的意味がプッシュされたスタックが得られる、という補題です。
前節と同じ方法でこの補題を証明しましょう。*)
induction e; crush.
(**(** We are left with this unproved conclusion:
[[
tprogDenote
(tconcat (tcompile e2 ts)
(tconcat (tcompile e1 (arg2 :: ts))
(TCons (TiBinop ts t) (TNil (res :: ts))))) s =
(tbinopDenote t (texpDenote e1) (texpDenote e2), s)
]]
We need an analogue to the [app_assoc_reverse] theorem that we used to rewrite the goal in the last section. We can abort this proof and prove such a lemma about [tconcat].
*)*)
(**
次のような未証明の結論が残りました。
[[
tprogDenote
(tconcat (tcompile e2 ts)
(tconcat (tcompile e1 (arg2 :: ts))
(TCons (TiBinop ts t) (TNil (res :: ts))))) s =
(tbinopDenote t (texpDenote e1) (texpDenote e2), s)
]]
前節でゴールを書き換えるのに使った定理[app_assoc_reverse]に類似したものが必要です。
この証明はここで中止し、[tconcat]に対するそのような補題を証明します。
*)
Abort.
Lemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')
(s : vstack ts),
tprogDenote (tconcat p p') s
= tprogDenote p' (tprogDenote p s).
induction p; crush.
Qed.
(**
(** This one goes through completely automatically.
Some code behind the scenes registers [app_assoc_reverse] for use by [crush]. We must register [tconcat_correct] similarly to get the same effect:%\index{Vernacular commands!Hint Rewrite}% *)
*)
(**
これは完全に自動で証明されます。
[app_assoc_reverse]が[crush]で利用されるのは、水面下のコードがそのように登録してくれるからです。
[tconcat_correct]についても、同じ効果を得るための登録が必要です。%\index{Vernacular commands!Hint Rewrite}%
*)
Hint Rewrite tconcat_correct.
(**
(** Here we meet the pervasive concept of a _hint_. Many proofs can be found through exhaustive enumerations of combinations of possible proof steps; hints provide the set of steps to consider. The tactic [crush] is applying such brute force search for us silently, and it will consider more possibilities as we add more hints. This particular hint asks that the lemma be used for left-to-right rewriting.
Now we are ready to return to [tcompile_correct'], proving it automatically this time. *)
*)
(**
ここで、_[ヒント]_という便利な概念を説明しましょう。
証明ステップの組み合わせを徹底的に列挙してしまうと、証明がたくさん見つかる可能性があります。
そこで、考えるべきステップの集合を指定するためにヒントを与えます。
タクティク[crush]は基本的にはしらみつぶしの探索を適用し、ヒントを与えるとその分だけ多くの可能性を考慮します。
この[Hint Rewrite tconcat_correct.]により、補題[tconcat_correct]を左から右への書き換えに使うというヒントを与えています。
それでは[tcompile_correct']に戻り、今度は自動で証明してみましょう。
*)
Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
tprogDenote (tcompile e ts) s = (texpDenote e, s).
induction e; crush.
Qed.
(** (** We can register this main lemma as another hint, allowing us to prove the final theorem trivially. *)*)
(**
この主補題を新しいヒントとして登録すれば、最後の定理の証明が自明になります。
*)
Hint Rewrite tcompile_correct'.
Theorem tcompile_correct : forall t (e : texp t),
tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
crush.
Qed.
(* end thide *)
(**
(** It is probably worth emphasizing that we are doing more than building mathematical models. Our compilers are functional programs that can be executed efficiently. One strategy for doing so is based on%\index{program extraction}% _program extraction_, which generates OCaml code from Coq developments.
To set up the feature properly in recent versions of Coq, we must run the command [Require Extraction.]. However, this book %PDF%#HTML# is still built with a patched old version of Coq that neither requires nor allows that command, so it is commented out in this rendering!
Now we run a command to output the OCaml version of [tcompile]:%\index{Vernacular commands!Extraction}% *)
*)
(**
ここで強調しておきたいのは、いま私たちは数学的なモデルを構築しているだけではないということです。
開発したコンパイラは、効率的に実行できる関数型のプログラムになります。
そのための手段として、CoqコードからOCamlコードを生成する_[プログラム抽出]_%\index{program extraction}%があります。
たとえば、OCaml版の[tcompile]を出力するには次のようにコマンドを実行します。%\index{Vernacular commands!Extraction}%
*)
Require Extraction.
Extraction tcompile.
(**
(** <<
let rec tcompile t e ts =
match e with
| TNConst n ->
TCons (ts, (Cons (Nat, ts)), (Cons (Nat, ts)), (TiNConst (ts, n)), (TNil
(Cons (Nat, ts))))
| TBConst b ->
TCons (ts, (Cons (Bool, ts)), (Cons (Bool, ts)), (TiBConst (ts, b)),
(TNil (Cons (Bool, ts))))
| TBinop (t1, t2, t0, b, e1, e2) ->
tconcat ts (Cons (t2, ts)) (Cons (t0, ts)) (tcompile t2 e2 ts)
(tconcat (Cons (t2, ts)) (Cons (t1, (Cons (t2, ts)))) (Cons (t0, ts))
(tcompile t1 e1 (Cons (t2, ts))) (TCons ((Cons (t1, (Cons (t2,
ts)))), (Cons (t0, ts)), (Cons (t0, ts)), (TiBinop (t1, t2, t0, ts,
b)), (TNil (Cons (t0, ts))))))
>>
We can compile this code with the usual OCaml compiler and obtain an executable program with halfway decent performance.
This chapter has been a whirlwind tour through two examples of the style of Coq development that I advocate. Parts II and III of the book focus on the key elements of that style, namely dependent types and scripted proof automation, respectively. Before we get there, we will spend some time in Part I on more standard foundational material. Part I may still be of interest to seasoned Coq hackers, since I follow the highly automated proof style even at that early stage. *)
*)
(** <<
let rec tcompile t e ts =
match e with
| TNConst n ->
TCons (ts, (Cons (Nat, ts)), (Cons (Nat, ts)), (TiNConst (ts, n)), (TNil
(Cons (Nat, ts))))
| TBConst b ->
TCons (ts, (Cons (Bool, ts)), (Cons (Bool, ts)), (TiBConst (ts, b)),
(TNil (Cons (Bool, ts))))
| TBinop (t1, t2, t0, b, e1, e2) ->
tconcat ts (Cons (t2, ts)) (Cons (t0, ts)) (tcompile t2 e2 ts)
(tconcat (Cons (t2, ts)) (Cons (t1, (Cons (t2, ts)))) (Cons (t0, ts))
(tcompile t1 e1 (Cons (t2, ts))) (TCons ((Cons (t1, (Cons (t2,
ts)))), (Cons (t0, ts)), (Cons (t0, ts)), (TiBinop (t1, t2, t0, ts,
b)), (TNil (Cons (t0, ts))))))
>>
このコードは通常のOCamlコンパイラでコンパイルが可能であり、そこそこ効率が良い実行可能プログラムが得られます。
本章では、筆者が提案するCoqの開発スタイルの例を二つ、駆け足で紹介してきました。
本書の第2部と第3部では、この開発スタイルを支える依存型およびスクリプトによる証明の自動化にそれぞれ焦点を当てます。
その前に、第1部では、より標準的な基礎となる題材について説明します。
早い段階から強力に自動化するスタイルで証明していくので、経験抱負なCoqハッカーにとっても第1部の解説は興味深いものになるでしょう。
*)
|
//////////////////////////////////////////////////////////////////////////////
//name : servo_ui
//input : input_rs232:16
//output : output_control:16
//output : output_rs232:16
//source_file : servo_ui.c
///========
///
///Created by C2CHIP
//////////////////////////////////////////////////////////////////////////////
// Register Allocation
// ===================
// Register Name Size
// 0 array 2
// 1 temporary_register 2
// 2 temporary_register 2
// 3 temporary_register 2
// 4 temporary_register 2
// 5 temporary_register 36
// 6 temporary_register 38
// 7 temporary_register 24
// 8 temporary_register 42
// 9 temporary_register 8
// 10 temporary_register 64
// 11 temporary_register 58
// 12 temporary_register 80
// 13 stdin_get_char return address 2
// 14 variable stdin_get_char return value 2
// 15 stdout_put_char return address 2
// 16 variable character 2
// 17 print_string return address 2
// 18 array 2
// 19 variable i 2
// 20 is_num return address 2
// 21 variable is_num return value 2
// 22 variable character 2
// 23 scan return address 2
// 24 variable scan return value 2
// 25 variable character 2
// 26 variable value 2
// 27 servo_ui return address 2
// 28 variable servo 2
// 29 variable position 2
// 30 array 2
// 31 array 2
// 32 array 2
// 33 array 2
// 34 array 2
// 35 array 2
// 36 array 2
// 37 array 2
module servo_ui(input_rs232,input_rs232_stb,output_control_ack,output_rs232_ack,clk,rst,output_control,output_rs232,output_control_stb,output_rs232_stb,input_rs232_ack);
integer file_count;
real fp_value;
input [15:0] input_rs232;
input input_rs232_stb;
input output_control_ack;
input output_rs232_ack;
input clk;
input rst;
output [15:0] output_control;
output [15:0] output_rs232;
output output_control_stb;
output output_rs232_stb;
output input_rs232_ack;
reg [15:0] timer;
reg timer_enable;
reg stage_0_enable;
reg stage_1_enable;
reg stage_2_enable;
reg [8:0] program_counter;
reg [8:0] program_counter_0;
reg [48:0] instruction_0;
reg [4:0] opcode_0;
reg [5:0] dest_0;
reg [5:0] src_0;
reg [5:0] srcb_0;
reg [31:0] literal_0;
reg [8:0] program_counter_1;
reg [4:0] opcode_1;
reg [5:0] dest_1;
reg [31:0] register_1;
reg [31:0] registerb_1;
reg [31:0] literal_1;
reg [5:0] dest_2;
reg [31:0] result_2;
reg write_enable_2;
reg [15:0] address_2;
reg [15:0] data_out_2;
reg [15:0] data_in_2;
reg memory_enable_2;
reg [15:0] address_4;
reg [31:0] data_out_4;
reg [31:0] data_in_4;
reg memory_enable_4;
reg [15:0] s_output_control_stb;
reg [15:0] s_output_rs232_stb;
reg [15:0] s_output_control;
reg [15:0] s_output_rs232;
reg [15:0] s_input_rs232_ack;
reg [15:0] memory_2 [180:0];
reg [48:0] instructions [285:0];
reg [31:0] registers [37:0];
//////////////////////////////////////////////////////////////////////////////
// MEMORY INITIALIZATION
//
// In order to reduce program size, array contents have been stored into
// memory at initialization. In an FPGA, this will result in the memory being
// initialized when the FPGA configures.
// Memory will not be re-initialized at reset.
// Dissable this behaviour using the no_initialize_memory switch
initial
begin
memory_2[2] = 83;
memory_2[3] = 101;
memory_2[4] = 114;
memory_2[5] = 118;
memory_2[6] = 111;
memory_2[7] = 32;
memory_2[8] = 67;
memory_2[9] = 111;
memory_2[10] = 110;
memory_2[11] = 116;
memory_2[12] = 114;
memory_2[13] = 111;
memory_2[14] = 108;
memory_2[15] = 108;
memory_2[16] = 101;
memory_2[17] = 114;
memory_2[18] = 10;
memory_2[19] = 0;
memory_2[20] = 74;
memory_2[21] = 111;
memory_2[22] = 110;
memory_2[23] = 97;
memory_2[24] = 116;
memory_2[25] = 104;
memory_2[26] = 97;
memory_2[27] = 110;
memory_2[28] = 32;
memory_2[29] = 80;
memory_2[30] = 32;
memory_2[31] = 68;
memory_2[32] = 97;
memory_2[33] = 119;
memory_2[34] = 115;
memory_2[35] = 111;
memory_2[36] = 110;
memory_2[37] = 10;
memory_2[38] = 0;
memory_2[39] = 50;
memory_2[40] = 48;
memory_2[41] = 49;
memory_2[42] = 51;
memory_2[43] = 45;
memory_2[44] = 49;
memory_2[45] = 50;
memory_2[46] = 45;
memory_2[47] = 50;
memory_2[48] = 52;
memory_2[49] = 10;
memory_2[50] = 0;
memory_2[51] = 69;
memory_2[52] = 110;
memory_2[53] = 116;
memory_2[54] = 101;
memory_2[55] = 114;
memory_2[56] = 32;
memory_2[57] = 83;
memory_2[58] = 101;
memory_2[59] = 114;
memory_2[60] = 118;
memory_2[61] = 111;
memory_2[62] = 32;
memory_2[63] = 48;
memory_2[64] = 32;
memory_2[65] = 116;
memory_2[66] = 111;
memory_2[67] = 32;
memory_2[68] = 55;
memory_2[69] = 58;
memory_2[70] = 10;
memory_2[71] = 0;
memory_2[72] = 126;
memory_2[73] = 36;
memory_2[74] = 10;
memory_2[75] = 0;
memory_2[76] = 115;
memory_2[77] = 101;
memory_2[78] = 114;
memory_2[79] = 118;
memory_2[80] = 111;
memory_2[81] = 32;
memory_2[82] = 115;
memory_2[83] = 104;
memory_2[84] = 111;
memory_2[85] = 117;
memory_2[86] = 108;
memory_2[87] = 100;
memory_2[88] = 32;
memory_2[89] = 98;
memory_2[90] = 101;
memory_2[91] = 32;
memory_2[92] = 98;
memory_2[93] = 101;
memory_2[94] = 116;
memory_2[95] = 119;
memory_2[96] = 101;
memory_2[97] = 101;
memory_2[98] = 110;
memory_2[99] = 32;
memory_2[100] = 48;
memory_2[101] = 32;
memory_2[102] = 97;
memory_2[103] = 110;
memory_2[104] = 100;
memory_2[105] = 32;
memory_2[106] = 55;
memory_2[107] = 0;
memory_2[108] = 69;
memory_2[109] = 110;
memory_2[110] = 116;
memory_2[111] = 101;
memory_2[112] = 114;
memory_2[113] = 32;
memory_2[114] = 80;
memory_2[115] = 111;
memory_2[116] = 115;
memory_2[117] = 105;
memory_2[118] = 116;
memory_2[119] = 105;
memory_2[120] = 111;
memory_2[121] = 110;
memory_2[122] = 32;
memory_2[123] = 45;
memory_2[124] = 53;
memory_2[125] = 48;
memory_2[126] = 48;
memory_2[127] = 32;
memory_2[128] = 116;
memory_2[129] = 111;
memory_2[130] = 32;
memory_2[131] = 53;
memory_2[132] = 48;
memory_2[133] = 48;
memory_2[134] = 58;
memory_2[135] = 10;
memory_2[136] = 0;
memory_2[137] = 126;
memory_2[138] = 36;
memory_2[139] = 10;
memory_2[140] = 0;
memory_2[141] = 112;
memory_2[142] = 111;
memory_2[143] = 115;
memory_2[144] = 105;
memory_2[145] = 116;
memory_2[146] = 105;
memory_2[147] = 111;
memory_2[148] = 110;
memory_2[149] = 32;
memory_2[150] = 115;
memory_2[151] = 104;
memory_2[152] = 111;
memory_2[153] = 117;
memory_2[154] = 108;
memory_2[155] = 100;
memory_2[156] = 32;
memory_2[157] = 98;
memory_2[158] = 101;
memory_2[159] = 32;
memory_2[160] = 98;
memory_2[161] = 101;
memory_2[162] = 116;
memory_2[163] = 119;
memory_2[164] = 101;
memory_2[165] = 101;
memory_2[166] = 110;
memory_2[167] = 32;
memory_2[168] = 45;
memory_2[169] = 53;
memory_2[170] = 48;
memory_2[171] = 48;
memory_2[172] = 32;
memory_2[173] = 97;
memory_2[174] = 110;
memory_2[175] = 100;
memory_2[176] = 32;
memory_2[177] = 53;
memory_2[178] = 48;
memory_2[179] = 48;
memory_2[180] = 0;
end
//////////////////////////////////////////////////////////////////////////////
// INSTRUCTION INITIALIZATION
//
// Initialise the contents of the instruction memory
//
// Intruction Set
// ==============
// 0 {'float': False, 'literal': True, 'right': False, 'unsigned': False, 'op': 'jmp_and_link'}
// 1 {'float': False, 'literal': False, 'right': False, 'unsigned': False, 'op': 'stop'}
// 2 {'right': False, 'float': False, 'unsigned': False, 'literal': False, 'input': 'rs232', 'op': 'read'}
// 3 {'float': False, 'literal': False, 'right': False, 'unsigned': False, 'op': 'nop'}
// 4 {'float': False, 'literal': False, 'right': False, 'unsigned': False, 'op': 'move'}
// 5 {'float': False, 'literal': False, 'right': False, 'unsigned': False, 'op': 'jmp_to_reg'}
// 6 {'right': False, 'float': False, 'unsigned': False, 'literal': False, 'output': 'rs232', 'op': 'write'}
// 7 {'float': False, 'literal': True, 'right': False, 'unsigned': False, 'op': 'literal'}
// 8 {'float': False, 'literal': False, 'right': False, 'unsigned': True, 'op': '+'}
// 9 {'right': False, 'element_size': 2, 'float': False, 'unsigned': False, 'literal': False, 'op': 'memory_read_request'}
// 10 {'right': False, 'element_size': 2, 'float': False, 'unsigned': False, 'literal': False, 'op': 'memory_read_wait'}
// 11 {'right': False, 'element_size': 2, 'float': False, 'unsigned': False, 'literal': False, 'op': 'memory_read'}
// 12 {'float': False, 'literal': True, 'right': False, 'unsigned': False, 'op': 'jmp_if_false'}
// 13 {'float': False, 'literal': True, 'right': True, 'unsigned': True, 'op': '+'}
// 14 {'float': False, 'literal': True, 'right': False, 'unsigned': False, 'op': 'goto'}
// 15 {'float': False, 'literal': True, 'right': True, 'unsigned': False, 'op': '>='}
// 16 {'float': False, 'literal': True, 'right': True, 'unsigned': False, 'op': '<='}
// 17 {'float': False, 'literal': True, 'right': True, 'unsigned': True, 'op': '=='}
// 18 {'float': False, 'literal': True, 'right': True, 'unsigned': True, 'op': '-'}
// 19 {'float': False, 'literal': True, 'right': True, 'unsigned': False, 'op': '*'}
// 20 {'float': False, 'literal': True, 'right': True, 'unsigned': True, 'op': '>='}
// 21 {'float': False, 'literal': True, 'right': True, 'unsigned': True, 'op': '<='}
// 22 {'right': False, 'float': False, 'unsigned': False, 'literal': False, 'output': 'control', 'op': 'write'}
// Intructions
// ===========
initial
begin
instructions[0] = {5'd0, 6'd27, 6'd0, 32'd161};//{'dest': 27, 'label': 161, 'op': 'jmp_and_link'}
instructions[1] = {5'd1, 6'd0, 6'd0, 32'd0};//{'op': 'stop'}
instructions[2] = {5'd2, 6'd1, 6'd0, 32'd0};//{'dest': 1, 'input': 'rs232', 'op': 'read'}
instructions[3] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[4] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[5] = {5'd4, 6'd14, 6'd1, 32'd0};//{'dest': 14, 'src': 1, 'op': 'move'}
instructions[6] = {5'd5, 6'd0, 6'd13, 32'd0};//{'src': 13, 'op': 'jmp_to_reg'}
instructions[7] = {5'd4, 6'd1, 6'd16, 32'd0};//{'dest': 1, 'src': 16, 'op': 'move'}
instructions[8] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[9] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[10] = {5'd6, 6'd0, 6'd1, 32'd0};//{'src': 1, 'output': 'rs232', 'op': 'write'}
instructions[11] = {5'd5, 6'd0, 6'd15, 32'd0};//{'src': 15, 'op': 'jmp_to_reg'}
instructions[12] = {5'd7, 6'd19, 6'd0, 32'd0};//{'dest': 19, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[13] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[14] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[15] = {5'd4, 6'd2, 6'd19, 32'd0};//{'dest': 2, 'src': 19, 'op': 'move'}
instructions[16] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[17] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[18] = {5'd8, 6'd3, 6'd2, 32'd18};//{'dest': 3, 'src': 2, 'srcb': 18, 'signed': False, 'op': '+'}
instructions[19] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[20] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[21] = {5'd9, 6'd0, 6'd3, 32'd0};//{'element_size': 2, 'src': 3, 'sequence': 32208080, 'op': 'memory_read_request'}
instructions[22] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[23] = {5'd10, 6'd0, 6'd3, 32'd0};//{'element_size': 2, 'src': 3, 'sequence': 32208080, 'op': 'memory_read_wait'}
instructions[24] = {5'd11, 6'd1, 6'd3, 32'd0};//{'dest': 1, 'src': 3, 'sequence': 32208080, 'element_size': 2, 'op': 'memory_read'}
instructions[25] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[26] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[27] = {5'd12, 6'd0, 6'd1, 32'd45};//{'src': 1, 'label': 45, 'op': 'jmp_if_false'}
instructions[28] = {5'd4, 6'd3, 6'd19, 32'd0};//{'dest': 3, 'src': 19, 'op': 'move'}
instructions[29] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[30] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[31] = {5'd8, 6'd4, 6'd3, 32'd18};//{'dest': 4, 'src': 3, 'srcb': 18, 'signed': False, 'op': '+'}
instructions[32] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[33] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[34] = {5'd9, 6'd0, 6'd4, 32'd0};//{'element_size': 2, 'src': 4, 'sequence': 32212752, 'op': 'memory_read_request'}
instructions[35] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[36] = {5'd10, 6'd0, 6'd4, 32'd0};//{'element_size': 2, 'src': 4, 'sequence': 32212752, 'op': 'memory_read_wait'}
instructions[37] = {5'd11, 6'd2, 6'd4, 32'd0};//{'dest': 2, 'src': 4, 'sequence': 32212752, 'element_size': 2, 'op': 'memory_read'}
instructions[38] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[39] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[40] = {5'd4, 6'd16, 6'd2, 32'd0};//{'dest': 16, 'src': 2, 'op': 'move'}
instructions[41] = {5'd0, 6'd15, 6'd0, 32'd7};//{'dest': 15, 'label': 7, 'op': 'jmp_and_link'}
instructions[42] = {5'd4, 6'd1, 6'd19, 32'd0};//{'dest': 1, 'src': 19, 'op': 'move'}
instructions[43] = {5'd13, 6'd19, 6'd19, 32'd1};//{'src': 19, 'right': 1, 'dest': 19, 'signed': False, 'op': '+', 'size': 2}
instructions[44] = {5'd14, 6'd0, 6'd0, 32'd46};//{'label': 46, 'op': 'goto'}
instructions[45] = {5'd14, 6'd0, 6'd0, 32'd47};//{'label': 47, 'op': 'goto'}
instructions[46] = {5'd14, 6'd0, 6'd0, 32'd13};//{'label': 13, 'op': 'goto'}
instructions[47] = {5'd5, 6'd0, 6'd17, 32'd0};//{'src': 17, 'op': 'jmp_to_reg'}
instructions[48] = {5'd4, 6'd2, 6'd22, 32'd0};//{'dest': 2, 'src': 22, 'op': 'move'}
instructions[49] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[50] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[51] = {5'd15, 6'd1, 6'd2, 32'd48};//{'src': 2, 'right': 48, 'dest': 1, 'signed': True, 'op': '>=', 'type': 'int', 'size': 2}
instructions[52] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[53] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[54] = {5'd12, 6'd0, 6'd1, 32'd59};//{'src': 1, 'label': 59, 'op': 'jmp_if_false'}
instructions[55] = {5'd4, 6'd2, 6'd22, 32'd0};//{'dest': 2, 'src': 22, 'op': 'move'}
instructions[56] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[57] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[58] = {5'd16, 6'd1, 6'd2, 32'd57};//{'src': 2, 'right': 57, 'dest': 1, 'signed': True, 'op': '<=', 'type': 'int', 'size': 2}
instructions[59] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[60] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[61] = {5'd12, 6'd0, 6'd1, 32'd68};//{'src': 1, 'label': 68, 'op': 'jmp_if_false'}
instructions[62] = {5'd7, 6'd1, 6'd0, 32'd1};//{'dest': 1, 'literal': 1, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[63] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[64] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[65] = {5'd4, 6'd21, 6'd1, 32'd0};//{'dest': 21, 'src': 1, 'op': 'move'}
instructions[66] = {5'd5, 6'd0, 6'd20, 32'd0};//{'src': 20, 'op': 'jmp_to_reg'}
instructions[67] = {5'd14, 6'd0, 6'd0, 32'd68};//{'label': 68, 'op': 'goto'}
instructions[68] = {5'd7, 6'd1, 6'd0, 32'd0};//{'dest': 1, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[69] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[70] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[71] = {5'd4, 6'd21, 6'd1, 32'd0};//{'dest': 21, 'src': 1, 'op': 'move'}
instructions[72] = {5'd5, 6'd0, 6'd20, 32'd0};//{'src': 20, 'op': 'jmp_to_reg'}
instructions[73] = {5'd7, 6'd25, 6'd0, 32'd0};//{'dest': 25, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[74] = {5'd7, 6'd26, 6'd0, 32'd0};//{'dest': 26, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[75] = {5'd0, 6'd13, 6'd0, 32'd2};//{'dest': 13, 'label': 2, 'op': 'jmp_and_link'}
instructions[76] = {5'd4, 6'd1, 6'd14, 32'd0};//{'dest': 1, 'src': 14, 'op': 'move'}
instructions[77] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[78] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[79] = {5'd4, 6'd25, 6'd1, 32'd0};//{'dest': 25, 'src': 1, 'op': 'move'}
instructions[80] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[81] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[82] = {5'd4, 6'd2, 6'd25, 32'd0};//{'dest': 2, 'src': 25, 'op': 'move'}
instructions[83] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[84] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[85] = {5'd17, 6'd1, 6'd2, 32'd45};//{'src': 2, 'right': 45, 'dest': 1, 'signed': False, 'op': '==', 'type': 'int', 'size': 2}
instructions[86] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[87] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[88] = {5'd12, 6'd0, 6'd1, 32'd95};//{'src': 1, 'label': 95, 'op': 'jmp_if_false'}
instructions[89] = {5'd7, 6'd1, 6'd0, -32'd1};//{'dest': 1, 'literal': -1, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[90] = {5'd7, 6'd1, 6'd0, 32'd0};//{'dest': 1, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[91] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[92] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[93] = {5'd4, 6'd26, 6'd1, 32'd0};//{'dest': 26, 'src': 1, 'op': 'move'}
instructions[94] = {5'd14, 6'd0, 6'd0, 32'd116};//{'label': 116, 'op': 'goto'}
instructions[95] = {5'd4, 6'd2, 6'd25, 32'd0};//{'dest': 2, 'src': 25, 'op': 'move'}
instructions[96] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[97] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[98] = {5'd17, 6'd1, 6'd2, 32'd43};//{'src': 2, 'right': 43, 'dest': 1, 'signed': False, 'op': '==', 'type': 'int', 'size': 2}
instructions[99] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[100] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[101] = {5'd12, 6'd0, 6'd1, 32'd108};//{'src': 1, 'label': 108, 'op': 'jmp_if_false'}
instructions[102] = {5'd7, 6'd1, 6'd0, 32'd1};//{'dest': 1, 'literal': 1, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[103] = {5'd7, 6'd1, 6'd0, 32'd0};//{'dest': 1, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[104] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[105] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[106] = {5'd4, 6'd26, 6'd1, 32'd0};//{'dest': 26, 'src': 1, 'op': 'move'}
instructions[107] = {5'd14, 6'd0, 6'd0, 32'd116};//{'label': 116, 'op': 'goto'}
instructions[108] = {5'd7, 6'd1, 6'd0, 32'd1};//{'dest': 1, 'literal': 1, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[109] = {5'd4, 6'd2, 6'd25, 32'd0};//{'dest': 2, 'src': 25, 'op': 'move'}
instructions[110] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[111] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[112] = {5'd18, 6'd1, 6'd2, 32'd48};//{'src': 2, 'right': 48, 'dest': 1, 'signed': False, 'op': '-', 'type': 'int', 'size': 2}
instructions[113] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[114] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[115] = {5'd4, 6'd26, 6'd1, 32'd0};//{'dest': 26, 'src': 1, 'op': 'move'}
instructions[116] = {5'd0, 6'd13, 6'd0, 32'd2};//{'dest': 13, 'label': 2, 'op': 'jmp_and_link'}
instructions[117] = {5'd4, 6'd1, 6'd14, 32'd0};//{'dest': 1, 'src': 14, 'op': 'move'}
instructions[118] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[119] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[120] = {5'd4, 6'd25, 6'd1, 32'd0};//{'dest': 25, 'src': 1, 'op': 'move'}
instructions[121] = {5'd4, 6'd2, 6'd26, 32'd0};//{'dest': 2, 'src': 26, 'op': 'move'}
instructions[122] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[123] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[124] = {5'd19, 6'd1, 6'd2, 32'd10};//{'src': 2, 'right': 10, 'dest': 1, 'signed': True, 'op': '*', 'type': 'int', 'size': 2}
instructions[125] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[126] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[127] = {5'd4, 6'd26, 6'd1, 32'd0};//{'dest': 26, 'src': 1, 'op': 'move'}
instructions[128] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[129] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[130] = {5'd4, 6'd2, 6'd26, 32'd0};//{'dest': 2, 'src': 26, 'op': 'move'}
instructions[131] = {5'd4, 6'd4, 6'd25, 32'd0};//{'dest': 4, 'src': 25, 'op': 'move'}
instructions[132] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[133] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[134] = {5'd18, 6'd3, 6'd4, 32'd48};//{'src': 4, 'right': 48, 'dest': 3, 'signed': False, 'op': '-', 'type': 'int', 'size': 2}
instructions[135] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[136] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[137] = {5'd8, 6'd1, 6'd2, 32'd3};//{'srcb': 3, 'src': 2, 'dest': 1, 'signed': False, 'op': '+', 'type': 'int', 'size': 2}
instructions[138] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[139] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[140] = {5'd4, 6'd26, 6'd1, 32'd0};//{'dest': 26, 'src': 1, 'op': 'move'}
instructions[141] = {5'd4, 6'd3, 6'd25, 32'd0};//{'dest': 3, 'src': 25, 'op': 'move'}
instructions[142] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[143] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[144] = {5'd4, 6'd22, 6'd3, 32'd0};//{'dest': 22, 'src': 3, 'op': 'move'}
instructions[145] = {5'd0, 6'd20, 6'd0, 32'd48};//{'dest': 20, 'label': 48, 'op': 'jmp_and_link'}
instructions[146] = {5'd4, 6'd2, 6'd21, 32'd0};//{'dest': 2, 'src': 21, 'op': 'move'}
instructions[147] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[148] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[149] = {5'd17, 6'd1, 6'd2, 32'd0};//{'src': 2, 'right': 0, 'dest': 1, 'signed': False, 'op': '==', 'type': 'int', 'size': 2}
instructions[150] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[151] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[152] = {5'd12, 6'd0, 6'd1, 32'd155};//{'src': 1, 'label': 155, 'op': 'jmp_if_false'}
instructions[153] = {5'd14, 6'd0, 6'd0, 32'd156};//{'label': 156, 'op': 'goto'}
instructions[154] = {5'd14, 6'd0, 6'd0, 32'd155};//{'label': 155, 'op': 'goto'}
instructions[155] = {5'd14, 6'd0, 6'd0, 32'd116};//{'label': 116, 'op': 'goto'}
instructions[156] = {5'd4, 6'd1, 6'd26, 32'd0};//{'dest': 1, 'src': 26, 'op': 'move'}
instructions[157] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[158] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[159] = {5'd4, 6'd24, 6'd1, 32'd0};//{'dest': 24, 'src': 1, 'op': 'move'}
instructions[160] = {5'd5, 6'd0, 6'd23, 32'd0};//{'src': 23, 'op': 'jmp_to_reg'}
instructions[161] = {5'd7, 6'd28, 6'd0, 32'd0};//{'dest': 28, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[162] = {5'd7, 6'd29, 6'd0, 32'd0};//{'dest': 29, 'literal': 0, 'size': 2, 'signed': 2, 'op': 'literal'}
instructions[163] = {5'd7, 6'd30, 6'd0, 32'd2};//{'dest': 30, 'literal': 2, 'op': 'literal'}
instructions[164] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[165] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[166] = {5'd4, 6'd5, 6'd30, 32'd0};//{'dest': 5, 'src': 30, 'op': 'move'}
instructions[167] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[168] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[169] = {5'd4, 6'd18, 6'd5, 32'd0};//{'dest': 18, 'src': 5, 'op': 'move'}
instructions[170] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[171] = {5'd7, 6'd31, 6'd0, 32'd20};//{'dest': 31, 'literal': 20, 'op': 'literal'}
instructions[172] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[173] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[174] = {5'd4, 6'd6, 6'd31, 32'd0};//{'dest': 6, 'src': 31, 'op': 'move'}
instructions[175] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[176] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[177] = {5'd4, 6'd18, 6'd6, 32'd0};//{'dest': 18, 'src': 6, 'op': 'move'}
instructions[178] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[179] = {5'd7, 6'd32, 6'd0, 32'd39};//{'dest': 32, 'literal': 39, 'op': 'literal'}
instructions[180] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[181] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[182] = {5'd4, 6'd7, 6'd32, 32'd0};//{'dest': 7, 'src': 32, 'op': 'move'}
instructions[183] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[184] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[185] = {5'd4, 6'd18, 6'd7, 32'd0};//{'dest': 18, 'src': 7, 'op': 'move'}
instructions[186] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[187] = {5'd7, 6'd33, 6'd0, 32'd51};//{'dest': 33, 'literal': 51, 'op': 'literal'}
instructions[188] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[189] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[190] = {5'd4, 6'd8, 6'd33, 32'd0};//{'dest': 8, 'src': 33, 'op': 'move'}
instructions[191] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[192] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[193] = {5'd4, 6'd18, 6'd8, 32'd0};//{'dest': 18, 'src': 8, 'op': 'move'}
instructions[194] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[195] = {5'd7, 6'd34, 6'd0, 32'd72};//{'dest': 34, 'literal': 72, 'op': 'literal'}
instructions[196] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[197] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[198] = {5'd4, 6'd9, 6'd34, 32'd0};//{'dest': 9, 'src': 34, 'op': 'move'}
instructions[199] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[200] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[201] = {5'd4, 6'd18, 6'd9, 32'd0};//{'dest': 18, 'src': 9, 'op': 'move'}
instructions[202] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[203] = {5'd0, 6'd23, 6'd0, 32'd73};//{'dest': 23, 'label': 73, 'op': 'jmp_and_link'}
instructions[204] = {5'd4, 6'd1, 6'd24, 32'd0};//{'dest': 1, 'src': 24, 'op': 'move'}
instructions[205] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[206] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[207] = {5'd4, 6'd28, 6'd1, 32'd0};//{'dest': 28, 'src': 1, 'op': 'move'}
instructions[208] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[209] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[210] = {5'd4, 6'd2, 6'd28, 32'd0};//{'dest': 2, 'src': 28, 'op': 'move'}
instructions[211] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[212] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[213] = {5'd20, 6'd1, 6'd2, 32'd0};//{'src': 2, 'right': 0, 'dest': 1, 'signed': False, 'op': '>=', 'type': 'int', 'size': 2}
instructions[214] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[215] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[216] = {5'd12, 6'd0, 6'd1, 32'd221};//{'src': 1, 'label': 221, 'op': 'jmp_if_false'}
instructions[217] = {5'd4, 6'd2, 6'd28, 32'd0};//{'dest': 2, 'src': 28, 'op': 'move'}
instructions[218] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[219] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[220] = {5'd21, 6'd1, 6'd2, 32'd7};//{'src': 2, 'right': 7, 'dest': 1, 'signed': False, 'op': '<=', 'type': 'int', 'size': 2}
instructions[221] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[222] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[223] = {5'd12, 6'd0, 6'd1, 32'd226};//{'src': 1, 'label': 226, 'op': 'jmp_if_false'}
instructions[224] = {5'd14, 6'd0, 6'd0, 32'd235};//{'label': 235, 'op': 'goto'}
instructions[225] = {5'd14, 6'd0, 6'd0, 32'd234};//{'label': 234, 'op': 'goto'}
instructions[226] = {5'd7, 6'd35, 6'd0, 32'd76};//{'dest': 35, 'literal': 76, 'op': 'literal'}
instructions[227] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[228] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[229] = {5'd4, 6'd10, 6'd35, 32'd0};//{'dest': 10, 'src': 35, 'op': 'move'}
instructions[230] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[231] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[232] = {5'd4, 6'd18, 6'd10, 32'd0};//{'dest': 18, 'src': 10, 'op': 'move'}
instructions[233] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[234] = {5'd14, 6'd0, 6'd0, 32'd187};//{'label': 187, 'op': 'goto'}
instructions[235] = {5'd7, 6'd36, 6'd0, 32'd108};//{'dest': 36, 'literal': 108, 'op': 'literal'}
instructions[236] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[237] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[238] = {5'd4, 6'd11, 6'd36, 32'd0};//{'dest': 11, 'src': 36, 'op': 'move'}
instructions[239] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[240] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[241] = {5'd4, 6'd18, 6'd11, 32'd0};//{'dest': 18, 'src': 11, 'op': 'move'}
instructions[242] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[243] = {5'd7, 6'd37, 6'd0, 32'd137};//{'dest': 37, 'literal': 137, 'op': 'literal'}
instructions[244] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[245] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[246] = {5'd4, 6'd9, 6'd37, 32'd0};//{'dest': 9, 'src': 37, 'op': 'move'}
instructions[247] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[248] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[249] = {5'd4, 6'd18, 6'd9, 32'd0};//{'dest': 18, 'src': 9, 'op': 'move'}
instructions[250] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[251] = {5'd4, 6'd2, 6'd29, 32'd0};//{'dest': 2, 'src': 29, 'op': 'move'}
instructions[252] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[253] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[254] = {5'd20, 6'd1, 6'd2, 32'd0};//{'src': 2, 'right': 0, 'dest': 1, 'signed': False, 'op': '>=', 'type': 'int', 'size': 2}
instructions[255] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[256] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[257] = {5'd12, 6'd0, 6'd1, 32'd262};//{'src': 1, 'label': 262, 'op': 'jmp_if_false'}
instructions[258] = {5'd4, 6'd2, 6'd29, 32'd0};//{'dest': 2, 'src': 29, 'op': 'move'}
instructions[259] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[260] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[261] = {5'd21, 6'd1, 6'd2, 32'd7};//{'src': 2, 'right': 7, 'dest': 1, 'signed': False, 'op': '<=', 'type': 'int', 'size': 2}
instructions[262] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[263] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[264] = {5'd12, 6'd0, 6'd1, 32'd267};//{'src': 1, 'label': 267, 'op': 'jmp_if_false'}
instructions[265] = {5'd14, 6'd0, 6'd0, 32'd276};//{'label': 276, 'op': 'goto'}
instructions[266] = {5'd14, 6'd0, 6'd0, 32'd275};//{'label': 275, 'op': 'goto'}
instructions[267] = {5'd7, 6'd0, 6'd0, 32'd141};//{'dest': 0, 'literal': 141, 'op': 'literal'}
instructions[268] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[269] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[270] = {5'd4, 6'd12, 6'd0, 32'd0};//{'dest': 12, 'src': 0, 'op': 'move'}
instructions[271] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[272] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[273] = {5'd4, 6'd18, 6'd12, 32'd0};//{'dest': 18, 'src': 12, 'op': 'move'}
instructions[274] = {5'd0, 6'd17, 6'd0, 32'd12};//{'dest': 17, 'label': 12, 'op': 'jmp_and_link'}
instructions[275] = {5'd14, 6'd0, 6'd0, 32'd235};//{'label': 235, 'op': 'goto'}
instructions[276] = {5'd4, 6'd1, 6'd28, 32'd0};//{'dest': 1, 'src': 28, 'op': 'move'}
instructions[277] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[278] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[279] = {5'd22, 6'd0, 6'd1, 32'd0};//{'src': 1, 'output': 'control', 'op': 'write'}
instructions[280] = {5'd4, 6'd1, 6'd29, 32'd0};//{'dest': 1, 'src': 29, 'op': 'move'}
instructions[281] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[282] = {5'd3, 6'd0, 6'd0, 32'd0};//{'op': 'nop'}
instructions[283] = {5'd22, 6'd0, 6'd1, 32'd0};//{'src': 1, 'output': 'control', 'op': 'write'}
instructions[284] = {5'd14, 6'd0, 6'd0, 32'd187};//{'label': 187, 'op': 'goto'}
instructions[285] = {5'd5, 6'd0, 6'd27, 32'd0};//{'src': 27, 'op': 'jmp_to_reg'}
end
//////////////////////////////////////////////////////////////////////////////
// CPU IMPLEMENTAION OF C PROCESS
//
// This section of the file contains a CPU implementing the C process.
always @(posedge clk)
begin
//implement memory for 2 byte x n arrays
if (memory_enable_2 == 1'b1) begin
memory_2[address_2] <= data_in_2;
end
data_out_2 <= memory_2[address_2];
memory_enable_2 <= 1'b0;
write_enable_2 <= 0;
//stage 0 instruction fetch
if (stage_0_enable) begin
stage_1_enable <= 1;
instruction_0 <= instructions[program_counter];
opcode_0 = instruction_0[48:44];
dest_0 = instruction_0[43:38];
src_0 = instruction_0[37:32];
srcb_0 = instruction_0[5:0];
literal_0 = instruction_0[31:0];
if(write_enable_2) begin
registers[dest_2] <= result_2;
end
program_counter_0 <= program_counter;
program_counter <= program_counter + 1;
end
//stage 1 opcode fetch
if (stage_1_enable) begin
stage_2_enable <= 1;
register_1 <= registers[src_0];
registerb_1 <= registers[srcb_0];
dest_1 <= dest_0;
literal_1 <= literal_0;
opcode_1 <= opcode_0;
program_counter_1 <= program_counter_0;
end
//stage 2 opcode fetch
if (stage_2_enable) begin
dest_2 <= dest_1;
case(opcode_1)
16'd0:
begin
program_counter <= literal_1;
result_2 <= program_counter_1 + 1;
write_enable_2 <= 1;
stage_0_enable <= 1;
stage_1_enable <= 0;
stage_2_enable <= 0;
end
16'd1:
begin
stage_0_enable <= 0;
stage_1_enable <= 0;
stage_2_enable <= 0;
end
16'd2:
begin
stage_0_enable <= 0;
stage_1_enable <= 0;
stage_2_enable <= 0;
s_input_rs232_ack <= 1'b1;
end
16'd4:
begin
result_2 <= register_1;
write_enable_2 <= 1;
end
16'd5:
begin
program_counter <= register_1;
stage_0_enable <= 1;
stage_1_enable <= 0;
stage_2_enable <= 0;
end
16'd6:
begin
stage_0_enable <= 0;
stage_1_enable <= 0;
stage_2_enable <= 0;
s_output_rs232_stb <= 1'b1;
s_output_rs232 <= register_1;
end
16'd7:
begin
result_2 <= literal_1;
write_enable_2 <= 1;
end
16'd8:
begin
result_2 <= $unsigned(register_1) + $unsigned(registerb_1);
write_enable_2 <= 1;
end
16'd9:
begin
address_2 <= register_1;
end
16'd11:
begin
result_2 <= data_out_2;
write_enable_2 <= 1;
end
16'd12:
begin
if (register_1 == 0) begin
program_counter <= literal_1;
stage_0_enable <= 1;
stage_1_enable <= 0;
stage_2_enable <= 0;
end
end
16'd13:
begin
result_2 <= $unsigned(register_1) + $unsigned(literal_1);
write_enable_2 <= 1;
end
16'd14:
begin
program_counter <= literal_1;
stage_0_enable <= 1;
stage_1_enable <= 0;
stage_2_enable <= 0;
end
16'd15:
begin
result_2 <= $signed(register_1) >= $signed(literal_1);
write_enable_2 <= 1;
end
16'd16:
begin
result_2 <= $signed(register_1) <= $signed(literal_1);
write_enable_2 <= 1;
end
16'd17:
begin
result_2 <= $unsigned(register_1) == $unsigned(literal_1);
write_enable_2 <= 1;
end
16'd18:
begin
result_2 <= $unsigned(register_1) - $unsigned(literal_1);
write_enable_2 <= 1;
end
16'd19:
begin
result_2 <= $signed(register_1) * $signed(literal_1);
write_enable_2 <= 1;
end
16'd20:
begin
result_2 <= $unsigned(register_1) >= $unsigned(literal_1);
write_enable_2 <= 1;
end
16'd21:
begin
result_2 <= $unsigned(register_1) <= $unsigned(literal_1);
write_enable_2 <= 1;
end
16'd22:
begin
stage_0_enable <= 0;
stage_1_enable <= 0;
stage_2_enable <= 0;
s_output_control_stb <= 1'b1;
s_output_control <= register_1;
end
endcase
end
if (s_input_rs232_ack == 1'b1 && input_rs232_stb == 1'b1) begin
result_2 <= input_rs232;
write_enable_2 <= 1;
s_input_rs232_ack <= 1'b0;
stage_0_enable <= 1;
stage_1_enable <= 1;
stage_2_enable <= 1;
end
if (s_output_rs232_stb == 1'b1 && output_rs232_ack == 1'b1) begin
s_output_rs232_stb <= 1'b0;
stage_0_enable <= 1;
stage_1_enable <= 1;
stage_2_enable <= 1;
end
if (s_output_control_stb == 1'b1 && output_control_ack == 1'b1) begin
s_output_control_stb <= 1'b0;
stage_0_enable <= 1;
stage_1_enable <= 1;
stage_2_enable <= 1;
end
if (timer == 0) begin
if (timer_enable) begin
stage_0_enable <= 1;
stage_1_enable <= 1;
stage_2_enable <= 1;
timer_enable <= 0;
end
end else begin
timer <= timer - 1;
end
if (rst == 1'b1) begin
stage_0_enable <= 1;
stage_1_enable <= 0;
stage_2_enable <= 0;
timer <= 0;
timer_enable <= 0;
program_counter <= 0;
s_input_rs232_ack <= 0;
s_output_control_stb <= 0;
s_output_rs232_stb <= 0;
end
end
assign input_rs232_ack = s_input_rs232_ack;
assign output_control_stb = s_output_control_stb;
assign output_control = s_output_control;
assign output_rs232_stb = s_output_rs232_stb;
assign output_rs232 = s_output_rs232;
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HS__UDP_DFF_NR_PP_PKG_S_BLACKBOX_V
`define SKY130_FD_SC_HS__UDP_DFF_NR_PP_PKG_S_BLACKBOX_V
/**
* udp_dff$NR_pp$PKG$s: Negative edge triggered D flip-flop with
* active high
*
* Verilog stub definition (black box with power pins).
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_hs__udp_dff$NR_pp$PKG$s (
Q ,
D ,
CLK_N ,
RESET ,
SLEEP_B,
KAPWR ,
VGND ,
VPWR
);
output Q ;
input D ;
input CLK_N ;
input RESET ;
input SLEEP_B;
input KAPWR ;
input VGND ;
input VPWR ;
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_HS__UDP_DFF_NR_PP_PKG_S_BLACKBOX_V
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__NOR4BB_4_V
`define SKY130_FD_SC_LP__NOR4BB_4_V
/**
* nor4bb: 4-input NOR, first two inputs inverted.
*
* Verilog wrapper for nor4bb with size of 4 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_lp__nor4bb.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_lp__nor4bb_4 (
Y ,
A ,
B ,
C_N ,
D_N ,
VPWR,
VGND,
VPB ,
VNB
);
output Y ;
input A ;
input B ;
input C_N ;
input D_N ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
sky130_fd_sc_lp__nor4bb base (
.Y(Y),
.A(A),
.B(B),
.C_N(C_N),
.D_N(D_N),
.VPWR(VPWR),
.VGND(VGND),
.VPB(VPB),
.VNB(VNB)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_lp__nor4bb_4 (
Y ,
A ,
B ,
C_N,
D_N
);
output Y ;
input A ;
input B ;
input C_N;
input D_N;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
sky130_fd_sc_lp__nor4bb base (
.Y(Y),
.A(A),
.B(B),
.C_N(C_N),
.D_N(D_N)
);
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_LP__NOR4BB_4_V
|
module MMIO_slave(
input fclk,
input rst_n,
//AXI Inputs
output S_AXI_ACLK,
input [31:0] S_AXI_ARADDR,
input [11:0] S_AXI_ARID,
output S_AXI_ARREADY,
input S_AXI_ARVALID,
input [31:0] S_AXI_AWADDR,
input [11:0] S_AXI_AWID,
output S_AXI_AWREADY,
input S_AXI_AWVALID,
output [11:0] S_AXI_BID,
input S_AXI_BREADY,
output [1:0] S_AXI_BRESP,
output S_AXI_BVALID,
output [31:0] S_AXI_RDATA,
output [11:0] S_AXI_RID,
output S_AXI_RLAST,
input S_AXI_RREADY,
output [1:0] S_AXI_RRESP,
output S_AXI_RVALID,
input [31:0] S_AXI_WDATA,
output S_AXI_WREADY,
input [3:0] S_AXI_WSTRB,
input S_AXI_WVALID,
// MMIO regs
output [31:0] MMIO_CMD,
output [31:0] MMIO_CAM0_CMD,
output [31:0] MMIO_CAM1_CMD,
output [31:0] MMIO_FRAME_BYTES0,
output [31:0] MMIO_TRIBUF_ADDR0,
output [31:0] MMIO_FRAME_BYTES1,
output [31:0] MMIO_TRIBUF_ADDR1,
output [31:0] MMIO_FRAME_BYTES2,
output [31:0] MMIO_TRIBUF_ADDR2,
input [31:0] debug0,
input [31:0] debug1,
input [31:0] debug2,
input [31:0] debug3,
output reg rw_cam0_cmd_valid,
input [17:0] rw_cam0_resp,
input rw_cam0_resp_valid,
output reg rw_cam1_cmd_valid,
input [17:0] rw_cam1_resp,
input rw_cam1_resp_valid,
output MMIO_IRQ
);
assign S_AXI_ACLK = fclk;
//Convert Input signals to AXI lite, to avoid ID matching
wire [31:0] LITE_ARADDR;
wire LITE_ARREADY;
wire LITE_ARVALID;
wire [31:0] LITE_AWADDR;
wire LITE_AWREADY;
wire LITE_AWVALID;
wire LITE_BREADY;
reg [1:0] LITE_BRESP;
wire LITE_BVALID;
reg [31:0] LITE_RDATA;
wire LITE_RREADY;
reg [1:0] LITE_RRESP;
wire LITE_RVALID;
wire [31:0] LITE_WDATA;
wire LITE_WREADY;
wire [3:0] LITE_WSTRB;
wire LITE_WVALID;
wire MMIO_READY;
assign MMIO_READY = 1;
ict106_axilite_conv axilite(
.ACLK(S_AXI_ACLK),
.ARESETN(rst_n),
.S_AXI_ARADDR(S_AXI_ARADDR),
.S_AXI_ARID(S_AXI_ARID),
.S_AXI_ARREADY(S_AXI_ARREADY),
.S_AXI_ARVALID(S_AXI_ARVALID),
.S_AXI_AWADDR(S_AXI_AWADDR),
.S_AXI_AWID(S_AXI_AWID),
.S_AXI_AWREADY(S_AXI_AWREADY),
.S_AXI_AWVALID(S_AXI_AWVALID),
.S_AXI_BID(S_AXI_BID),
.S_AXI_BREADY(S_AXI_BREADY),
.S_AXI_BRESP(S_AXI_BRESP),
.S_AXI_BVALID(S_AXI_BVALID),
.S_AXI_RDATA(S_AXI_RDATA),
.S_AXI_RID(S_AXI_RID),
.S_AXI_RLAST(S_AXI_RLAST),
.S_AXI_RREADY(S_AXI_RREADY),
.S_AXI_RRESP(S_AXI_RRESP),
.S_AXI_RVALID(S_AXI_RVALID),
.S_AXI_WDATA(S_AXI_WDATA),
.S_AXI_WREADY(S_AXI_WREADY),
.S_AXI_WSTRB(S_AXI_WSTRB),
.S_AXI_WVALID(S_AXI_WVALID),
.M_AXI_ARADDR(LITE_ARADDR),
.M_AXI_ARREADY(LITE_ARREADY),
.M_AXI_ARVALID(LITE_ARVALID),
.M_AXI_AWADDR(LITE_AWADDR),
.M_AXI_AWREADY(LITE_AWREADY),
.M_AXI_AWVALID(LITE_AWVALID),
.M_AXI_BREADY(LITE_BREADY),
.M_AXI_BRESP(LITE_BRESP),
.M_AXI_BVALID(LITE_BVALID),
.M_AXI_RDATA(LITE_RDATA),
.M_AXI_RREADY(LITE_RREADY),
.M_AXI_RRESP(LITE_RRESP),
.M_AXI_RVALID(LITE_RVALID),
.M_AXI_WDATA(LITE_WDATA),
.M_AXI_WREADY(LITE_WREADY),
.M_AXI_WSTRB(LITE_WSTRB),
.M_AXI_WVALID(LITE_WVALID)
);
`include "math.v"
`include "macros.vh"
// Needs to be at least
parameter MMIO_SIZE = `MMIO_SIZE;
parameter [31:0] MMIO_STARTADDR = 32'h7000_0000;
parameter W = 32;
//This will only work on Verilog 2005
localparam MMIO_BITS = clog2(MMIO_SIZE);
reg [W-1:0] data[MMIO_SIZE-1:0];
parameter IDLE = 0, RWAIT = 1;
parameter OK = 2'b00, SLVERR = 2'b10;
//READS
reg r_state;
wire [MMIO_BITS-1:0] r_select;
assign r_select = LITE_ARADDR[MMIO_BITS+1:2];
assign ar_good = {LITE_ARADDR[31:(2+MMIO_BITS)], {MMIO_BITS{1'b0}}, LITE_ARADDR[1:0]} == MMIO_STARTADDR;
assign LITE_ARREADY = (r_state == IDLE);
assign LITE_RVALID = (r_state == RWAIT);
// TODO cam0_cmd_write might be valid for multiple cycles??
wire cam0_cmd_write;
assign cam0_cmd_write = (w_state==RWAIT) && LITE_WREADY && (w_select_r==`MMIO_CAM_CMD(0));
`REG(fclk, rw_cam0_cmd_valid, 0, cam0_cmd_write)
reg [31:0] cam0_resp;
reg [31:0] cam0_resp_cnt;
always @(posedge fclk or negedge rst_n) begin
if (!rst_n) begin
cam0_resp <= 32'h0;
cam0_resp_cnt[12:0] <= 0;
end
else if (rw_cam0_resp_valid) begin
cam0_resp <= {14'h0,rw_cam0_resp[17:0]};
cam0_resp_cnt <= cam0_resp_cnt + 1'b1;
end
end
// TODO cam1_cmd_write might be valid for multiple cycles??
wire cam1_cmd_write;
assign cam1_cmd_write = (w_state==RWAIT) && LITE_WREADY && (w_select_r==`MMIO_CAM_CMD(1));
`REG(fclk, rw_cam1_cmd_valid, 0, cam1_cmd_write)
reg [31:0] cam1_resp;
reg [31:0] cam1_resp_cnt;
always @(posedge fclk or negedge rst_n) begin
if (!rst_n) begin
cam1_resp <= 32'h0;
cam1_resp_cnt[12:0] <= 0;
end
else if (rw_cam1_resp_valid) begin
cam1_resp <= {14'h0,rw_cam1_resp[17:0]};
cam1_resp_cnt <= cam1_resp_cnt + 1'b1;
end
end
// Only need to specify read only registers
reg [31:0] read_data;
always @(*) begin
case(r_select)
`MMIO_DEBUG(0) : read_data = debug0;
`MMIO_DEBUG(1) : read_data = debug1;
`MMIO_DEBUG(2) : read_data = debug2;
`MMIO_DEBUG(3) : read_data = debug3;
`MMIO_CAM_RESP(0) : read_data = cam0_resp;
`MMIO_CAM_RESP_CNT(0) : read_data = cam0_resp_cnt;
`MMIO_CAM_RESP(1) : read_data = cam1_resp;
`MMIO_CAM_RESP_CNT(1) : read_data = cam1_resp_cnt;
default : read_data = data[r_select];
endcase
end
// MMIO Mappings
assign MMIO_CMD = data[`MMIO_CMD ];
assign MMIO_CAM0_CMD = data[`MMIO_CAM_CMD(0) ];
assign MMIO_CAM1_CMD = data[`MMIO_CAM_CMD(1) ];
assign MMIO_FRAME_BYTES0 = data[`MMIO_FRAME_BYTES(0) ];
assign MMIO_TRIBUF_ADDR0 = data[`MMIO_TRIBUF_ADDR(0) ];
assign MMIO_FRAME_BYTES1 = data[`MMIO_FRAME_BYTES(1) ];
assign MMIO_TRIBUF_ADDR1 = data[`MMIO_TRIBUF_ADDR(1) ];
assign MMIO_FRAME_BYTES2 = data[`MMIO_FRAME_BYTES(2) ];
assign MMIO_TRIBUF_ADDR2 = data[`MMIO_TRIBUF_ADDR(2) ];
always @(posedge fclk) begin
if(rst_n == 0) begin
r_state <= IDLE;
end else case(r_state)
IDLE: begin
if(LITE_ARVALID) begin
LITE_RRESP <= ar_good ? OK : SLVERR;
LITE_RDATA <= read_data;
r_state <= RWAIT;
end
end
RWAIT: begin
if(LITE_RREADY)
r_state <= IDLE;
end
endcase
end
//WRITES
reg w_state;
reg [MMIO_BITS-1:0] w_select_r;
reg w_wrotedata;
reg w_wroteresp;
wire [MMIO_BITS-1:0] w_select;
assign w_select = LITE_AWADDR[MMIO_BITS+1:2];
assign aw_good = {LITE_ARADDR[31:(2+MMIO_BITS)], {MMIO_BITS{1'b0}}, LITE_AWADDR[1:0]} == MMIO_STARTADDR;
assign LITE_AWREADY = (w_state == IDLE);
assign LITE_WREADY = (w_state == RWAIT) && !w_wrotedata;
assign LITE_BVALID = (w_state == RWAIT) && !w_wroteresp;
always @(posedge fclk) begin
if(rst_n == 0) begin
w_state <= IDLE;
w_wrotedata <= 0;
w_wroteresp <= 0;
end else case(w_state)
IDLE: begin
if(LITE_AWVALID) begin
LITE_BRESP <= aw_good ? OK : SLVERR;
w_select_r <= w_select;
w_state <= RWAIT;
w_wrotedata <= 0;
w_wroteresp <= 0;
end
end
RWAIT: begin
data[0] <= 0;
if (LITE_WREADY) begin
data[w_select_r] <= LITE_WDATA;
end
if((w_wrotedata || LITE_WVALID) && (w_wroteresp || LITE_BREADY)) begin
w_wrotedata <= 0;
w_wroteresp <= 0;
w_state <= IDLE;
end
else if (LITE_WVALID) begin
w_wrotedata <= 1;
end
else if (LITE_BREADY) begin
w_wroteresp <= 1;
end
end
endcase
end
reg v_state;
always @(posedge fclk) begin
if (rst_n == 0)
v_state <= IDLE;
else case(v_state)
IDLE:
if (LITE_WVALID && LITE_WREADY && w_select_r == 2'b00)
v_state <= RWAIT;
RWAIT:
if (MMIO_READY)
v_state <= IDLE;
endcase
end
// interrupts
assign MMIO_IRQ = 0;
endmodule // Conf
|
//////////////////////////////////////////////////////////////////////
//// ////
//// uart_sync_flops.v ////
//// ////
//// ////
//// This file is part of the "UART 16550 compatible" project ////
//// http://www.opencores.org/cores/uart16550/ ////
//// ////
//// Documentation related to this project: ////
//// - http://www.opencores.org/cores/uart16550/ ////
//// ////
//// Projects compatibility: ////
//// - WISHBONE ////
//// RS232 Protocol ////
//// 16550D uart (mostly supported) ////
//// ////
//// Overview (main Features): ////
//// UART core receiver logic ////
//// ////
//// Known problems (limits): ////
//// None known ////
//// ////
//// To Do: ////
//// Thourough testing. ////
//// ////
//// Author(s): ////
//// - Andrej Erzen ([email protected]) ////
//// - Tadej Markovic ([email protected]) ////
//// ////
//// Created: 2004/05/20 ////
//// Last Updated: 2004/05/20 ////
//// (See log for the revision history) ////
//// Modified for use in the ZAP project by Revanth Kamaraj ////
//// ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2000, 2001 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
//
// CVS Revision History
//
// $Log: not supported by cvs2svn $
//
module uart_sync_flops
(
// internal signals
rst_i,
clk_i,
stage1_rst_i,
stage1_clk_en_i,
async_dat_i,
sync_dat_o
);
parameter Tp = 1;
parameter width = 1;
parameter init_value = 1'b0;
input rst_i; // reset input
input clk_i; // clock input
input stage1_rst_i; // synchronous reset for stage 1 FF
input stage1_clk_en_i; // synchronous clock enable for stage 1 FF
input [width-1:0] async_dat_i; // asynchronous data input
output [width-1:0] sync_dat_o; // synchronous data output
//
// Interal signal declarations
//
reg [width-1:0] sync_dat_o;
reg [width-1:0] flop_0;
// first stage
always @ (posedge clk_i or posedge rst_i)
begin
if (rst_i)
flop_0 <= #Tp {width{init_value}};
else
flop_0 <= #Tp async_dat_i;
end
// second stage
always @ (posedge clk_i or posedge rst_i)
begin
if (rst_i)
sync_dat_o <= #Tp {width{init_value}};
else if (stage1_rst_i)
sync_dat_o <= #Tp {width{init_value}};
else if (stage1_clk_en_i)
sync_dat_o <= #Tp flop_0;
end
endmodule
|
//======================================================================
//
// tb_coretest.v
// -------------
// Testbench for coretest. Generates commands and observes responses.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2014, Secworks Sweden AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following
// conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
//------------------------------------------------------------------
// Simulator directives.
//------------------------------------------------------------------
`timescale 1ns/10ps
module tb_coretest();
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
parameter DEBUG = 0;
parameter VERBOSE = 0;
parameter CMD_MONITOR = 1;
parameter REC_MONITOR = 0;
parameter CLK_HALF_PERIOD = 1;
parameter CLK_PERIOD = CLK_HALF_PERIOD * 2;
// Command and response constants.
parameter SOC = 8'h55;
parameter EOC = 8'haa;
parameter RESET_CMD = 8'h01;
parameter READ_CMD = 8'h10;
parameter WRITE_CMD = 8'h11;
parameter SOR = 8'haa;
parameter EOR = 8'h55;
parameter UNKNOWN = 8'hfe;
parameter ERROR = 8'hfd;
parameter READ_OK = 8'h7f;
parameter WRITE_OK = 8'h7e;
parameter RESET_OK = 8'h7d;
parameter MAX_MEM = 16'h00ff;
//----------------------------------------------------------------
// Register and Wire declarations.
//----------------------------------------------------------------
reg [31 : 0] cycle_ctr;
reg [31 : 0] error_ctr;
reg [31 : 0] tc_ctr;
reg tb_clk;
reg tb_reset_n;
reg tb_rx_syn;
reg [7 : 0] tb_rx_data;
wire tb_rx_ack;
wire tb_tx_syn;
wire [7 : 0] tb_tx_data;
reg tb_tx_ack;
wire tb_core_reset_;
wire tb_core_cs;
wire tb_core_we;
wire [15 : 0] tb_core_address;
wire [31 : 0] tb_core_write_data;
reg [31 : 0] tb_core_read_data;
reg tb_core_error;
reg [7 : 0] received_tx_data;
reg [31 : 0] test_mem [0 : (MAX_MEM - 1'b1)];
//----------------------------------------------------------------
// Device Under Test.
//----------------------------------------------------------------
coretest dut(
.clk(tb_clk),
.reset_n(tb_reset_n),
// Interface to communication core
.rx_syn(tb_rx_syn),
.rx_data(tb_rx_data),
.rx_ack(tb_rx_ack),
.tx_syn(tb_tx_syn),
.tx_data(tb_tx_data),
.tx_ack(tb_tx_ack),
// Interface to the core being tested.
.core_reset_n(tb_core_reset_n),
.core_cs(tb_core_cs),
.core_we(tb_core_we),
.core_address(tb_core_address),
.core_write_data(tb_core_write_data),
.core_read_data(tb_core_read_data),
.core_error(tb_core_error)
);
//----------------------------------------------------------------
// clk_gen
//
// Clock generator process.
//----------------------------------------------------------------
always
begin : clk_gen
#CLK_HALF_PERIOD tb_clk = !tb_clk;
end // clk_gen
//----------------------------------------------------------------
// sys_monitor
//
// System monitor. Can display status about the dut and TB
// every cycle.
//----------------------------------------------------------------
always
begin : sys_monitor
#(CLK_PERIOD);
if (DEBUG)
begin
dump_dut_state();
$display("");
end
if (VERBOSE)
begin
$display("cycle: 0x%016x", cycle_ctr);
end
cycle_ctr = cycle_ctr + 1;
end
//----------------------------------------------------------------
// command_monitor
//
// Observes any read/write or reset commands generated
// by the DUT.
//----------------------------------------------------------------
always
begin : command_monitor
#(CLK_PERIOD);
if (CMD_MONITOR)
begin
if (!tb_core_reset_n)
begin
$display("Core is being reset by coretest.");
end
if (tb_core_cs)
begin
if (tb_core_we)
begin
$display("Core is being written to: address 0x%08x = 0x%08x",
tb_core_address, tb_core_write_data);
end
else
begin
$display("Core is being read from: address 0x%08x = 0x%08x",
tb_core_address, tb_core_read_data);
end
end
end
end
//----------------------------------------------------------------
// receive_logic
//
// The logic needed to the correct handshake expected by the DUT
// when it is sending bytes.
//----------------------------------------------------------------
always @ (posedge tb_clk)
begin : receive_logic
if (tb_tx_syn)
begin
if (REC_MONITOR)
begin
$display("Receiving byte 0x%02x from the DUT.", tb_tx_data);
end
#(2 * CLK_PERIOD);
tb_tx_ack = 1;
#(2 * CLK_PERIOD);
tb_tx_ack = 0;
end
end // receive_logic
//----------------------------------------------------------------
// test_mem_logic
//
// The logic needed to implement the test memory. We basically
// implement a simple memory to allow read and write operations
// via commands to the DUT to really be executed.
//----------------------------------------------------------------
always @ (posedge tb_clk)
begin : test_mem_logic
if (tb_core_cs)
begin
if (tb_core_we)
begin
if (tb_core_address < MAX_MEM)
begin
$display("Writing to test_mem[0x%08x] = 0x%08x",
tb_core_address, tb_core_write_data);
test_mem[tb_core_address] = tb_core_write_data;
end
else
begin
$display("Writing to incorrect address 0x%08x",
tb_core_address);
tb_core_error = 1;
end
end
else
begin
if (tb_core_address < MAX_MEM)
begin
$display("Reading from test_mem[0x%08x] = 0x%08x",
tb_core_address, tb_core_read_data);
tb_core_read_data = test_mem[tb_core_address];
end
else
begin
$display("Reading from incorrect address 0x%08x",
tb_core_address);
tb_core_error = 1;
end
end
end
else
begin
tb_core_read_data = 32'h00000000;
tb_core_error = 0;
end
end
//----------------------------------------------------------------
// dump_dut_state()
//
// Dump the state of the dut when needed.
//----------------------------------------------------------------
task dump_dut_state();
begin
$display("State of DUT");
$display("------------");
$display("Inputs and outputs:");
$display("rx_syn = 0x%01x, rx_data = 0x%02x, rx_ack = 0x%01x",
dut.rx_syn, dut.rx_data, dut.rx_ack);
$display("tx_syn = 0x%01x, tx_data = 0x%02x, tx_ack = 0x%01x",
dut.tx_syn, dut.tx_data, dut.tx_ack);
$display("cs = 0x%01x, we = 0x%01x, address = 0x%04x, write_data = 0x%08x, read_data = 0x%08x, error = 0x%01x",
dut.core_cs, dut.core_we, dut.core_address, dut.core_write_data, dut.core_read_data, dut.core_error);
$display("");
$display("RX chain signals:");
$display("rx_buffer_wr_ptr = 0x%02x, rx_buffer_rd_ptr = 0x%02x, rx_buffer_ctr = 0x%02x, rx_buffer_empty = 0x%01x, rx_buffer_full = 0x%01x",
dut.rx_buffer_wr_ptr_reg, dut.rx_buffer_rd_ptr_reg, dut.rx_buffer_ctr_reg, dut.rx_buffer_empty, dut.rx_buffer_full);
$display("");
$display("Control signals and FSM state:");
$display("test_engine_reg = 0x%02x, cmd_reg = 0x%02x",
dut.test_engine_reg, dut.cmd_reg);
$display("");
end
endtask // dump_dut_state
//----------------------------------------------------------------
// reset_dut()
//----------------------------------------------------------------
task reset_dut();
begin
$display("*** Toggle reset.");
tb_reset_n = 0;
#(2 * CLK_PERIOD);
tb_reset_n = 1;
end
endtask // reset_dut
//----------------------------------------------------------------
// init_sim()
//
// Initialize all counters and testbed functionality as well
// as setting the DUT inputs to defined values.
//----------------------------------------------------------------
task init_sim();
reg [8 : 0] i;
begin
cycle_ctr = 0;
error_ctr = 0;
tc_ctr = 0;
tb_clk = 0;
tb_reset_n = 1;
tb_rx_syn = 0;
tb_rx_data = 8'h00;
tb_tx_ack = 0;
for (i = 0 ; i < 256 ; i = i + 1)
begin
test_mem[i[7 : 0]] = {4{i[7 : 0]}};
end
end
endtask // init_sim
//----------------------------------------------------------------
// send_byte
//
// Send a byte of data to the DUT.
//----------------------------------------------------------------
task send_byte(input [7 : 0] data);
integer i;
begin
if (VERBOSE)
begin
$display("*** Sending byte 0x%02x to the dut.", data);
$display("*** Setting RX data and RX SYN.");
end
tb_rx_data = data;
tb_rx_syn = 1;
while (!tb_rx_ack)
begin
#CLK_PERIOD;
if (VERBOSE)
begin
$display("*** Waiting for RX ACK.");
end
end
if (VERBOSE)
begin
$display("*** RX ACK seen. Dropping SYN.");
end
tb_rx_syn = 0;
#(2 * CLK_PERIOD);
end
endtask // send_byte
//----------------------------------------------------------------
// send_reset_command
//
// Generates a reset command to the dut.
//----------------------------------------------------------------
task send_reset_command();
begin
$display("*** Sending reset command.");
send_byte(SOC);
send_byte(RESET_CMD);
send_byte(EOC);
$display("*** Sending reset command done.");
end
endtask // send_write_command
//----------------------------------------------------------------
// send_read_command
//
// Generates a read command to the dut.
//----------------------------------------------------------------
task send_read_command(input [15 : 0] addr);
begin
$display("*** Sending read command: address 0x%04x.", addr);
send_byte(SOC);
send_byte(READ_CMD);
send_byte(addr[15 : 8]);
send_byte(addr[7 : 0]);
send_byte(EOC);
$display("*** Sending read command done.");
end
endtask // send_write_command
//----------------------------------------------------------------
// send_write_command
//
// Generates a write command to the dut.
//----------------------------------------------------------------
task send_write_command(input [15 : 0] addr, input [31 : 0] data);
begin
$display("*** Sending write command: address 0x%04x = 0x%08x.", addr, data);
send_byte(SOC);
send_byte(WRITE_CMD);
send_byte(addr[15 : 8]);
send_byte(addr[7 : 0]);
send_byte(data[31 : 24]);
send_byte(data[23 : 16]);
send_byte(data[15 : 8]);
send_byte(data[7 : 0]);
send_byte(EOC);
$display("*** Sending write command done.");
end
endtask // send_write_command
//----------------------------------------------------------------
// display_test_result()
//
// Display the accumulated test results.
//----------------------------------------------------------------
task display_test_result();
begin
if (error_ctr == 0)
begin
$display("*** All %02d test cases completed successfully", tc_ctr);
end
else
begin
$display("*** %02d test cases did not complete successfully.", error_ctr);
end
end
endtask // display_test_result
//----------------------------------------------------------------
// coretest_test
// The main test functionality.
//----------------------------------------------------------------
initial
begin : coretest_test
$display(" -- Testbench for coretest started --");
init_sim();
dump_dut_state();
reset_dut();
dump_dut_state();
#(64 * CLK_PERIOD);
send_reset_command();
send_read_command(16'h0023);
send_read_command(16'h0055);
send_write_command(16'h00aa, 32'h1337beef);
send_read_command(16'h00aa);
send_write_command(16'h0010, 32'h55aa55aa);
send_read_command(16'h0010);
#(200 * CLK_PERIOD);
display_test_result();
$display("*** Simulation done.");
$finish;
end // coretest_test
endmodule // tb_coretest
//======================================================================
// EOF tb_coretest.v
//======================================================================
|
`include "elink_regmap.v"
module esaxi (/*autoarg*/
// Outputs
txwr_access, txwr_packet, txrd_access, txrd_packet, rxrr_wait,
s_axi_arready, s_axi_awready, s_axi_bid, s_axi_bresp, s_axi_bvalid,
s_axi_rid, s_axi_rdata, s_axi_rlast, s_axi_rresp, s_axi_rvalid,
s_axi_wready,
// Inputs
txwr_wait, txrd_wait, rxrr_access, rxrr_packet, s_axi_aclk,
s_axi_aresetn, s_axi_arid, s_axi_araddr, s_axi_arburst,
s_axi_arcache, s_axi_arlock, s_axi_arlen, s_axi_arprot,
s_axi_arqos, s_axi_arsize, s_axi_arvalid, s_axi_awid, s_axi_awaddr,
s_axi_awburst, s_axi_awcache, s_axi_awlock, s_axi_awlen,
s_axi_awprot, s_axi_awqos, s_axi_awsize, s_axi_awvalid,
s_axi_bready, s_axi_rready, s_axi_wid, s_axi_wdata, s_axi_wlast,
s_axi_wstrb, s_axi_wvalid
);
parameter [11:0] ID = 12'h810;
parameter IDW = 12;
parameter PW = 104;
parameter [15:0] RETURN_ADDR = {ID,`EGROUP_RR};
parameter AW = 32;
parameter DW = 32;
/*****************************/
/*Write request for TX fifo */
/*****************************/
output txwr_access;
output [PW-1:0] txwr_packet;
input txwr_wait;
/*****************************/
/*Read request for TX fifo */
/*****************************/
output txrd_access;
output [PW-1:0] txrd_packet;
input txrd_wait;
/*****************************/
/*Read response from RX fifo */
/*****************************/
input rxrr_access;
input [PW-1:0] rxrr_packet;
output rxrr_wait;
/*****************************/
/*AXI slave interface */
/*****************************/
//Clock and reset
input s_axi_aclk;
input s_axi_aresetn;
//Read address channel
input [IDW-1:0] s_axi_arid; //write address ID
input [31:0] s_axi_araddr;
input [1:0] s_axi_arburst;
input [3:0] s_axi_arcache;
input [1:0] s_axi_arlock;
input [7:0] s_axi_arlen;
input [2:0] s_axi_arprot;
input [3:0] s_axi_arqos;
output s_axi_arready;
input [2:0] s_axi_arsize;
input s_axi_arvalid;
//Write address channel
input [IDW-1:0] s_axi_awid; //write address ID
input [31:0] s_axi_awaddr;
input [1:0] s_axi_awburst;
input [3:0] s_axi_awcache;
input [1:0] s_axi_awlock;
input [7:0] s_axi_awlen;
input [2:0] s_axi_awprot;
input [3:0] s_axi_awqos;
input [2:0] s_axi_awsize;
input s_axi_awvalid;
output s_axi_awready;
//Buffered write response channel
output [IDW-1:0] s_axi_bid; //write address ID
output [1:0] s_axi_bresp;
output s_axi_bvalid;
input s_axi_bready;
//Read channel
output [IDW-1:0] s_axi_rid; //write address ID
output [31:0] s_axi_rdata;
output s_axi_rlast;
output [1:0] s_axi_rresp;
output s_axi_rvalid;
input s_axi_rready;
//Write channel
input [IDW-1:0] s_axi_wid; //write address ID
input [31:0] s_axi_wdata;
input s_axi_wlast;
input [3:0] s_axi_wstrb;
input s_axi_wvalid;
output s_axi_wready;
//###################################################
//#WIRE/REG DECLARATIONS
//###################################################
reg s_axi_awready;
reg s_axi_wready;
reg s_axi_bvalid;
reg [1:0] s_axi_bresp;
reg s_axi_arready;
reg [31:0] axi_awaddr; // 32b for epiphany addr
reg [1:0] axi_awburst;
reg [2:0] axi_awsize;
reg [IDW-1:0] axi_bid; //what to do with this?
reg [31:0] axi_araddr;
reg [7:0] axi_arlen;
reg [1:0] axi_arburst;
reg [2:0] axi_arsize;
reg [31:0] s_axi_rdata;
reg [1:0] s_axi_rresp;
reg s_axi_rlast;
reg s_axi_rvalid;
reg [IDW-1:0] s_axi_rid;
reg read_active;
reg [31:0] read_addr;
reg write_active;
reg b_wait; // waiting to issue write response (unlikely?)
reg txwr_access;
reg [1:0] txwr_datamode;
reg [31:0] txwr_dstaddr;
reg [31:0] txwr_data;
reg [31:0] txwr_data_reg;
reg [31:0] txwr_dstaddr_reg;
reg [1:0] txwr_datamode_reg;
reg txrd_access;
reg [1:0] txrd_datamode;
reg [31:0] txrd_dstaddr;
reg [31:0] txrd_srcaddr; //read reaspne address
reg pre_wr_en; // delay for data alignment
reg ractive_reg; // need leading edge of active for 1st req
reg rnext;
wire last_wr_beat;
wire last_rd_beat;
wire [31:0] rxrr_mux_data;
wire [DW-1:0] rxrr_data;
//###################################################
//#PACKET TO MESH
//###################################################
//TXWR
emesh2packet e2p_txwr (
// Outputs
.packet_out (txwr_packet[PW-1:0]),
// Inputs
.access_in (txwr_access),
.write_in (1'b1),
.datamode_in (txwr_datamode[1:0]),
.ctrlmode_in (4'b0),
.dstaddr_in (txwr_dstaddr[AW-1:0]),
.data_in (txwr_data[DW-1:0]),
.srcaddr_in (32'b0)//only 32b slave write supported
);
//TXRD
emesh2packet e2p_txrd (
// Outputs
.packet_out (txrd_packet[PW-1:0]),
// Inputs
.access_in (txrd_access),
.write_in (txrd_write),
.datamode_in (txrd_datamode[1:0]),
.ctrlmode_in (4'b0),
.dstaddr_in (txrd_dstaddr[AW-1:0]),
.data_in (32'b0),
.srcaddr_in (txrd_srcaddr[AW-1:0])
);
//RXRR
packet2emesh p2e_rxrr (
// Outputs
.access_out (),
.write_out (),
.datamode_out (),
.ctrlmode_out (),
.dstaddr_out (),
.data_out (rxrr_data[DW-1:0]),
.srcaddr_out (),
// Inputs
.packet_in (rxrr_packet[PW-1:0])
);
//###################################################
//#WRITE ADDRESS CHANNEL
//###################################################
assign last_wr_beat = s_axi_wready & s_axi_wvalid & s_axi_wlast;
// axi_awready is asserted when there is no write transfer in progress
always @(posedge s_axi_aclk )
begin
if(~s_axi_aresetn)
begin
s_axi_awready <= 1'b1; //TODO: why not set default as 1?
write_active <= 1'b0;
end
else
begin
// we're always ready for an address cycle if we're not doing something else
// note: might make this faster by going ready on last beat instead of after,
// but if we want the very best each channel should be fifo'd.
if( ~s_axi_awready & ~write_active & ~b_wait )
s_axi_awready <= 1'b1;
else if( s_axi_awvalid )
s_axi_awready <= 1'b0;
// the write cycle is "active" as soon as we capture an address, it
// ends on the last beat.
if( s_axi_awready & s_axi_awvalid )
write_active <= 1'b1;
else if( last_wr_beat )
write_active <= 1'b0;
end // else: !if(~s_axi_aresetn)
end // always @ (posedge s_axi_aclk )
// capture address & other aw info, update address during cycle
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
axi_bid[IDW-1:0] <= 'd0; // capture for write response
axi_awaddr[31:0] <= 32'd0;
axi_awsize[2:0] <= 3'd0;
axi_awburst[1:0] <= 2'd0;
end
else
begin
if( s_axi_awready & s_axi_awvalid )
begin
axi_bid[IDW-1:0] <= s_axi_awid[IDW-1:0];
axi_awaddr[31:0] <= s_axi_awaddr[31:0];
axi_awsize[2:0] <= s_axi_awsize[2:0]; // 0=byte, 1=16b, 2=32b
axi_awburst[1:0] <= s_axi_awburst[1:0]; // type, 0=fixed, 1=incr, 2=wrap
end
else if( s_axi_wvalid & s_axi_wready )
if( axi_awburst == 2'b01 )
begin //incremental burst
// the write address for all the beats in the transaction are increments by the data width.
// note: this should be based on awsize instead to support narrow bursts, i think.
axi_awaddr[31:2] <= axi_awaddr[31:2] + 30'd1;
//awaddr alignedto data width
axi_awaddr[1:0] <= 2'b0;
end // both fixed & wrapping types are treated as fixed, no update.
end // else: !if(~s_axi_aresetn)
//###################################################
//#WRITE RESPONSE CHANNEL
//###################################################
assign s_axi_bid = axi_bid;
always @ (posedge s_axi_aclk)
if(~s_axi_aresetn)
s_axi_wready <= 1'b0;
else
begin
if( last_wr_beat )
s_axi_wready <= 1'b0;
else if( write_active )
s_axi_wready <= ~txwr_wait;
end
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
s_axi_bvalid <= 1'b0;
s_axi_bresp[1:0] <= 2'b0;
b_wait <= 1'b0;
end
else
begin
if( last_wr_beat )
begin
s_axi_bvalid <= 1'b1;
s_axi_bresp[1:0] <= 2'b0; // 'okay' response
b_wait <= ~s_axi_bready; // note: assumes bready will not drop without valid?
end
else if (s_axi_bready & s_axi_bvalid)
begin
s_axi_bvalid <= 1'b0;
b_wait <= 1'b0;
end
end // else: !if( s_axi_aresetn == 1'b0 )
//###################################################
//#READ REQUEST CHANNEL
//###################################################
assign last_rd_beat = s_axi_rvalid & s_axi_rlast & s_axi_rready;
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
s_axi_arready <= 1'b0;
read_active <= 1'b0;
end
else
begin
//arready
if( ~s_axi_arready & ~read_active )
s_axi_arready <= 1'b1;
else if( s_axi_arvalid )
s_axi_arready <= 1'b0;
//read_active
if( s_axi_arready & s_axi_arvalid )
read_active <= 1'b1;
else if( last_rd_beat )
read_active <= 1'b0;
end // else: !if( s_axi_aresetn == 1'b0 )
//Read address channel state machine
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
axi_araddr[31:0] <= 0;
axi_arlen <= 8'd0;
axi_arburst <= 2'd0;
axi_arsize[2:0] <= 3'b0;
s_axi_rlast <= 1'b0;
s_axi_rid[IDW-1:0] <= 'd0;
end
else
begin
if( s_axi_arready & s_axi_arvalid )
begin
axi_araddr[31:0] <= s_axi_araddr[31:0]; //NOTE: upper 2 bits get chopped by Zynq
axi_arlen[7:0] <= s_axi_arlen[7:0];
axi_arburst <= s_axi_arburst;
axi_arsize <= s_axi_arsize;
s_axi_rlast <= ~(|s_axi_arlen[7:0]);
s_axi_rid[IDW-1:0] <= s_axi_arid[IDW-1:0];
end
else if( s_axi_rvalid & s_axi_rready)
begin
axi_arlen[7:0] <= axi_arlen[7:0] - 1;
if(axi_arlen[7:0] == 8'd1)
s_axi_rlast <= 1'b1;
if( s_axi_arburst == 2'b01)
begin //incremental burst
// the read address for all the beats in the transaction are increments by awsize
// note: this should be based on awsize instead to support narrow bursts, i think?
axi_araddr[31:2] <= axi_araddr[31:2] + 1;//TODO: doesn;t seem right...
//araddr aligned to 4 byte boundary
axi_araddr[1:0] <= 2'b0;
//for awsize = 4 bytes (010)
end
end // if ( s_axi_rvalid & s_axi_rready)
end // else: !if( s_axi_aresetn == 1'b0 )
//###################################################
//#WRITE REQUEST
//###################################################
assign txwr_write = 1'b1;
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
txwr_data_reg[31:0] <= 32'd0;
txwr_dstaddr_reg[31:0] <= 32'd0;
txwr_datamode_reg[1:0] <= 2'd0;
txwr_access <= 1'b0;
pre_wr_en <= 1'b0;
end
else
begin
pre_wr_en <= s_axi_wready & s_axi_wvalid;
txwr_access <= pre_wr_en;
txwr_datamode_reg[1:0] <= axi_awsize[1:0];
txwr_dstaddr_reg[31:2] <= axi_awaddr[31:2]; //set lsbs of address based on write strobes
if(s_axi_wstrb[0] | (axi_awsize[1:0]==2'b10))
begin
txwr_data_reg[31:0] <= s_axi_wdata[31:0];
txwr_dstaddr_reg[1:0] <= 2'd0;
end
else if(s_axi_wstrb[1])
begin
txwr_data_reg[31:0] <= {8'd0, s_axi_wdata[31:8]};
txwr_dstaddr_reg[1:0] <= 2'd1;
end
else if(s_axi_wstrb[2])
begin
txwr_data_reg[31:0] <= {16'd0, s_axi_wdata[31:16]};
txwr_dstaddr_reg[1:0] <= 2'd2;
end
else
begin
txwr_data_reg[31:0] <= {24'd0, s_axi_wdata[31:24]};
txwr_dstaddr_reg[1:0] <= 2'd3;
end
end // else: !if(~s_axi_aresetn)
//Pipeline stage!
always @( posedge s_axi_aclk )
begin
txwr_data[31:0] <= txwr_data_reg[31:0];
txwr_dstaddr[31:0] <= txwr_dstaddr_reg[31:0];
txwr_datamode[1:0] <= txwr_datamode_reg[1:0];
end
//###################################################
//#READ REQUEST (DATA CHANNEL)
//###################################################
// -- reads are performed by sending a read
// -- request out the tx port and waiting for
// -- data to come back through the rx read response port.
// --
// -- because elink reads are not generally
// -- returned in order, we will only allow
// -- one at a time.
//TODO: Fix this nonsense, need to improve performance
//Allow up to N outstanding transactions, use ID to match them up
//Need to look at txrd_wait signal
assign txrd_write = 1'b0;
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
txrd_access <= 1'b0;
txrd_datamode[1:0] <= 2'd0;
txrd_dstaddr[31:0] <= 32'd0;
txrd_srcaddr[31:0] <= 32'd0;
ractive_reg <= 1'b0;
rnext <= 1'b0;
end
else
begin
ractive_reg <= read_active;
rnext <= s_axi_rvalid & s_axi_rready & ~s_axi_rlast;
txrd_access <= ( ~ractive_reg & read_active ) | rnext;
txrd_datamode[1:0] <= axi_arsize[1:0];
txrd_dstaddr[31:0] <= axi_araddr[31:0];
txrd_srcaddr[31:0] <= {RETURN_ADDR, 16'd0};
//TODO: use arid+srcaddr for out of order ?
end
//###################################################
//#READ RESPONSE (DATA CHANNEL)
//###################################################
//Read response AXI state machine
//Only one outstanding read
assign rxrr_wait = 1'b0;
always @( posedge s_axi_aclk )
if (~s_axi_aresetn)
begin
s_axi_rvalid <= 1'b0;
s_axi_rdata[31:0] <= 32'd0;
s_axi_rresp <= 2'd0;
end
else
begin
if( rxrr_access )
begin
s_axi_rvalid <= 1'b1;
s_axi_rresp <= 2'd0;
case( axi_arsize[1:0] )
2'b00: s_axi_rdata[31:0] <= {4{rxrr_data[7:0]}}; //8-bit
2'b01: s_axi_rdata[31:0] <= {2{rxrr_data[15:0]}}; //16-bit
default: s_axi_rdata[31:0] <= rxrr_data[31:0]; //32-bit
endcase // case ( axi_arsize[1:0] )
end
else if( s_axi_rready )
s_axi_rvalid <= 1'b0;
end // else: !if( s_axi_aresetn == 1'b0 )
endmodule // esaxi
/*
Copyright (C) 2015 Adapteva, Inc.
Contributed by Andreas Olofsson <[email protected]>
Contributed by Fred Huettig <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.This program is distributed in the hope
that it will be useful,but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have received a copy
of the GNU General Public License along with this program (see the file
COPYING). If not, see <http://www.gnu.org/licenses/>.
*/
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [2:0] in;
wire a,y,y_fixed;
wire b = in[0];
wire en = in[1];
pullup(a);
ChildA childa ( .A(a), .B(b), .en(en), .Y(y),.Yfix(y_fixed) );
initial in=0;
// Test loop
always @ (posedge clk) begin
in <= in + 1;
$display ( "a %d b %d en %d y %d yfix: %d)" , a, b, en, y, y_fixed);
if (en) begin
// driving b
// a should be b
// y and yfix should also be b
if (a!=b || y != b || y_fixed != b) begin
$display ( "Expected a %d y %b yfix %b" , a, y, y_fixed);
$stop;
end
end else begin
// not driving b
// a should be 1 (pullup)
// y and yfix shold be 1
if (a!=1 || y != 1 || y_fixed != 1) begin
$display( "Expected a,y,yfix == 1");
$stop;
end
end
if (in==3) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module ChildA(inout A, input B, input en, output Y, output Yfix);
// workaround
wire a_in = A;
ChildB childB(.A(A), .Y(Y));
assign A = en ? B : 1'bz;
ChildB childBfix(.A(a_in),.Y(Yfix));
endmodule
module ChildB(input A, output Y);
assign Y = A;
endmodule
|
// megafunction wizard: %Shift register (RAM-based)%VBB%
// GENERATION: STANDARD
// VERSION: WM1.0
// MODULE: ALTSHIFT_TAPS
// ============================================================
// File Name: SHIFTREGRAM.v
// Megafunction Name(s):
// ALTSHIFT_TAPS
//
// Simulation Library Files(s):
// altera_mf
// ============================================================
// ************************************************************
// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
//
// 13.0.1 Build 232 06/12/2013 SP 1 SJ Full Version
// ************************************************************
//Copyright (C) 1991-2013 Altera Corporation
//Your use of Altera Corporation's design tools, logic functions
//and other software and tools, and its AMPP partner logic
//functions, and any output files from any of the foregoing
//(including device programming or simulation files), and any
//associated documentation or information are expressly subject
//to the terms and conditions of the Altera Program License
//Subscription Agreement, Altera MegaCore Function License
//Agreement, or other applicable license agreement, including,
//without limitation, that your use is for the sole purpose of
//programming logic devices manufactured by Altera and sold by
//Altera or its authorized distributors. Please refer to the
//applicable agreement for further details.
module SHIFTREGRAM (
clken,
clock,
shiftin,
shiftout,
taps);
input clken;
input clock;
input [12:0] shiftin;
output [12:0] shiftout;
output [168:0] taps;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clken;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
endmodule
// ============================================================
// CNX file retrieval info
// ============================================================
// Retrieval info: PRIVATE: ACLR NUMERIC "0"
// Retrieval info: PRIVATE: CLKEN NUMERIC "1"
// Retrieval info: PRIVATE: GROUP_TAPS NUMERIC "0"
// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone II"
// Retrieval info: PRIVATE: NUMBER_OF_TAPS NUMERIC "13"
// Retrieval info: PRIVATE: RAM_BLOCK_TYPE NUMERIC "1"
// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0"
// Retrieval info: PRIVATE: TAP_DISTANCE NUMERIC "5"
// Retrieval info: PRIVATE: WIDTH NUMERIC "13"
// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all
// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Cyclone II"
// Retrieval info: CONSTANT: LPM_HINT STRING "RAM_BLOCK_TYPE=M4K"
// Retrieval info: CONSTANT: LPM_TYPE STRING "altshift_taps"
// Retrieval info: CONSTANT: NUMBER_OF_TAPS NUMERIC "13"
// Retrieval info: CONSTANT: TAP_DISTANCE NUMERIC "5"
// Retrieval info: CONSTANT: WIDTH NUMERIC "13"
// Retrieval info: USED_PORT: clken 0 0 0 0 INPUT VCC "clken"
// Retrieval info: USED_PORT: clock 0 0 0 0 INPUT NODEFVAL "clock"
// Retrieval info: USED_PORT: shiftin 0 0 13 0 INPUT NODEFVAL "shiftin[12..0]"
// Retrieval info: USED_PORT: shiftout 0 0 13 0 OUTPUT NODEFVAL "shiftout[12..0]"
// Retrieval info: USED_PORT: taps 0 0 169 0 OUTPUT NODEFVAL "taps[168..0]"
// Retrieval info: CONNECT: @clken 0 0 0 0 clken 0 0 0 0
// Retrieval info: CONNECT: @clock 0 0 0 0 clock 0 0 0 0
// Retrieval info: CONNECT: @shiftin 0 0 13 0 shiftin 0 0 13 0
// Retrieval info: CONNECT: shiftout 0 0 13 0 @shiftout 0 0 13 0
// Retrieval info: CONNECT: taps 0 0 169 0 @taps 0 0 169 0
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM.v TRUE
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM.inc FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM.cmp FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM.bsf FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM_inst.v TRUE
// Retrieval info: GEN_FILE: TYPE_NORMAL SHIFTREGRAM_bb.v TRUE
// Retrieval info: LIB_FILE: altera_mf
|
(*
Copyright 2014 Cornell University
Copyright 2015 Cornell University
Copyright 2016 Cornell University
This file is part of VPrl (the Verified Nuprl project).
VPrl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
VPrl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VPrl. If not, see <http://www.gnu.org/licenses/>.
Websites: http://nuprl.org/html/verification/
http://nuprl.org/html/Nuprl2Coq
https://github.com/vrahli/NuprlInCoq
Authors: Abhishek Anand & Vincent Rahli
*)
Require Export computation_preserve4.
(** %\noindent% The following lemma expresses a consequence of the fact the
first argument of a [NonCanonicalOp] is always principal. Hence,
if an arbitrary non-canonical term [(oterm (NCan op) lbt)] computes
to a value in at most [S k] steps, [lbt] must be of the form
[lbt = (bterm [] la)::lbtt] and there is an [m] such that $m \le k$ and
[la] (the principal argument) computes to some canonical term
[(oterm (Can c) lbtc)] in m and the whole term computes
also takes m steps to compute to
[((oterm (NCan op) ((bterm [] (oterm (Can c) lbtc))::lbtt)))]
*)
Lemma compute_decompose_aux {p} :
forall lib (op : NonCanonicalOp) (k: nat) (lbt : list BTerm) (a : NTerm),
isprogram (oterm (NCan op) lbt)
-> computes_to_val_like_in_max_k_steps lib (oterm (NCan op) lbt) a (S k)
-> { la : NTerm
$ { lbtt: list BTerm
$ { t : @NTerm p
$ { m : nat
$ m <= k
# lbt = bterm [] la :: lbtt
# reduces_in_atmost_k_steps lib la t m
# reduces_in_atmost_k_steps lib
(oterm (NCan op) lbt)
(oterm (NCan op) ((bterm [] t)::lbtt))
m
# is_can_or_exc t}}}}
[+]
{v : NVar
& {t : NTerm
& {u : NTerm
& {x : NTerm
& {w : NTerm
& {m : nat
& m <= k
# op = NFresh
# lbt = [bterm [v] t]
# let a := get_fresh_atom t in
reduces_in_atmost_k_steps lib (subst t v (mk_utoken a)) x m
# alpha_eq x (subst u v (mk_utoken a))
# subset (get_utokens u) (get_utokens t)
# reduces_in_atmost_k_steps lib (oterm (NCan op) lbt) (mk_fresh v w) m
# alpha_eq u w
# isvalue_like u
}}}}}}.
Proof.
induction k as [| k Hind]; introv Hpr Hcv.
- repnud Hcv.
unfold reduces_in_atmost_k_steps in Hcv0.
simpl in Hcv0.
rename Hcv0 into Hcomp.
dlist lbt SSCase as [| arg1]; invertsn Hcomp.
(**takes care of nilcase as no ncop takes 0 bterms*)
SSCase "conscase".
destruct arg1 as [arg1vs arg1nt];
dlist arg1vs SSSCase as [|arg1v1];
[|].
{ SSSCase "nilcase".
destruct arg1nt as [v89|f|arg1o arg1bts];[inverts Hcomp| |];[|].
{ csunf Hcomp; allsimpl.
left.
exists (sterm f) lbt (sterm f) 0.
allrw @reduces_in_atmost_k_steps_0.
dands; eauto 3 with slow. }
left.
dopid arg1o as [arg1c | arg1nc | arg1exc | arg1abs] SSSSCase.
+ SSSSCase "Can".
exists (oterm (Can arg1c) arg1bts) lbt (oterm (Can arg1c) arg1bts) 0.
dands; spc; left; sp.
+ SSSSCase "NCan".
rw @compute_step_ncan_ncan in Hcomp.
remember (compute_step lib (oterm (NCan arg1nc) arg1bts)).
destruct c; spc; inverts Hcomp.
provefalse.
unfold isvalue_like in Hcv; allsimpl; sp.
+ SSSSCase "Exc".
csunf Hcomp; allsimpl.
destruct op;
try (complete (apply compute_step_catch_success in Hcomp; repdors; exrepnd; subst;
try (complete (inversion Hcomp1)); try (complete (inversion Hcv0));
unfold reduces_in_atmost_k_steps;
exists (oterm Exc arg1bts)
lbt
(oterm Exc arg1bts) 0; dands; auto;
right; sp)).
apply compute_step_catch_success in Hcomp; exrepnd; subst.
destruct Hcomp as [Hcomp|Hcomp]; exrepnd; GC; cpx; subst; ginv.
* exists (mk_exception a' e)
[bterm [] a0; bterm [v] b]
(mk_exception a' e) 0; dands; simpl; auto;
allrw @fold_try; allrw @fold_exception;
unfold reduces_in_atmost_k_steps;
unfold computes_to_value_in_max_k_steps; simpl; eauto with slow.
+ SSSSCase "Abs".
rw @compute_step_ncan_abs in Hcomp.
remember (compute_step_lib lib arg1abs arg1bts).
destruct c; spc; inverts Hcomp.
unfold isvalue_like in Hcv; allsimpl; sp.
}
{ SSSCase "conscase".
right.
csunf Hcomp; allsimpl.
apply compute_step_fresh_success in Hcomp; exrepnd; subst.
repndors; exrepnd; subst.
- unfold isvalue_like in Hcv; allsimpl; sp.
- exists arg1v1 arg1nt arg1nt
(subst arg1nt arg1v1 (mk_utoken (get_fresh_atom arg1nt)))
arg1nt
0; dands; eauto with slow;
rw @reduces_in_atmost_k_steps_0; auto.
- unfold isvalue_like in Hcv; allsimpl; tcsp.
}
- unfold computes_to_val_like_in_max_k_steps in Hcv; repnd.
rw @reduces_in_atmost_k_steps_S in Hcv0; exrepnd.
rename Hcv0 into Hcomp.
dlist lbt SSCase as [| arg1];
[dopid_noncan op SSSCase; inverts Hcomp|];[].
(**takes care of nilcase as no ncop takes 0 bterms*)
SSCase "conscase".
destruct arg1 as [arg1vs arg1nt];
dlist arg1vs SSSCase as [|arg1v1];[|].
{ SSSCase "nilcase".
destruct arg1nt as [v89|f| arg1o arg1bts]; [inverts Hcomp| |];[|].
{ csunf Hcomp; allsimpl.
left.
exists (sterm f) lbt (sterm f) 0.
allrw @reduces_in_atmost_k_steps_0.
dands; eauto 3 with slow; try omega. }
dopid arg1o as [arg1c | arg1nc | arg1exc | arg1abs] SSSSCase.
+ SSSSCase "Can".
left.
exists (oterm (Can arg1c) arg1bts) lbt (oterm (Can arg1c) arg1bts) 0.
dands;spc; try omega; left; sp.
+ SSSSCase "NCan".
rw @compute_step_ncan_ncan in Hcomp.
remember (compute_step lib (oterm (NCan arg1nc) arg1bts)) as Hc.
destruct Hc; ginv.
make_and Hcv1 Hcv.
applydup Hind in Hcv1Hcv;
[| eauto with slow; fail].
clear Hind; repndors; exrepnd; cpx.
left.
exists (oterm (NCan arg1nc) arg1bts) lbtt t (S m); dands; auto; try omega.
{ rw @reduces_in_atmost_k_steps_S.
rw <- HeqHc; eexists; dands; eauto. }
{ rw @reduces_in_atmost_k_steps_S.
rw @compute_step_ncan_ncan; rw <- HeqHc.
eexists; dands; eauto. }
+ SSSSCase "Exc".
csunf Hcomp; allsimpl.
left.
exists (oterm Exc arg1bts) lbt (oterm Exc arg1bts) 0.
dands; auto; try omega; allrw @reduces_in_atmost_k_steps_0; auto.
right; sp.
+ SSSSCase "Abs".
rw @compute_step_ncan_abs in Hcomp.
remember (compute_step_lib lib arg1abs arg1bts) as Hc.
destruct Hc; ginv.
symmetry in HeqHc.
make_and Hcv1 Hcv.
applydup Hind in Hcv1Hcv;
[|apply isprogram_compute_step_lib in HeqHc; eauto with slow].
clear Hind; repndors; exrepnd; cpx.
left.
exists (oterm (Abs arg1abs) arg1bts) lbtt t (S m); dands; auto; try omega.
{ rw @reduces_in_atmost_k_steps_S.
csunf; simpl; rw HeqHc; eexists; dands; eauto. }
{ rw @reduces_in_atmost_k_steps_S.
rw @compute_step_ncan_abs; rw HeqHc.
eexists; dands; eauto. }
}
{ SSSCase "conscase".
csunf Hcomp; allsimpl.
apply compute_step_fresh_success in Hcomp; exrepnd; subst; fold_terms.
right.
exists arg1v1 arg1nt.
repndors; exrepnd; subst.
- pose proof (reduces_in_atmost_k_step_fresh_id lib arg1v1 a) as h.
repeat (autodimp h hyp).
destruct h.
exists (S k); auto.
- apply reduces_in_atmost_k_steps_if_isvalue_like in Hcv1; subst; eauto with slow.
exists arg1nt
(subst arg1nt arg1v1 (mk_utoken (get_fresh_atom arg1nt)))
arg1nt
0;
dands; eauto with slow; try omega;
rw @reduces_in_atmost_k_steps_0; auto.
- fold_terms.
make_and Hcv1 Hcv.
apply Hind in Hcv1Hcv; fold_terms; clear Hind.
+ repndors; exrepnd; ginv.
remember (get_fresh_atom arg1nt) as ua.
remember (get_fresh_atom (subst_utokens x [(ua, mk_var v)])) as ua'.
pose proof (get_fresh_atom_prop arg1nt) as fa; rw <- Hequa in fa.
pose proof (get_fresh_atom_prop (subst_utokens x [(ua,mk_var v)])) as fa'; rw <- Hequa' in fa'.
applydup @isprog_ntwf_eauto in Hpr as wf.
allrw @nt_wf_fresh.
pose proof (compute_step_subst_utoken lib arg1nt x [(v,mk_utoken ua)]) as h.
repeat (autodimp h hyp); eauto 3 with slow.
{ unfold get_utokens_sub; simpl; rw disjoint_singleton_l; tcsp. }
exrepnd.
unfold get_utokens_sub in h2; allsimpl; allrw disjoint_singleton_l.
allrw @fold_subst.
assert (wf_term x) as wfx.
{ apply compute_step_preserves_wf in Hcomp2; auto;[].
apply wf_term_subst; eauto 3 with slow. }
pose proof (reduces_in_atmost_k_steps_change_utok_sub
lib m (subst_utokens x [(ua, mk_var v)])
x0
[(v,mk_utoken ua')]
[(v,mk_utoken ua)]) as q.
repeat (autodimp q hyp); eauto 3 with slow.
{ apply nt_wf_eq; apply wf_subst_utokens; eauto 3 with slow. }
{ constructor; auto; intros i j.
apply get_utokens_subst_utokens_subset in j.
rw in_app_iff in j; allsimpl; repndors; tcsp.
apply in_remove in j; repnd; tcsp. }
{ unfold get_utokens_sub; simpl; apply disjoint_singleton_l; tcsp. }
{ unfold get_utokens_sub; simpl; apply disjoint_singleton_l.
intro j.
apply get_utokens_subst_utokens_subset in j.
rw in_app_iff in j; allsimpl; repndors; tcsp.
apply in_remove in j; repnd; tcsp. }
exrepnd; allrw @fold_subst.
assert (alpha_eq
(subst (subst_utokens x [(ua, mk_var v)]) v (mk_utoken ua))
(subst w0 v (mk_utoken ua))) as aeq.
{ apply lsubst_alpha_congr3; eauto 3 with slow.
apply (alpha_eq_trans _ (subst_utokens (subst w0 v (mk_utoken ua)) [(ua, mk_var v)])).
- apply alpha_eq_subst_utokens; eauto with slow.
- apply simple_alphaeq_subst_utokens_subst; auto.
}
assert (alpha_eq (subst (subst_utokens x [(ua, mk_var v)]) v (mk_utoken ua))
x) as aeq2 by eauto with slow.
dup q5 as c.
eapply reduces_in_atmost_k_steps_alpha in c; eauto; exrepnd.
unfold get_utokens_sub in q2; allsimpl; allrw disjoint_singleton_l.
assert (!LIn ua' (get_utokens u)) as ni.
{ intro j; apply Hcv1Hcv6 in j.
apply get_utokens_subst_utokens_subset in j.
rw in_app_iff in j; allsimpl; repndors; tcsp.
apply in_remove in j; repnd; tcsp.
destruct fa'.
apply get_utokens_subst_utokens_subset2; simpl; auto.
rw in_remove; sp. }
assert (alpha_eq u w1) as aeq0.
{ assert (alpha_eq (subst u v (mk_utoken ua')) (subst w1 v (mk_utoken ua'))) as h by eauto with slow.
pose proof (change_bvars_alpha_wspec [v] u) as k1.
pose proof (change_bvars_alpha_wspec [v] w1) as k2.
exrepnd.
allrw disjoint_singleton_l.
pose proof (lsubst_alpha_congr2 ntcv0 u [(v,mk_utoken ua')]) as p1.
pose proof (lsubst_alpha_congr2 ntcv w1 [(v,mk_utoken ua')]) as p2.
autodimp p1 hyp; autodimp p2 hyp; eauto 3 with slow.
allrw @fold_subst.
assert (alpha_eq (subst ntcv0 v (mk_utoken ua')) (subst ntcv v (mk_utoken ua'))) as h' by eauto with slow.
apply alpha_eq_subst_utoken_not_in_implies in h'; eauto with slow.
{ intro j; destruct ni; apply alphaeq_preserves_utokens in k3; rw k3; auto. }
{ intro j; destruct q2; apply alphaeq_preserves_utokens in k0; rw k0; auto. }
}
exists w1 t2' w (S m); dands; eauto 3 with slow; try omega.
{ rw @reduces_in_atmost_k_steps_S.
exists x; dands; auto. }
{ introv j.
apply q4 in j.
apply get_utokens_subst_utokens_subset in j.
rw in_app_iff in j; allsimpl; repndors; tcsp.
apply in_remove in j; repnd; tcsp.
apply alphaeq_preserves_utokens in h1; rw h1 in j.
apply get_utokens_subst in j; boolvar; tcsp; allsimpl; allrw in_app_iff;
allsimpl; repndors; tcsp.
}
{ rw @reduces_in_atmost_k_steps_S.
unfold mk_fresh.
rw @compute_step_fresh_if_isnoncan_like; auto.
rw <- Hequa; rw Hcomp2; simpl.
eexists; dands; eauto; fold_terms. }
{ apply nt_wf_subst; eauto 3 with slow.
apply nt_wf_eq; apply wf_subst_utokens; eauto 3 with slow. }
+ allrw @isprogram_fresh.
apply implies_isprog_vars_subst_utokens; eauto 3 with slow.
apply compute_step_preserves in Hcomp2; repnd.
allrw @isprog_vars_eq; repnd; dands; auto.
{ eapply subvars_trans;[exact Hcomp0|].
rw @cl_subst_subst_aux; eauto 3 with slow; unfold subst_aux.
rw @free_vars_lsubst_aux_cl; eauto 3 with slow. }
{ apply nt_wf_subst; eauto 3 with slow. }
}
Qed.
Lemma compute_decompose {p} :
forall lib (op : NonCanonicalOp) (k: nat) (lbt : list BTerm) (a : NTerm),
isprogram (oterm (NCan op) lbt)
-> computes_to_value_in_max_k_steps lib (S k) (oterm (NCan op) lbt) a
-> { la : NTerm
$ { lbtt: list BTerm
$ { t : @NTerm p
$ { m : nat
$ m <= k
# lbt = (bterm [] la)::lbtt
# reduces_in_atmost_k_steps lib la t m
# reduces_in_atmost_k_steps lib
(oterm (NCan op) lbt)
(oterm (NCan op) ((bterm [] t)::lbtt))
m
# is_can_or_exc t}}}}
[+]
{v : NVar
& {t : NTerm
& {u : NTerm
& {x : NTerm
& {w : NTerm
& {m : nat
& m <= k
# op = NFresh
# lbt = [bterm [v] t]
# let a := get_fresh_atom t in
reduces_in_atmost_k_steps lib (subst t v (mk_utoken a)) x m
# alpha_eq x (subst u v (mk_utoken a))
# subset (get_utokens u) (get_utokens t)
# reduces_in_atmost_k_steps lib (oterm (NCan op) lbt) (mk_fresh v w) m
# alpha_eq u w
# isvalue_like u
}}}}}}.
Proof.
introv isp comp.
apply @compute_decompose_aux with (a := a); auto.
unfold computes_to_value_in_max_k_steps in comp; repnd.
unfold computes_to_val_like_in_max_k_steps; dands; auto.
left.
inversion comp; subst; sp.
Qed.
Lemma nterm_trico_like {o} :
forall (t : @NTerm o),
isvariable t
[+] isvalue_like t
[+] isnoncan_like t.
Proof.
introv.
destruct t as [v|f|op bs]; simpl; tcsp; eauto 3 with slow.
right.
dopid op as [can|ncan|exc|abs] Case; unfold isvalue_like, isnoncan_like; simpl; sp.
Qed.
(* !!MOVE *)
Lemma alphaeq_vs_implies_alphaeq {o} :
forall (t1 t2 : @NTerm o) l,
alphaeq_vs l t1 t2 -> alphaeq t1 t2.
Proof.
introv aeq.
apply alphaeq_exists.
eexists; eauto.
Qed.
Lemma simple_subst_aux_subst_utokens_aux_aeq {o} :
forall (t1 t2 : @NTerm o) a v,
wf_term t2
-> !LIn v (bound_vars t1)
-> !LIn v (free_vars t1)
-> alpha_eq t1 t2
-> alpha_eq
(subst_aux (subst_utokens_aux t1 [(a, mk_var v)]) v (mk_utoken a))
t2.
Proof.
nterm_ind1s t1 as [x|f ind|op bs ind] Case; introv wf ni1 ni2 aeq; auto.
- Case "vterm".
allsimpl.
unfold subst_aux; simpl.
allrw not_over_or; repnd; GC.
inversion aeq; subst; clear aeq.
boolvar; tcsp.
- Case "oterm".
rw @subst_utokens_aux_oterm.
apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst.
allrw @wf_oterm_iff; repnd.
allsimpl.
remember (get_utok op) as guo; symmetry in Heqguo; destruct guo.
+ allapply @get_utok_some; subst; allsimpl.
destruct bs'; allsimpl; cpx; allsimpl; GC.
unfold subst_utok, subst_aux; simpl.
repeat (boolvar; subst; allsimpl; auto).
+ unfold subst_aux; simpl.
allrw map_map; unfold compose.
apply alpha_eq_oterm_combine; allrw map_length; dands; auto.
introv i.
rw <- map_combine_left in i.
rw in_map_iff in i; exrepnd; cpx; allsimpl.
destruct a1 as [l1 t1].
destruct a0 as [l2 t2].
allsimpl.
applydup aeq0 in i1.
applydup in_combine in i1; repnd.
allrw lin_flat_map.
assert (!LIn v l1) as nivl1.
{ intro i; destruct ni1; eexists; dands; eauto; simpl; rw in_app_iff; sp. }
boolvar; tcsp.
apply alphaeqbt_eq in i0.
rw @alphaeqbt_all in i0.
pose proof (i0 (allvars (lsubst_aux (subst_utokens_aux t1 [(a, mk_var v)]) [(v, mk_utoken a)]))) as aeq.
inversion aeq as [? ? ? ? ? len1 len2 disj norep ae]; subst; allsimpl.
allrw disjoint_app_r; repnd.
apply alphaeq_vs_implies_alphaeq in ae.
apply alphaeq_eq in ae.
apply alphaeqbt_eq.
apply (aeqbt _ vs); simpl; auto.
{ allrw disjoint_app_r; dands; auto. }
apply alphaeq_eq.
rw @lsubst_aux_cswap_cswap; eauto 3 with slow; simpl; fold_terms.
rw @cswap_subst_utokens_aux; simpl.
apply (ind t1 (cswap (mk_swapping l1 vs) t1) l1); auto.
{ rw @osize_cswap; eauto 3 with slow. }
{ apply wf_term_cswap; apply wf in i2.
apply wf_bterm_iff in i2; auto. }
{ rw @bound_vars_cswap.
rw in_swapbvars; intro k; exrepnd.
apply swapvars_eq in k0; eauto 2 with slow; subst.
destruct ni1.
eexists; dands; eauto; simpl; rw in_app_iff; sp. }
{ rw @free_vars_cswap; eauto 2 with slow.
rw in_swapbvars; intro k; exrepnd.
apply swapvars_eq in k0; eauto 2 with slow; subst.
destruct ni2.
eexists; dands; eauto; simpl; rw in_remove_nvars; sp. }
Qed.
Lemma simple_subst_subst_utokens_aeq {o} :
forall (t : @NTerm o) a v,
wf_term t
-> !LIn v (free_vars t)
-> alpha_eq
(subst (subst_utokens t [(a, mk_var v)]) v (mk_utoken a))
t.
Proof.
introv wf ni.
unfsubst.
pose proof (unfold_subst_utokens [(a,mk_var v)] t) as aeq; exrepnd; allsimpl.
allrw disjoint_singleton_r.
rw aeq0.
apply simple_subst_aux_subst_utokens_aux_aeq; eauto with slow.
intro i.
apply alphaeq_preserves_free_vars in aeq1; rw <- aeq1 in i; sp.
Qed.
Lemma reduces_to_fresh {o} :
forall lib (t : @NTerm o) u v,
let a := get_fresh_atom t in
wf_term t
-> reduces_to lib (subst t v (mk_utoken a)) u
-> {z : NTerm
& reduces_to lib (mk_fresh v t) (mk_fresh v z)
# alpha_eq z (subst_utokens u [(a,mk_var v)])}.
Proof.
introv; simpl.
introv wf r.
unfold reduces_to in r; exrepnd.
revert t v u wf r0.
induction k; introv wf comp.
- allrw @reduces_in_atmost_k_steps_0; subst.
exists t; dands; eauto 1 with slow.
apply alpha_eq_sym.
apply simple_alphaeq_subst_utokens_subst.
pose proof (get_fresh_atom_prop t) as h; eauto 3 with slow.
- allrw @reduces_in_atmost_k_steps_S; exrepnd.
remember (get_fresh_atom t) as a.
pose proof (get_fresh_atom_prop t) as gfa.
rw <- Heqa in gfa.
allrw in_app_iff; allrw not_over_or; repnd.
pose proof (nterm_trico_like t) as tri1; repndors.
{
apply isvariable_implies in tri1; exrepnd; subst t; allsimpl; GC.
unfsubst in comp1; allsimpl; boolvar.
- csunf comp1; allsimpl; ginv.
apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto 1 with slow; subst.
exists (@vterm o v0); dands; eauto with slow.
unfold subst_utokens; simpl.
unfold subst_utok; simpl; boolvar; tcsp.
- csunf comp1; allsimpl; ginv.
}
{
assert (isvalue_like (subst t v (mk_utoken a))) as isv.
{ apply isvalue_like_subst; auto. }
rw @compute_step_value_like in comp1; auto; ginv.
apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto 1 with slow; subst.
exists t; dands; eauto 1 with slow.
apply alpha_eq_sym; apply simple_alphaeq_subst_utokens_subst; eauto 3 with slow.
}
assert (compute_step lib (mk_fresh v t)
= csuccess (mk_fresh v (subst_utokens u0 [(a,mk_var v)]))) as cs.
{ unfold mk_fresh; rw @compute_step_fresh_if_isnoncan_like; auto.
rw <- Heqa; rw comp1; simpl; auto. }
remember (get_fresh_atom (subst_utokens u0 [(a, mk_var v)])) as a'.
applydup @compute_step_preserves in comp1; eauto 3 with slow; repnd;
[|apply nt_wf_subst; eauto 3 with slow].
assert (alpha_eq u0 (subst (subst_utokens u0 [(a, mk_var v)]) v (mk_utoken a))) as aeq.
{ apply alpha_eq_sym.
apply simple_subst_subst_utokens_aeq; auto.
- apply compute_step_preserves_wf in comp1; auto.
apply wf_term_subst; eauto with slow.
- rw subvars_eq in comp3; intro i; apply comp3 in i.
unfsubst in i.
rw @free_vars_lsubst_aux_cl in i; eauto 3 with slow; allsimpl.
rw in_remove_nvars in i; allsimpl; tcsp.
}
pose proof (reduces_in_atmost_k_steps_alpha
lib u0 (subst (subst_utokens u0 [(a, mk_var v)]) v (mk_utoken a))
comp2 aeq k u comp0) as r; exrepnd.
pose proof (get_fresh_atom_prop (subst_utokens u0 [(a,mk_var v)])) as gfa'.
rw <- Heqa' in gfa'.
pose proof (reduces_in_atmost_k_steps_change_utok_sub
lib k (subst_utokens u0 [(a, mk_var v)])
t2' [(v,mk_utoken a)] [(v,mk_utoken a')]) as chu.
repeat (autodimp chu hyp).
{ apply nt_wf_eq; apply wf_subst_utokens; eauto 3 with slow. }
{ apply nr_ut_sub_cons; auto.
introv j i.
apply get_utokens_subst_utokens_subset in i; allsimpl.
unfold get_utokens_utok_ren in i; allsimpl; allrw app_nil_r.
apply in_remove in i; repnd; tcsp. }
{ unfold get_utokens_sub; simpl; apply disjoint_singleton_l.
introv i.
apply get_utokens_subst_utokens_subset in i; allsimpl.
unfold get_utokens_utok_ren in i; allsimpl; allrw app_nil_r.
apply in_remove in i; repnd; tcsp. }
{ unfold get_utokens_sub; simpl; apply disjoint_singleton_l; tcsp. }
exrepnd.
allrw @fold_subst.
pose proof (IHk (subst_utokens u0 [(a, mk_var v)]) v s) as ih.
rw <- Heqa' in ih.
repeat (autodimp ih hyp).
{ apply wf_subst_utokens; eauto 3 with slow. }
exrepnd.
exists z.
dands.
{ eapply reduces_to_trans;[|exact ih1].
apply reduces_to_if_step; auto. }
{ eapply alpha_eq_trans;[exact ih0|].
apply (alpha_eq_subst_utokens _ _ [(a', mk_var v)] [(a', mk_var v)]) in chu1; eauto 3 with slow.
eapply alpha_eq_trans;[exact chu1|].
apply (alpha_eq_subst_utokens _ _ [(a, mk_var v)] [(a, mk_var v)]) in r0; eauto 3 with slow.
eapply alpha_eq_trans;[|apply alpha_eq_sym; exact r0].
apply (alpha_eq_subst_utokens _ _ [(a, mk_var v)] [(a, mk_var v)]) in chu0; eauto 3 with slow.
eapply alpha_eq_trans;[|apply alpha_eq_sym; exact chu0].
allunfold @get_utokens_sub; allsimpl; allrw disjoint_singleton_l.
pose proof (simple_alphaeq_subst_utokens_subst w v a') as h1.
autodimp h1 hyp; tcsp.
pose proof (simple_alphaeq_subst_utokens_subst w v a) as h2.
autodimp h2 hyp; tcsp.
eapply alpha_eq_trans;[exact h1|]; eauto with slow.
}
Qed.
Lemma reduces_to_change_utok_sub {o} :
forall lib (t u : @NTerm o) sub sub',
nt_wf t
-> reduces_to lib (lsubst t sub) u
-> nr_ut_sub t sub
-> nr_ut_sub t sub'
-> dom_sub sub = dom_sub sub'
-> disjoint (get_utokens_sub sub) (get_utokens t)
-> disjoint (get_utokens_sub sub') (get_utokens t)
-> {w, s : NTerm
$ alpha_eq u (lsubst w sub)
# disjoint (get_utokens_sub sub) (get_utokens w)
# subvars (free_vars w) (free_vars t)
# subset (get_utokens w) (get_utokens t)
# reduces_to lib (lsubst t sub') s
# alpha_eq s (lsubst w sub')}.
Proof.
introv wf r nrut1 nrut2 eqdoms d1 d2.
allunfold @reduces_to; exrepnd.
pose proof (reduces_in_atmost_k_steps_change_utok_sub lib k t u sub sub') as h.
repeat (autodimp h hyp); exrepnd.
eexists; eexists; dands; eauto.
Qed.
(*
*** Local Variables:
*** coq-load-path: ("." "../util/" "../terms/")
*** End:
*)
|
/*
* Zero delay memory module for Zet
* Copyright (C) 2008-2010 Zeus Gomez Marmolejo <[email protected]>
*
* This file is part of the Zet processor. This processor is free
* hardware; you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software
* Foundation; either version 3, or (at your option) any later version.
*
* Zet is distrubuted in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Zet; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
module memory (
// Wishbone slave interface
input wb_clk_i,
input wb_rst_i,
input [15:0] wb_dat_i,
output [15:0] wb_dat_o,
input [19:1] wb_adr_i,
input wb_we_i,
input [ 1:0] wb_sel_i,
input wb_stb_i,
input wb_cyc_i,
output wb_ack_o
);
// Registers and nets
reg [15:0] ram[0:2**19-1];
wire we;
wire [7:0] bhw, blw;
// Assignments
assign wb_dat_o = ram[wb_adr_i];
assign wb_ack_o = wb_stb_i;
assign we = wb_we_i & wb_stb_i & wb_cyc_i;
assign bhw = wb_sel_i[1] ? wb_dat_i[15:8]
: ram[wb_adr_i][15:8];
assign blw = wb_sel_i[0] ? wb_dat_i[7:0]
: ram[wb_adr_i][7:0];
// Behaviour
always @(posedge wb_clk_i)
if (we) ram[wb_adr_i] <= { bhw, blw };
endmodule
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Francis Bruno, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, see <http://www.gnu.org/licenses>.
//
// This code is available under licenses for commercial use. Please contact
// Francis Bruno for more information.
//
// http://www.gplgpu.com
// http://www.asicsolutions.com
//
// Title : Memory Controller Host Interface
// File : mc_hst.v
// Author : Frank Bruno
// Created : 30-Dec-2005
// RCS File : $Source:$
// Status : $Id:$
//
//
//////////////////////////////////////////////////////////////////////////////
//
// Description :
// Receives requests from the HBI block in the form of a active high hst_req
// signal. Requests will only be made when our hst_rdy output is asserted
// high. Address, read (data directions), and page count are captured with
// the request. They are then brought across the clock domains to mclock by
// the synchronized request signal. Once in mclock domain, the request is
// made to the RAM arbiter.
//
// In other interface modules, address translation may occur as part of the
// clock domain crossing, but we are already given a linear address from the
// host bus so no extra translation is necessary. Also in other interfaces,
// request may be of up to 32 pages. Requests to the RAM arbiter may only be
// 4 pages, read or write, so large request must be broken up. The HBI only
// ever requests 1 or 2 page writes and 4 page reads, so we don't have to
// break things up, although we must mask out read data so garbage doesn't
// get written for the unused write cycles.
//
//////////////////////////////////////////////////////////////////////////////
//
// Modules Instantiated:
//
///////////////////////////////////////////////////////////////////////////////
//
// Modification History:
//
// $Log:$
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
`timescale 1 ns / 10 ps
module mc_hst
(
input mclock,
input reset_n,
input hst_clock,
input hst_gnt, // Grant back from arbiter
input [22:0] hst_org, // Address for HBI request
input hst_read, // Read/write select for HBI request
input hst_req, // Request from HBI (sync to hst_clock)
input rc_push_en,
input rc_pop_en, /* Should also add a select bus so I know
who the push or pop is for. */
output reg [22:0] hst_arb_addr, // MC internal address to arbiter
output reg hst_pop, // Data increment for write data from HBI
output reg hst_push, // Write enable for read data back to HBI
output reg hst_rdy, /* Ready flag must be asserted before HBI
sends request */
output reg [1:0] hst_mw_addr, // The address to read from MW
output reg [1:0] hst_arb_page, // MC internal page count to arbiter
output reg hst_arb_read, // MC internal r/w select to arbiter
output hst_arb_req // MC internal request to arbiter
);
reg [22:0] capt_addr[1:0];
reg [1:0] capt_read;
reg input_select, output_select, capt_select;
reg [1:0] req_sync_1, req_sync_2, req_sync_3;
reg [1:0] hst_push_cnt;
reg [1:0] busy;
reg [1:0] clear_busy;
reg [1:0] clear_busy0;
reg [1:0] clear_busy1;
reg [1:0] avail_mc;
reg final_select;
reg [1:0] hst_arb_req_int;
assign hst_arb_req = |hst_arb_req_int;
// Implement asynchronous interface and capture registers.
// This process should be the only things that runs on hst_clock.
// It captures the request on hst_clock and generates synchronization logic
// to get back to hst_clock domain. It also generates the ready flag
always @ (posedge hst_clock or negedge reset_n) begin
if(!reset_n) begin
input_select <= 1'b0;
hst_rdy <= 1'b1;
capt_addr[0] <= 23'b0;
capt_addr[1] <= 23'b0;
capt_read <= 2'b0;
busy <= 2'b0;
clear_busy0 <= 2'b0;
clear_busy1 <= 2'b0;
end else begin // if (!reset_n)
clear_busy0 <= clear_busy;
clear_busy1 <= clear_busy0;
hst_rdy <= ~&busy;
// If we detect an edge on either clear, then clear the busy flag
if (clear_busy1[0] ^ clear_busy0[0]) busy[0] <= 1'b0;
if (clear_busy1[1] ^ clear_busy0[1]) busy[1] <= 1'b0;
// Capture registers grab necessary data whenever a new request is made
if (hst_req && ~&busy) begin
input_select <= ~input_select;
busy[input_select] <= 1'b1;
capt_addr[input_select] <= hst_org;
capt_read[input_select] <= hst_read;
hst_rdy <= 1'b0;
end
end // else: !if(!reset_n)
end // always @ (posedge hst_clock)
// This is the main mclock domain process.
// It implements synchronizers to move the request from hst_clock over to
// mclock domain. It also has all the mclock capture registers that forward
// the request on to the arbiter.
always @ (posedge mclock or negedge reset_n) begin
if(!reset_n) begin
hst_arb_req_int<= 1'b0;
req_sync_1 <= 2'b0;
req_sync_2 <= 2'b0;
req_sync_3 <= 2'b0;
avail_mc <= 2'b0;
capt_select <= 1'b0;
output_select <= 1'b0;
clear_busy <= 2'b0;
final_select <= 1'b0;
end else begin
// Triple register the request toggle for clock synchronization
req_sync_1 <= busy;
req_sync_2 <= req_sync_1;
req_sync_3 <= req_sync_2;
if (~req_sync_3[0] && req_sync_2[0]) avail_mc[0] <= 1'b1;
if (~req_sync_3[1] && req_sync_2[1]) avail_mc[1] <= 1'b1;
// A rising or falling transition on the synchronized request toggle
// indicates a new request is in the capture registers. In that case it
// is moved to the arbiter request registers and the request signal to
// the arbiter is asserted.
if (avail_mc[output_select]) begin
// make a new request to the arbiter
output_select <= ~output_select;
hst_arb_req_int[output_select] <= 1'b1;
avail_mc[output_select] <= 1'b0;
end // if (req_sync_2 ^ req_sync_3)
hst_arb_read <= capt_read[capt_select];
hst_arb_page <= capt_read[capt_select] ? 2'h3 : 2'h1;
hst_arb_addr <= capt_addr[capt_select];
// When we get a grant from the arbiter, deassert arbiter request and
// generate the grant toggle that is used to reassert ready.
// I should never get a request and grant in the same cycle
if(hst_gnt) begin
capt_select <= ~capt_select;
hst_arb_req_int[capt_select] <= 1'b0;
end // if (hst_gnt)
if (&hst_push_cnt | hst_mw_addr[0]) begin
clear_busy[final_select] <= ~clear_busy[final_select];
final_select <= ~final_select;
end
end // else: !if(!reset_n)
end // always @ (posedge mclock or negedge reset_n)
// finally, we need a process to forward push's and pop's correctly, and to
// mask writes that are part of the burst, but we don't have any data for.
always @ (posedge mclock or negedge reset_n) begin
if(!reset_n) begin
hst_push <= 1'b0;
hst_pop <= 1'b0;
hst_mw_addr <= 2'b0;
hst_push_cnt <= 2'b0;
end else begin
if (rc_push_en) begin
hst_push <= 1'b1;
hst_push_cnt <= hst_push_cnt + 2'b1;
end else hst_push <= 1'b0;
if (rc_pop_en) begin
hst_pop <= 1'b1;
hst_mw_addr <= hst_mw_addr + 2'b1;
end else hst_pop <= 1'b0;
end // else: !if(!reset_n)
end // always @ (posedge mclock)
endmodule
|
`define bsg_dff_macro(bits,strength) \
if (harden_p && (width_p==bits) && (strength_p==strength)) \
begin: macro \
bsg_rp_tsmc_250_dff_s``strength``_b``bits dff(.*); \
end
module bsg_dff #(width_p=-1, harden_p=1, strength_p=1)
(input clock_i
,input [width_p-1:0] data_i
,output [width_p-1:0] data_o
);
`bsg_dff_macro(80,1) else
`bsg_dff_macro(79,1) else
`bsg_dff_macro(78,1) else
`bsg_dff_macro(77,1) else
`bsg_dff_macro(76,1) else
`bsg_dff_macro(75,1) else
`bsg_dff_macro(74,1) else
`bsg_dff_macro(73,1) else
`bsg_dff_macro(72,1) else
`bsg_dff_macro(71,1) else
`bsg_dff_macro(70,1) else
`bsg_dff_macro(69,1) else
`bsg_dff_macro(68,1) else
`bsg_dff_macro(67,1) else
`bsg_dff_macro(66,1) else
`bsg_dff_macro(65,1) else
`bsg_dff_macro(64,1) else
`bsg_dff_macro(63,1) else
`bsg_dff_macro(62,1) else
`bsg_dff_macro(61,1) else
`bsg_dff_macro(60,1) else
`bsg_dff_macro(59,1) else
`bsg_dff_macro(58,1) else
`bsg_dff_macro(57,1) else
`bsg_dff_macro(56,1) else
`bsg_dff_macro(55,1) else
`bsg_dff_macro(54,1) else
`bsg_dff_macro(53,1) else
`bsg_dff_macro(52,1) else
`bsg_dff_macro(51,1) else
`bsg_dff_macro(50,1) else
`bsg_dff_macro(49,1) else
`bsg_dff_macro(48,1) else
`bsg_dff_macro(47,1) else
`bsg_dff_macro(46,1) else
`bsg_dff_macro(45,1) else
`bsg_dff_macro(44,1) else
`bsg_dff_macro(43,1) else
`bsg_dff_macro(42,1) else
`bsg_dff_macro(41,1) else
`bsg_dff_macro(40,1) else
`bsg_dff_macro(39,1) else
`bsg_dff_macro(38,1) else
`bsg_dff_macro(37,1) else
`bsg_dff_macro(36,1) else
`bsg_dff_macro(35,1) else
`bsg_dff_macro(34,1) else
`bsg_dff_macro(33,1) else
`bsg_dff_macro(32,1) else
`bsg_dff_macro(31,1) else
`bsg_dff_macro(30,1) else
`bsg_dff_macro(29,1) else
`bsg_dff_macro(28,1) else
`bsg_dff_macro(27,1) else
`bsg_dff_macro(26,1) else
`bsg_dff_macro(25,1) else
`bsg_dff_macro(24,1) else
`bsg_dff_macro(23,1) else
`bsg_dff_macro(22,1) else
`bsg_dff_macro(21,1) else
`bsg_dff_macro(20,1) else
`bsg_dff_macro(19,1) else
`bsg_dff_macro(18,1) else
`bsg_dff_macro(17,1) else
`bsg_dff_macro(16,1) else
`bsg_dff_macro(15,1) else
`bsg_dff_macro(14,1) else
`bsg_dff_macro(13,1) else
`bsg_dff_macro(12,1) else
`bsg_dff_macro(11,1) else
`bsg_dff_macro(10,1) else
`bsg_dff_macro(9,1) else
`bsg_dff_macro(8,1) else
`bsg_dff_macro(7,1) else
`bsg_dff_macro(6,1) else
`bsg_dff_macro(5,1) else
`bsg_dff_macro(4,1) else
`bsg_dff_macro(3,1) else
`bsg_dff_macro(2,1) else
`bsg_dff_macro(1,1) else
`bsg_dff_macro(40,2) else
`bsg_dff_macro(39,2) else
`bsg_dff_macro(38,2) else
`bsg_dff_macro(37,2) else
`bsg_dff_macro(36,2) else
`bsg_dff_macro(35,2) else
`bsg_dff_macro(34,2) else
`bsg_dff_macro(33,2) else
`bsg_dff_macro(32,2) else
`bsg_dff_macro(31,2) else
`bsg_dff_macro(30,2) else
`bsg_dff_macro(29,2) else
`bsg_dff_macro(28,2) else
`bsg_dff_macro(27,2) else
`bsg_dff_macro(26,2) else
`bsg_dff_macro(25,2) else
`bsg_dff_macro(24,2) else
`bsg_dff_macro(23,2) else
`bsg_dff_macro(22,2) else
`bsg_dff_macro(21,2) else
`bsg_dff_macro(20,2) else
`bsg_dff_macro(19,2) else
`bsg_dff_macro(18,2) else
`bsg_dff_macro(17,2) else
`bsg_dff_macro(16,2) else
`bsg_dff_macro(15,2) else
`bsg_dff_macro(14,2) else
`bsg_dff_macro(13,2) else
`bsg_dff_macro(12,2) else
`bsg_dff_macro(11,2) else
`bsg_dff_macro(10,2) else
`bsg_dff_macro(9,2) else
`bsg_dff_macro(8,2) else
`bsg_dff_macro(7,2) else
`bsg_dff_macro(6,2) else
`bsg_dff_macro(5,2) else
`bsg_dff_macro(4,2) else
`bsg_dff_macro(3,2) else
`bsg_dff_macro(2,2) else
`bsg_dff_macro(1,2) else
`bsg_dff_macro(40,4) else
`bsg_dff_macro(39,4) else
`bsg_dff_macro(38,4) else
`bsg_dff_macro(37,4) else
`bsg_dff_macro(36,4) else
`bsg_dff_macro(35,4) else
`bsg_dff_macro(34,4) else
`bsg_dff_macro(33,4) else
`bsg_dff_macro(32,4) else
`bsg_dff_macro(31,4) else
`bsg_dff_macro(30,4) else
`bsg_dff_macro(29,4) else
`bsg_dff_macro(28,4) else
`bsg_dff_macro(27,4) else
`bsg_dff_macro(26,4) else
`bsg_dff_macro(25,4) else
`bsg_dff_macro(24,4) else
`bsg_dff_macro(23,4) else
`bsg_dff_macro(22,4) else
`bsg_dff_macro(21,4) else
`bsg_dff_macro(20,4) else
`bsg_dff_macro(19,4) else
`bsg_dff_macro(18,4) else
`bsg_dff_macro(17,4) else
`bsg_dff_macro(16,4) else
`bsg_dff_macro(15,4) else
`bsg_dff_macro(14,4) else
`bsg_dff_macro(13,4) else
`bsg_dff_macro(12,4) else
`bsg_dff_macro(11,4) else
`bsg_dff_macro(10,4) else
`bsg_dff_macro(9,4) else
`bsg_dff_macro(8,4) else
`bsg_dff_macro(7,4) else
`bsg_dff_macro(6,4) else
`bsg_dff_macro(5,4) else
`bsg_dff_macro(4,4) else
`bsg_dff_macro(3,4) else
`bsg_dff_macro(2,4) else
`bsg_dff_macro(1,4) else
`bsg_dff_macro(32,2)
else
`bsg_dff_macro(32,8)
else
begin: notmacro
reg [width_p-1:0] data_r;
assign data_o = data_r;
always @(posedge clock_i)
data_r <= data_i;
end
endmodule
`BSG_ABSTRACT_MODULE(bsg_dff)
|
// Copyright 1986-2018 Xilinx, Inc. All Rights Reserved.
// --------------------------------------------------------------------------------
// Tool Version: Vivado v.2018.2 (win64) Build 2258646 Thu Jun 14 20:03:12 MDT 2018
// Date : Sun Sep 22 02:35:49 2019
// Host : varun-laptop running 64-bit Service Pack 1 (build 7601)
// Command : write_verilog -force -mode synth_stub
// d:/github/Digital-Hardware-Modelling/xilinx-vivado/hls_tutorial_lab1/hls_tutorial_lab1.srcs/sources_1/bd/zybo_zynq_design/ip/zybo_zynq_design_auto_pc_0/zybo_zynq_design_auto_pc_0_stub.v
// Design : zybo_zynq_design_auto_pc_0
// Purpose : Stub declaration of top-level module interface
// Device : xc7z010clg400-1
// --------------------------------------------------------------------------------
// This empty module with port declaration file causes synthesis tools to infer a black box for IP.
// The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion.
// Please paste the declaration into a Verilog source file or add the file as an additional source.
(* X_CORE_INFO = "axi_protocol_converter_v2_1_17_axi_protocol_converter,Vivado 2018.2" *)
module zybo_zynq_design_auto_pc_0(aclk, aresetn, s_axi_awid, s_axi_awaddr,
s_axi_awlen, s_axi_awsize, s_axi_awburst, s_axi_awlock, s_axi_awcache, s_axi_awprot,
s_axi_awqos, s_axi_awvalid, s_axi_awready, s_axi_wid, s_axi_wdata, s_axi_wstrb, s_axi_wlast,
s_axi_wvalid, s_axi_wready, s_axi_bid, s_axi_bresp, s_axi_bvalid, s_axi_bready, s_axi_arid,
s_axi_araddr, s_axi_arlen, s_axi_arsize, s_axi_arburst, s_axi_arlock, s_axi_arcache,
s_axi_arprot, s_axi_arqos, s_axi_arvalid, s_axi_arready, s_axi_rid, s_axi_rdata, s_axi_rresp,
s_axi_rlast, s_axi_rvalid, s_axi_rready, m_axi_awaddr, m_axi_awprot, m_axi_awvalid,
m_axi_awready, m_axi_wdata, m_axi_wstrb, m_axi_wvalid, m_axi_wready, m_axi_bresp,
m_axi_bvalid, m_axi_bready, m_axi_araddr, m_axi_arprot, m_axi_arvalid, m_axi_arready,
m_axi_rdata, m_axi_rresp, m_axi_rvalid, m_axi_rready)
/* synthesis syn_black_box black_box_pad_pin="aclk,aresetn,s_axi_awid[11:0],s_axi_awaddr[31:0],s_axi_awlen[3:0],s_axi_awsize[2:0],s_axi_awburst[1:0],s_axi_awlock[1:0],s_axi_awcache[3:0],s_axi_awprot[2:0],s_axi_awqos[3:0],s_axi_awvalid,s_axi_awready,s_axi_wid[11:0],s_axi_wdata[31:0],s_axi_wstrb[3:0],s_axi_wlast,s_axi_wvalid,s_axi_wready,s_axi_bid[11:0],s_axi_bresp[1:0],s_axi_bvalid,s_axi_bready,s_axi_arid[11:0],s_axi_araddr[31:0],s_axi_arlen[3:0],s_axi_arsize[2:0],s_axi_arburst[1:0],s_axi_arlock[1:0],s_axi_arcache[3:0],s_axi_arprot[2:0],s_axi_arqos[3:0],s_axi_arvalid,s_axi_arready,s_axi_rid[11:0],s_axi_rdata[31:0],s_axi_rresp[1:0],s_axi_rlast,s_axi_rvalid,s_axi_rready,m_axi_awaddr[31:0],m_axi_awprot[2:0],m_axi_awvalid,m_axi_awready,m_axi_wdata[31:0],m_axi_wstrb[3:0],m_axi_wvalid,m_axi_wready,m_axi_bresp[1:0],m_axi_bvalid,m_axi_bready,m_axi_araddr[31:0],m_axi_arprot[2:0],m_axi_arvalid,m_axi_arready,m_axi_rdata[31:0],m_axi_rresp[1:0],m_axi_rvalid,m_axi_rready" */;
input aclk;
input aresetn;
input [11:0]s_axi_awid;
input [31:0]s_axi_awaddr;
input [3:0]s_axi_awlen;
input [2:0]s_axi_awsize;
input [1:0]s_axi_awburst;
input [1:0]s_axi_awlock;
input [3:0]s_axi_awcache;
input [2:0]s_axi_awprot;
input [3:0]s_axi_awqos;
input s_axi_awvalid;
output s_axi_awready;
input [11:0]s_axi_wid;
input [31:0]s_axi_wdata;
input [3:0]s_axi_wstrb;
input s_axi_wlast;
input s_axi_wvalid;
output s_axi_wready;
output [11:0]s_axi_bid;
output [1:0]s_axi_bresp;
output s_axi_bvalid;
input s_axi_bready;
input [11:0]s_axi_arid;
input [31:0]s_axi_araddr;
input [3:0]s_axi_arlen;
input [2:0]s_axi_arsize;
input [1:0]s_axi_arburst;
input [1:0]s_axi_arlock;
input [3:0]s_axi_arcache;
input [2:0]s_axi_arprot;
input [3:0]s_axi_arqos;
input s_axi_arvalid;
output s_axi_arready;
output [11:0]s_axi_rid;
output [31:0]s_axi_rdata;
output [1:0]s_axi_rresp;
output s_axi_rlast;
output s_axi_rvalid;
input s_axi_rready;
output [31:0]m_axi_awaddr;
output [2:0]m_axi_awprot;
output m_axi_awvalid;
input m_axi_awready;
output [31:0]m_axi_wdata;
output [3:0]m_axi_wstrb;
output m_axi_wvalid;
input m_axi_wready;
input [1:0]m_axi_bresp;
input m_axi_bvalid;
output m_axi_bready;
output [31:0]m_axi_araddr;
output [2:0]m_axi_arprot;
output m_axi_arvalid;
input m_axi_arready;
input [31:0]m_axi_rdata;
input [1:0]m_axi_rresp;
input m_axi_rvalid;
output m_axi_rready;
endmodule
|
// -*- Mode: Verilog -*-
// Filename : adc_clk_gen.v
// Description : ADC Clock Generator
// Author : Philip Tracton
// Created On : Tue Dec 22 21:44:39 2015
// Last Modified By: Philip Tracton
// Last Modified On: Tue Dec 22 21:44:39 2015
// Update Count : 0
// Status : Unknown, Use with caution!
module adc_clk_gen (/*AUTOARG*/
// Outputs
adc_clk,
// Inputs
wb_clk, rst_pad_i, clk_speed_select
) ;
input wb_clk;
input rst_pad_i;
input [2:0] clk_speed_select;
output reg adc_clk;
reg [15:0] adc_clk_count;
wire [7:0] adc_clk_count_terminal = (1 << clk_speed_select)-1;
always @(posedge wb_clk)
if (rst_pad_i) begin
adc_clk <= 0;
adc_clk_count <= 0;
end else begin
adc_clk_count <= adc_clk_count+1;
if (adc_clk_count >= adc_clk_count_terminal) begin
adc_clk <= ~adc_clk;
adc_clk_count <= 0;
end
end
endmodule // adc_clk_gen
|
// Copyright 1986-2016 Xilinx, Inc. All Rights Reserved.
// --------------------------------------------------------------------------------
// Tool Version: Vivado v.2016.3 (win64) Build 1682563 Mon Oct 10 19:07:27 MDT 2016
// Date : Wed Sep 27 18:05:22 2017
// Host : vldmr-PC running 64-bit Service Pack 1 (build 7601)
// Command : write_verilog -force -mode synth_stub -rename_top decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix -prefix
// decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix_ dbg_ila_stub.v
// Design : dbg_ila
// Purpose : Stub declaration of top-level module interface
// Device : xc7k325tffg676-1
// --------------------------------------------------------------------------------
// This empty module with port declaration file causes synthesis tools to infer a black box for IP.
// The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion.
// Please paste the declaration into a Verilog source file or add the file as an additional source.
(* X_CORE_INFO = "ila,Vivado 2016.3" *)
module decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix(clk, probe0, probe1, probe2, probe3, probe4, probe5,
probe6, probe7, probe8, probe9, probe10, probe11, probe12, probe13, probe14, probe15, probe16, probe17,
probe18, probe19, probe20, probe21, probe22, probe23, probe24, probe25)
/* synthesis syn_black_box black_box_pad_pin="clk,probe0[63:0],probe1[63:0],probe2[0:0],probe3[0:0],probe4[0:0],probe5[0:0],probe6[0:0],probe7[63:0],probe8[0:0],probe9[0:0],probe10[0:0],probe11[0:0],probe12[63:0],probe13[0:0],probe14[0:0],probe15[0:0],probe16[0:0],probe17[0:0],probe18[7:0],probe19[8:0],probe20[0:0],probe21[2:0],probe22[2:0],probe23[0:0],probe24[7:0],probe25[0:0]" */;
input clk;
input [63:0]probe0;
input [63:0]probe1;
input [0:0]probe2;
input [0:0]probe3;
input [0:0]probe4;
input [0:0]probe5;
input [0:0]probe6;
input [63:0]probe7;
input [0:0]probe8;
input [0:0]probe9;
input [0:0]probe10;
input [0:0]probe11;
input [63:0]probe12;
input [0:0]probe13;
input [0:0]probe14;
input [0:0]probe15;
input [0:0]probe16;
input [0:0]probe17;
input [7:0]probe18;
input [8:0]probe19;
input [0:0]probe20;
input [2:0]probe21;
input [2:0]probe22;
input [0:0]probe23;
input [7:0]probe24;
input [0:0]probe25;
endmodule
|
`ifndef _regstatus
`define _regstatus
// two read ports, two write port
module regstatus (
input clk,
input rst,
input wr_regs_en,
input [4:0] wr_regs_tag,
input [3:0] wr_regs_rb_tag,
input [4:0] rd_reg_tag1,
input [4:0] rd_reg_tag2,
input commit_en,
input [4:0] commit_reg_tag,
input flush_regs,
output [3:0] rd_rb_tag1,
output rd_bsy1,
output [3:0] rd_rb_tag2,
output rd_bsy2
);
typedef struct packed {
bit [3:0] rb_tag;
bit bsy;
}regstatusStruct;
regstatusStruct regs_array [31:0];
always @(posedge clk, negedge rst) begin
if (!rst) begin
for ( int i = 0; i < $size(regs_array); i++) begin
regs_array[i] <= {$size(regstatusStruct){1'b0}};
end
end
else begin
if (flush_regs) begin
for ( int i = 0; i < $size(regs_array); i++) begin
regs_array[i] <= {$size(regstatusStruct){1'b0}};
end
end
else begin
if (wr_regs_en) begin
regs_array[wr_regs_tag].rb_tag <= wr_regs_rb_tag;
regs_array[wr_regs_tag].bsy <= 1'b1;
end
if (commit_en) begin
//wr_regs_en has higher priority
if (!(wr_regs_en && wr_regs_tag == commit_reg_tag)) begin
regs_array[commit_reg_tag].bsy <= 1'b0;
end
end
end
end
end // always @ (posedge clk, negedge rst)
assign rd_rb_tag1 = regs_array[rd_reg_tag1].rb_tag;
assign rd_bsy1 = regs_array[rd_reg_tag1].bsy;
assign rd_rb_tag2 = regs_array[rd_reg_tag2].rb_tag;
assign rd_bsy2 = regs_array[rd_reg_tag2].bsy;
endmodule // regstatus
`endif
|
/*******************************************************************************
* This file is owned and controlled by Xilinx and must be used solely *
* for design, simulation, implementation and creation of design files *
* limited to Xilinx devices or technologies. Use with non-Xilinx *
* devices or technologies is expressly prohibited and immediately *
* terminates your license. *
* *
* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" SOLELY *
* FOR USE IN DEVELOPING PROGRAMS AND SOLUTIONS FOR XILINX DEVICES. BY *
* PROVIDING THIS DESIGN, CODE, OR INFORMATION AS ONE POSSIBLE *
* IMPLEMENTATION OF THIS FEATURE, APPLICATION OR STANDARD, XILINX IS *
* MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION IS FREE FROM ANY *
* CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE FOR OBTAINING ANY *
* RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. XILINX EXPRESSLY *
* DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO THE ADEQUACY OF THE *
* IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OR *
* REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM CLAIMS OF *
* INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE. *
* *
* Xilinx products are not intended for use in life support appliances, *
* devices, or systems. Use in such applications are expressly *
* prohibited. *
* *
* (c) Copyright 1995-2016 Xilinx, Inc. *
* All rights reserved. *
*******************************************************************************/
// You must compile the wrapper file car.v when simulating
// the core, car. When compiling the wrapper file, be sure to
// reference the XilinxCoreLib Verilog simulation library. For detailed
// instructions, please refer to the "CORE Generator Help".
// The synthesis directives "translate_off/translate_on" specified below are
// supported by Xilinx, Mentor Graphics and Synplicity synthesis
// tools. Ensure they are correct for your synthesis tool(s).
`timescale 1ns/1ps
module car(
clka,
addra,
douta
);
input clka;
input [12 : 0] addra;
output [11 : 0] douta;
// synthesis translate_off
BLK_MEM_GEN_V7_3 #(
.C_ADDRA_WIDTH(13),
.C_ADDRB_WIDTH(13),
.C_ALGORITHM(1),
.C_AXI_ID_WIDTH(4),
.C_AXI_SLAVE_TYPE(0),
.C_AXI_TYPE(1),
.C_BYTE_SIZE(9),
.C_COMMON_CLK(0),
.C_DEFAULT_DATA("0"),
.C_DISABLE_WARN_BHV_COLL(0),
.C_DISABLE_WARN_BHV_RANGE(0),
.C_ENABLE_32BIT_ADDRESS(0),
.C_FAMILY("artix7"),
.C_HAS_AXI_ID(0),
.C_HAS_ENA(0),
.C_HAS_ENB(0),
.C_HAS_INJECTERR(0),
.C_HAS_MEM_OUTPUT_REGS_A(0),
.C_HAS_MEM_OUTPUT_REGS_B(0),
.C_HAS_MUX_OUTPUT_REGS_A(0),
.C_HAS_MUX_OUTPUT_REGS_B(0),
.C_HAS_REGCEA(0),
.C_HAS_REGCEB(0),
.C_HAS_RSTA(0),
.C_HAS_RSTB(0),
.C_HAS_SOFTECC_INPUT_REGS_A(0),
.C_HAS_SOFTECC_OUTPUT_REGS_B(0),
.C_INIT_FILE("BlankString"),
.C_INIT_FILE_NAME("car.mif"),
.C_INITA_VAL("0"),
.C_INITB_VAL("0"),
.C_INTERFACE_TYPE(0),
.C_LOAD_INIT_FILE(1),
.C_MEM_TYPE(3),
.C_MUX_PIPELINE_STAGES(0),
.C_PRIM_TYPE(1),
.C_READ_DEPTH_A(6000),
.C_READ_DEPTH_B(6000),
.C_READ_WIDTH_A(12),
.C_READ_WIDTH_B(12),
.C_RST_PRIORITY_A("CE"),
.C_RST_PRIORITY_B("CE"),
.C_RST_TYPE("SYNC"),
.C_RSTRAM_A(0),
.C_RSTRAM_B(0),
.C_SIM_COLLISION_CHECK("ALL"),
.C_USE_BRAM_BLOCK(0),
.C_USE_BYTE_WEA(0),
.C_USE_BYTE_WEB(0),
.C_USE_DEFAULT_DATA(0),
.C_USE_ECC(0),
.C_USE_SOFTECC(0),
.C_WEA_WIDTH(1),
.C_WEB_WIDTH(1),
.C_WRITE_DEPTH_A(6000),
.C_WRITE_DEPTH_B(6000),
.C_WRITE_MODE_A("WRITE_FIRST"),
.C_WRITE_MODE_B("WRITE_FIRST"),
.C_WRITE_WIDTH_A(12),
.C_WRITE_WIDTH_B(12),
.C_XDEVICEFAMILY("artix7")
)
inst (
.CLKA(clka),
.ADDRA(addra),
.DOUTA(douta),
.RSTA(),
.ENA(),
.REGCEA(),
.WEA(),
.DINA(),
.CLKB(),
.RSTB(),
.ENB(),
.REGCEB(),
.WEB(),
.ADDRB(),
.DINB(),
.DOUTB(),
.INJECTSBITERR(),
.INJECTDBITERR(),
.SBITERR(),
.DBITERR(),
.RDADDRECC(),
.S_ACLK(),
.S_ARESETN(),
.S_AXI_AWID(),
.S_AXI_AWADDR(),
.S_AXI_AWLEN(),
.S_AXI_AWSIZE(),
.S_AXI_AWBURST(),
.S_AXI_AWVALID(),
.S_AXI_AWREADY(),
.S_AXI_WDATA(),
.S_AXI_WSTRB(),
.S_AXI_WLAST(),
.S_AXI_WVALID(),
.S_AXI_WREADY(),
.S_AXI_BID(),
.S_AXI_BRESP(),
.S_AXI_BVALID(),
.S_AXI_BREADY(),
.S_AXI_ARID(),
.S_AXI_ARADDR(),
.S_AXI_ARLEN(),
.S_AXI_ARSIZE(),
.S_AXI_ARBURST(),
.S_AXI_ARVALID(),
.S_AXI_ARREADY(),
.S_AXI_RID(),
.S_AXI_RDATA(),
.S_AXI_RRESP(),
.S_AXI_RLAST(),
.S_AXI_RVALID(),
.S_AXI_RREADY(),
.S_AXI_INJECTSBITERR(),
.S_AXI_INJECTDBITERR(),
.S_AXI_SBITERR(),
.S_AXI_DBITERR(),
.S_AXI_RDADDRECC()
);
// synthesis translate_on
endmodule
|
module SPI_AD(
input SPI_CLK,
input New_Word,
input [12:0] Addr,
input [7:0] Data,
output reg [7:0] q,
input RW, //1 Write; 0 :read
output reg SPI_CS,
inout reg SPI_Data,
output reg Over
);
reg [15:0] CMD;
reg [7:0] Wr_Data;
reg [7:0] SPI_Counter;
always @(negedge SPI_CLK or posedge New_Word ) begin
if(New_Word) begin
CMD <={RW,1'b0,1'b0,Addr[12:0]};
Wr_Data <= Data;
SPI_Counter <= 8'd0;
Over <= 1'b0;
SPI_CS <= 1'b1;
SPI_Data <= 1'b0;
end
else begin
if(SPI_Counter <8'd16) begin // first CMD
SPI_Counter <= SPI_Counter + 1'b1;
SPI_Data <= CMD[15];
CMD <= CMD <<1;
SPI_CS <= 1'b0;
q <= 8'd00;
end
else if(SPI_Counter <8'd24) begin //Data
SPI_Counter <= SPI_Counter + 1'b1;
if(RW) begin
q <= {q[6:0],SPI_Data};
SPI_Data <= 1'bz;
end
else begin
SPI_Data <= Wr_Data[7];
Wr_Data <= Wr_Data <<1;
end
SPI_CS <= 1'b0;
end
else if(SPI_Counter <8'd25) begin //Data
SPI_Counter <= SPI_Counter + 1'b1;
if(RW) begin
q <= {q[6:0],SPI_Data};
SPI_Data <= 1'bz;
end
SPI_CS <= 1'b1;
end
else if(SPI_Counter <8'd32) begin // interval
SPI_Counter <= SPI_Counter + 1'b1;
SPI_CS <= 1'b1;
SPI_Data <= 1'bz;
Over <= 1'b1;
end
else begin
SPI_Data <= 1'bz;
SPI_CS <= 1'b1;
Over <= 1'b1;
end
end
end
endmodule
|
//
// Copyright (c) 2015 Jan Adelsbach <[email protected]>.
// All Rights Reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
`include "pdp1_defs.v"
module pdp1_alu(al_op, al_a, al_b, al_r, al_ovfl, al_w);
parameter pdp_model = "PDP-1D";
input [0:4] al_op;
input [0:17] al_a;
input [0:17] al_b;
output reg [0:17] al_r;
output reg al_ovfl;
output reg al_w;
wire [0:17] w_add_opa;
wire [0:17] w_add_opb;
assign w_add_opa = (al_op == `PDP1_OP_ISP |
al_op == `PDP1_OP_IDX) ? 18'h1 : al_a;
assign w_add_opb = (al_op == `PDP1_OP_SUB) ? ~al_b : al_b;
wire [0:17] w_add_immed1;
wire [0:17] w_add_result;
wire [0:17] w_add_normalized;
wire w_add_ovfl;
assign {w_add_ovfl, w_add_immed1} = w_add_opa + w_add_opb;
assign w_add_result = (w_add_ovfl) ? (w_add_immed1) + 1 : w_add_immed1;
assign w_add_normalized = (&w_add_result) ? 18'h0 : w_add_result;
always @(al_op or al_a or al_b or w_add_result or
w_add_normalized or w_add_ovfl) begin
al_w = 1'b1;
case(al_op)
`PDP1_OP_ADD,
`PDP1_OP_SUB:
begin
al_r <= w_add_normalized;
al_ovfl <= (~w_add_opa[0] ^ w_add_opb[0]) &
(w_add_opa[0] ^ w_add_result[0]);
end
`PDP1_OP_ISP,
`PDP1_OP_IDX:
begin
al_r <= w_add_normalized;
al_ovfl <= 0;
end
`PDP1_OP_AND:
al_r <= al_a & al_b;
`PDP1_OP_XOR:
al_r <= al_a ^ al_b;
`PDP1_OP_IOR:
al_r <= al_a | al_b;
default:
{al_ovfl, al_r, al_w} <= 0;
endcase // case (al_op)
end
endmodule // pdp1_alu
|
// ========== Copyright Header Begin ==========================================
//
// OpenSPARC T1 Processor File: bw_ctu_pad_cluster.v
// Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
//
// The above named program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License version 2 as published by the Free Software Foundation.
//
// The above named program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this work; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// ========== Copyright Header End ============================================
//
// Unit Name: bw_ctu_pad_cluster
// Block Name: ctu_pad_cluster
//
//-----------------------------------------------------------------------------
`include "sys.h"
module bw_ctu_pad_cluster (
// Inouts:
jclk , // Differential System Clock Inputs
tsr_testio , // Tempsensor test signals
vddo , // 1.5V vdd
vdda // 1.8V analog vdd
);
inout [1:0] jclk;
inout [1:0] tsr_testio;
inout vddo;
inout vdda;
//synopsys translate_off
//synopsys translate_on
endmodule
|
/*
* Copyright 2012, Homer Hsing <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
`define M 97 // M is the degree of the irreducible polynomial
`define WIDTH (2*`M-1) // width for a GF(3^M) element
/* PE: processing element */
module PE(clk, reset, ctrl, d0, d1, d2, out);
input clk;
input reset;
input [10:0] ctrl;
input [197:0] d0;
input [`WIDTH:0] d1, d2;
output [`WIDTH:0] out;
reg [197:0] R0;
reg [`WIDTH:0] R1, R2, R3;
wire [1:0] e0, e1, e2; /* part of R0 */
wire [`WIDTH:0] ppg0, ppg1, ppg2, /* output of PPG */
mx0, mx1, mx2, mx3, mx4, mx5, mx6, /* output of MUX */
ad0, ad1, ad2, /* output of GF(3^m) adder */
cu0, cu1, cu2, /* output of cubic */
mo0, mo1, mo2, /* output of mod_p */
t0, t1, t2;
wire c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10;
assign {c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10} = ctrl;
assign mx0 = c0 ? d1 : ad2;
assign mx1 = c2 ? d2 : ad2;
always @ (posedge clk)
if(reset) R1 <= 0;
else if (c1) R1 <= mx0;
always @ (posedge clk)
if(reset) R2 <= 0;
else if (c3) R2 <= mx1;
always @ (posedge clk)
if(reset) R0 <= 0;
else if (c4) R0 <= d0;
else if (c5) R0 <= R0 << 6;
assign {e2,e1,e0} = R0[197:192];
PPG
ppg_0 (e0, R1, ppg0),
ppg_1 (e1, R2, ppg1),
ppg_2 (e2, R1, ppg2);
v0 v0_ (ppg0, cu0);
v1 v1_ (ppg1, cu1);
v2 v2_ (ppg2, cu2);
assign mx2 = c6 ? ppg0 : cu0;
assign mx3 = c6 ? ppg1 : cu1;
assign mx4 = c6 ? mo1 : cu2;
assign mx5 = c7 ? mo2 : R3;
mod_p
mod_p_0 (mx3, mo0),
mod_p_1 (ppg2, t0),
mod_p_2 (t0, mo1),
mod_p_3 (R3, t1),
mod_p_4 (t1, t2),
mod_p_5 (t2, mo2);
assign mx6 = c9 ? mo0 : mx3;
f3m_add
f3m_add_0 (mx2, mx6, ad0),
f3m_add_1 (mx4, c8 ? mx5 : 0, ad1),
f3m_add_2 (ad0, ad1, ad2);
always @ (posedge clk)
if (reset) R3 <= 0;
else if (c10) R3 <= ad2;
else R3 <= 0; /* change */
assign out = R3;
endmodule
// C = (x*B mod p(x))
module mod_p(B, C);
input [`WIDTH:0] B;
output [`WIDTH:0] C;
wire [`WIDTH+2:0] A;
assign A = {B[`WIDTH:0], 2'd0}; // A == B*x
wire [1:0] w0;
f3_mult m0 (A[195:194], 2'd2, w0);
f3_add s0 (A[1:0], {w0[0], w0[1]}, C[1:0]); //f3_sub s0 (A[1:0], w0, C[1:0]);
assign C[23:2] = A[23:2];
wire [1:0] w12;
f3_mult m12 (A[195:194], 2'd1, w12);
f3_add s12 (A[25:24], {w12[0], w12[1]}, C[25:24]); // f3_sub s12 (A[25:24], w12, C[25:24]);
assign C[193:26] = A[193:26];
endmodule
// PPG: partial product generator, C == A*d in GF(3^m)
module PPG(d, A, C);
input [1:0] d;
input [`WIDTH:0] A;
output [`WIDTH:0] C;
genvar i;
generate
for (i=0; i < `M; i=i+1)
begin: ppg0
f3_mult f3_mult_0 (d, A[2*i+1:2*i], C[2*i+1:2*i]);
end
endgenerate
endmodule
// f3m_add: C = A + B, in field F_{3^M}
module f3m_add(A, B, C);
input [`WIDTH : 0] A, B;
output [`WIDTH : 0] C;
genvar i;
generate
for(i=0; i<`M; i=i+1) begin: aa
f3_add aa(A[(2*i+1) : 2*i], B[(2*i+1) : 2*i], C[(2*i+1) : 2*i]);
end
endgenerate
endmodule
// f3_add: C == A+B (mod 3)
module f3_add(A, B, C);
input [1:0] A, B;
output [1:0] C;
wire a0, a1, b0, b1, c0, c1;
assign {a1, a0} = A;
assign {b1, b0} = B;
assign C = {c1, c0};
assign c0 = ( a0 & ~a1 & ~b0 & ~b1) |
(~a0 & ~a1 & b0 & ~b1) |
(~a0 & a1 & ~b0 & b1) ;
assign c1 = (~a0 & a1 & ~b0 & ~b1) |
( a0 & ~a1 & b0 & ~b1) |
(~a0 & ~a1 & ~b0 & b1) ;
endmodule
// f3_mult: C = A*B (mod 3)
module f3_mult(A, B, C);
input [1:0] A;
input [1:0] B;
output [1:0] C;
wire a0, a1, b0, b1;
assign {a1, a0} = A;
assign {b1, b0} = B;
assign C[0] = (~a1 & a0 & ~b1 & b0) | (a1 & ~a0 & b1 & ~b0);
assign C[1] = (~a1 & a0 & b1 & ~b0) | (a1 & ~a0 & ~b1 & b0);
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HDLL__A31OI_BLACKBOX_V
`define SKY130_FD_SC_HDLL__A31OI_BLACKBOX_V
/**
* a31oi: 3-input AND into first input of 2-input NOR.
*
* Y = !((A1 & A2 & A3) | B1)
*
* Verilog stub definition (black box without power pins).
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_hdll__a31oi (
Y ,
A1,
A2,
A3,
B1
);
output Y ;
input A1;
input A2;
input A3;
input B1;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
supply1 VPB ;
supply0 VNB ;
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_HDLL__A31OI_BLACKBOX_V
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HS__DFSBP_2_V
`define SKY130_FD_SC_HS__DFSBP_2_V
/**
* dfsbp: Delay flop, inverted set, complementary outputs.
*
* Verilog wrapper for dfsbp with size of 2 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_hs__dfsbp.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hs__dfsbp_2 (
CLK ,
D ,
Q ,
Q_N ,
SET_B,
VPWR ,
VGND
);
input CLK ;
input D ;
output Q ;
output Q_N ;
input SET_B;
input VPWR ;
input VGND ;
sky130_fd_sc_hs__dfsbp base (
.CLK(CLK),
.D(D),
.Q(Q),
.Q_N(Q_N),
.SET_B(SET_B),
.VPWR(VPWR),
.VGND(VGND)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hs__dfsbp_2 (
CLK ,
D ,
Q ,
Q_N ,
SET_B
);
input CLK ;
input D ;
output Q ;
output Q_N ;
input SET_B;
// Voltage supply signals
supply1 VPWR;
supply0 VGND;
sky130_fd_sc_hs__dfsbp base (
.CLK(CLK),
.D(D),
.Q(Q),
.Q_N(Q_N),
.SET_B(SET_B)
);
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_HS__DFSBP_2_V
|
module top (
input CLK,
input RX,
output TX,
output reg LED1,
output reg LED2,
output reg LED3,
output reg LED4,
output reg LED5
);
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ_HZ = 12000000;
localparam integer HALF_PERIOD = CLOCK_FREQ_HZ / (2 * BAUD_RATE);
reg [7:0] buffer;
reg buffer_valid;
reg [$clog2(3*HALF_PERIOD):0] cycle_cnt;
reg [3:0] bit_cnt = 0;
reg recv = 0;
initial begin
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
end
always @(posedge CLK) begin
buffer_valid <= 0;
if (!recv) begin
if (!RX) begin
cycle_cnt <= HALF_PERIOD;
bit_cnt <= 0;
recv <= 1;
end
end else begin
if (cycle_cnt == 2*HALF_PERIOD) begin
cycle_cnt <= 0;
bit_cnt <= bit_cnt + 1;
if (bit_cnt == 9) begin
buffer_valid <= 1;
recv <= 0;
end else begin
buffer <= {RX, buffer[7:1]};
end
end else begin
cycle_cnt <= cycle_cnt + 1;
end
end
end
always @(posedge CLK) begin
if (buffer_valid) begin
if (buffer == "1") LED1 <= !LED1;
if (buffer == "2") LED2 <= !LED2;
if (buffer == "3") LED3 <= !LED3;
if (buffer == "4") LED4 <= !LED4;
if (buffer == "5") LED5 <= !LED5;
end
end
assign TX = RX;
endmodule
|
module aes_8_bit (rst, clk, key_in, d_in, d_out, d_vld);
input rst, clk;
input [7:0] key_in;
input [7:0] d_in;
output [7:0] d_out;
output reg d_vld;
//key scheduler controller
wire [3:0] round_cnt_w;
reg input_sel, sbox_sel, last_out_sel, bit_out_sel;
reg [7:0] rcon_en;
reg [3:0] cnt;
reg [7:0] round_cnt;
reg [2:0] state;
wire [7:0] rk_delayed_out, rk_last_out;
reg [1:0] c3;
wire pld;
reg [7:0] mc_en_reg;
reg pld_reg;
wire [7:0] mc_en;
reg [7:0] d_out;
wire [7:0] d_out_w;
always @ (posedge clk)
begin
d_out <= d_out_w;
end
assign pld = pld_reg;
assign mc_en = mc_en_reg;
assign round_cnt_w = round_cnt[7:4];
key_expansion key (key_in, rk_delayed_out, round_cnt_w, rk_last_out, clk, input_sel, sbox_sel, last_out_sel, bit_out_sel, rcon_en);
aes_data_path data_path (d_in, d_out_w, pld, c3, clk, mc_en, rk_delayed_out, rk_last_out);
parameter load = 3'h0; //load 16 byte
parameter b1st = 3'h1; //first byte need rcon
parameter b2nd = 3'h2; //2byte go through sbox
parameter b3rd = 3'h3; //last byte go through sbox from redundant register
parameter norm = 3'h4; //normal round calculate two columns
parameter shif = 3'h5; //shift 4 byte
//state machine for key schedule
always @ (posedge clk)
begin
if (rst == 1'b1)
begin
state <= load;
cnt <= 4'h0;
end
else
begin
case (state)
load:
begin
cnt <= cnt + 4'h1;
if (cnt == 4'hf)
begin
state <= b1st;
cnt <= 4'h0;
end
end
b1st:
begin
state <= b2nd;
cnt <= 4'h0;
end
b2nd:
begin
cnt <= cnt + 4'h1;
if (cnt == 4'h1)
begin
state <= b3rd;
cnt <= 4'h0;
end
end
b3rd:
begin
state <= norm;
cnt <= 4'h0;
end
norm:
begin
cnt <= cnt + 4'h1;
if(cnt == 4'h7)
begin
state <= shif;
cnt <= 4'h0;
end
end
shif:
begin
cnt <= cnt + 4'h1;
if(cnt == 4'h3)
begin
state <= b1st;
cnt <= 4'h0;
end
end
endcase
end
end
//mux select and rcon enable for key schedule
always @ (*)
begin
case(state)
load:
begin
input_sel <= 1'b0;
sbox_sel <= 1'b1;
last_out_sel <= 1'b0;
bit_out_sel <= 1'b0;
rcon_en <= 8'h00;
end
b1st:
begin
input_sel <= 1'b1;
sbox_sel <= 1'b1;
last_out_sel <= 1'b0;
bit_out_sel <= 1'b1;
rcon_en <= 8'hFF;
end
b2nd:
begin
input_sel <= 1'b1;
sbox_sel <= 1'b1;
last_out_sel <= 1'b0;
bit_out_sel <= 1'b1;
rcon_en <= 8'h00;
end
b3rd:
begin
input_sel <= 1'b1;
sbox_sel <= 1'b0;
last_out_sel <= 1'b0;
bit_out_sel <= 1'b1;
rcon_en <= 8'h00;
end
norm:
begin
input_sel <= 1'b1;
sbox_sel <= 1'b0;
last_out_sel <= 1'b1;
bit_out_sel <= 1'b1;
rcon_en <= 8'h00;
end
shif:
begin
input_sel <= 1'b1;
sbox_sel <= 1'b0;
last_out_sel <= 1'b1;
bit_out_sel <= 1'b0;
rcon_en <= 8'h00;
end
default:
begin
input_sel <= 1'b0;
sbox_sel <= 1'b1;
last_out_sel <= 1'b0;
bit_out_sel <= 1'b0;
rcon_en <= 8'h00;
end
endcase
end
//round counter
always @ (posedge clk)
begin
if (rst == 1'b1 || cnt == 4'hf || round_cnt_w == 4'ha)
begin
round_cnt <= 6'h00;
end
else
begin
round_cnt <= round_cnt + 6'h01;
end
end
//state machine shift row
always @ (posedge clk)
begin
if (state == load)
begin
c3 <= 2'h3;
end
else
begin
case (round_cnt[3:0])
4'h0: c3 <= 2'h2;
4'h1: c3 <= 2'h1;
4'h2: c3 <= 2'h0;
4'h3: c3 <= 2'h3;
4'h4: c3 <= 2'h2;
4'h5: c3 <= 2'h1;
4'h6: c3 <= 2'h1;
4'h7: c3 <= 2'h3;
4'h8: c3 <= 2'h2;
4'h9: c3 <= 2'h3;
4'hA: c3 <= 2'h2;
4'hB: c3 <= 2'h3;
4'hC: c3 <= 2'h3;
4'hD: c3 <= 2'h3;
4'hE: c3 <= 2'h3;
4'hF: c3 <= 2'h3;
endcase
end
end
//mixcoloumn enable
always @ (posedge clk)
begin
if (round_cnt[1:0] == 2'b11)
begin
mc_en_reg <= 8'h00;
end
else
begin
mc_en_reg <= 8'hFF;
end
end
//parelle load
always @ (posedge clk)
begin
if (state == load)
begin
pld_reg <= 1'b0;
end
else
begin
if (round_cnt[1:0] == 2'b11)
begin
pld_reg <= 1'b1;
end
else
begin
pld_reg <= 1'b0;
end
end
end
always @(posedge clk)
begin
if (rst == 1'b1)
begin
d_vld <= 1'b0;
end
else
begin
if (round_cnt == 8'h90)
begin
d_vld <= 1'b1;
end
end
end
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__SRDLXTP_BEHAVIORAL_V
`define SKY130_FD_SC_LP__SRDLXTP_BEHAVIORAL_V
/**
* srdlxtp: ????.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_dlatch_p_pp_pkg_sn/sky130_fd_sc_lp__udp_dlatch_p_pp_pkg_sn.v"
`celldefine
module sky130_fd_sc_lp__srdlxtp (
Q ,
D ,
GATE ,
SLEEP_B
);
// Module ports
output Q ;
input D ;
input GATE ;
input SLEEP_B;
// Module supplies
supply1 KAPWR;
supply1 VPWR ;
supply0 VGND ;
supply1 VPB ;
supply0 VNB ;
// Local signals
wire buf_Q ;
wire GATE_delayed;
wire D_delayed ;
reg notifier ;
wire awake ;
// Name Output Other arguments
sky130_fd_sc_lp__udp_dlatch$P_pp$PKG$sN dlatch0 (buf_Q , D_delayed, GATE_delayed, SLEEP_B, notifier, KAPWR, VGND, VPWR);
assign awake = ( SLEEP_B === 1'b1 );
bufif1 bufif10 (Q , buf_Q, VPWR );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_LP__SRDLXTP_BEHAVIORAL_V |
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HVL__NOR2_FUNCTIONAL_V
`define SKY130_FD_SC_HVL__NOR2_FUNCTIONAL_V
/**
* nor2: 2-input NOR.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
`celldefine
module sky130_fd_sc_hvl__nor2 (
Y,
A,
B
);
// Module ports
output Y;
input A;
input B;
// Local signals
wire nor0_out_Y;
// Name Output Other arguments
nor nor0 (nor0_out_Y, A, B );
buf buf0 (Y , nor0_out_Y );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_HVL__NOR2_FUNCTIONAL_V |
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HD__DLYMETAL6S6S_PP_SYMBOL_V
`define SKY130_FD_SC_HD__DLYMETAL6S6S_PP_SYMBOL_V
/**
* dlymetal6s6s: 6-inverter delay with output from 6th inverter on
* horizontal route.
*
* Verilog stub (with power pins) for graphical symbol definition
* generation.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_hd__dlymetal6s6s (
//# {{data|Data Signals}}
input A ,
output X ,
//# {{power|Power}}
input VPB ,
input VPWR,
input VGND,
input VNB
);
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_HD__DLYMETAL6S6S_PP_SYMBOL_V
|
// ***************************************************************************
// ***************************************************************************
// Copyright 2011(c) Analog Devices, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// - Neither the name of Analog Devices, Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
// - The use of this software may or may not infringe the patent rights
// of one or more patent holders. This license does not release you
// from the requirement that you obtain separate licenses from these
// patent holders to use this software.
// - Use of the software either in source or binary form, must be run
// on or directly connected to an Analog Devices Inc. component.
//
// THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED.
//
// IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY
// RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ***************************************************************************
// ***************************************************************************
`timescale 1ns/100ps
module system_top (
// fmc fpga interface
eth_rx_clk,
eth_rx_cntrl,
eth_rx_data,
eth_tx_clk_out,
eth_tx_cntrl,
eth_tx_data,
eth_mdc,
eth_mdio_i,
eth_mdio_o,
eth_mdio_t,
eth_phy_resetn,
// phy interface
phy_resetn,
phy_rx_clk,
phy_rx_cntrl,
phy_rx_data,
phy_tx_clk_out,
phy_tx_cntrl,
phy_tx_data,
phy_mdc,
phy_mdio);
// fmc fpga interface
output eth_rx_clk;
output eth_rx_cntrl;
output [ 3:0] eth_rx_data;
input eth_tx_clk_out;
input eth_tx_cntrl;
input [ 3:0] eth_tx_data;
input eth_mdc;
output eth_mdio_i;
input eth_mdio_o;
input eth_mdio_t;
input eth_phy_resetn;
// phy interface
output phy_resetn;
input phy_rx_clk;
input phy_rx_cntrl;
input [ 3:0] phy_rx_data;
output phy_tx_clk_out;
output phy_tx_cntrl;
output [ 3:0] phy_tx_data;
output phy_mdc;
inout phy_mdio;
// simple pass through
assign eth_rx_clk = phy_rx_clk;
assign eth_rx_cntrl = phy_rx_cntrl;
assign eth_rx_data = phy_rx_data;
assign phy_tx_clk_out = eth_tx_clk_out;
assign phy_tx_cntrl = eth_tx_cntrl;
assign phy_tx_data = eth_tx_data;
assign phy_mdc = eth_mdc;
assign phy_mdio = (eth_mdio_t == 1'b0) ? eth_mdio_o : 1'bz;
assign eth_mdio_i = phy_mdio;
assign phy_resetn = eth_phy_resetn;
endmodule
// ***************************************************************************
// ***************************************************************************
|
(*****
This file provides a generalized version of arithmetic with "mixed
radix" numerical systems. Later, parameters are entered into the
general functions, and they are partially evaluated until only runtime
basic arithmetic operations remain.
CPS
---
Fuctions are written in continuation passing style (CPS). This means
that each operation is passed a "continuation" function, which it is
expected to call on its own output (like a callback). See the end of
this comment for a motivating example explaining why we do CPS,
despite a fair amount of resulting boilerplate code for each
operation. The code block for an operation called A would look like
this:
```
Definition A_cps x y {T} f : T := ...
Definition A x y := A_cps x y id.
Lemma A_cps_id x y : forall {T} f, @A_cps x y T f = f (A x y).
Hint Opaque A : uncps.
Hint Rewrite A_cps_id : uncps.
Lemma eval_A x y : eval (A x y) = ...
Hint Rewrite eval_A : push_basesystem_eval.
```
`A_cps` is the main, CPS-style definition of the operation (`f` is the
continuation function). `A` is the non-CPS version of `A_cps`, simply
defined by passing an identity function to `A_cps`. `A_cps_id` states
that we can replace the CPS version with the non-cps version. `eval_A`
is the actual correctness lemma for the operation, stating that it has
the correct arithmetic properties. In general, the middle block
containing `A` and `A_cps_id` is boring boilerplate and can be safely
ignored.
HintDbs
-------
+ `uncps` : Converts CPS operations to their non-CPS versions.
+ `push_basesystem_eval` : Contains all the correctness lemmas for
operations in this file, which are in terms of the `eval` function.
Positional/Associational
------------------------
We represent mixed-radix numbers in a few different ways:
+ "Positional" : a tuple of numbers and a weight function (nat->Z),
which is evaluated by multiplying the `i`th element of the tuple by
`weight i`, and then summing the products.
+ "Associational" : a list of pairs of numbers--the first is the
weight, the second is the runtime value. Evaluated by multiplying each
pair and summing the products.
The associational representation is good for basic operations like
addition and multiplication; for addition, one can simply just append
two associational lists. But the end-result code should use the
positional representation (with each digit representing a machine
word). Since converting to and fro can be easily compiled away once
the weight function is known, we use associational to write most of
the operations and liberally convert back and forth to ensure correct
output. In particular, it is important to convert before carrying.
Runtime Operations
------------------
Since some instances of e.g. Z.add or Z.mul operate on (compile-time)
weights, and some operate on runtime values, we need a way to
differentiate these cases before partial evaluation. We define a
runtime_scope to mark certain additions/multiplications as runtime
values, so they will not be unfolded during partial evaluation. For
instance, if we have:
```
Definition f (x y : Z * Z) := (fst x + fst y, (snd x + snd y)%RT).
```
then when we are partially evaluating `f`, we can easily exclude the
runtime operations (`cbv - [runtime_add]`) and prevent Coq from trying
to simplify the second addition.
Why CPS?
--------
Let's suppose we want to add corresponding elements of two `list Z`s
(so on inputs `[1,2,3]` and `[2,3,1]`, we get `[3,5,4]`). We might
write our function like this :
```
Fixpoint add_lists (p q : list Z) :=
match p, q with
| p0 :: p', q0 :: q' =>
dlet sum := p0 + q0 in
sum :: add_lists p' q'
| _, _ => nil
end.
```
(Note : `dlet` is a notation for `Let_In`, which is just a dumb
wrapper for `let`. This allows us to `cbv - [Let_In]` if we want to
not simplify certain `let`s.)
A CPS equivalent of `add_lists` would look like this:
```
Fixpoint add_lists_cps (p q : list Z) {T} (f:list Z->T) :=
match p, q with
| p0 :: p', q0 :: q' =>
dlet sum := p0 + q0 in
add_lists_cps p' q' (fun r => f (sum :: r))
| _, _ => f nil
end.
```
Now let's try some partial evaluation. The expression we'll evaluate is:
```
Definition x :=
(fun a0 a1 a2 b0 b1 b2 =>
let r := add_lists [a0;a1;a2] [b0;b1;b2] in
let rr := add_lists r r in
add_lists rr rr).
```
Or, using `add_lists_cps`:
```
Definition y :=
(fun a0 a1 a2 b0 b1 b2 =>
add_lists_cps [a0;a1;a2] [b0;b1;b2]
(fun r => add_lists_cps r r
(fun rr => add_lists_cps rr rr id))).
```
If we run `Eval cbv -[Z.add] in x` and `Eval cbv -[Z.add] in y`, we get
identical output:
```
fun a0 a1 a2 b0 b1 b2 : Z =>
[a0 + b0 + (a0 + b0) + (a0 + b0 + (a0 + b0));
a1 + b1 + (a1 + b1) + (a1 + b1 + (a1 + b1));
a2 + b2 + (a2 + b2) + (a2 + b2 + (a2 + b2))]
```
However, there are a lot of common subexpressions here--this is what
the `dlet` we put into the functions should help us avoid. Let's try
`Eval cbv -[Let_In Z.add] in x`:
```
fun a0 a1 a2 b0 b1 b2 : Z =>
(fix add_lists (p q : list Z) {struct p} :
list Z :=
match p with
| [] => []
| p0 :: p' =>
match q with
| [] => []
| q0 :: q' =>
dlet sum := p0 + q0 in
sum :: add_lists p' q'
end
end)
((fix add_lists (p q : list Z) {struct p} :
list Z :=
match p with
| [] => []
| p0 :: p' =>
match q with
| [] => []
| q0 :: q' =>
dlet sum := p0 + q0 in
sum :: add_lists p' q'
end
end)
(dlet sum := a0 + b0 in
sum
:: (dlet sum0 := a1 + b1 in
sum0 :: (dlet sum1 := a2 + b2 in
[sum1])))
(dlet sum := a0 + b0 in
sum
:: (dlet sum0 := a1 + b1 in
sum0 :: (dlet sum1 := a2 + b2 in
[sum1]))))
((fix add_lists (p q : list Z) {struct p} :
list Z :=
match p with
| [] => []
| p0 :: p' =>
match q with
| [] => []
| q0 :: q' =>
dlet sum := p0 + q0 in
sum :: add_lists p' q'
end
end)
(dlet sum := a0 + b0 in
sum
:: (dlet sum0 := a1 + b1 in
sum0 :: (dlet sum1 := a2 + b2 in
[sum1])))
(dlet sum := a0 + b0 in
sum
:: (dlet sum0 := a1 + b1 in
sum0 :: (dlet sum1 := a2 + b2 in
[sum1]))))
```
Not so great. Because the `dlet`s are stuck in the inner terms, we
can't simplify the expression very nicely. Let's try that on the CPS
version (`Eval cbv -[Let_In Z.add] in y`):
```
fun a0 a1 a2 b0 b1 b2 : Z =>
dlet sum := a0 + b0 in
dlet sum0 := a1 + b1 in
dlet sum1 := a2 + b2 in
dlet sum2 := sum + sum in
dlet sum3 := sum0 + sum0 in
dlet sum4 := sum1 + sum1 in
dlet sum5 := sum2 + sum2 in
dlet sum6 := sum3 + sum3 in
dlet sum7 := sum4 + sum4 in
[sum5; sum6; sum7]
```
Isn't that lovely? Since we can push continuation functions "under"
the `dlet`s, we can end up with a nice, concise, simplified
expression.
One might suggest that we could just inline the `dlet`s and do common
subexpression elimination. But some of our terms have so many `dlet`s
that inlining them all would make a term too huge to process in
reasonable time, so this is not really an option.
*****)
Require Import Coq.ZArith.ZArith Coq.micromega.Psatz Coq.omega.Omega.
Require Import Coq.ZArith.BinIntDef.
Local Open Scope Z_scope.
Require Import Crypto.Tactics.Algebra_syntax.Nsatz.
Require Import Crypto.Util.Tactics Crypto.Util.Decidable Crypto.Util.LetIn.
Require Import Crypto.Util.ZUtil Crypto.Util.ListUtil Crypto.Util.Sigma.
Require Import Crypto.Util.CPSUtil Crypto.Util.Prod Crypto.Util.Tactics.
Require Import Crypto.ModularArithmetic.PrimeFieldTheorems.
Require Import Coq.Lists.List. Import ListNotations.
Require Crypto.Util.Tuple. Local Notation tuple := Tuple.tuple.
Local Ltac prove_id :=
repeat match goal with
| _ => progress intros
| _ => progress simpl
| _ => progress cbv [Let_In]
| _ => progress (autorewrite with uncps push_id in * )
| _ => break_if
| _ => break_match
| _ => contradiction
| _ => reflexivity
| _ => nsatz
| _ => solve [auto]
end.
Create HintDb push_basesystem_eval discriminated.
Local Ltac prove_eval :=
repeat match goal with
| _ => progress intros
| _ => progress simpl
| _ => progress cbv [Let_In]
| _ => progress (autorewrite with push_basesystem_eval uncps push_id cancel_pair in * )
| _ => break_if
| _ => break_match
| _ => split
| H : _ /\ _ |- _ => destruct H
| H : Some _ = Some _ |- _ => progress (inversion H; subst)
| _ => discriminate
| _ => reflexivity
| _ => nsatz
end.
Definition mod_eq (m:positive) a b := a mod m = b mod m.
Global Instance mod_eq_equiv m : RelationClasses.Equivalence (mod_eq m).
Proof. constructor; congruence. Qed.
Definition mod_eq_dec m a b : {mod_eq m a b} + {~ mod_eq m a b}
:= Z.eq_dec _ _.
Lemma mod_eq_Z2F_iff m a b :
mod_eq m a b <-> Logic.eq (F.of_Z m a) (F.of_Z m b).
Proof. rewrite <-F.eq_of_Z_iff; reflexivity. Qed.
Delimit Scope runtime_scope with RT.
Definition runtime_mul := Z.mul.
Global Notation "a * b" := (runtime_mul a%RT b%RT) : runtime_scope.
Definition runtime_add := Z.add.
Global Notation "a + b" := (runtime_add a%RT b%RT) : runtime_scope.
Definition runtime_opp := Z.opp.
Global Notation "- a" := (runtime_opp a%RT) : runtime_scope.
Definition runtime_and := Z.land.
Global Notation "a &' b" := (runtime_and a%RT b%RT) : runtime_scope.
Definition runtime_shr := Z.shiftr.
Global Notation "a >> b" := (runtime_shr a%RT b%RT) : runtime_scope.
Module B.
Definition limb := (Z*Z)%type. (* position coefficient and run-time value *)
Module Associational.
Definition eval (p:list limb) : Z :=
List.fold_right Z.add 0%Z (List.map (fun t => fst t * snd t) p).
Lemma eval_nil : eval nil = 0. Proof. reflexivity. Qed.
Lemma eval_cons p q : eval (p::q) = (fst p) * (snd p) + eval q. Proof. reflexivity. Qed.
Lemma eval_app p q: eval (p++q) = eval p + eval q.
Proof. induction p; simpl eval; rewrite ?eval_nil, ?eval_cons; nsatz. Qed.
Hint Rewrite eval_nil eval_cons eval_app : push_basesystem_eval.
Definition multerm (t t' : limb) : limb :=
(fst t * fst t', (snd t * snd t')%RT).
Lemma eval_map_multerm (a:limb) (q:list limb)
: eval (List.map (multerm a) q) = fst a * snd a * eval q.
Proof.
induction q; cbv [multerm]; simpl List.map;
autorewrite with push_basesystem_eval cancel_pair; nsatz.
Qed. Hint Rewrite eval_map_multerm : push_basesystem_eval.
Definition mul_cps (p q:list limb) {T} (f : list limb->T) :=
flat_map_cps (fun t => @map_cps _ _ (multerm t) q) p f.
Definition mul (p q:list limb) := mul_cps p q id.
Lemma mul_cps_id p q: forall {T} f, @mul_cps p q T f = f (mul p q).
Proof. cbv [mul_cps mul]; prove_id. Qed.
Hint Opaque mul : uncps.
Hint Rewrite mul_cps_id : uncps.
Lemma eval_mul p q: eval (mul p q) = eval p * eval q.
Proof. cbv [mul mul_cps]; induction p; prove_eval. Qed.
Hint Rewrite eval_mul : push_basesystem_eval.
Fixpoint split_cps (s:Z) (xs:list limb)
{T} (f :list limb*list limb->T) :=
match xs with
| nil => f (nil, nil)
| cons x xs' =>
split_cps s xs'
(fun sxs' =>
if dec (fst x mod s = 0)
then f (fst sxs', cons (fst x / s, snd x) (snd sxs'))
else f (cons x (fst sxs'), snd sxs'))
end.
Definition split s xs := split_cps s xs id.
Lemma split_cps_id s p: forall {T} f,
@split_cps s p T f = f (split s p).
Proof.
induction p;
repeat match goal with
| _ => rewrite IHp
| _ => progress (cbv [split]; prove_id)
end.
Qed.
Hint Opaque split : uncps.
Hint Rewrite split_cps_id : uncps.
Lemma eval_split s p (s_nonzero:s<>0):
eval (fst (split s p)) + s*eval (snd (split s p)) = eval p.
Proof.
cbv [split]; induction p; prove_eval.
match goal with
H:_ |- _ =>
unique pose proof (Z_div_exact_full_2 _ _ s_nonzero H)
end; nsatz.
Qed. Hint Rewrite @eval_split using auto : push_basesystem_eval.
Definition reduce_cps (s:Z) (c:list limb) (p:list limb)
{T} (f : list limb->T) :=
split_cps s p
(fun ab => mul_cps c (snd ab)
(fun rr =>f (fst ab ++ rr))).
Definition reduce s c p := reduce_cps s c p id.
Lemma reduce_cps_id s c p {T} f:
@reduce_cps s c p T f = f (reduce s c p).
Proof. cbv [reduce_cps reduce]; prove_id. Qed.
Hint Opaque reduce : uncps.
Hint Rewrite reduce_cps_id : uncps.
Lemma reduction_rule a b s c m (m_eq:Z.pos m = s - c):
(a + s * b) mod m = (a + c * b) mod m.
Proof.
rewrite m_eq. pose proof (Pos2Z.is_pos m).
replace (a + s * b) with ((a + c*b) + b*(s-c)) by ring.
rewrite Z.add_mod, Z_mod_mult, Z.add_0_r, Z.mod_mod by omega.
trivial.
Qed.
Lemma eval_reduce s c p (s_nonzero:s<>0) m (m_eq : Z.pos m = s - eval c) :
mod_eq m (eval (reduce s c p)) (eval p).
Proof.
cbv [reduce reduce_cps mod_eq]; prove_eval.
erewrite <-reduction_rule by eauto; prove_eval.
Qed.
Hint Rewrite eval_reduce using (omega || assumption) : push_basesystem_eval.
(* Why TF does this hint get picked up outside the section (while other eval_ hints do not?) *)
Definition negate_snd_cps (p:list limb) {T} (f:list limb ->T) :=
map_cps (fun cx => (fst cx, (-snd cx)%RT)) p f.
Definition negate_snd p := negate_snd_cps p id.
Lemma negate_snd_id p {T} f : @negate_snd_cps p T f = f (negate_snd p).
Proof. cbv [negate_snd_cps negate_snd]; prove_id. Qed.
Hint Opaque negate_snd : uncps.
Hint Rewrite negate_snd_id : uncps.
Lemma eval_negate_snd p : eval (negate_snd p) = - eval p.
Proof.
cbv [negate_snd_cps negate_snd]; induction p; prove_eval.
Qed. Hint Rewrite eval_negate_snd : push_basesystem_eval.
Section Carries.
Context {modulo div:Z->Z->Z}.
Context {div_mod : forall a b:Z, b <> 0 ->
a = b * (div a b) + modulo a b}.
Definition carryterm_cps (w fw:Z) (t:limb) {T} (f:list limb->T) :=
if dec (fst t = w)
then dlet t2 := snd t in
f ((w*fw, div t2 fw) :: (w, modulo t2 fw) :: @nil limb)
else f [t].
Definition carryterm w fw t := carryterm_cps w fw t id.
Lemma carryterm_cps_id w fw t {T} f :
@carryterm_cps w fw t T f
= f (@carryterm w fw t).
Proof. cbv [carryterm_cps carryterm Let_In]; prove_id. Qed.
Hint Opaque carryterm : uncps.
Hint Rewrite carryterm_cps_id : uncps.
Lemma eval_carryterm w fw (t:limb) (fw_nonzero:fw<>0):
eval (carryterm w fw t) = eval [t].
Proof.
cbv [carryterm_cps carryterm Let_In]; prove_eval.
specialize (div_mod (snd t) fw fw_nonzero).
nsatz.
Qed. Hint Rewrite eval_carryterm using auto : push_basesystem_eval.
Definition carry_cps (w fw:Z) (p:list limb) {T} (f:list limb->T) :=
flat_map_cps (carryterm_cps w fw) p f.
Definition carry w fw p := carry_cps w fw p id.
Lemma carry_cps_id w fw p {T} f:
@carry_cps w fw p T f = f (carry w fw p).
Proof. cbv [carry_cps carry]; prove_id. Qed.
Hint Opaque carry : uncps.
Hint Rewrite carry_cps_id : uncps.
Lemma eval_carry w fw p (fw_nonzero:fw<>0):
eval (carry w fw p) = eval p.
Proof. cbv [carry_cps carry]; induction p; prove_eval. Qed.
Hint Rewrite eval_carry using auto : push_basesystem_eval.
End Carries.
End Associational.
Hint Rewrite
@Associational.carry_cps_id
@Associational.carryterm_cps_id
@Associational.reduce_cps_id
@Associational.split_cps_id
@Associational.mul_cps_id : uncps.
Module Positional.
Section Positional.
Import Associational.
Context (weight : nat -> Z) (* [weight i] is the weight of position [i] *)
(weight_0 : weight 0%nat = 1%Z)
(weight_nonzero : forall i, weight i <> 0).
(** Converting from positional to associational *)
Definition to_associational_cps {n:nat} (xs:tuple Z n)
{T} (f:list limb->T) :=
map_cps weight (seq 0 n)
(fun r =>
to_list_cps n xs (fun rr => combine_cps r rr f)).
Definition to_associational {n} xs :=
@to_associational_cps n xs _ id.
Lemma to_associational_cps_id {n} x {T} f:
@to_associational_cps n x T f = f (to_associational x).
Proof. cbv [to_associational_cps to_associational]; prove_id. Qed.
Hint Opaque to_associational : uncps.
Hint Rewrite @to_associational_cps_id : uncps.
Definition eval {n} x :=
@to_associational_cps n x _ Associational.eval.
Lemma eval_to_associational {n} x :
Associational.eval (@to_associational n x) = eval x.
Proof.
cbv [to_associational_cps eval to_associational]; prove_eval.
Qed. Hint Rewrite @eval_to_associational : push_basesystem_eval.
(** (modular) equality that tolerates redundancy **)
Definition eq {sz} m (a b : tuple Z sz) : Prop :=
mod_eq m (eval a) (eval b).
(** Converting from associational to positional *)
Definition zeros n : tuple Z n := Tuple.repeat 0 n.
Lemma eval_zeros n : eval (zeros n) = 0.
Proof.
cbv [eval Associational.eval to_associational_cps zeros].
pose proof (seq_length n 0). generalize dependent (seq 0 n).
intro xs; revert n; induction xs; intros;
[autorewrite with uncps; reflexivity|].
intros; destruct n; [distr_length|].
specialize (IHxs n). autorewrite with uncps in *.
rewrite [email protected]_list_repeat in *.
simpl List.repeat. rewrite map_cons, combine_cons, map_cons.
simpl fold_right. rewrite IHxs by distr_length. ring.
Qed. Hint Rewrite eval_zeros : push_basesystem_eval.
Definition add_to_nth_cps {n} i x t {T} (f:tuple Z n->T) :=
@on_tuple_cps _ _ 0 (update_nth_cps i (runtime_add x)) n n t _ f.
Definition add_to_nth {n} i x t := @add_to_nth_cps n i x t _ id.
Lemma add_to_nth_cps_id {n} i x xs {T} f:
@add_to_nth_cps n i x xs T f = f (add_to_nth i x xs).
Proof.
cbv [add_to_nth_cps add_to_nth]; erewrite !on_tuple_cps_correct
by (intros; autorewrite with uncps; reflexivity); prove_id.
Unshelve.
intros; subst. autorewrite with uncps push_id. distr_length.
Qed.
Hint Opaque add_to_nth : uncps.
Hint Rewrite @add_to_nth_cps_id : uncps.
Lemma eval_add_to_nth {n} (i:nat) (x:Z) (H:(i<n)%nat) (xs:tuple Z n):
eval (@add_to_nth n i x xs) = weight i * x + eval xs.
Proof.
cbv [eval to_associational_cps add_to_nth add_to_nth_cps runtime_add].
erewrite on_tuple_cps_correct by (intros; autorewrite with uncps; reflexivity).
prove_eval.
cbv [Tuple.on_tuple].
rewrite !Tuple.to_list_from_list.
autorewrite with uncps push_id.
rewrite ListUtil.combine_update_nth_r at 1.
rewrite <-(update_nth_id i (List.combine _ _)) at 2.
rewrite <-!(ListUtil.splice_nth_equiv_update_nth_update _ _ (weight 0, 0)); cbv [ListUtil.splice_nth id];
repeat match goal with
| _ => progress (apply Zminus_eq; ring_simplify)
| _ => progress autorewrite with push_basesystem_eval cancel_pair distr_length
| _ => progress rewrite <-?ListUtil.map_nth_default_always, ?map_fst_combine, ?List.firstn_all2, ?ListUtil.map_nth_default_always, ?nth_default_seq_inbouns, ?plus_O_n
end; trivial; lia.
Unshelve.
intros; subst. autorewrite with uncps push_id. distr_length.
Qed. Hint Rewrite @eval_add_to_nth using omega : push_basesystem_eval.
Fixpoint place_cps (t:limb) (i:nat) {T} (f:nat * Z->T) :=
if dec (fst t mod weight i = 0)
then f (i, let c := fst t / weight i in (c * snd t)%RT)
else match i with S i' => place_cps t i' f | O => f (O, fst t * snd t)%RT end.
Definition place t i := place_cps t i id.
Lemma place_cps_id t i {T} f :
@place_cps t i T f = f (place t i).
Proof. cbv [place]; induction i; prove_id. Qed.
Hint Opaque place : uncps.
Hint Rewrite place_cps_id : uncps.
Lemma place_cps_in_range (t:limb) (n:nat)
: (fst (place_cps t n id) < S n)%nat.
Proof. induction n; simpl; break_match; simpl; omega. Qed.
Lemma weight_place_cps t i
: weight (fst (place_cps t i id)) * snd (place_cps t i id)
= fst t * snd t.
Proof.
induction i; cbv [id]; simpl place_cps; break_match;
autorewrite with cancel_pair;
try find_apply_lem_hyp Z_div_exact_full_2; nsatz || auto.
Qed.
Definition from_associational_cps n (p:list limb)
{T} (f:tuple Z n->T):=
fold_right_cps
(fun t st =>
place_cps t (pred n)
(fun p=> add_to_nth_cps (fst p) (snd p) st id))
(zeros n) p f.
Definition from_associational n p := from_associational_cps n p id.
Lemma from_associational_cps_id {n} p {T} f:
@from_associational_cps n p T f = f (from_associational n p).
Proof.
cbv [from_associational_cps from_associational]; prove_id.
Qed.
Hint Opaque from_associational : uncps.
Hint Rewrite @from_associational_cps_id : uncps.
Lemma eval_from_associational {n} p (n_nonzero:n<>O):
eval (from_associational n p) = Associational.eval p.
Proof.
cbv [from_associational_cps from_associational]; induction p;
[|pose proof (place_cps_in_range a (pred n))]; prove_eval.
cbv [place]; rewrite weight_place_cps. nsatz.
Qed.
Hint Rewrite @eval_from_associational using omega
: push_basesystem_eval.
Section Carries.
Context {modulo div : Z->Z->Z}.
Context {div_mod : forall a b:Z, b <> 0 ->
a = b * (div a b) + modulo a b}.
Definition carry_cps {n m} (index:nat) (p:tuple Z n)
{T} (f:tuple Z m->T) :=
to_associational_cps p
(fun P => @Associational.carry_cps
modulo div
(weight index)
(weight (S index) / weight index)
P T
(fun R => from_associational_cps m R f)).
Definition carry {n m} i p := @carry_cps n m i p _ id.
Lemma carry_cps_id {n m} i p {T} f:
@carry_cps n m i p T f = f (carry i p).
Proof.
cbv [carry_cps carry]; prove_id; rewrite carry_cps_id; reflexivity.
Qed.
Hint Opaque carry : uncps. Hint Rewrite @carry_cps_id : uncps.
Lemma eval_carry {n m} i p: (n <> 0%nat) -> (m <> 0%nat) ->
weight (S i) / weight i <> 0 ->
eval (carry (n:=n) (m:=m) i p) = eval p.
Proof.
cbv [carry_cps carry]; intros. prove_eval.
rewrite @eval_carry by eauto.
apply eval_to_associational.
Qed.
Hint Rewrite @eval_carry : push_basesystem_eval.
(* N.B. It is important to reverse [idxs] here. Like
[fold_right], [fold_right_cps2] is written such that the first
terms in the list are actually used last in the computation. For
example, running:
`Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`
will produce [fun a b c d => (a + (b + (c + d)))].*)
Definition chained_carries_cps {n} (p:tuple Z n) (idxs : list nat)
{T} (f:tuple Z n->T) :=
fold_right_cps2 carry_cps p (rev idxs) f.
Definition chained_carries {n} p idxs := @chained_carries_cps n p idxs _ id.
Lemma chained_carries_id {n} p idxs : forall {T} f,
@chained_carries_cps n p idxs T f = f (chained_carries p idxs).
Proof. cbv [chained_carries_cps chained_carries]; prove_id. Qed.
Hint Opaque chained_carries : uncps.
Hint Rewrite @chained_carries_id : uncps.
Lemma eval_chained_carries {n} (p:tuple Z n) idxs :
(forall i, In i idxs -> weight (S i) / weight i <> 0) ->
eval (chained_carries p idxs) = eval p.
Proof.
cbv [chained_carries chained_carries_cps]; intros;
autorewrite with uncps push_id.
apply fold_right_invariant; [|intro; rewrite <-in_rev];
destruct n; prove_eval; auto.
Qed. Hint Rewrite @eval_chained_carries : push_basesystem_eval.
(* Reverse of [eval]; ranslate from Z to basesystem by putting
everything in first digit and then carrying. This function, like
[eval], is not defined using CPS. *)
Definition encode {n} (x : Z) : tuple Z n :=
chained_carries (from_associational n [(1,x)]) (seq 0 n).
Lemma eval_encode {n} x : (n <> 0%nat) ->
(forall i, In i (seq 0 n) -> weight (S i) / weight i <> 0) ->
eval (@encode n x) = x.
Proof. cbv [encode]; intros; prove_eval; auto. Qed.
Hint Rewrite @eval_encode : push_basesystem_eval.
End Carries.
Section Wrappers.
(* Simple wrappers for Associational definitions; convert to
associational, do the operation, convert back. *)
Definition add_cps {n} (p q : tuple Z n) {T} (f:tuple Z n->T) :=
to_associational_cps p
(fun P => to_associational_cps q
(fun Q => from_associational_cps n (P++Q) f)).
Definition mul_cps {n m} (p q : tuple Z n) {T} (f:tuple Z m->T) :=
to_associational_cps p
(fun P => to_associational_cps q
(fun Q => Associational.mul_cps P Q
(fun PQ => from_associational_cps m PQ f))).
Definition reduce_cps {m n} (s:Z) (c:list B.limb) (p : tuple Z m)
{T} (f:tuple Z n->T) :=
to_associational_cps p
(fun P => Associational.reduce_cps s c P
(fun R => from_associational_cps n R f)).
Definition carry_reduce_cps {n div modulo}
(s:Z) (c:list limb) (p : tuple Z n)
{T} (f: tuple Z n ->T) :=
carry_cps (div:=div) (modulo:=modulo) (n:=n) (m:=S n) (pred n) p
(fun r => reduce_cps (m:=S n) (n:=n) s c r f).
Definition negate_snd_cps {n} (p : tuple Z n)
{T} (f:tuple Z n->T) :=
to_associational_cps p
(fun P => Associational.negate_snd_cps P
(fun R => from_associational_cps n R f)).
End Wrappers.
Hint Unfold
Positional.add_cps
Positional.mul_cps
Positional.reduce_cps
Positional.carry_reduce_cps
Positional.negate_snd_cps
.
Section Subtraction.
Context {m n} {coef : tuple Z n}
{coef_mod : mod_eq m (eval coef) 0}.
Definition sub_cps (p q : tuple Z n) {T} (f:tuple Z n->T):=
add_cps coef p
(fun cp => negate_snd_cps q
(fun _q => add_cps cp _q f)).
Definition sub p q := sub_cps p q id.
Lemma sub_id p q {T} f : @sub_cps p q T f = f (sub p q).
Proof. cbv [sub_cps sub]; autounfold; prove_id. Qed.
Hint Opaque sub : uncps.
Hint Rewrite sub_id : uncps.
Lemma eval_sub p q : mod_eq m (eval (sub p q)) (eval p - eval q).
Proof.
cbv [sub sub_cps]; autounfold; destruct n; prove_eval.
transitivity (eval coef + (eval p - eval q)).
{ apply f_equal2; ring. }
{ cbv [mod_eq] in *; rewrite Z.add_mod_full, coef_mod, Z.add_0_l, Zmod_mod. reflexivity. }
Qed.
Definition opp_cps (p : tuple Z n) {T} (f:tuple Z n->T):=
sub_cps (zeros n) p f.
End Subtraction.
(* Lemmas about converting to/from F. Will be useful in proving
that basesystem is isomorphic to F.commutative_ring_modulo.*)
Section F.
Context {sz:nat} {sz_nonzero : sz<>0%nat} {m :positive}.
Context (weight_divides : forall i : nat, weight (S i) / weight i <> 0).
Context {modulo div:Z->Z->Z}
{div_mod : forall a b:Z, b <> 0 ->
a = b * (div a b) + modulo a b}.
Definition Fencode (x : F m) : tuple Z sz :=
encode (div:=div) (modulo:=modulo) (F.to_Z x).
Definition Fdecode (x : tuple Z sz) : F m := F.of_Z m (eval x).
Lemma Fdecode_Fencode_id x : Fdecode (Fencode x) = x.
Proof.
cbv [Fdecode Fencode]; rewrite @eval_encode by auto.
apply F.of_Z_to_Z.
Qed.
Lemma eq_Feq_iff a b :
Logic.eq (Fdecode a) (Fdecode b) <-> eq m a b.
Proof. cbv [Fdecode]; rewrite <-F.eq_of_Z_iff; reflexivity. Qed.
End F.
End Positional.
(* Helper lemmas and definitions for [eval]; this needs to be in a
separate section so the weight function can change. *)
Section EvalHelpers.
Lemma eval_single wt (x:Z) : eval (n:=1) wt x = wt 0%nat * x.
Proof. cbv - [Z.mul Z.add]. ring. Qed.
Lemma eval_step {n} (x:tuple Z n) : forall wt z,
eval wt (Tuple.append z x) = wt 0%nat * z + eval (fun i => wt (S i)) x.
Proof.
destruct n; [reflexivity|].
intros; cbv [eval to_associational_cps].
autorewrite with uncps. rewrite map_S_seq. reflexivity.
Qed.
Lemma eval_wt_equiv {n} :forall wta wtb (x:tuple Z n),
(forall i, wta i = wtb i) -> eval wta x = eval wtb x.
Proof.
destruct n; [reflexivity|].
induction n; intros; [rewrite !eval_single, H; reflexivity|].
simpl tuple in *; destruct x.
change (t, z) with (Tuple.append (n:=S n) z t).
rewrite !eval_step. rewrite (H 0%nat). apply Group.cancel_left.
apply IHn; auto.
Qed.
Definition eval_from {n} weight (offset:nat) (x : tuple Z n) : Z :=
eval (fun i => weight (i+offset)%nat) x.
Lemma eval_from_0 {n} wt x : @eval_from n wt 0 x = eval wt x.
Proof. cbv [eval_from]. auto using eval_wt_equiv. Qed.
End EvalHelpers.
End Positional.
Hint Unfold
Positional.add_cps
Positional.mul_cps
Positional.reduce_cps
Positional.carry_reduce_cps
Positional.negate_snd_cps
Positional.opp_cps
.
Hint Rewrite
@Associational.carry_cps_id
@Associational.carryterm_cps_id
@Associational.reduce_cps_id
@Associational.split_cps_id
@Associational.mul_cps_id
@Positional.carry_cps_id
@Positional.from_associational_cps_id
@Positional.place_cps_id
@Positional.add_to_nth_cps_id
@Positional.to_associational_cps_id
@Positional.chained_carries_id
@Positional.sub_id
: uncps.
Hint Rewrite
@Associational.eval_mul
@Positional.eval_to_associational
@Associational.eval_carry
@Associational.eval_carryterm
@Associational.eval_reduce
@Associational.eval_split
@Positional.eval_zeros
@Positional.eval_carry
@Positional.eval_from_associational
@Positional.eval_add_to_nth
@Positional.eval_chained_carries
@Positional.eval_sub
using (assumption || vm_decide) : push_basesystem_eval.
End B.
(* Modulo and div that do shifts if possible, otherwise normal mod/div *)
Section DivMod.
Definition modulo (a b : Z) : Z :=
if dec (2 ^ (Z.log2 b) = b)
then let x := (Z.ones (Z.log2 b)) in (a &' x)%RT
else Z.modulo a b.
Definition div (a b : Z) : Z :=
if dec (2 ^ (Z.log2 b) = b)
then let x := Z.log2 b in (a >> x)%RT
else Z.div a b.
Lemma div_mod a b (H:b <> 0) : a = b * div a b + modulo a b.
Proof.
cbv [div modulo]; intros. break_if; auto using Z.div_mod.
rewrite Z.land_ones, Z.shiftr_div_pow2 by apply Z.log2_nonneg.
pose proof (Z.div_mod a b H). congruence.
Qed.
End DivMod.
Import B.
Ltac basesystem_partial_evaluation_RHS :=
let t0 := match goal with |- _ _ ?t => t end in
let t := (eval cbv delta [
(* this list must contain all definitions referenced by t that reference [Let_In], [runtime_add], [runtime_opp], [runtime_mul], [runtime_shr], or [runtime_and] *)
Positional.to_associational_cps Positional.to_associational Positional.eval Positional.zeros Positional.add_to_nth_cps Positional.add_to_nth Positional.place_cps Positional.place Positional.from_associational_cps Positional.from_associational Positional.carry_cps Positional.carry Positional.chained_carries_cps Positional.chained_carries Positional.sub_cps Positional.sub Positional.negate_snd_cps Positional.add_cps Positional.opp_cps Associational.eval Associational.multerm Associational.mul_cps Associational.mul Associational.split_cps Associational.split Associational.reduce_cps Associational.reduce Associational.carryterm_cps Associational.carryterm Associational.carry_cps Associational.carry Associational.negate_snd_cps Associational.negate_snd div modulo
] in t0) in
let t := (eval pattern @runtime_mul in t) in
let t := match t with ?t _ => t end in
let t := (eval pattern @runtime_add in t) in
let t := match t with ?t _ => t end in
let t := (eval pattern @runtime_opp in t) in
let t := match t with ?t _ => t end in
let t := (eval pattern @runtime_shr in t) in
let t := match t with ?t _ => t end in
let t := (eval pattern @runtime_and in t) in
let t := match t with ?t _ => t end in
let t := (eval pattern @Let_In in t) in
let t := match t with ?t _ => t end in
let t1 := fresh "t1" in
pose t as t1;
transitivity (t1
(@Let_In)
(@runtime_and)
(@runtime_shr)
(@runtime_opp)
(@runtime_add)
(@runtime_mul));
[replace_with_vm_compute t1; clear t1|reflexivity].
(** This block of tactic code works around bug #5434
(https://coq.inria.fr/bugs/show_bug.cgi?id=5434), that
[vm_compute] breaks an invariant in pretyping/constr_matching.ml.
So we refresh all of the names in match statements in the goal by
crawling it.
In particular, [replace_with_vm_compute] creates a [vm_compute]d
term which has anonymous binders where pretyping expects there to
be named binders. This shows up when you try to match on the
function (the branch statement of the match) with an Ltac pattern
like [(fun x : ?T => ?C)] rather than [(fun x : ?T => @?C x)]; we
use the former in reification to save the cost of many extra
invocations of [cbv beta]. Luckily, patterns like [(fun x : ?T =>
@?C x)] don't trigger this anomaly, so we can walk the term,
fixing all match statements whose branches are functions whose
binder names were eaten by [vm_compute] (note that in a match,
every branch where the corresponding constructor takes arguments
is represented internally as a function (lambda term)). We fix
the match statements by pulling out the branch with the [@?]
pattern that doesn't trigger the anomaly, and then recreating the
match with a destructuring [let] that hasn't been through
[vm_compute], and therefore has name information that
constr_matching is happy with. *)
Ltac replace_match_with_destructuring_match T :=
match T with
| ?F ?X
=> let F' := replace_match_with_destructuring_match F in
let X' := replace_match_with_destructuring_match X in
constr:(F' X')
(* we must use [@?f a b] here and not [?f], or else we get an anomaly *)
| match ?d with pair a b => @?f a b end
=> let d' := replace_match_with_destructuring_match d in
let T' := fresh in
constr:(let '(a, b) := d' in
match f a b with
| T' => ltac:(let v := (eval cbv beta delta [T'] in T') in
let v := replace_match_with_destructuring_match v in
exact v)
end)
| ?x => x
end.
Ltac do_replace_match_with_destructuring_match_in_goal :=
let G := get_goal in
let G' := replace_match_with_destructuring_match G in
change G'.
(* TODO : move *)
Lemma F_of_Z_opp {m} x : F.of_Z m (- x) = F.opp (F.of_Z m x).
Proof.
cbv [F.opp]; intros. rewrite F.to_Z_of_Z, <-Z.sub_0_l.
etransitivity; rewrite F.of_Z_mod;
[rewrite Z.opp_mod_mod|]; reflexivity.
Qed.
Hint Rewrite <[email protected]_Z_add : pull_FofZ.
Hint Rewrite <[email protected]_Z_mul : pull_FofZ.
Hint Rewrite <[email protected]_Z_sub : pull_FofZ.
Hint Rewrite <-@F_of_Z_opp : pull_FofZ.
Ltac F_mod_eq :=
cbv [Positional.Fdecode]; autorewrite with pull_FofZ;
apply mod_eq_Z2F_iff.
Ltac solve_op_mod_eq wt x :=
transitivity (Positional.eval wt x); repeat autounfold;
[|autorewrite with uncps push_id push_basesystem_eval;
reflexivity];
cbv [mod_eq]; apply f_equal2; [|reflexivity];
apply f_equal;
basesystem_partial_evaluation_RHS;
do_replace_match_with_destructuring_match_in_goal.
Ltac solve_op_F wt x := F_mod_eq; solve_op_mod_eq wt x.
|
// ========== Copyright Header Begin ==========================================
//
// OpenSPARC T1 Processor File: sctag_pcx_rptr_2.v
// Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
//
// The above named program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License version 2 as published by the Free Software Foundation.
//
// The above named program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this work; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// ========== Copyright Header End ============================================
module sctag_pcx_rptr_2 (/*AUTOARG*/
// Outputs
sig_buf,
// Inputs
sig
);
// this repeater has 164 bits
output [163:0] sig_buf;
input [163:0] sig;
assign sig_buf = sig;
//output pcx_sctag_data_rdy_px1_buf;
//output [`PCX_WIDTH-1:0] pcx_sctag_data_px2_buf; // pcx to sctag packet
//output pcx_sctag_atm_px1_buf; // indicates that the current packet is atm with the next
//output sctag_pcx_stall_pq_buf;
//input pcx_sctag_data_rdy_px1;
//input [`PCX_WIDTH-1:0] pcx_sctag_data_px2; // pcx to sctag packet
//input pcx_sctag_atm_px1; // indicates that the current packet is atm with the next
//input sctag_pcx_stall_pq;
//assign pcx_sctag_data_rdy_px1_buf = pcx_sctag_data_rdy_px1;
//assign pcx_sctag_data_px2_buf = pcx_sctag_data_px2;
//assign pcx_sctag_atm_px1_buf = pcx_sctag_atm_px1;
//assign sctag_pcx_stall_pq_buf = sctag_pcx_stall_pq;
endmodule
|
/**
* This is written by Zhiyang Ong
* and Andrew Mattheisen
* for EE577b Troy WideWord Processor Project
*/
`timescale 1ns/10ps
/**
* `timescale time_unit base / precision base
*
* -Specifies the time units and precision for delays:
* -time_unit is the amount of time a delay of 1 represents.
* The time unit must be 1 10 or 100
* -base is the time base for each unit, ranging from seconds
* to femtoseconds, and must be: s ms us ns ps or fs
* -precision and base represent how many decimal points of
* precision to use relative to the time units.
*/
// Testbench for behavioral model for the program counter
// Import the modules that will be tested for in this testbench
//`include "prog_counter.v"
`include "program_counter.syn.v"
`include "/auto/home-scf-06/ee577/design_pdk/osu_stdcells/lib/tsmc018/lib/osu018_stdcells.v"
// IMPORTANT: To run this, try: ncverilog -f prog_counter.f +gui
module tb_prog_counter();
// ============================================================
/**
* Declare signal types for testbench to drive and monitor
* signals during the simulation of the prog_counter
*
* The reg data type holds a value until a new value is driven
* onto it in an "initial" or "always" block. It can only be
* assigned a value in an "always" or "initial" block, and is
* used to apply stimulus to the inputs of the DUT.
*
* The wire type is a passive data type that holds a value driven
* onto it by a port, assign statement or reg type. Wires cannot be
* assigned values inside "always" and "initial" blocks. They can
* be used to hold the values of the DUT's outputs
*/
// Declare "wire" signals: outputs from the DUT
// next_pc output signal
wire [0:31] n_pc;
// ============================================================
// Declare "reg" signals: inputs to the DUT
// clk, rst
reg clock,reset;
// cur_pc
reg [0:31] c_pc;
// ============================================================
// Counter for loop to enumerate all the values of r
integer count;
// ============================================================
// Defining constants: parameter [name_of_constant] = value;
//parameter size_of_input = 6'd32;
// ============================================================
/**
* Each sequential control block, such as the initial or always
* block, will execute concurrently in every module at the start
* of the simulation
*/
always begin
/**
* Clock frequency is arbitrarily chosen;
* Period = 5ns <==> 200 MHz clock
*/
#5 clock = 0;
#5 clock = 1;
end
// ============================================================
/**
* Instantiate an instance of regfile() so that
* inputs can be passed to the Device Under Test (DUT)
* Given instance name is "rg"
*/
program_counter pc (
// instance_name(signal name),
// Signal name can be the same as the instance name
// next_pc,cur_pc,rst,clk
n_pc,c_pc,reset,clock);
// ============================================================
/**
* Initial block start executing sequentially @ t=0
* If and when a delay is encountered, the execution of this block
* pauses or waits until the delay time has passed, before resuming
* execution
*
* Each intial or always block executes concurrently; that is,
* multiple "always" or "initial" blocks will execute simultaneously
*
* E.g.
* always
* begin
* #10 clk_50 = ~clk_50; // Invert clock signal every 10 ns
* // Clock signal has a period of 20 ns or 50 MHz
* end
*/
initial
begin
$sdf_annotate("../sdf/program_counter.sdf",pc,"TYPICAL", "1.0:1.0:1.0", "FROM_MTM");
// "$time" indicates the current time in the simulation
$display($time, " << Starting the simulation >>");
c_pc=$random;
reset=1'b1;
#9
c_pc=200;
reset=1'b0;
// Write to 8 data locations
for(count=200; count<216; count=count+1)
begin
#20
//c_pc=count;
c_pc=n_pc;
reset=1'b0;
end
// end simulation
#30
$display($time, " << Finishing the simulation >>");
$finish;
end
endmodule
|
//
// Copyright (c) 2015 Jan Adelsbach <[email protected]>.
// All Rights Reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
`define PDP1_SBS_ESM 11'o0055
`define PDP1_SBS_LSM 11'o0054
`define PDP1_SBS_CBS 11'o0056
`define PDP1_SBS_CKS 11'o0033
module pdp1_sbs(i_clk, i_rst,
sb_ireq, sb_dne,
pb_att, pb_op, pb_sqb,
tr_lp, tr_ptr, tr_tyo, tr_tyi, tr_tp, tr_drm);
input i_clk;
input i_rst;
output reg sb_ireq;
input sb_dne;
input pb_att;
input [0:10] pb_op;
output [0:5] pb_sqb;
input tr_lp;
input tr_ptr;
input tr_tyo;
input tr_tyi;
input tr_tp;
input tr_drm;
reg r_en;
wire w_tr_any;
assign pb_sqb = {tr_lp, tr_ptr, tr_tyo, tr_tyi, tr_tp, tr_drm, r_en};
assign w_tr_any = (|pb_sqb[0:4]);
always @(posedge i_clk) begin
if(i_rst) begin
sb_ireq <= 1'b0;
r_en <= 1'b0;
end
else begin
if(pb_att) begin
case(pb_op)
`PDP1_SBS_ESM:
r_en <= 1'b1;
`PDP1_SBS_LSM:
r_en <= 1'b0;
`PDP1_SBS_CBS:
sb_ireq <= 1'b0;
endcase // case (pb_op)
end
else begin
if(w_tr_any & ~sb_dne)
sb_ireq <= 1'b1;
else if(sb_dne & sb_ireq)
sb_ireq <= 1'b0;
end
end
end
endmodule // pdp1_sbs
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__DLRBN_PP_SYMBOL_V
`define SKY130_FD_SC_LP__DLRBN_PP_SYMBOL_V
/**
* dlrbn: Delay latch, inverted reset, inverted enable,
* complementary outputs.
*
* Verilog stub (with power pins) for graphical symbol definition
* generation.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_lp__dlrbn (
//# {{data|Data Signals}}
input D ,
output Q ,
output Q_N ,
//# {{control|Control Signals}}
input RESET_B,
//# {{clocks|Clocking}}
input GATE_N ,
//# {{power|Power}}
input VPB ,
input VPWR ,
input VGND ,
input VNB
);
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_LP__DLRBN_PP_SYMBOL_V
|
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** Suppose we are writing a program involving two record types
defined as follows:
<<
Person = {name:String, age:Nat}
Student = {name:String, age:Nat, gpa:Nat}
>>
*)
(** In the simply typed lamdba-calculus with records, the term
<<
(\r:Person. (r.age)+1) {name="Pat",age=21,gpa=1}
>>
is not typable: it involves an application of a function that wants
a one-field record to an argument that actually provides two
fields, while the [T_App] rule demands that the domain type of the
function being applied must match the type of the argument
precisely.
But this is silly: we're passing the function a _better_ argument
than it needs! The only thing the body of the function can
possibly do with its record argument [r] is project the field [age]
from it: nothing else is allowed by the type, and the presence or
absence of an extra [gpa] field makes no difference at all. So,
intuitively, it seems that this function should be applicable to
any record value that has at least an [age] field.
Looking at the same thing from another point of view, a record with
more fields is "at least as good in any context" as one with just a
subset of these fields, in the sense that any value belonging to
the longer record type can be used _safely_ in any context
expecting the shorter record type. If the context expects
something with the shorter type but we actually give it something
with the longer type, nothing bad will happen (formally, the
program will not get stuck).
The general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally written [S <: T], if a
value of type [S] can safely be used in any context where a value
of type [T] is expected. The idea of subtyping applies not only to
records, but to all of the type constructors in the language --
functions, pairs, etc. *)
(** ** Subtyping and Object-Oriented Languages *)
(** Subtyping plays a fundamental role in many programming
languages -- in particular, it is closely related to the notion of
_subclassing_ in object-oriented languages.
An _object_ in Java, C[#], etc. can be thought of as a record,
some of whose fields are functions ("methods") and some of whose
fields are data values ("fields" or "instance variables").
Invoking a method [m] of an object [o] on some arguments [a1..an]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of which methods
and which data fields the object offers.
Classes and interfaces are related by the _subclass_ and
_subinterface_ relations. An object belonging to a subclass (or
subinterface) is required to provide all the methods and fields of
one belonging to a superclass (or superinterface), plus possibly
some more.
The fact that an object from a subclass (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is is extremely handy for
organizing complex libraries. For example, a GUI toolkit like
Java's Swing framework might define an abstract interface
[Component] that collects together the common fields and methods
of all objects having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples of such object would include the buttons, checkboxes, and
scrollbars of a typical GUI. A method that relies only on this
common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other
features besides these. For example, fields can be updated.
Fields and methods can be declared [private]. Classes also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, etc., etc.
To keep things simple here, we won't deal with any of these
issues -- in fact, we won't even talk any more about objects or
classes. (There is a lot of discussion in _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** Our goal for this chapter is to add subtyping to the simply typed
lambda-calculus.
This involves two steps:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
The second step is actually very simple. We add just a single rule
to the typing relation: the so-called _rule of subsumption_:
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
This rule says, intuitively, that it is OK to "forget" some of
what we know about a term. *)
(** For example, we may know that [t] is a record with two
fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about
one of the fields ([T = {y:B->B}]) so that we can pass [t] to a
function that requires just a single-field record. *)
(** ** The Subtype Relation *)
(** The first step -- the definition of the relation [S <: T] -- is
where all the action is. Let's look at each of the clauses of its
definition. *)
(** *** Structural Rules *)
(** To start off, we impose two "structural rules" that are
independent of any particular type constructor: a rule of
_transitivity_, which says intuitively that, if [S] is better than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two functions [f] and [g] with these types:
f : C -> Student
g : (C->Person) -> D
That is, [f] is a function that yields a record of type [Student],
and [g] is a (higher-order) function that expects its (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, that
[Student] is a subtype of [Person]. Then the application [g f] is
safe even though their types do not match up precisely, because
the only thing [g] can do with [f] is to apply it to some
argument (of type [C]); the result will actually be a [Student],
while [g] will be expecting a [Person], but this is safe because
the only thing [g] can then do is to project out the two fields
that it knows about ([name] and [age]), and these will certainly
be among the fields that are present.
This example suggests that the subtyping rule for arrow types
should say that two arrow types are in the subtype relation if
their results are:
S2 <: T2
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> T2
We can generalize this to allow the arguments of the two arrow
types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
Notice that the argument types are subtypes "the other way round":
in order to conclude that [S1->S2] to be a subtype of [T1->T2], it
must be the case that [T1] is a subtype of [S1]. The arrow
constructor is said to be _contravariant_ in its first argument
and _covariant_ in its second.
Here is an example that illustrates this:
f : Person -> C
g : (Student -> C) -> D
The application [g f] is safe, because the only thing the body of
[g] can do with [f] is to apply it to some argument of type
[Student]. Since [f] requires records having (at least) the
fields of a [Person], this will always work. So [Person -> C] is a
subtype of [Student -> C] since [Student] is a subtype of
[Person].
The intuition is that, if we have a function [f] of type [S1->S2],
then we know that [f] accepts elements of type [S1]; clearly, [f]
will also accept elements of any subtype [T1] of [S1]. The type of
[f] also tells us that it returns elements of type [S2]; we can
also view these results belonging to any supertype [T2] of
[S2]. That is, any function [f] of type [S1->S2] can also be
viewed as having type [T1->T2].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types is that it is
always safe to use a "bigger" record in place of a "smaller" one.
That is, given a record type, adding extra fields will always
result in a subtype. If some code is expecting a record with
fields [x] and [y], it is perfectly safe for it to receive a record
with fields [x], [y], and [z]; the [z] field will simply be ignored.
For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}
{name:String, age:Nat} <: {name:String}
{name:String} <: {}
This is known as "width subtyping" for records. *)
(** We can also create a subtype of a record type by replacing the type
of one of its fields with a subtype. If some code is expecting a
record with a field [x] of type [T], it will be happy with a record
having a field [x] of type [S] as long as [S] is a subtype of
[T]. For example,
{x:Student} <: {x:Person}
This is known as "depth subtyping". *)
(** Finally, although the fields of a record type are written in a
particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as "permutation subtyping". *)
(** We could formalize these requirements in a single subtyping rule
for records as follows:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
That is, the record on the left should have all the field labels of
the one on the right (and possibly more), while the types of the
common fields should be in the subtype relation. However, this rule
is rather heavy and hard to read. If we like, we can decompose it
into three simpler rules, which can be combined using [S_Trans] to
achieve all the same effects. *)
(** First, adding fields to the end of a record type gives a subtype:
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
We can use [S_RcdWidth] to drop later fields of a multi-field
record while keeping earlier fields, showing for example that
[{age:Nat,name:String} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{name:String, gpa:Nat, age:Nat} <: Person]. We
haven't quite achieved this yet: using just [S_RcdDepth] and
[S_RcdWidth] we can only drop fields from the _end_ of a record
type. So we need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> T2
Give a concrete example of functions [f] and [g] with the following types...
f : Student -> Nat
g : (Person -> Nat) -> Nat
... such that the application [g f] will get stuck during
execution.
f : getGradeOfStudent...
g : getAgeNextYear...
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
element -- a type that lies above every other type and is
inhabited by all (well-typed) values. We do this by adding to the
language one new type constant, called [Top], together with a
subtyping rule that places it above every other type in the
subtype relation:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** Suppose we have types [S], [T], [U], and [V] with [S <: T]
and [U <: V]. Which of the following subtyping assertions
are then true? Write _true_ or _false_ after each one.
([A], [B], and [C] here are base types.)
- [T->S <: T->S]
true
- [Top->U <: S->Top]
true
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
true
- [T->T->U <: S->S->V]
true
- [(T->T)->U <: (S->S)->V]
false
- [((T->S)->T)->U <: ((S->T)->S)->V]
false
- [S*V <: T*U]
false
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
- [Top -> Student]
- [Person -> Student]
- [Student -> Person]
- [Student -> Top]
- [Top]
Where does the type [Top->Top->Student] fit into this order?
Cannot fit?
[Top->Top->Student] <: [Student -> Top]
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** Which of the following statements are true? Write _true_ or
_false_ after each one.
forall S T,
S <: T ->
S->S <: T->T
- false
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
- false
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
- true
exists S,
S <: S->S
- false
exists S,
S->S <: S
- true
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
- true
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
true
- There exists a type that is a subtype of every other type.
false
- There exists a pair type that is a supertype of every other
pair type.
true (top*top)
- There exists a pair type that is a subtype of every other
pair type.
false
- There exists an arrow type that is a supertype of every other
arrow type.
false
- There exists an arrow type that is a subtype of every other
arrow type.
false
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
true (top, top->top, top->top->top, ...)
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
false
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
False? Basic types don't always have subtypes.
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in the subtype
relation) that makes the following assertion true? (Assume we
have [Unit] among the base types and [unit] as a constant of this
type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) : A->A
(A->A)*unit <: T*Top /\ <: T <: A->A
A->A
- What is the _largest_ type [T] that makes the same assertion true?
A->A
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
(A->A * B->B) <: T
(A->A * B->B)
- What is the _largest_ type [T] that makes the same assertion true?
Top
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
A*T <: A*(A->A) /\ T = T1->T2 /\ A <: T1 /\ T2 <: A
Top->A
- What is the _largest_ type [T] that makes the same assertion true?
A->A
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
exists S, T = T1->T2 /\ A <: T1 /\ T2 <: S
Top->A
- What is the _largest_ type [T] that makes the same
assertion true?
A->Top
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
None. [x x] is not typeable.
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
(A->A)*(B->B) <: Top /\ Top <: T
Top
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,
how many different types [T] are there such that [{x:A, y:C->C} <:
T]? (We consider two types to be different if they are written
differently, even if each is a subtype of the other. For example,
[{x:A,y:B}] and [{y:B,x:A}] are different.)
19
{x:A, y:C->C}, {x:A, y:C->Top}, {x:A, y:Top},
{x:Top, y:C->C}, {x:Top, y:C->Top}, {x:Top, y:Top},
{y:C->C, x:A}, {y:C->Top, x:A}, {y:Top, x:A},
{y:C->C, x:Top}, {y:C->Top, x:Top}, {y:Top, x:Top},
{y:C->C}, {y:C->Top}, {y:Top}, {x:A}, {x:Top}, {}, Top
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
Of cause not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- in particular, the syntax and
operational semantics of the language -- are identical to what we
saw in the last chapter. We just need to extend the typing
relation with the subsumption rule and add a new [Inductive]
definition for the subtyping relation. Let's first do the
identical bits. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** In the rest of the chapter, we formalize just base types,
booleans, arrow types, [Unit], and [Top], omitting record types
and leaving product types as an exercise. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
(* prod *)
| TProd : ty -> ty -> ty
.
Notation "T1 '**' T2" := (TProd T1 T2) (at level 20, right associativity).
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" | Case_aux c "TProd"
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
(* pairs *)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most interesting part. We begin by
defining the subtyping relation and developing some of its
important technical properties. *)
(** The definition of subtyping is just what we sketched in the
motivating discussion. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
(*
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
*)
| S_Prod : forall S1 S2 T1 T2,
S1 <: T1 ->
S2 <: T2 ->
S1 ** S2 <: T1 ** T2
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow" | Case_aux c "S_Prod"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty := String ** TTop ** TTop.
Definition Student : ty := String ** Float ** TTop.
Definition Employee : ty := String ** TTop ** Integer.
Example sub_student_person :
Student <: Person.
Proof.
unfold Student, Person. auto.
Qed.
Example sub_employee_person :
Employee <: Person.
Proof.
unfold Employee, Person. auto.
Qed.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
unfold Student, Person...
Qed.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
unfold Person...
Qed.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (T1 ** T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (T1 ** T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (T1 ** T2) ->
Gamma |- (tsnd t) \in T2
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit" | Case_aux c "T_Sub"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** Do the following exercises after you have added product types to
the language. For each informal typing judgement, write it as a
formal statement in Coq and prove it. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
Lemma typing_example_0 :
forall A B z,
empty |- (tpair (tabs z A (tvar z))
(tabs z B (tvar z)))
\in (TArrow A A ** TArrow B B).
Proof.
intros. apply T_Pair; apply T_Abs; apply T_Var; apply extend_eq.
Qed.
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
Lemma typing_example_1 :
forall A B x z,
empty |- (tapp
(tabs x (TTop ** TArrow B B) (tsnd (tvar x)))
(tpair (tabs z A (tvar z)) (tabs z B (tvar z))))
\in (TArrow B B).
Proof.
intros.
eapply T_App.
apply T_Abs. eapply T_Snd. apply T_Var. apply extend_eq.
apply T_Pair. eapply T_Sub.
apply T_Abs. apply T_Var. apply extend_eq. apply S_Top.
apply T_Abs. apply T_Var. apply extend_eq.
Qed.
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
Lemma typing_example_2 :
forall A B x z,
empty |- (tapp
(tabs z (TArrow (TArrow C C) (TTop ** TArrow B B))
(tsnd (tapp (tvar z) (tabs x C (tvar x)))))
(tabs z (TArrow C C)
(tpair (tabs z A (tvar z)) (tabs z B (tvar z)))))
\in (TArrow B B).
Proof.
intros.
eapply T_App.
apply T_Abs. eapply T_Snd. eapply T_App. apply T_Var.
apply extend_eq. apply T_Abs. apply T_Var. apply extend_eq.
apply T_Abs. apply T_Pair. eapply T_Sub.
apply T_Abs. apply T_Var. apply extend_eq. apply S_Top.
apply T_Abs. apply T_Var. apply extend_eq.
Qed.
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** The fundamental properties of the system that we want to check are
the same as always: progress and preservation. Unlike the
extension of the STLC with references, we don't need to change the
_statements_ of these properties to take subtyping into account.
However, their proofs do become a little bit more involved. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later proofs as the built-in [inversion] tactic: given a
hypothesis that there exists a derivation of some subtyping
statement [S <: T] and some constraints on the shape of [S] and/or
[T], each one reasons about what this derivation must look like to
tell us something further about the shapes of [S] and [T] and the
existence of subtype relations between their parts. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
destruct U;
(induction Hs; try solve by inversion; auto);
rewrite (IHHs2 HeqV) in *;
rewrite (IHHs1 HeqV) in *;
auto.
Qed.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
subtype_cases (induction Hs) Case; intros.
Case "S_Refl".
exists V1, V2. split; auto.
Case "S_Trans".
apply IHHs2 in HeqV.
destruct HeqV as [U1 [U2 [HU [HV1U1 HU2V2]]]].
apply IHHs1 in HU.
destruct HU as [W1 [W2 [HS [HU1W1 HW2U2]]]].
exists W1, W2.
split. auto. split.
apply S_Trans with U1; auto.
apply S_Trans with U2; auto.
Case "S_Top".
solve by inversion.
Case "S_Arrow".
inversion HeqV; subst.
exists S1, S2. split; auto.
Case "S_Prod".
solve by inversion.
Qed.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
change too much -- we just need one small refinement. When we're
considering the case where the term in question is an application
[t1 t2] where both [t1] and [t2] are values, we need to know that
[t1] has the _form_ of a lambda-abstraction, so that we can apply
the [ST_AppAbs] reduction rule. In the ordinary STLC, this is
obvious: we know that [t1] has a function type [T11->T12], and
there is only one rule that can be used to give a function type to
a value -- rule [T_Abs] -- and the form of the conclusion of this
rule forces [t1] to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work
because there's another rule that can be used to show that a value
has a function type: subsumption. Fortunately, this possibility
doesn't change things much: if the last rule used to show [Gamma
|- t1 : T11->T12] is subsumption, then there is some
_sub_-derivation whose subject is also [t1], and we can reason by
induction until we finally bottom out at a use of [T_Abs].
This bit of reasoning is packaged up in the following lemma, which
tells us the possible "canonical forms" (i.e. values) of function
type. *)
(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
Gamma |- s \in (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
intros.
remember (TArrow T1 T2) as T. (* tricky, see following lemma *)
generalize dependent T2. generalize dependent T1.
has_type_cases (induction H) Case;
intros; try solve by inversion...
subst. apply sub_inversion_arrow in H1.
destruct H1 as [U1 [U2 [H2 [H3 H4]]]]...
Qed.
(** [] *)
(** Similarly, the canonical forms of type [Bool] are the constants
[true] and [false]. *)
Lemma canonical_forms_of_Bool : forall Gamma s,
Gamma |- s \in TBool ->
value s ->
(s = ttrue \/ s = tfalse).
Proof with eauto.
intros Gamma s Hty Hv.
remember TBool as T.
has_type_cases (induction Hty) Case; try solve by inversion...
Case "T_Sub".
subst. apply sub_inversion_Bool in H. subst...
Qed.
Lemma sub_inversion_pair : forall U V1 V2,
U <: V1 ** V2 ->
exists U1, exists U2,
U = U1 ** U2 /\ (U1 <: V1) /\ (U2 <: V2).
Proof with auto.
intros U V1 V2 Hs.
remember (V1 ** V2) as V.
generalize dependent V2. generalize dependent V1.
subtype_cases (induction Hs) Case; intros.
Case "S_Refl". exists V1, V2. split; auto.
Case "S_Trans".
apply IHHs2 in HeqV.
destruct HeqV as [U1 [U2 [HU [HU1V1 HU2V2]]]].
apply IHHs1 in HU.
destruct HU as [W1 [W2 [HS [HW1U1 HW2V2]]]].
exists W1, W2.
split. auto. split. auto.
apply S_Trans with U1; auto.
apply S_Trans with U2; auto.
Case "S_Top". solve by inversion.
Case "S_Arrow". inversion HeqV; subst...
Case "S_Prod". inversion HeqV; subst. exists S1, S2...
Qed.
Lemma canonical_forms_of_pair : forall Gamma t T1 T2,
Gamma |- t \in T1 ** T2 ->
value t ->
exists v1, exists v2, t = tpair v1 v2 .
Proof with eauto.
intros.
remember (T1 ** T2) as T.
revert HeqT. revert T2. revert T1.
has_type_cases (induction H) Case;
intros; try solve by inversion...
subst. apply sub_inversion_pair in H1.
destruct H1 as [U1 [U2 [HS [HUT1 HUT2]]]].
eauto.
Qed.
(* ########################################## *)
(** ** Progress *)
(** The proof of progress proceeds like the one for the pure
STLC, except that in several places we invoke canonical forms
lemmas... *)
(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-
t : T] then [t] is a value or [t ==> t'] for some term [t'].
_Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed
by induction on the typing derivation.
The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are
immediate because abstractions, [unit], [true], and [false] are
already values. The [T_Var] case is vacuous because variables
cannot be typed in the empty context. The remaining cases are
more interesting:
- If the last step in the typing derivation uses rule [T_App],
then there are terms [t1] [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-
t2 : T1]. Moreover, by the induction hypothesis, either [t1] is
a value or it steps, and either [t2] is a value or it steps.
There are three possibilities to consider:
- Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]
by [ST_App1].
- Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].
Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a
value.
- Finally, suppose [t1] and [t2] are both values. By Lemma
[canonical_forms_for_arrow_types], we know that [t1] has the
form [\x:S1.s2] for some [x], [S1], and [s2]. But then
[(\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a
value.
- If the final step of the derivation uses rule [T_If], then there
are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else
t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and
[empty |- t3 : T]. Moreover, by the induction hypothesis,
either [t1] is a value or it steps.
- If [t1] is a value, then by the canonical forms lemma for
booleans, either [t1 = true] or [t1 = false]. In either
case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].
- If [t1] can step, then so can [t], by rule [ST_If].
- If the final step of the derivation is by [T_Sub], then there is
a type [S] such that [S <: T] and [empty |- t : S]. The desired
result is exactly the induction hypothesis for the typing
subderivation.
*)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_If".
right.
destruct IHHt1.
SCase "t1 is a value"...
assert (t1 = ttrue \/ t1 = tfalse)
by (eapply canonical_forms_of_Bool; eauto).
inversion H0; subst...
inversion H. rename x into t1'. eauto.
Case "T_Pair".
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 steps".
destruct H0 as [t2' H1]. right...
SCase "t1 steps".
destruct H as [t1' H1]. right...
Case "T_Fst".
right. destruct IHHt; subst...
SCase "t is a value".
destruct (canonical_forms_of_pair empty t T1 T2 Ht H)
as [V1 [V2 He]].
subst. inversion H; subst...
SCase "t steps". inversion H...
Case "T_Snd".
right. destruct IHHt; subst...
SCase "t is a value".
destruct (canonical_forms_of_pair empty t T1 T2 Ht H)
as [V1 [V2 He]].
subst. inversion H; subst...
SCase "t steps". inversion H...
Qed.
(* ########################################## *)
(** ** Inversion Lemmas for Typing *)
(** The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the "inversion lemmas for subtyping" above, there are a
number of facts about the typing relation that are "obvious from
the definition" in the pure STLC (and hence can be obtained
directly from the [inversion] tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same [has_type] statement.
The following "inversion lemma" tells us that, if we have a
derivation of some typing statement [Gamma |- \x:S1.t2 : T] whose
subject is an abstraction, then there must be some subderivation
giving a type to the body [t2]. *)
(** _Lemma_: If [Gamma |- \x:S1.t2 : T], then there is a type [S2]
such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].
(Notice that the lemma does _not_ say, "then [T] itself is an arrow
type" -- this is tempting, but false!)
_Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as
described. Proceed by induction on the derivation of [Gamma |-
\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those
rules cannot be used to give a type to a syntactic abstraction.
- If the last step of the derivation is a use of [T_Abs] then
there is a type [T12] such that [T = S1 -> T12] and [Gamma,
x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we
need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].
- If the last step of the derivation is a use of [T_Sub] then
there is a type [S] such that [S <: T] and [Gamma |- \x:S1.t2 :
S]. The IH for the typing subderivation tell us that there is
some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :
S2]. Picking type [S2] gives us what we need, since [S1 -> S2
<: T] then follows by [S_Trans]. *)
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
Gamma |- (tabs x S1 t2) \in T ->
(exists S2, (TArrow S1 S2) <: T
/\ (extend Gamma x S1) |- t2 \in S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
(** Similarly... *)
Lemma typing_inversion_var : forall Gamma x T,
Gamma |- (tvar x) \in T ->
exists S,
Gamma x = Some S /\ S <: T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
Gamma |- (tapp t1 t2) \in T2 ->
exists T1,
Gamma |- t1 \in (TArrow T1 T2) /\
Gamma |- t2 \in T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
Qed.
Lemma typing_inversion_true : forall Gamma T,
Gamma |- ttrue \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember ttrue as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_false : forall Gamma T,
Gamma |- tfalse \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember tfalse as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_if : forall Gamma t1 t2 t3 T,
Gamma |- (tif t1 t2 t3) \in T ->
Gamma |- t1 \in TBool
/\ Gamma |- t2 \in T
/\ Gamma |- t3 \in T.
Proof with eauto.
intros Gamma t1 t2 t3 T Hty.
remember (tif t1 t2 t3) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_If".
auto.
Case "T_Sub".
destruct (IHHty H0) as [H1 [H2 H3]]...
Qed.
Lemma typing_inversion_unit : forall Gamma T,
Gamma |- tunit \in T ->
TUnit <: T.
Proof with eauto.
intros Gamma T Htyp. remember tunit as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_pair : forall Gamma t1 t2 T,
Gamma |- (tpair t1 t2) \in T ->
exists T1, exists T2,
T1 ** T2 <: T /\ Gamma |- t1 \in T1 /\ Gamma |- t2 \in T2.
Proof with eauto.
intros Gamma t1 t2 T Hty.
remember (tpair t1 t2) as t.
has_type_cases (induction Hty) Case;
intros; inversion Heqt; subst; try solve by inversion.
Case "T_Sub".
destruct (IHHty H0) as [T1 [T2 [HS [H1 H2]]]].
exists T1, T2. split; auto. eapply S_Trans...
Case "T_Pair".
exists T1, T2...
Qed.
Lemma typing_inversion_fst : forall Gamma t T,
Gamma |- (tfst t) \in T ->
exists T1, exists T2,
T1 <: T
/\ Gamma |- t \in (T1 ** T2).
Proof with eauto.
intros Gamma t0 T Hty.
remember (tfst t0) as t.
has_type_cases (induction Hty) Case;
intros; inversion Heqt; subst; try solve by inversion.
Case "T_Sub".
destruct (IHHty H0) as [T1 [T2 [H1 H2]]]...
Case "T_Fst".
exists T1, T2...
Qed.
Lemma typing_inversion_snd : forall Gamma t T,
Gamma |- (tsnd t) \in T ->
exists T1, exists T2,
T2 <: T
/\ Gamma |- t \in (T1 ** T2).
Proof with eauto.
intros Gamma t0 T Hty.
remember (tsnd t0) as t.
has_type_cases (induction Hty) Case;
intros; inversion Heqt; subst; try solve by inversion.
Case "T_Sub".
destruct (IHHty H0) as [T1 [T2 [H1 H2]]]...
Case "T_Snd".
exists T1, T2...
Qed.
(** The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful "combination lemma" telling
us exactly what we'll actually require below. *)
Lemma abs_arrow : forall x S1 s2 T1 T2,
empty |- (tabs x S1 s2) \in (TArrow T1 T2) ->
T1 <: S1
/\ (extend empty x S1) |- s2 \in T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
inversion Hty as [S2 [Hsub Hty1]].
apply sub_inversion_arrow in Hsub.
inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
Lemma pair_prod : forall t1 t2 T1 T2,
empty |- (tpair t1 t2) \in (T1 ** T2) ->
empty |- t1 \in T1 /\ empty |- t2 \in T2.
Proof with eauto.
intros t1 t2 T1 T2 Hty.
apply typing_inversion_pair in Hty.
destruct Hty as [U1 [U2 [HUT [H1 H2]]]].
apply sub_inversion_pair in HUT.
destruct HUT as [V1 [V2 [HUV [H3 H4]]]].
inversion HUV; subst...
Qed.
(* ########################################## *)
(** ** Context Invariance *)
(** The context invariance lemma follows the same pattern as in the
pure STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_If".
apply T_If...
Case "T_Pair".
apply T_Pair...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case;
subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H4) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** ** Substitution *)
(** The _substitution lemma_ is proved along the same lines as
for the pure STLC. The only significant change is that there are
several places where, instead of the built-in [inversion] tactic,
we need to use the inversion lemmas that we proved above to
extract structural information from assumptions about the
well-typedness of subterms. *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt)
as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra)
as [T' HT']...
inversion HT'.
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt)
as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "ttrue".
assert (TBool <: S)
by apply (typing_inversion_true _ _ Htypt)...
Case "tfalse".
assert (TBool <: S)
by apply (typing_inversion_false _ _ Htypt)...
Case "tif".
assert ((extend Gamma x U) |- t1 \in TBool
/\ (extend Gamma x U) |- t2 \in S
/\ (extend Gamma x U) |- t3 \in S)
by apply (typing_inversion_if _ _ _ _ _ Htypt).
inversion H as [H1 [H2 H3]].
apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.
auto.
Case "tunit".
assert (TUnit <: S)
by apply (typing_inversion_unit _ _ Htypt)...
Case "tpair".
destruct (typing_inversion_pair _ _ _ _ Htypt)
as [T1 [T2 [H1 [H2 H3]]]].
inversion H1; subst...
Case "tfst".
destruct (typing_inversion_fst _ _ _ Htypt)
as [T1 [T2 [H1 H2]]].
inversion H1; subst...
Case "tsnd".
destruct (typing_inversion_snd _ _ _ Htypt)
as [T1 [T2 [H1 H2]]].
inversion H1; subst...
Qed.
(* ########################################## *)
(** ** Preservation *)
(** The proof of preservation now proceeds pretty much as in earlier
chapters, using the substitution lemma at the appropriate point
and again using inversion lemmas from above to extract structural
information from typing assumptions. *)
(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type
such that [empty |- t : T] and [t ==> t'], then [empty |- t' :
T].
_Proof_: Let [t] and [T] be given such that [empty |- t : T]. We
proceed by induction on the structure of this typing derivation,
leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and
[T_False] cases are vacuous because abstractions and constants
don't step. Case [T_Var] is vacuous as well, since the context is
empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] and [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and
[empty |- t2 : T1].
By the definition of the step relation, there are three ways
[t1 t2] can step. Cases [ST_App1] and [ST_App2] follow
immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =
\x:S.t12] for some type [S] and term [t12], and [t' =
[x:=t2]t12].
By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by the substitution lemma
([substitution_preserves_typing]) that [empty |- [x:=t2]
t12 : T2] as desired.
- If the final step of the derivation uses rule [T_If], then
there are terms [t1], [t2], and [t3] such that [t = if t1 then
t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :
T] and [empty |- t3 : T]. Moreover, by the induction
hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].
There are three cases to consider, depending on which rule was
used to show [t ==> t'].
- If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2
else t3] with [t1 ==> t1']. By the induction hypothesis,
[empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].
- If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then
either [t' = t2] or [t' = t3], and [empty |- t' : T]
follows by assumption.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub]. [] *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Case "T_Fst".
inversion HE; subst...
destruct (pair_prod _ _ _ _ HT)...
Case "T_Snd".
inversion HE; subst...
destruct (pair_prod _ _ _ _ HT)...
Qed.
(** ** Records, via Products and Top *)
(** This formalization of the STLC with subtyping has omitted record
types, for brevity. If we want to deal with them more seriously,
we have two choices.
First, we can treat them as part of the core language, writing
down proper syntax, typing, and subtyping rules for them. Chapter
[RecordSub] shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and [Unit] types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
[Unit] as the base case in the encoding of tuples and the "don't
care" placeholder in the encoding of records, we use [Top]. So:
<<
{a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))
{c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))
>>
The encoding of record values doesn't change at all. It is
easy (and instructive) to check that the subtyping rules above are
validated by the encoding. For the rest of this chapter, we'll
follow this encoding-based approach. *)
(* ###################################################### *)
(** ** Exercises *)
(* Inductive value : tm -> Prop :=
| v_abs : forall x T t, value (tabs x T t)
| v_true : value ttrue
| v_false : value tfalse
| v_unit : value tunit *)
(* Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'. *)
(* Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T. *)
(** **** Exercise: 2 stars (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with Unit and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
neither
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
preservation
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
neither
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
neither
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
neither
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
both
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
preservation
[] *)
(* ###################################################################### *)
(** * Exercise: Adding Products *)
(** **** Exercise: 4 stars (products) *)
(** Adding pairs, projections, and product types to the system we have
defined is a relatively straightforward matter. Carry out this
extension:
- Add constructors for pairs, first and second projections, and
product types to the definitions of [ty] and [tm]. (Don't
forget to add corresponding cases to [T_cases] and [t_cases].)
- Extend the substitution function and value relation as in
MoreSTLC.
- Extend the operational semantics with the same reduction rules
as in MoreSTLC.
- Extend the subtyping relation with this rule:
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
- Extend the typing relation with the same rules for pairs and
projections as in MoreSTLC.
- Extend the proofs of progress, preservation, and all their
supporting lemmas to deal with the new constructs. (You'll also
need to add some completely new lemmas.)
[] *)
(* $Date: 2014-12-01 15:16:08 -0500 (Mon, 01 Dec 2014) $ *)
|
// Copyright 1986-2016 Xilinx, Inc. All Rights Reserved.
// --------------------------------------------------------------------------------
// Tool Version: Vivado v.2016.4 (lin64) Build 1733598 Wed Dec 14 22:35:42 MST 2016
// Date : Sat Jan 21 17:57:15 2017
// Host : natu-OMEN-by-HP-Laptop running 64-bit Ubuntu 16.04.1 LTS
// Command : write_verilog -force -mode synth_stub -rename_top decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix -prefix
// decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix_ mul8_8_stub.v
// Design : mul8_8
// Purpose : Stub declaration of top-level module interface
// Device : xcku035-fbva676-3-e
// --------------------------------------------------------------------------------
// This empty module with port declaration file causes synthesis tools to infer a black box for IP.
// The synthesis directives are for Synopsys Synplify support to prevent IO buffer insertion.
// Please paste the declaration into a Verilog source file or add the file as an additional source.
(* x_core_info = "mult_gen_v12_0_12,Vivado 2016.4" *)
module decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix(CLK, A, B, P)
/* synthesis syn_black_box black_box_pad_pin="CLK,A[7:0],B[7:0],P[15:0]" */;
input CLK;
input [7:0]A;
input [7:0]B;
output [15:0]P;
endmodule
|
// file: clk_166M_83M_exdes.v
//
// (c) Copyright 2008 - 2011 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
//----------------------------------------------------------------------------
// Clocking wizard example design
//----------------------------------------------------------------------------
// This example design instantiates the created clocking network, where each
// output clock drives a counter. The high bit of each counter is ported.
//----------------------------------------------------------------------------
`timescale 1ps/1ps
module clk_166M_83M_exdes
#(
parameter TCQ = 100
)
(// Clock in ports
input CLK_IN1,
// Reset that only drives logic in example design
input COUNTER_RESET,
// High bits of counters driven by clocks
output [3:1] COUNT,
// Status and control signals
input RESET,
output LOCKED
);
// Parameters for the counters
//-------------------------------
// Counter width
localparam C_W = 16;
// Number of counters
localparam NUM_C = 3;
genvar count_gen;
// When the clock goes out of lock, reset the counters
wire reset_int = !LOCKED || RESET || COUNTER_RESET;
reg [NUM_C:1] rst_sync;
reg [NUM_C:1] rst_sync_int;
reg [NUM_C:1] rst_sync_int1;
reg [NUM_C:1] rst_sync_int2;
// Declare the clocks and counters
wire [NUM_C:1] clk_int;
wire [NUM_C:1] clk;
reg [C_W-1:0] counter [NUM_C:1];
// Instantiation of the clocking network
//--------------------------------------
clk_166M_83M clknetwork
(// Clock in ports
.CLK_IN1 (CLK_IN1),
// Clock out ports
.CLK_OUT1 (clk_int[1]),
.CLK_OUT2 (clk_int[2]),
.CLK_OUT3 (clk_int[3]),
// Status and control signals
.RESET (RESET),
.LOCKED (LOCKED));
// Connect the output clocks to the design
//-----------------------------------------
assign clk[1] = clk_int[1];
assign clk[2] = clk_int[2];
assign clk[3] = clk_int[3];
// Reset synchronizer
//-----------------------------------
generate for (count_gen = 1; count_gen <= NUM_C; count_gen = count_gen + 1) begin: counters_1
always @(posedge reset_int or posedge clk[count_gen]) begin
if (reset_int) begin
rst_sync[count_gen] <= 1'b1;
rst_sync_int[count_gen]<= 1'b1;
rst_sync_int1[count_gen]<= 1'b1;
rst_sync_int2[count_gen]<= 1'b1;
end
else begin
rst_sync[count_gen] <= 1'b0;
rst_sync_int[count_gen] <= rst_sync[count_gen];
rst_sync_int1[count_gen] <= rst_sync_int[count_gen];
rst_sync_int2[count_gen] <= rst_sync_int1[count_gen];
end
end
end
endgenerate
// Output clock sampling
//-----------------------------------
generate for (count_gen = 1; count_gen <= NUM_C; count_gen = count_gen + 1) begin: counters
always @(posedge clk[count_gen] or posedge rst_sync_int2[count_gen]) begin
if (rst_sync_int2[count_gen]) begin
counter[count_gen] <= #TCQ { C_W { 1'b 0 } };
end else begin
counter[count_gen] <= #TCQ counter[count_gen] + 1'b 1;
end
end
// alias the high bit of each counter to the corresponding
// bit in the output bus
assign COUNT[count_gen] = counter[count_gen][C_W-1];
end
endgenerate
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HS__SDLCLKP_BEHAVIORAL_V
`define SKY130_FD_SC_HS__SDLCLKP_BEHAVIORAL_V
/**
* sdlclkp: Scan gated clock.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import sub cells.
`include "../u_dl_p_no_pg/sky130_fd_sc_hs__u_dl_p_no_pg.v"
`celldefine
module sky130_fd_sc_hs__sdlclkp (
GCLK,
GATE,
CLK ,
SCE ,
VPWR,
VGND
);
// Module ports
output GCLK;
input GATE;
input CLK ;
input SCE ;
input VPWR;
input VGND;
// Local signals
wire m0 ;
wire m0n ;
wire clkn ;
wire CLK_delayed ;
wire SCE_delayed ;
wire GATE_delayed ;
wire SCE_gate_delayed;
reg notifier ;
wire awake ;
wire SCE_awake ;
wire GATE_awake ;
// Name Output Other arguments
not not0 (m0n , m0 );
not not1 (clkn , CLK_delayed );
nor nor0 (SCE_gate_delayed, GATE_delayed, SCE_delayed );
sky130_fd_sc_hs__u_dl_p_no_pg u_dl_p_no_pg0 (m0 , SCE_gate_delayed, clkn, notifier, VPWR, VGND);
and and0 (GCLK , m0n, CLK_delayed );
assign awake = ( VPWR === 1'b1 );
assign SCE_awake = ( awake & ( GATE_delayed === 1'b0 ) );
assign GATE_awake = ( awake & ( SCE_delayed === 1'b0 ) );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_HS__SDLCLKP_BEHAVIORAL_V |
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 01/11/2016 09:49:31 PM
// Design Name:
// Module Name: Problem2
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Problem2(
input A,
input B,
input C,
input D,
output reg X
);
always @ (A or B or C or D)
begin
if ((~A & B & ~C & ~D) == 1)
X = 1;
else if ((~A & ~B & C & D) == 1)
X = 1;
else if ((A & D & ~B & ~C) == 1)
X = 1;
else if ((A & B & C & ~D) == 1)
X = 1;
else if ((~A & ~B & C & ~D) == 1)
X = 1;
//else if ((A & D & ~ B & C) == 1)
//X = 1;
else if ((D & ~B & C) == 1)
X = 1;
else if ((~A & B & C & D) == 1)
X = 1;
else if ((A & ~B & C & ~D) == 1)
X = 1;
else if ((~A & ~B & C & ~D) == 1)
X = 1;
else if ((A & B & C & D) == 1)
X = 1;
else
X = 0;
end
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__AND2_FUNCTIONAL_PP_V
`define SKY130_FD_SC_LP__AND2_FUNCTIONAL_PP_V
/**
* and2: 2-input AND.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_lp__udp_pwrgood_pp_pg.v"
`celldefine
module sky130_fd_sc_lp__and2 (
X ,
A ,
B ,
VPWR,
VGND,
VPB ,
VNB
);
// Module ports
output X ;
input A ;
input B ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
// Local signals
wire and0_out_X ;
wire pwrgood_pp0_out_X;
// Name Output Other arguments
and and0 (and0_out_X , A, B );
sky130_fd_sc_lp__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_X, and0_out_X, VPWR, VGND);
buf buf0 (X , pwrgood_pp0_out_X );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_LP__AND2_FUNCTIONAL_PP_V |
// megafunction wizard: %ROM: 1-PORT%
// GENERATION: STANDARD
// VERSION: WM1.0
// MODULE: altsyncram
// ============================================================
// File Name: bios.v
// Megafunction Name(s):
// altsyncram
//
// Simulation Library Files(s):
// altera_mf
// ============================================================
// ************************************************************
// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
//
// 13.1.4 Build 182 03/12/2014 SJ Full Version
// ************************************************************
//Copyright (C) 1991-2014 Altera Corporation
//Your use of Altera Corporation's design tools, logic functions
//and other software and tools, and its AMPP partner logic
//functions, and any output files from any of the foregoing
//(including device programming or simulation files), and any
//associated documentation or information are expressly subject
//to the terms and conditions of the Altera Program License
//Subscription Agreement, Altera MegaCore Function License
//Agreement, or other applicable license agreement, including,
//without limitation, that your use is for the sole purpose of
//programming logic devices manufactured by Altera and sold by
//Altera or its authorized distributors. Please refer to the
//applicable agreement for further details.
// synopsys translate_off
`timescale 1 ps / 1 ps
// synopsys translate_on
module bios (
address,
clock,
q);
input [11:0] address;
input clock;
output [7:0] q;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
tri1 clock;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif
wire [7:0] sub_wire0;
wire [7:0] q = sub_wire0[7:0];
altsyncram altsyncram_component (
.address_a (address),
.clock0 (clock),
.q_a (sub_wire0),
.aclr0 (1'b0),
.aclr1 (1'b0),
.address_b (1'b1),
.addressstall_a (1'b0),
.addressstall_b (1'b0),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_a ({8{1'b1}}),
.data_b (1'b1),
.eccstatus (),
.q_b (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_a (1'b0),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_a = "NONE",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_output_a = "BYPASS",
altsyncram_component.init_file = "bios.mif",
altsyncram_component.intended_device_family = "Cyclone III",
altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = 4096,
altsyncram_component.operation_mode = "ROM",
altsyncram_component.outdata_aclr_a = "NONE",
altsyncram_component.outdata_reg_a = "UNREGISTERED",
altsyncram_component.widthad_a = 12,
altsyncram_component.width_a = 8,
altsyncram_component.width_byteena_a = 1;
endmodule
// ============================================================
// CNX file retrieval info
// ============================================================
// Retrieval info: PRIVATE: ADDRESSSTALL_A NUMERIC "0"
// Retrieval info: PRIVATE: AclrAddr NUMERIC "0"
// Retrieval info: PRIVATE: AclrByte NUMERIC "0"
// Retrieval info: PRIVATE: AclrOutput NUMERIC "0"
// Retrieval info: PRIVATE: BYTE_ENABLE NUMERIC "0"
// Retrieval info: PRIVATE: BYTE_SIZE NUMERIC "8"
// Retrieval info: PRIVATE: BlankMemory NUMERIC "0"
// Retrieval info: PRIVATE: CLOCK_ENABLE_INPUT_A NUMERIC "0"
// Retrieval info: PRIVATE: CLOCK_ENABLE_OUTPUT_A NUMERIC "0"
// Retrieval info: PRIVATE: Clken NUMERIC "0"
// Retrieval info: PRIVATE: IMPLEMENT_IN_LES NUMERIC "0"
// Retrieval info: PRIVATE: INIT_FILE_LAYOUT STRING "PORT_A"
// Retrieval info: PRIVATE: INIT_TO_SIM_X NUMERIC "0"
// Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone III"
// Retrieval info: PRIVATE: JTAG_ENABLED NUMERIC "0"
// Retrieval info: PRIVATE: JTAG_ID STRING "NONE"
// Retrieval info: PRIVATE: MAXIMUM_DEPTH NUMERIC "0"
// Retrieval info: PRIVATE: MIFfilename STRING "bios.mif"
// Retrieval info: PRIVATE: NUMWORDS_A NUMERIC "4096"
// Retrieval info: PRIVATE: RAM_BLOCK_TYPE NUMERIC "0"
// Retrieval info: PRIVATE: RegAddr NUMERIC "1"
// Retrieval info: PRIVATE: RegOutput NUMERIC "0"
// Retrieval info: PRIVATE: SYNTH_WRAPPER_GEN_POSTFIX STRING "0"
// Retrieval info: PRIVATE: SingleClock NUMERIC "1"
// Retrieval info: PRIVATE: UseDQRAM NUMERIC "0"
// Retrieval info: PRIVATE: WidthAddr NUMERIC "12"
// Retrieval info: PRIVATE: WidthData NUMERIC "8"
// Retrieval info: PRIVATE: rden NUMERIC "0"
// Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all
// Retrieval info: CONSTANT: ADDRESS_ACLR_A STRING "NONE"
// Retrieval info: CONSTANT: CLOCK_ENABLE_INPUT_A STRING "BYPASS"
// Retrieval info: CONSTANT: CLOCK_ENABLE_OUTPUT_A STRING "BYPASS"
// Retrieval info: CONSTANT: INIT_FILE STRING "bios.mif"
// Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "Cyclone III"
// Retrieval info: CONSTANT: LPM_HINT STRING "ENABLE_RUNTIME_MOD=NO"
// Retrieval info: CONSTANT: LPM_TYPE STRING "altsyncram"
// Retrieval info: CONSTANT: NUMWORDS_A NUMERIC "4096"
// Retrieval info: CONSTANT: OPERATION_MODE STRING "ROM"
// Retrieval info: CONSTANT: OUTDATA_ACLR_A STRING "NONE"
// Retrieval info: CONSTANT: OUTDATA_REG_A STRING "UNREGISTERED"
// Retrieval info: CONSTANT: WIDTHAD_A NUMERIC "12"
// Retrieval info: CONSTANT: WIDTH_A NUMERIC "8"
// Retrieval info: CONSTANT: WIDTH_BYTEENA_A NUMERIC "1"
// Retrieval info: USED_PORT: address 0 0 12 0 INPUT NODEFVAL "address[11..0]"
// Retrieval info: USED_PORT: clock 0 0 0 0 INPUT VCC "clock"
// Retrieval info: USED_PORT: q 0 0 8 0 OUTPUT NODEFVAL "q[7..0]"
// Retrieval info: CONNECT: @address_a 0 0 12 0 address 0 0 12 0
// Retrieval info: CONNECT: @clock0 0 0 0 0 clock 0 0 0 0
// Retrieval info: CONNECT: q 0 0 8 0 @q_a 0 0 8 0
// Retrieval info: GEN_FILE: TYPE_NORMAL bios.v TRUE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios.inc FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios.cmp FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios.bsf FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios_inst.v FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios_bb.v FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios_waveforms.html FALSE
// Retrieval info: GEN_FILE: TYPE_NORMAL bios_wave*.jpg FALSE
// Retrieval info: LIB_FILE: altera_mf
|
`timescale 1ns/100ps
/**
* `timescale time_unit base / precision base
*
* -Specifies the time units and precision for delays:
* -time_unit is the amount of time a delay of 1 represents.
* The time unit must be 1 10 or 100
* -base is the time base for each unit, ranging from seconds
* to femtoseconds, and must be: s ms us ns ps or fs
* -precision and base represent how many decimal points of
* precision to use relative to the time units.
*/
/**
* This is written by Zhiyang Ong
* for EE577b Homework 2, Question 2
*/
// Testbench for behavioral model for the decoder
// Import the modules that will be tested for in this testbench
`include "encoder.syn.v"
`include "decoder.syn.v"
`include "pipelinedec.v"
`include "/auto/home-scf-06/ee577/design_pdk/osu_stdcells/lib/tsmc018/lib/osu018_stdcells.v"
// IMPORTANT: To run this, try: ncverilog -f ee577bHw2q2.f +gui
module tb_pipeline();
/**
* Declare signal types for testbench to drive and monitor
* signals during the simulation of the arbiter
*
* The reg data type holds a value until a new value is driven
* onto it in an "initial" or "always" block. It can only be
* assigned a value in an "always" or "initial" block, and is
* used to apply stimulus to the inputs of the DUT.
*
* The wire type is a passive data type that holds a value driven
* onto it by a port, assign statement or reg type. Wires cannot be
* assigned values inside "always" and "initial" blocks. They can
* be used to hold the values of the DUT's outputs
*/
// Declare "wire" signals: outputs from the DUTs
// Output of stage 1
wire [11:0] c;
// Output of stage 2
wire [11:0] cx;
// Output of stage 3
wire [6:0] q;
//wire [10:0] rb;
// Declare "reg" signals: inputs to the DUTs
// 1st stage
reg [6:0] b;
reg [6:0] r_b;
reg [11:0] e;
reg [11:0] r_e;
// 2nd stage
reg [11:0] r_c;
reg [11:0] rr_e;
reg [6:0] rr_b;
//reg [15:1] err;
// 3rd stage
//reg [14:0] cx;
//reg [10:0] qx;
reg [11:0] r_qx;
reg [6:0] rb;
reg clk,reset;
reg [11:0] e2;
encoder enc (
// instance_name(signal name),
// Signal name can be the same as the instance name
r_b,c);
decoder dec (
// instance_name(signal name),
// Signal name can be the same as the instance name
r_qx,q);
large_xor xr (
// instance_name(signal name),
// Signal name can be the same as the instance name
r_c,rr_e,cx);
/**
* Each sequential control block, such as the initial or always
* block, will execute concurrently in every module at the start
* of the simulation
*/
always begin
// Clock frequency is arbitrarily chosen
#10 clk = 0;
#10 clk = 1;
end
// Create the register (flip-flop) for the initial/1st stage
always@(posedge clk)
begin
if(reset)
begin
r_b<=0;
r_e<=0;
end
else
begin
r_e<=e;
r_b<=b;
end
end
// Create the register (flip-flop) for the 2nd stage
always@(posedge clk)
begin
if(reset)
begin
r_c<=0;
rr_e<=0;
rr_b<=0;
end
else
begin
r_c<=c;
rr_e<=r_e;
rr_b<=r_b;
end
end
// Create the register (flip-flop) for the 3rd stage
always@(posedge clk)
begin
if(reset)
begin
rb<=0;
end
else
begin
r_qx<=cx;
rb<=rr_b;
e2<=rr_e;
end
end
/**
* Initial block start executing sequentially @ t=0
* If and when a delay is encountered, the execution of this block
* pauses or waits until the delay time has passed, before resuming
* execution
*
* Each intial or always block executes concurrently; that is,
* multiple "always" or "initial" blocks will execute simultaneously
*
* E.g.
* always
* begin
* #10 clk_50 = ~clk_50; // Invert clock signal every 10 ns
* // Clock signal has a period of 20 ns or 50 MHz
* end
*/
initial
begin
$sdf_annotate("../sdf/encoder.sdf",enc,"TYPICAL", "1.0:1.0:1.0", "FROM_MTM");
$sdf_annotate("../sdf/decoder.sdf",dec,"TYPICAL", "1.0:1.0:1.0", "FROM_MTM");
// "$time" indicates the current time in the simulation
$display(" << Starting the simulation >>");
reset=1;
#20;
reset=0;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000001000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000010000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b001000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#20;
b = $random;
e = 12'b000000000000;
$display(q, "<< Displaying q >>");
$display(rb, "<< Displaying rb >>");
#300;
$display(" << Finishing the simulation >>");
$finish;
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 11/13/2013 03:24:40 PM
// Design Name:
// Module Name: stream_tg
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module stream_tg #(
parameter DATA_WIDTH = 64,
parameter KEEP_WIDTH = 8,
parameter START_ADDR = 0,
parameter START_DATA = 0,
parameter BTT = 23'd8,
parameter DRR = 1'b0,
parameter DSA = 6'd0
)
(
input aclk,
input aresetn,
output [71:0] write_cmd,
output write_cmd_valid,
input write_cmd_ready,
output [DATA_WIDTH-1: 0] write_data,
output write_data_valid,
input write_data_ready,
output [KEEP_WIDTH-1: 0] write_data_keep,
output write_data_last,
output [71:0] read_cmd,
output read_cmd_valid,
input read_cmd_ready,
input [DATA_WIDTH-1: 0] read_data,
input read_data_valid,
input [KEEP_WIDTH-1: 0] read_data_keep,
input read_data_last,
output read_data_ready,
input [7:0] read_sts_data,
input read_sts_valid,
output read_sts_ready,
input [31:0] write_sts_data,
input write_sts_valid,
output write_sts_ready,
output compare_error
);
//local parameters for test state machine
localparam ITERATIONS = 1; //test iterations. Each iteration involves state transition from WRITE TO COMPARE
localparam IDLE = 3'd0;
localparam START = 3'd1;
localparam WRITE_CMD = 3'd2;
localparam WRITE_DATA = 3'd3;
localparam READ_CMD = 3'd4;
localparam READ_DATA = 3'd5;
localparam COMPARE = 3'd6;
localparam FINISH = 3'd7;
//localparam BTT = 23'd16;
localparam TYPE = 1'd1;
localparam EOF = 1'd1;
//localparam DRR = 1'd1;
localparam TAG = 4'd0;
localparam RSVD = 4'd0;
reg [31:0] iter_count_r;
reg [2:0] test_state_r;
reg [71:0] write_cmd_r;
reg write_cmd_valid_r;
reg [DATA_WIDTH-1: 0] write_data_r, write_data_r1;
reg write_data_valid_r;
reg [KEEP_WIDTH-1: 0] write_data_keep_r, write_data_keep_r1;
reg write_data_last_r;
reg [71:0] read_cmd_r;
reg read_cmd_valid_r;
reg [DATA_WIDTH-1: 0] read_data_r, read_data_r1;
reg read_data_valid_r;
reg [KEEP_WIDTH-1: 0] read_data_keep_r, read_data_keep_r1;
reg read_data_last_r, read_data_last_r1;
reg compare_error_r;
assign compare_error = compare_error_r;
assign write_cmd = write_cmd_r;
assign write_cmd_valid = write_cmd_valid_r;
assign write_data = write_data_r;
assign write_data_valid = write_data_valid_r;
assign write_data_keep = write_data_keep_r;
assign write_data_last = write_data_last_r;
assign read_cmd = read_cmd_r;
assign read_cmd_valid = read_cmd_valid_r;
assign read_data_ready = 1'b1;
assign read_sts_ready = 1'b1;
assign write_sts_ready = 1'b1;
//main state machine
always @(posedge aclk)
if (~aresetn) begin
write_cmd_r[22:0] <= BTT;
write_cmd_r[23] <= TYPE;
write_cmd_r[29:24] <= DSA;
write_cmd_r[30] <= EOF;
write_cmd_r[31] <= DRR;
write_cmd_r[63:32] <= START_ADDR;
write_cmd_r[67:64] <= TAG;
write_cmd_r[71:68] <= RSVD;
read_cmd_r[22:0] <= BTT;
read_cmd_r[23] <= TYPE;
read_cmd_r[29:24] <= DSA;
read_cmd_r[30] <= EOF;
read_cmd_r[31] <= DRR;
read_cmd_r[63:32] <= START_ADDR;
read_cmd_r[67:64] <= TAG;
read_cmd_r[71:68] <= RSVD;
write_data_r <= START_DATA;
write_cmd_valid_r <= 1'b0;
write_data_valid_r <= 1'b0;
read_cmd_valid_r <= 1'b0;
write_data_keep_r <= 0;
write_data_last_r <= 1'b0;
//iter_count_r <= 0;
test_state_r <= IDLE;
compare_error_r <= 1'b0;
read_data_r <= 0;
read_data_keep_r <= 0;
read_data_last_r <= 0;
end
else
case (test_state_r)
IDLE: begin test_state_r <= START; end
START: begin
test_state_r <= WRITE_CMD;
write_cmd_valid_r <= 1'b1;
end
WRITE_CMD: begin
if (write_cmd_ready) begin
write_cmd_valid_r <= 1'b0;
test_state_r <= WRITE_DATA;
write_data_keep_r <= {{KEEP_WIDTH}{1'b1}};
write_data_last_r <= 1'b1;
write_data_valid_r <= 1'b1;
write_cmd_r[63:32] <= write_cmd_r[63:32] + 1;
end
end
WRITE_DATA: begin
if (write_data_ready) begin
write_data_valid_r <= 1'b0;
write_data_last_r <= 1'b0;
end
if (write_sts_valid & write_sts_data[7]) begin
test_state_r <= READ_CMD;
read_cmd_valid_r <= 1'b1;
end
end
READ_CMD: begin
if (read_cmd_ready) begin
read_cmd_valid_r <= 1'b0;
end
if (read_sts_valid & read_sts_data[7]) begin
test_state_r <= READ_DATA;
read_cmd_r[63:32] <= read_cmd_r[63:32] + 1;
end
end
READ_DATA: begin
if (read_data_valid) begin
read_data_r <= read_data;
read_data_keep_r <= read_data_keep;
read_data_last_r <= read_data_last;
end
if (read_data_last_r) begin
test_state_r <= COMPARE;
end
end
COMPARE: begin
if ((read_data_r1 != write_data_r1) | (read_data_keep_r1 != write_data_keep_r1)) begin
compare_error_r <= 1'b1;
end
test_state_r <= FINISH;
end
FINISH: begin
//test_state_r <= FINISH;
test_state_r <= START;
end
endcase
always @(posedge aclk) begin
read_data_r1 <= read_data_r;
read_data_keep_r1 <= read_data_keep_r;
write_data_r1 <= write_data_r;
write_data_keep_r1 <= write_data_keep_r;
end
endmodule
|
module display(CLK, BPM, PLAY, SEGA, SEGD);
input CLK; // 100MHz clock input
input [7:0] BPM; // 8-bit BPM value
//input [5:0] TONE; // 6-bit tone code
//input [3:0] DURATION; // 4-bit duration code
input PLAY; // Play/Pause Input
output reg [3:0] SEGA; // Display-select (common anode) output
output [7:0] SEGD; // Display-pattern output
wire [11:0] BCD;
reg [3:0] CURRENT_DIG;// Which BCD digit is currently displaying
//assign BCD = 12'h123;
byte_to_BCD btb_blk (BPM, BCD);
bcdtoseg seg_disp_blk (1'b1, 1'b1, CURRENT_DIG[3], CURRENT_DIG[2], CURRENT_DIG[1], CURRENT_DIG[0], 1'b1, /*unconnected*/
, SEGD[7], SEGD[6], SEGD[5], SEGD[4], SEGD[3], SEGD[2], SEGD[1]);
// Turn decimal point off
assign SEGD[0] = 1;
reg [16:0] waveCount;
parameter
KHZ_WAVE = 17'd100000, // The full period of a 1kHz wave with 100MHz clock
DISP_D0 = ~4'b0001,
DISP_D1 = ~4'b0010,
DISP_D2 = ~4'b0100,
DISP_D3 = ~4'b1000,
DISP_OFF = ~4'b0000;
initial begin
waveCount = 0;
// OFF
SEGA = ~4'h0;
CURRENT_DIG[3:0] = 4'h0;
end
always @(posedge CLK) begin
//increment waveCount to use as 1KHz wave
waveCount = waveCount + 1;
//increment the counter to count up to duration
//active contains state of whether you've finished the note or not
//selecting the digit to display
// TODO: Display state on the first digit, e.g. P for paused
if (waveCount < KHZ_WAVE/4) begin
if (~PLAY) begin
SEGA = DISP_D0;
CURRENT_DIG = 4'hF;
end else begin
SEGA = DISP_OFF;
CURRENT_DIG = 4'd0;
end
end else if (waveCount < KHZ_WAVE/2) begin
SEGA = DISP_D1;
CURRENT_DIG = BCD[11:8];
end else if (waveCount < KHZ_WAVE*3/4) begin
SEGA = DISP_D2;
CURRENT_DIG = BCD[7:4];
end else if (waveCount < KHZ_WAVE)begin
SEGA = DISP_D3;
CURRENT_DIG = BCD[3:0];
end else
waveCount = 0;
end
endmodule
|
`include "mux.v"
module HalfAdder(input a,b, output sum, carry);
Xor g1(a, b, sum);
And g2(a, b, carry);
endmodule
module FullAdder(input a,b,c, output sum, carry);
wire s1, c1, c2;
Xor g1(a, b, s1);
Xor g2(s1, c, sum);
And g3(a, b, c1);
And g4(s1, c, c2);
Xor g5(c2, c1, carry);
endmodule
module Add16(input[15:0] a,b, output[15:0] out);
wire [15:0] c;
FullAdder g01(a[0], b[0], 1'b0, out[0], c[0]);
FullAdder g02(a[1], b[1], c[0], out[1], c[1]);
FullAdder g03(a[2], b[2], c[1], out[2], c[2]);
FullAdder g04(a[3], b[3], c[2], out[3], c[3]);
FullAdder g05(a[4], b[4], c[3], out[4], c[4]);
FullAdder g06(a[5], b[5], c[4], out[5], c[5]);
FullAdder g07(a[6], b[6], c[5], out[6], c[6]);
FullAdder g08(a[7], b[7], c[6], out[7], c[7]);
FullAdder g09(a[8], b[8], c[7], out[8], c[8]);
FullAdder g10(a[9], b[9], c[8], out[9], c[9]);
FullAdder g11(a[10], b[10], c[9], out[10], c[10]);
FullAdder g12(a[11], b[11], c[10], out[11], c[11]);
FullAdder g13(a[12], b[12], c[11], out[12], c[12]);
FullAdder g14(a[13], b[13], c[12], out[13], c[13]);
FullAdder g15(a[14], b[14], c[13], out[14], c[14]);
FullAdder g16(a[15], b[15], c[14], out[15], c[15]);
endmodule
module Inc16(input[15:0] in, output[15:0] out);
Add16 g1(in, 16'h1, out);
endmodule
// x[16], y[16], // 16-bit inputs
// zx, // zero the x input?
// nx, // negate the x input?
// zy, // zero the y input?
// ny, // negate the y input?
// f, // compute out = x + y (if 1) or x & y (if 0)
// no; // negate the out output?
// out[16], zr, ng; // zr:zero, ng:negative
module ALU(input[15:0] x, y, input zx,nx,zy,ny,f,no, output[15:0] out, output zr, ng);
wire[15:0] x1, notx1, x2, y1, noty1, y2, andxy, addxy, o1, noto1, o2;
wire orLow, orHigh, notzr;
Mux16 g1(x, 16'b0, zx, x1); // if (zx == 1) set x = 0
Not16 g2(x1, notx1);
Mux16 g3(x1, notx1, nx, x2); // if (nx == 1) set x = !x
Mux16 g4(y, 16'b0, zy, y1); // if (zy == 1) set y = 0
Not16 g5(y1, noty1);
Mux16 g6(y1, noty1, ny, y2); // if (ny == 1) set y = !y
Add16 g7(x2, y2, addxy); // addxy = x + y
And16 g8(x2, y2, andxy); // andxy = x & y
Mux16 g9(andxy, addxy, f, o1); // if (f == 1) set out = x + y else set out = x & y
Not16 g10(o1, noto1);
Mux16 g11(o1, noto1, no, o2); // if (no == 1) set out = !out
// o2 就是 out, 但必須中間節點才能再次當作輸入,所以先用 o2。
And16 g12(o2, o2, out);
Or8Way g13(out[7:0], orLow); // orLow = Or(out[0..7]);
Or8Way g14(out[15:8], orHigh);// orHigh = Or(out[8..15]);
Or g15(orLow, orHigh, notzr); // nzr = Or(out[0..15]);
Not g16(notzr, zr); // zr = !nzr
And g17(o2[15], o2[15], ng); // ng = out[15]
And16 g18(o2, o2, out);
endmodule
|
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: xilinx.com:ip:axis_dwidth_converter:1.1
// IP Revision: 0
`timescale 1ns/1ps
(* DowngradeIPIdentifiedWarnings = "yes" *)
module daala_zynq_axis_dwidth_converter_0_0 (
aclk,
aresetn,
s_axis_tvalid,
s_axis_tready,
s_axis_tdata,
s_axis_tlast,
m_axis_tvalid,
m_axis_tready,
m_axis_tdata,
m_axis_tkeep,
m_axis_tlast
);
(* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 CLKIF CLK" *)
input aclk;
(* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 RSTIF RST" *)
input aresetn;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S_AXIS TVALID" *)
input s_axis_tvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S_AXIS TREADY" *)
output s_axis_tready;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S_AXIS TDATA" *)
input [63 : 0] s_axis_tdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S_AXIS TLAST" *)
input s_axis_tlast;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M_AXIS TVALID" *)
output m_axis_tvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M_AXIS TREADY" *)
input m_axis_tready;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M_AXIS TDATA" *)
output [255 : 0] m_axis_tdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M_AXIS TKEEP" *)
output [31 : 0] m_axis_tkeep;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M_AXIS TLAST" *)
output m_axis_tlast;
axis_dwidth_converter_v1_1_axis_dwidth_converter #(
.C_FAMILY("zynq"),
.C_S_AXIS_TDATA_WIDTH(64),
.C_M_AXIS_TDATA_WIDTH(256),
.C_AXIS_TID_WIDTH(1),
.C_AXIS_TDEST_WIDTH(1),
.C_S_AXIS_TUSER_WIDTH(1),
.C_M_AXIS_TUSER_WIDTH(1),
.C_AXIS_SIGNAL_SET('B00010011)
) inst (
.aclk(aclk),
.aresetn(aresetn),
.aclken(1'H1),
.s_axis_tvalid(s_axis_tvalid),
.s_axis_tready(s_axis_tready),
.s_axis_tdata(s_axis_tdata),
.s_axis_tstrb(8'HFF),
.s_axis_tkeep(8'HFF),
.s_axis_tlast(s_axis_tlast),
.s_axis_tid(1'H0),
.s_axis_tdest(1'H0),
.s_axis_tuser(1'H0),
.m_axis_tvalid(m_axis_tvalid),
.m_axis_tready(m_axis_tready),
.m_axis_tdata(m_axis_tdata),
.m_axis_tstrb(),
.m_axis_tkeep(m_axis_tkeep),
.m_axis_tlast(m_axis_tlast),
.m_axis_tid(),
.m_axis_tdest(),
.m_axis_tuser()
);
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// Generic Two-Port Synchronous RAM ////
//// ////
//// This file is part of pci bridge project ////
//// http://www.opencores.org/cvsweb.shtml/pci/ ////
//// ////
//// Description ////
//// This block is a wrapper with common two-port ////
//// synchronous memory interface for different ////
//// types of ASIC and FPGA RAMs. Beside universal memory ////
//// interface it also provides behavioral model of generic ////
//// two-port synchronous RAM. ////
//// It should be used in all OPENCORES designs that want to be ////
//// portable accross different target technologies and ////
//// independent of target memory. ////
//// ////
//// Supported ASIC RAMs are: ////
//// - Artisan Double-Port Sync RAM ////
//// - Avant! Two-Port Sync RAM (*) ////
//// - Virage 2-port Sync RAM ////
//// ////
//// Supported FPGA RAMs are: ////
//// - Xilinx Virtex RAMB4_S16_S16 ////
//// ////
//// To Do: ////
//// - fix Avant! ////
//// - xilinx rams need external tri-state logic ////
//// - add additional RAMs (Altera, VS etc) ////
//// ////
//// Author(s): ////
//// - Damjan Lampret, [email protected] ////
//// - Miha Dolenc, [email protected] ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2000 Authors and OPENCORES.ORG ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
//
// CVS Revision History
//
// $Log: pci_pci_tpram.v,v $
// Revision 1.4 2004/08/19 15:27:34 mihad
// Changed minimum pci image size to 256 bytes because
// of some PC system problems with size of IO images.
//
// Revision 1.3 2003/10/17 09:11:52 markom
// mbist signals updated according to newest convention
//
// Revision 1.2 2003/08/14 13:06:03 simons
// synchronizer_flop replaced with pci_synchronizer_flop, artisan ram instance updated.
//
// Revision 1.1 2003/01/27 16:49:31 mihad
// Changed module and file names. Updated scripts accordingly. FIFO synchronizations changed.
//
// Revision 1.7 2002/10/18 03:36:37 tadejm
// Changed wrong signal name mbist_sen into mbist_ctrl_i.
//
// Revision 1.6 2002/10/17 22:51:08 tadejm
// Changed BIST signals for RAMs.
//
// Revision 1.5 2002/10/11 10:09:01 mihad
// Added additional testcase and changed rst name in BIST to trst
//
// Revision 1.4 2002/10/08 17:17:06 mihad
// Added BIST signals for RAMs.
//
// Revision 1.3 2002/09/30 17:22:27 mihad
// Added support for Virtual Silicon two port RAM. Didn't run regression on it yet!
//
// Revision 1.2 2002/08/19 16:51:36 mihad
// Extracted distributed RAM module from wb/pci_tpram.v to its own file, got rid of undef directives
//
// Revision 1.1 2002/02/01 14:43:31 mihad
// *** empty log message ***
//
//
// synopsys translate_off
//`include "timescale.v"
// synopsys translate_on
//`include "pci_constants.v"
module /*pci_pci_*/tpram
(
// Generic synchronous two-port RAM interface
clk_a,
rst_a,
ce_a,
we_a,
oe_a,
addr_a,
di_a,
do_a,
clk_b,
rst_b,
ce_b,
we_b,
oe_b,
addr_b,
di_b,
do_b
`ifdef PCI_BIST
,
// debug chain signals
mbist_si_i, // bist scan serial in
mbist_so_o, // bist scan serial out
mbist_ctrl_i // bist chain shift control
`endif
);
//
// Default address and data buses width
//
parameter aw = 8;
parameter dw = 40;
//
// Generic synchronous two-port RAM interface
//
input clk_a; // Clock
input rst_a; // Reset
input ce_a; // Chip enable input
input we_a; // Write enable input
input oe_a; // Output enable input
input [aw-1:0] addr_a; // address bus inputs
input [dw-1:0] di_a; // input data bus
output [dw-1:0] do_a; // output data bus
input clk_b; // Clock
input rst_b; // Reset
input ce_b; // Chip enable input
input we_b; // Write enable input
input oe_b; // Output enable input
input [aw-1:0] addr_b; // address bus inputs
input [dw-1:0] di_b; // input data bus
output [dw-1:0] do_b; // output data bus
`ifdef PCI_BIST
// debug chain signals
input mbist_si_i; // bist scan serial in
output mbist_so_o; // bist scan serial out
input [`PCI_MBIST_CTRL_WIDTH - 1:0] mbist_ctrl_i; // bist chain shift control
`endif
//
// Internal wires and registers
//
`ifdef PCI_VS_STP
`define PCI_PCI_RAM_SELECTED
`ifdef PCI_BIST
vs_hdtp_64x40_bist i_vs_hdtp_64x40_bist
`else
vs_hdtp_64x40 i_vs_hdtp_64x40
`endif
(
.RCK (clk_b),
.WCK (clk_a),
.RADR (addr_b),
.WADR (addr_a),
.DI (di_a),
.DOUT (do_b),
.REN (1'b0),
.WEN (!we_a)
`ifdef PCI_BIST
,
// debug chain signals
.mbist_si_i (mbist_si_i),
.mbist_so_o (mbist_so_o),
.mbist_ctrl_i (mbist_ctrl_i)
`endif
);
assign do_a = 0 ;
`endif
`ifdef PCI_ARTISAN_SDP
`define PCI_PCI_RAM_SELECTED
//
// Instantiation of ASIC memory:
//
// Artisan Synchronous Double-Port RAM (ra2sh)
//
`ifdef PCI_BIST
art_hsdp_64x40_bist /*#(dw, 1<<aw, aw) */ artisan_sdp
(
.QA(do_a),
.CLKA(clk_a),
.CENA(~ce_a),
.WENA(~we_a),
.AA(addr_a),
.DA(di_a),
.OENA(~oe_a),
.QB(do_b),
.CLKB(clk_b),
.CENB(~ce_b),
.WENB(~we_b),
.AB(addr_b),
.DB(di_b),
.OENB(~oe_b),
.mbist_si_i (mbist_si_i),
.mbist_so_o (mbist_so_o),
.mbist_ctrl_i (mbist_ctrl_i)
);
`else
art_hsdp_64x40 /*#(dw, 1<<aw, aw) */ artisan_sdp
(
.QA(do_a),
.CLKA(clk_a),
.CENA(~ce_a),
.WENA(~we_a),
.AA(addr_a),
.DA(di_a),
.OENA(~oe_a),
.QB(do_b),
.CLKB(clk_b),
.CENB(~ce_b),
.WENB(~we_b),
.AB(addr_b),
.DB(di_b),
.OENB(~oe_b)
);
`endif
`endif
`ifdef AVANT_ATP
`define PCI_PCI_RAM_SELECTED
//
// Instantiation of ASIC memory:
//
// Avant! Asynchronous Two-Port RAM
//
avant_atp avant_atp(
.web(~we),
.reb(),
.oeb(~oe),
.rcsb(),
.wcsb(),
.ra(addr),
.wa(addr),
.di(di),
.do(do)
);
`endif
`ifdef VIRAGE_STP
`define PCI_PCI_RAM_SELECTED
//
// Instantiation of ASIC memory:
//
// Virage Synchronous 2-port R/W RAM
//
virage_stp virage_stp(
.QA(do_a),
.QB(do_b),
.ADRA(addr_a),
.DA(di_a),
.WEA(we_a),
.OEA(oe_a),
.MEA(ce_a),
.CLKA(clk_a),
.ADRB(adr_b),
.DB(di_b),
.WEB(we_b),
.OEB(oe_b),
.MEB(ce_b),
.CLKB(clk_b)
);
`endif
`ifdef PCI_XILINX_RAMB4
`define PCI_PCI_RAM_SELECTED
//
// Instantiation of FPGA memory:
//
// Virtex/Spartan2
//
//
// Block 0
//
RAMB4_S16_S16 ramb4_s16_s16_0(
.CLKA(clk_a),
.RSTA(rst_a),
.ADDRA(addr_a),
.DIA(di_a[15:0]),
.ENA(ce_a),
.WEA(we_a),
.DOA(do_a[15:0]),
.CLKB(clk_b),
.RSTB(rst_b),
.ADDRB(addr_b),
.DIB(di_b[15:0]),
.ENB(ce_b),
.WEB(we_b),
.DOB(do_b[15:0])
);
//
// Block 1
//
RAMB4_S16_S16 ramb4_s16_s16_1(
.CLKA(clk_a),
.RSTA(rst_a),
.ADDRA(addr_a),
.DIA(di_a[31:16]),
.ENA(ce_a),
.WEA(we_a),
.DOA(do_a[31:16]),
.CLKB(clk_b),
.RSTB(rst_b),
.ADDRB(addr_b),
.DIB(di_b[31:16]),
.ENB(ce_b),
.WEB(we_b),
.DOB(do_b[31:16])
);
//
// Block 2
//
// block ram2 wires - non generic width of block rams
wire [15:0] blk2_di_a = {8'h00, di_a[39:32]} ;
wire [15:0] blk2_di_b = {8'h00, di_b[39:32]} ;
wire [15:0] blk2_do_a ;
wire [15:0] blk2_do_b ;
assign do_a[39:32] = blk2_do_a[7:0] ;
assign do_b[39:32] = blk2_do_b[7:0] ;
RAMB4_S16_S16 ramb4_s16_s16_2(
.CLKA(clk_a),
.RSTA(rst_a),
.ADDRA(addr_a),
.DIA(blk2_di_a),
.ENA(ce_a),
.WEA(we_a),
.DOA(blk2_do_a),
.CLKB(clk_b),
.RSTB(rst_b),
.ADDRB(addr_b),
.DIB(blk2_di_b),
.ENB(ce_b),
.WEB(we_b),
.DOB(blk2_do_b)
);
`endif
`ifdef PCI_XILINX_DIST_RAM
`define PCI_PCI_RAM_SELECTED
reg [(aw-1):0] out_address ;
always@(posedge clk_b or posedge rst_b)
begin
if ( rst_b )
out_address <= #1 0 ;
else if (ce_b)
out_address <= #1 addr_b ;
end
pci_ram_16x40d #(aw) pci_distributed_ram
(
.data_out (do_b),
.we (we_a),
.data_in (di_a),
.read_address (out_address),
.write_address (addr_a),
.wclk (clk_a)
);
assign do_a = 0 ;
`endif
`ifdef PCI_PCI_RAM_SELECTED
`else
//
// Generic two-port synchronous RAM model
//
//
// Generic RAM's registers and wires
//
reg [dw-1:0] mem [(1<<aw)-1:0]; // RAM content
reg [dw-1:0] do_reg_b, do_reg_a; // RAM data output register
//
// Data output drivers
//
assign do_a = do_reg_a ;
assign do_b = do_reg_b ;
//
// RAM read and write
//
always @(posedge clk_a) begin
if (ce_a)
begin
if (we_a)
mem[addr_a] <= #1 di_a;
do_reg_a <= #1 mem[addr_a];
end
end
always @(posedge clk_b) begin
if (ce_b)
begin
if (we_b)
mem[addr_b] <= #1 di_b;
do_reg_b <= #1 mem[addr_b];
end
end
// synopsys translate_off
integer f;
initial begin
for (f = 0; f < 1<<aw; f = f + 1) begin
mem[f] = 0;
end
end
// synopsys translate_on
`endif
endmodule
|
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: thomasdaede.com:user:daala_4x4_transpose:1.0
// IP Revision: 3
`timescale 1ns/1ps
(* DowngradeIPIdentifiedWarnings = "yes" *)
module daala_zynq_daala_4x4_transpose_0_0 (
axis_clk,
axis_aresetn,
s00_axis_tdata,
s00_axis_tlast,
s00_axis_tvalid,
s00_axis_tready,
m00_axis_tdata,
m00_axis_tlast,
m00_axis_tvalid,
m00_axis_tready
);
(* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 axis_clk CLK" *)
input axis_clk;
(* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 axis_aresetn RST" *)
input axis_aresetn;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S00_AXIS TDATA" *)
input [255 : 0] s00_axis_tdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S00_AXIS TLAST" *)
input s00_axis_tlast;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S00_AXIS TVALID" *)
input s00_axis_tvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 S00_AXIS TREADY" *)
output s00_axis_tready;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M00_AXIS TDATA" *)
output [255 : 0] m00_axis_tdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M00_AXIS TLAST" *)
output m00_axis_tlast;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M00_AXIS TVALID" *)
output m00_axis_tvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:axis:1.0 M00_AXIS TREADY" *)
input m00_axis_tready;
daala_4x4_transpose_v1_0 #(
.C_S00_AXIS_TDATA_WIDTH(256),
.C_M00_AXIS_TDATA_WIDTH(256)
) inst (
.axis_clk(axis_clk),
.axis_aresetn(axis_aresetn),
.s00_axis_tdata(s00_axis_tdata),
.s00_axis_tlast(s00_axis_tlast),
.s00_axis_tvalid(s00_axis_tvalid),
.s00_axis_tready(s00_axis_tready),
.m00_axis_tdata(m00_axis_tdata),
.m00_axis_tlast(m00_axis_tlast),
.m00_axis_tvalid(m00_axis_tvalid),
.m00_axis_tready(m00_axis_tready)
);
endmodule
|
// ***************************************************************************
// ***************************************************************************
// Copyright 2014 - 2017 (c) Analog Devices, Inc. All rights reserved.
//
// In this HDL repository, there are many different and unique modules, consisting
// of various HDL (Verilog or VHDL) components. The individual modules are
// developed independently, and may be accompanied by separate and unique license
// terms.
//
// The user should read each of these license terms, and understand the
// freedoms and responsibilities that he or she has by using this source/core.
//
// This core is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE.
//
// Redistribution and use of source or resulting binaries, with or without modification
// of this file, are permitted under one of the following two license terms:
//
// 1. The GNU General Public License version 2 as published by the
// Free Software Foundation, which can be found in the top level directory
// of this repository (LICENSE_GPL2), and also online at:
// <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
//
// OR
//
// 2. An ADI specific BSD license, which can be found in the top level directory
// of this repository (LICENSE_ADIBSD), and also on-line at:
// https://github.com/analogdevicesinc/hdl/blob/master/LICENSE_ADIBSD
// This will allow to generate bit files and not release the source code,
// as long as it attaches to an ADI device.
//
// ***************************************************************************
// ***************************************************************************
`timescale 1ns/100ps
module dmac_dest_fifo_inf #(
parameter ID_WIDTH = 3,
parameter DATA_WIDTH = 64,
parameter BEATS_PER_BURST_WIDTH = 4)(
input clk,
input resetn,
input enable,
output enabled,
input req_valid,
output req_ready,
output [ID_WIDTH-1:0] response_id,
output reg [ID_WIDTH-1:0] data_id = 'h0,
input data_eot,
input response_eot,
input en,
output reg [DATA_WIDTH-1:0] dout,
output reg valid,
output reg underflow,
output xfer_req,
output fifo_ready,
input fifo_valid,
input [DATA_WIDTH-1:0] fifo_data,
input fifo_last,
output response_valid,
input response_ready,
output response_resp_eot,
output [1:0] response_resp
);
`include "inc_id.vh"
reg active = 1'b0;
/* Last beat of the burst */
wire fifo_last_beat;
/* Last beat of the segment */
wire fifo_eot_beat;
assign enabled = enable;
assign fifo_ready = en & (fifo_valid | ~enable);
/* fifo_last == 1'b1 implies fifo_valid == 1'b1 */
assign fifo_last_beat = fifo_ready & fifo_last;
assign fifo_eot_beat = fifo_last_beat & data_eot;
assign req_ready = fifo_eot_beat | ~active;
assign xfer_req = active;
always @(posedge clk) begin
if (en) begin
dout <= fifo_valid ? fifo_data : {DATA_WIDTH{1'b0}};
valid <= fifo_valid & enable;
underflow <= ~(fifo_valid & enable);
end else begin
valid <= 1'b0;
underflow <= 1'b0;
end
end
always @(posedge clk) begin
if (resetn == 1'b0) begin
data_id <= 'h00;
end else if (fifo_last_beat == 1'b1) begin
data_id <= inc_id(data_id);
end
end
always @(posedge clk) begin
if (resetn == 1'b0) begin
active <= 1'b0;
end else if (req_valid == 1'b1) begin
active <= 1'b1;
end else if (fifo_eot_beat == 1'b1) begin
active <= 1'b0;
end
end
dmac_response_generator # (
.ID_WIDTH(ID_WIDTH)
) i_response_generator (
.clk(clk),
.resetn(resetn),
.enable(enable),
.enabled(),
.request_id(data_id),
.response_id(response_id),
.eot(response_eot),
.resp_valid(response_valid),
.resp_ready(response_ready),
.resp_eot(response_resp_eot),
.resp_resp(response_resp)
);
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 2017/01/23 23:55:53
// Design Name:
// Module Name: VGA_top
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module VGA_top(
input clk,
input rst,
input [7:0]snake,
input [7:0]apple_x,
input [7:0]apple_y,
output [9:0]x_pos,
output [9:0]y_pos,
output hsync,
output vsync,
output [11:0] color_out
);
wire clk_n;
clk_unit myclk(
.clk(clk),
.rst(rst),
.clk_n(clk_n)
);
VGA_Control VGA
(
.clk(clk_n),
.rst(rst),
.hsync(hsync),
.vsync(vsync),
.snake(snake),
.color_out(color_out),
.x_pos(x_pos),
.y_pos(y_pos),
.apple_x(apple_x),
.apple_y(apple_y)
);
endmodule
|
/*
Copyright (c) 2015-2018 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Language: Verilog 2001
`resetall
`timescale 1ns / 1ps
`default_nettype none
/*
* AXI4-Stream Ethernet FCS checker
*/
module axis_eth_fcs_check
(
input wire clk,
input wire rst,
/*
* AXI input
*/
input wire [7:0] s_axis_tdata,
input wire s_axis_tvalid,
output wire s_axis_tready,
input wire s_axis_tlast,
input wire s_axis_tuser,
/*
* AXI output
*/
output wire [7:0] m_axis_tdata,
output wire m_axis_tvalid,
input wire m_axis_tready,
output wire m_axis_tlast,
output wire m_axis_tuser,
/*
* Status
*/
output wire busy,
output wire error_bad_fcs
);
localparam [1:0]
STATE_IDLE = 2'd0,
STATE_PAYLOAD = 2'd1;
reg [1:0] state_reg = STATE_IDLE, state_next;
// datapath control signals
reg reset_crc;
reg update_crc;
reg shift_in;
reg shift_reset;
reg [7:0] s_axis_tdata_d0 = 8'd0;
reg [7:0] s_axis_tdata_d1 = 8'd0;
reg [7:0] s_axis_tdata_d2 = 8'd0;
reg [7:0] s_axis_tdata_d3 = 8'd0;
reg s_axis_tvalid_d0 = 1'b0;
reg s_axis_tvalid_d1 = 1'b0;
reg s_axis_tvalid_d2 = 1'b0;
reg s_axis_tvalid_d3 = 1'b0;
reg busy_reg = 1'b0;
reg error_bad_fcs_reg = 1'b0, error_bad_fcs_next;
reg s_axis_tready_reg = 1'b0, s_axis_tready_next;
reg [31:0] crc_state = 32'hFFFFFFFF;
wire [31:0] crc_next;
// internal datapath
reg [7:0] m_axis_tdata_int;
reg m_axis_tvalid_int;
reg m_axis_tready_int_reg = 1'b0;
reg m_axis_tlast_int;
reg m_axis_tuser_int;
wire m_axis_tready_int_early;
assign s_axis_tready = s_axis_tready_reg;
assign busy = busy_reg;
assign error_bad_fcs = error_bad_fcs_reg;
lfsr #(
.LFSR_WIDTH(32),
.LFSR_POLY(32'h4c11db7),
.LFSR_CONFIG("GALOIS"),
.LFSR_FEED_FORWARD(0),
.REVERSE(1),
.DATA_WIDTH(8),
.STYLE("AUTO")
)
eth_crc_8 (
.data_in(s_axis_tdata_d3),
.state_in(crc_state),
.data_out(),
.state_out(crc_next)
);
always @* begin
state_next = STATE_IDLE;
reset_crc = 1'b0;
update_crc = 1'b0;
shift_in = 1'b0;
shift_reset = 1'b0;
s_axis_tready_next = 1'b0;
m_axis_tdata_int = 8'd0;
m_axis_tvalid_int = 1'b0;
m_axis_tlast_int = 1'b0;
m_axis_tuser_int = 1'b0;
error_bad_fcs_next = 1'b0;
case (state_reg)
STATE_IDLE: begin
// idle state - wait for data
s_axis_tready_next = m_axis_tready_int_early;
reset_crc = 1'b1;
m_axis_tdata_int = s_axis_tdata_d3;
m_axis_tvalid_int = s_axis_tvalid_d3 && s_axis_tvalid;
m_axis_tlast_int = 1'b0;
m_axis_tuser_int = 1'b0;
if (s_axis_tready && s_axis_tvalid) begin
shift_in = 1'b1;
if (s_axis_tvalid_d3) begin
reset_crc = 1'b0;
update_crc = 1'b1;
if (s_axis_tlast) begin
shift_reset = 1'b1;
reset_crc = 1'b1;
m_axis_tlast_int = 1'b1;
m_axis_tuser_int = s_axis_tuser;
if ({s_axis_tdata, s_axis_tdata_d0, s_axis_tdata_d1, s_axis_tdata_d2} != ~crc_next) begin
m_axis_tuser_int = 1'b1;
error_bad_fcs_next = 1'b1;
end
s_axis_tready_next = m_axis_tready_int_early;
state_next = STATE_IDLE;
end else begin
state_next = STATE_PAYLOAD;
end
end else begin
state_next = STATE_IDLE;
end
end else begin
state_next = STATE_IDLE;
end
end
STATE_PAYLOAD: begin
// transfer payload
s_axis_tready_next = m_axis_tready_int_early;
m_axis_tdata_int = s_axis_tdata_d3;
m_axis_tvalid_int = s_axis_tvalid_d3 && s_axis_tvalid;
m_axis_tlast_int = 1'b0;
m_axis_tuser_int = 1'b0;
if (s_axis_tready && s_axis_tvalid) begin
shift_in = 1'b1;
update_crc = 1'b1;
if (s_axis_tlast) begin
shift_reset = 1'b1;
reset_crc = 1'b1;
m_axis_tlast_int = 1'b1;
m_axis_tuser_int = s_axis_tuser;
if ({s_axis_tdata, s_axis_tdata_d0, s_axis_tdata_d1, s_axis_tdata_d2} != ~crc_next) begin
m_axis_tuser_int = 1'b1;
error_bad_fcs_next = 1'b1;
end
s_axis_tready_next = m_axis_tready_int_early;
state_next = STATE_IDLE;
end else begin
state_next = STATE_PAYLOAD;
end
end else begin
state_next = STATE_PAYLOAD;
end
end
endcase
end
always @(posedge clk) begin
if (rst) begin
state_reg <= STATE_IDLE;
s_axis_tready_reg <= 1'b0;
busy_reg <= 1'b0;
error_bad_fcs_reg <= 1'b0;
s_axis_tvalid_d0 <= 1'b0;
s_axis_tvalid_d1 <= 1'b0;
s_axis_tvalid_d2 <= 1'b0;
s_axis_tvalid_d3 <= 1'b0;
crc_state <= 32'hFFFFFFFF;
end else begin
state_reg <= state_next;
s_axis_tready_reg <= s_axis_tready_next;
busy_reg <= state_next != STATE_IDLE;
error_bad_fcs_reg <= error_bad_fcs_next;
// datapath
if (reset_crc) begin
crc_state <= 32'hFFFFFFFF;
end else if (update_crc) begin
crc_state <= crc_next;
end
if (shift_reset) begin
s_axis_tvalid_d0 <= 1'b0;
s_axis_tvalid_d1 <= 1'b0;
s_axis_tvalid_d2 <= 1'b0;
s_axis_tvalid_d3 <= 1'b0;
end else if (shift_in) begin
s_axis_tvalid_d0 <= s_axis_tvalid;
s_axis_tvalid_d1 <= s_axis_tvalid_d0;
s_axis_tvalid_d2 <= s_axis_tvalid_d1;
s_axis_tvalid_d3 <= s_axis_tvalid_d2;
end
end
if (shift_in) begin
s_axis_tdata_d0 <= s_axis_tdata;
s_axis_tdata_d1 <= s_axis_tdata_d0;
s_axis_tdata_d2 <= s_axis_tdata_d1;
s_axis_tdata_d3 <= s_axis_tdata_d2;
end
end
// output datapath logic
reg [7:0] m_axis_tdata_reg = 8'd0;
reg m_axis_tvalid_reg = 1'b0, m_axis_tvalid_next;
reg m_axis_tlast_reg = 1'b0;
reg m_axis_tuser_reg = 1'b0;
reg [7:0] temp_m_axis_tdata_reg = 8'd0;
reg temp_m_axis_tvalid_reg = 1'b0, temp_m_axis_tvalid_next;
reg temp_m_axis_tlast_reg = 1'b0;
reg temp_m_axis_tuser_reg = 1'b0;
// datapath control
reg store_axis_int_to_output;
reg store_axis_int_to_temp;
reg store_axis_temp_to_output;
assign m_axis_tdata = m_axis_tdata_reg;
assign m_axis_tvalid = m_axis_tvalid_reg;
assign m_axis_tlast = m_axis_tlast_reg;
assign m_axis_tuser = m_axis_tuser_reg;
// enable ready input next cycle if output is ready or the temp reg will not be filled on the next cycle (output reg empty or no input)
assign m_axis_tready_int_early = m_axis_tready || (!temp_m_axis_tvalid_reg && (!m_axis_tvalid_reg || !m_axis_tvalid_int));
always @* begin
// transfer sink ready state to source
m_axis_tvalid_next = m_axis_tvalid_reg;
temp_m_axis_tvalid_next = temp_m_axis_tvalid_reg;
store_axis_int_to_output = 1'b0;
store_axis_int_to_temp = 1'b0;
store_axis_temp_to_output = 1'b0;
if (m_axis_tready_int_reg) begin
// input is ready
if (m_axis_tready || !m_axis_tvalid_reg) begin
// output is ready or currently not valid, transfer data to output
m_axis_tvalid_next = m_axis_tvalid_int;
store_axis_int_to_output = 1'b1;
end else begin
// output is not ready, store input in temp
temp_m_axis_tvalid_next = m_axis_tvalid_int;
store_axis_int_to_temp = 1'b1;
end
end else if (m_axis_tready) begin
// input is not ready, but output is ready
m_axis_tvalid_next = temp_m_axis_tvalid_reg;
temp_m_axis_tvalid_next = 1'b0;
store_axis_temp_to_output = 1'b1;
end
end
always @(posedge clk) begin
if (rst) begin
m_axis_tvalid_reg <= 1'b0;
m_axis_tready_int_reg <= 1'b0;
temp_m_axis_tvalid_reg <= 1'b0;
end else begin
m_axis_tvalid_reg <= m_axis_tvalid_next;
m_axis_tready_int_reg <= m_axis_tready_int_early;
temp_m_axis_tvalid_reg <= temp_m_axis_tvalid_next;
end
// datapath
if (store_axis_int_to_output) begin
m_axis_tdata_reg <= m_axis_tdata_int;
m_axis_tlast_reg <= m_axis_tlast_int;
m_axis_tuser_reg <= m_axis_tuser_int;
end else if (store_axis_temp_to_output) begin
m_axis_tdata_reg <= temp_m_axis_tdata_reg;
m_axis_tlast_reg <= temp_m_axis_tlast_reg;
m_axis_tuser_reg <= temp_m_axis_tuser_reg;
end
if (store_axis_int_to_temp) begin
temp_m_axis_tdata_reg <= m_axis_tdata_int;
temp_m_axis_tlast_reg <= m_axis_tlast_int;
temp_m_axis_tuser_reg <= m_axis_tuser_int;
end
end
endmodule
`resetall
|
// Arbitrary-sized RAM.
//
// Both Lattice and Synopsis do not seem
// to be capable of infering cascaded BRAMs
// out-of-the-box, hence the mess below.
module ram #(
parameter WIDTH = 16,
parameter ADDR_WIDTH = 8
) (
input [WIDTH - 1:0] din,
input wire [ADDR_WIDTH - 1:0] addr,
input wire write_en,
input clk,
output reg [WIDTH - 1:0] dout);
localparam HI = WIDTH - 1;
localparam NWORDS = (WIDTH + 15) / 16;
localparam WIDTH_PAD = NWORDS * 16 - WIDTH;
localparam WIDTH_ALIGN = NWORDS * 16;
// Address
// addr[ADDR_WIDTH - 1:0]
// is split to 'offset' (in 16-bit words):
// offset = addr[7:0]
// and 'selector':
// sel = addr[ADDR_WIDTH - 1:8]
// The 8-bit 'offset' part can be mapped to block RAM
// and 'sel' is then implemented on top of it as mux.
localparam SEL_WIDTH = ADDR_WIDTH <= 8 ? 0 : ADDR_WIDTH - 8;
localparam NSEL = 1 << SEL_WIDTH;
wire [WIDTH_ALIGN - 1:0] din_pad;
wire [NSEL*WIDTH_ALIGN - 1:0] douts;
wire [7:0] offset;
wire [SEL_WIDTH - 1:0] sel;
assign din_pad = din;
assign offset = addr[7:0];
assign sel = NSEL == 1 ? 1'b0 : addr[ADDR_WIDTH - 1:8];
genvar i, j;
generate
for(i = 0; i < NSEL; i = i + 1) begin
for(j = 0; j < WIDTH_ALIGN; j = j + 16) begin
ram256x16 bank (
.din(din_pad[j + 15:j]),
.addr(offset),
.write_en(write_en & (sel == i)), // TODO: use decoder?
.clk(clk),
.dout(douts[i*WIDTH_ALIGN + j + 15:i*WIDTH_ALIGN + j]));
end
end
endgenerate
integer k, l;
always @* begin
dout = {WIDTH{1'bx}};
for(k = 0; k < NSEL; k = k + 1) begin
if (sel == k) // TODO: use decoder?
for (l = 0; l < WIDTH; l = l + 1)
dout[l] = douts[k*WIDTH_ALIGN + l];
end
end
endmodule
|
`timescale 1ns / 1ps
/*
* Spartan3AN_PicoBlaze_LCD.v
*
* ___ _ _ _ _ ___ _ _ ___
* | __._ _ _| |_ ___ _| |_| |___ _| | . | \ |_ _|
* | _>| ' ' | . / ._/ . / . / ._/ . | | || |
* |___|_|_|_|___\___\___\___\___\___|_|_|_\_||_|
*
*
* Created on : 20/07/2015
* Author : Ernesto Andres Rincon Cruz
* Web : www.embeddedant.org
* Device : XC3S700AN - 4FGG484
* Board : Spartan-3AN Starter Kit.
*
* Revision History:
* Rev 1.0.0 - (ErnestoARC) First release 19/06/2015.
*/
//////////////////////////////////////////////////////////////////////////////////
module Spartan3AN_PicoBlaze_LCD(
//////////// CLOCK //////////
CLK_50M,
//////////// LCD //////////
LCD_DB,
LCD_E,
LCD_RS,
LCD_RW
);
//=======================================================
// PARAMETER declarations
//=======================================================
parameter LCD_PORT_ID = 8'h00;
//=======================================================
// PORT declarations
//=======================================================
input wire CLK_50M;
output wire [7:0] LCD_DB;
output wire LCD_E;
output wire LCD_RS;
output wire LCD_RW;
//=======================================================
// REG/WIRE declarations
//=======================================================
wire [7:0] Lcd_Port;
//=======================================================
// Structural coding
//=======================================================
//******************************************************************//
// Instantiate PicoBlaze and the Program ROM. //
//******************************************************************//
wire [9:0] address;
wire [17:0] instruction;
wire [7:0] port_id;
wire [7:0] out_port;
wire [7:0] in_port;
wire write_strobe;
wire read_strobe;
wire interrupt;
wire reset;
kcpsm3 kcpsm3_inst (
.address(address),
.instruction(instruction),
.port_id(port_id),
.write_strobe(write_strobe),
.out_port(out_port),
.read_strobe(read_strobe),
.in_port(in_port),
.interrupt(interrupt),
.interrupt_ack(),
.reset(reset),
.clk(CLK_50M));
picocode picocode_inst (
.address(address),
.instruction(instruction),
.clk(CLK_50M));
PicoBlaze_OutReg #(.LOCAL_PORT_ID(LCD_PORT_ID)) Lcd_Port_inst(
.clk(CLK_50M),
.reset(reset),
.port_id(port_id),
.write_strobe(write_strobe),
.out_port(out_port),
.new_out_port(Lcd_Port));
//=======================================================
// Connections & assigns
//=======================================================
//******************************************************************//
// Input PicoBlaze Interface. //
//******************************************************************//
assign in_port = 8'h00;
assign interrupt = 1'b0;
assign reset = 1'b0;
//******************************************************************//
// Output PicoBlaze Interface. //
//******************************************************************//
assign LCD_E=Lcd_Port[0];
assign LCD_RW=Lcd_Port[1];
assign LCD_RS=Lcd_Port[2];
assign LCD_DB={Lcd_Port[7:4],4'bzzzz};
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HS__OR3B_TB_V
`define SKY130_FD_SC_HS__OR3B_TB_V
/**
* or3b: 3-input OR, first input inverted.
*
* Autogenerated test bench.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_hs__or3b.v"
module top();
// Inputs are registered
reg A;
reg B;
reg C_N;
reg VPWR;
reg VGND;
// Outputs are wires
wire X;
initial
begin
// Initial state is x for all inputs.
A = 1'bX;
B = 1'bX;
C_N = 1'bX;
VGND = 1'bX;
VPWR = 1'bX;
#20 A = 1'b0;
#40 B = 1'b0;
#60 C_N = 1'b0;
#80 VGND = 1'b0;
#100 VPWR = 1'b0;
#120 A = 1'b1;
#140 B = 1'b1;
#160 C_N = 1'b1;
#180 VGND = 1'b1;
#200 VPWR = 1'b1;
#220 A = 1'b0;
#240 B = 1'b0;
#260 C_N = 1'b0;
#280 VGND = 1'b0;
#300 VPWR = 1'b0;
#320 VPWR = 1'b1;
#340 VGND = 1'b1;
#360 C_N = 1'b1;
#380 B = 1'b1;
#400 A = 1'b1;
#420 VPWR = 1'bx;
#440 VGND = 1'bx;
#460 C_N = 1'bx;
#480 B = 1'bx;
#500 A = 1'bx;
end
sky130_fd_sc_hs__or3b dut (.A(A), .B(B), .C_N(C_N), .VPWR(VPWR), .VGND(VGND), .X(X));
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_HS__OR3B_TB_V
|
/*******************************************************************************
* This file is owned and controlled by Xilinx and must be used solely *
* for design, simulation, implementation and creation of design files *
* limited to Xilinx devices or technologies. Use with non-Xilinx *
* devices or technologies is expressly prohibited and immediately *
* terminates your license. *
* *
* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" SOLELY *
* FOR USE IN DEVELOPING PROGRAMS AND SOLUTIONS FOR XILINX DEVICES. BY *
* PROVIDING THIS DESIGN, CODE, OR INFORMATION AS ONE POSSIBLE *
* IMPLEMENTATION OF THIS FEATURE, APPLICATION OR STANDARD, XILINX IS *
* MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION IS FREE FROM ANY *
* CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE FOR OBTAINING ANY *
* RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. XILINX EXPRESSLY *
* DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO THE ADEQUACY OF THE *
* IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OR *
* REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM CLAIMS OF *
* INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE. *
* *
* Xilinx products are not intended for use in life support appliances, *
* devices, or systems. Use in such applications are expressly *
* prohibited. *
* *
* (c) Copyright 1995-2014 Xilinx, Inc. *
* All rights reserved. *
*******************************************************************************/
// You must compile the wrapper file DMA_READ_QUEUE.v when simulating
// the core, DMA_READ_QUEUE. When compiling the wrapper file, be sure to
// reference the XilinxCoreLib Verilog simulation library. For detailed
// instructions, please refer to the "CORE Generator Help".
// The synthesis directives "translate_off/translate_on" specified below are
// supported by Xilinx, Mentor Graphics and Synplicity synthesis
// tools. Ensure they are correct for your synthesis tool(s).
`timescale 1ns/1ps
module DMA_READ_QUEUE(
clk,
srst,
din,
wr_en,
rd_en,
dout,
full,
empty
);
input clk;
input srst;
input [63 : 0] din;
input wr_en;
input rd_en;
output [63 : 0] dout;
output full;
output empty;
// synthesis translate_off
FIFO_GENERATOR_V8_4 #(
.C_ADD_NGC_CONSTRAINT(0),
.C_APPLICATION_TYPE_AXIS(0),
.C_APPLICATION_TYPE_RACH(0),
.C_APPLICATION_TYPE_RDCH(0),
.C_APPLICATION_TYPE_WACH(0),
.C_APPLICATION_TYPE_WDCH(0),
.C_APPLICATION_TYPE_WRCH(0),
.C_AXI_ADDR_WIDTH(32),
.C_AXI_ARUSER_WIDTH(1),
.C_AXI_AWUSER_WIDTH(1),
.C_AXI_BUSER_WIDTH(1),
.C_AXI_DATA_WIDTH(64),
.C_AXI_ID_WIDTH(4),
.C_AXI_RUSER_WIDTH(1),
.C_AXI_TYPE(0),
.C_AXI_WUSER_WIDTH(1),
.C_AXIS_TDATA_WIDTH(64),
.C_AXIS_TDEST_WIDTH(4),
.C_AXIS_TID_WIDTH(8),
.C_AXIS_TKEEP_WIDTH(4),
.C_AXIS_TSTRB_WIDTH(4),
.C_AXIS_TUSER_WIDTH(4),
.C_AXIS_TYPE(0),
.C_COMMON_CLOCK(1),
.C_COUNT_TYPE(0),
.C_DATA_COUNT_WIDTH(5),
.C_DEFAULT_VALUE("BlankString"),
.C_DIN_WIDTH(64),
.C_DIN_WIDTH_AXIS(1),
.C_DIN_WIDTH_RACH(32),
.C_DIN_WIDTH_RDCH(64),
.C_DIN_WIDTH_WACH(32),
.C_DIN_WIDTH_WDCH(64),
.C_DIN_WIDTH_WRCH(2),
.C_DOUT_RST_VAL("0"),
.C_DOUT_WIDTH(64),
.C_ENABLE_RLOCS(0),
.C_ENABLE_RST_SYNC(1),
.C_ERROR_INJECTION_TYPE(0),
.C_ERROR_INJECTION_TYPE_AXIS(0),
.C_ERROR_INJECTION_TYPE_RACH(0),
.C_ERROR_INJECTION_TYPE_RDCH(0),
.C_ERROR_INJECTION_TYPE_WACH(0),
.C_ERROR_INJECTION_TYPE_WDCH(0),
.C_ERROR_INJECTION_TYPE_WRCH(0),
.C_FAMILY("virtex6"),
.C_FULL_FLAGS_RST_VAL(0),
.C_HAS_ALMOST_EMPTY(0),
.C_HAS_ALMOST_FULL(0),
.C_HAS_AXI_ARUSER(0),
.C_HAS_AXI_AWUSER(0),
.C_HAS_AXI_BUSER(0),
.C_HAS_AXI_RD_CHANNEL(0),
.C_HAS_AXI_RUSER(0),
.C_HAS_AXI_WR_CHANNEL(0),
.C_HAS_AXI_WUSER(0),
.C_HAS_AXIS_TDATA(0),
.C_HAS_AXIS_TDEST(0),
.C_HAS_AXIS_TID(0),
.C_HAS_AXIS_TKEEP(0),
.C_HAS_AXIS_TLAST(0),
.C_HAS_AXIS_TREADY(1),
.C_HAS_AXIS_TSTRB(0),
.C_HAS_AXIS_TUSER(0),
.C_HAS_BACKUP(0),
.C_HAS_DATA_COUNT(0),
.C_HAS_DATA_COUNTS_AXIS(0),
.C_HAS_DATA_COUNTS_RACH(0),
.C_HAS_DATA_COUNTS_RDCH(0),
.C_HAS_DATA_COUNTS_WACH(0),
.C_HAS_DATA_COUNTS_WDCH(0),
.C_HAS_DATA_COUNTS_WRCH(0),
.C_HAS_INT_CLK(0),
.C_HAS_MASTER_CE(0),
.C_HAS_MEMINIT_FILE(0),
.C_HAS_OVERFLOW(0),
.C_HAS_PROG_FLAGS_AXIS(0),
.C_HAS_PROG_FLAGS_RACH(0),
.C_HAS_PROG_FLAGS_RDCH(0),
.C_HAS_PROG_FLAGS_WACH(0),
.C_HAS_PROG_FLAGS_WDCH(0),
.C_HAS_PROG_FLAGS_WRCH(0),
.C_HAS_RD_DATA_COUNT(0),
.C_HAS_RD_RST(0),
.C_HAS_RST(0),
.C_HAS_SLAVE_CE(0),
.C_HAS_SRST(1),
.C_HAS_UNDERFLOW(0),
.C_HAS_VALID(0),
.C_HAS_WR_ACK(0),
.C_HAS_WR_DATA_COUNT(0),
.C_HAS_WR_RST(0),
.C_IMPLEMENTATION_TYPE(0),
.C_IMPLEMENTATION_TYPE_AXIS(1),
.C_IMPLEMENTATION_TYPE_RACH(1),
.C_IMPLEMENTATION_TYPE_RDCH(1),
.C_IMPLEMENTATION_TYPE_WACH(1),
.C_IMPLEMENTATION_TYPE_WDCH(1),
.C_IMPLEMENTATION_TYPE_WRCH(1),
.C_INIT_WR_PNTR_VAL(0),
.C_INTERFACE_TYPE(0),
.C_MEMORY_TYPE(2),
.C_MIF_FILE_NAME("BlankString"),
.C_MSGON_VAL(1),
.C_OPTIMIZATION_MODE(0),
.C_OVERFLOW_LOW(0),
.C_PRELOAD_LATENCY(0),
.C_PRELOAD_REGS(1),
.C_PRIM_FIFO_TYPE("512x72"),
.C_PROG_EMPTY_THRESH_ASSERT_VAL(4),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_AXIS(1022),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_RACH(1022),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_RDCH(1022),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_WACH(1022),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_WDCH(1022),
.C_PROG_EMPTY_THRESH_ASSERT_VAL_WRCH(1022),
.C_PROG_EMPTY_THRESH_NEGATE_VAL(5),
.C_PROG_EMPTY_TYPE(0),
.C_PROG_EMPTY_TYPE_AXIS(5),
.C_PROG_EMPTY_TYPE_RACH(5),
.C_PROG_EMPTY_TYPE_RDCH(5),
.C_PROG_EMPTY_TYPE_WACH(5),
.C_PROG_EMPTY_TYPE_WDCH(5),
.C_PROG_EMPTY_TYPE_WRCH(5),
.C_PROG_FULL_THRESH_ASSERT_VAL(15),
.C_PROG_FULL_THRESH_ASSERT_VAL_AXIS(1023),
.C_PROG_FULL_THRESH_ASSERT_VAL_RACH(1023),
.C_PROG_FULL_THRESH_ASSERT_VAL_RDCH(1023),
.C_PROG_FULL_THRESH_ASSERT_VAL_WACH(1023),
.C_PROG_FULL_THRESH_ASSERT_VAL_WDCH(1023),
.C_PROG_FULL_THRESH_ASSERT_VAL_WRCH(1023),
.C_PROG_FULL_THRESH_NEGATE_VAL(14),
.C_PROG_FULL_TYPE(0),
.C_PROG_FULL_TYPE_AXIS(5),
.C_PROG_FULL_TYPE_RACH(5),
.C_PROG_FULL_TYPE_RDCH(5),
.C_PROG_FULL_TYPE_WACH(5),
.C_PROG_FULL_TYPE_WDCH(5),
.C_PROG_FULL_TYPE_WRCH(5),
.C_RACH_TYPE(0),
.C_RD_DATA_COUNT_WIDTH(5),
.C_RD_DEPTH(16),
.C_RD_FREQ(1),
.C_RD_PNTR_WIDTH(4),
.C_RDCH_TYPE(0),
.C_REG_SLICE_MODE_AXIS(0),
.C_REG_SLICE_MODE_RACH(0),
.C_REG_SLICE_MODE_RDCH(0),
.C_REG_SLICE_MODE_WACH(0),
.C_REG_SLICE_MODE_WDCH(0),
.C_REG_SLICE_MODE_WRCH(0),
.C_SYNCHRONIZER_STAGE(2),
.C_UNDERFLOW_LOW(0),
.C_USE_COMMON_OVERFLOW(0),
.C_USE_COMMON_UNDERFLOW(0),
.C_USE_DEFAULT_SETTINGS(0),
.C_USE_DOUT_RST(1),
.C_USE_ECC(0),
.C_USE_ECC_AXIS(0),
.C_USE_ECC_RACH(0),
.C_USE_ECC_RDCH(0),
.C_USE_ECC_WACH(0),
.C_USE_ECC_WDCH(0),
.C_USE_ECC_WRCH(0),
.C_USE_EMBEDDED_REG(0),
.C_USE_FIFO16_FLAGS(0),
.C_USE_FWFT_DATA_COUNT(1),
.C_VALID_LOW(0),
.C_WACH_TYPE(0),
.C_WDCH_TYPE(0),
.C_WR_ACK_LOW(0),
.C_WR_DATA_COUNT_WIDTH(5),
.C_WR_DEPTH(16),
.C_WR_DEPTH_AXIS(1024),
.C_WR_DEPTH_RACH(16),
.C_WR_DEPTH_RDCH(1024),
.C_WR_DEPTH_WACH(16),
.C_WR_DEPTH_WDCH(1024),
.C_WR_DEPTH_WRCH(16),
.C_WR_FREQ(1),
.C_WR_PNTR_WIDTH(4),
.C_WR_PNTR_WIDTH_AXIS(10),
.C_WR_PNTR_WIDTH_RACH(4),
.C_WR_PNTR_WIDTH_RDCH(10),
.C_WR_PNTR_WIDTH_WACH(4),
.C_WR_PNTR_WIDTH_WDCH(10),
.C_WR_PNTR_WIDTH_WRCH(4),
.C_WR_RESPONSE_LATENCY(1),
.C_WRCH_TYPE(0)
)
inst (
.CLK(clk),
.SRST(srst),
.DIN(din),
.WR_EN(wr_en),
.RD_EN(rd_en),
.DOUT(dout),
.FULL(full),
.EMPTY(empty),
.BACKUP(),
.BACKUP_MARKER(),
.RST(),
.WR_CLK(),
.WR_RST(),
.RD_CLK(),
.RD_RST(),
.PROG_EMPTY_THRESH(),
.PROG_EMPTY_THRESH_ASSERT(),
.PROG_EMPTY_THRESH_NEGATE(),
.PROG_FULL_THRESH(),
.PROG_FULL_THRESH_ASSERT(),
.PROG_FULL_THRESH_NEGATE(),
.INT_CLK(),
.INJECTDBITERR(),
.INJECTSBITERR(),
.ALMOST_FULL(),
.WR_ACK(),
.OVERFLOW(),
.ALMOST_EMPTY(),
.VALID(),
.UNDERFLOW(),
.DATA_COUNT(),
.RD_DATA_COUNT(),
.WR_DATA_COUNT(),
.PROG_FULL(),
.PROG_EMPTY(),
.SBITERR(),
.DBITERR(),
.M_ACLK(),
.S_ACLK(),
.S_ARESETN(),
.M_ACLK_EN(),
.S_ACLK_EN(),
.S_AXI_AWID(),
.S_AXI_AWADDR(),
.S_AXI_AWLEN(),
.S_AXI_AWSIZE(),
.S_AXI_AWBURST(),
.S_AXI_AWLOCK(),
.S_AXI_AWCACHE(),
.S_AXI_AWPROT(),
.S_AXI_AWQOS(),
.S_AXI_AWREGION(),
.S_AXI_AWUSER(),
.S_AXI_AWVALID(),
.S_AXI_AWREADY(),
.S_AXI_WID(),
.S_AXI_WDATA(),
.S_AXI_WSTRB(),
.S_AXI_WLAST(),
.S_AXI_WUSER(),
.S_AXI_WVALID(),
.S_AXI_WREADY(),
.S_AXI_BID(),
.S_AXI_BRESP(),
.S_AXI_BUSER(),
.S_AXI_BVALID(),
.S_AXI_BREADY(),
.M_AXI_AWID(),
.M_AXI_AWADDR(),
.M_AXI_AWLEN(),
.M_AXI_AWSIZE(),
.M_AXI_AWBURST(),
.M_AXI_AWLOCK(),
.M_AXI_AWCACHE(),
.M_AXI_AWPROT(),
.M_AXI_AWQOS(),
.M_AXI_AWREGION(),
.M_AXI_AWUSER(),
.M_AXI_AWVALID(),
.M_AXI_AWREADY(),
.M_AXI_WID(),
.M_AXI_WDATA(),
.M_AXI_WSTRB(),
.M_AXI_WLAST(),
.M_AXI_WUSER(),
.M_AXI_WVALID(),
.M_AXI_WREADY(),
.M_AXI_BID(),
.M_AXI_BRESP(),
.M_AXI_BUSER(),
.M_AXI_BVALID(),
.M_AXI_BREADY(),
.S_AXI_ARID(),
.S_AXI_ARADDR(),
.S_AXI_ARLEN(),
.S_AXI_ARSIZE(),
.S_AXI_ARBURST(),
.S_AXI_ARLOCK(),
.S_AXI_ARCACHE(),
.S_AXI_ARPROT(),
.S_AXI_ARQOS(),
.S_AXI_ARREGION(),
.S_AXI_ARUSER(),
.S_AXI_ARVALID(),
.S_AXI_ARREADY(),
.S_AXI_RID(),
.S_AXI_RDATA(),
.S_AXI_RRESP(),
.S_AXI_RLAST(),
.S_AXI_RUSER(),
.S_AXI_RVALID(),
.S_AXI_RREADY(),
.M_AXI_ARID(),
.M_AXI_ARADDR(),
.M_AXI_ARLEN(),
.M_AXI_ARSIZE(),
.M_AXI_ARBURST(),
.M_AXI_ARLOCK(),
.M_AXI_ARCACHE(),
.M_AXI_ARPROT(),
.M_AXI_ARQOS(),
.M_AXI_ARREGION(),
.M_AXI_ARUSER(),
.M_AXI_ARVALID(),
.M_AXI_ARREADY(),
.M_AXI_RID(),
.M_AXI_RDATA(),
.M_AXI_RRESP(),
.M_AXI_RLAST(),
.M_AXI_RUSER(),
.M_AXI_RVALID(),
.M_AXI_RREADY(),
.S_AXIS_TVALID(),
.S_AXIS_TREADY(),
.S_AXIS_TDATA(),
.S_AXIS_TSTRB(),
.S_AXIS_TKEEP(),
.S_AXIS_TLAST(),
.S_AXIS_TID(),
.S_AXIS_TDEST(),
.S_AXIS_TUSER(),
.M_AXIS_TVALID(),
.M_AXIS_TREADY(),
.M_AXIS_TDATA(),
.M_AXIS_TSTRB(),
.M_AXIS_TKEEP(),
.M_AXIS_TLAST(),
.M_AXIS_TID(),
.M_AXIS_TDEST(),
.M_AXIS_TUSER(),
.AXI_AW_INJECTSBITERR(),
.AXI_AW_INJECTDBITERR(),
.AXI_AW_PROG_FULL_THRESH(),
.AXI_AW_PROG_EMPTY_THRESH(),
.AXI_AW_DATA_COUNT(),
.AXI_AW_WR_DATA_COUNT(),
.AXI_AW_RD_DATA_COUNT(),
.AXI_AW_SBITERR(),
.AXI_AW_DBITERR(),
.AXI_AW_OVERFLOW(),
.AXI_AW_UNDERFLOW(),
.AXI_W_INJECTSBITERR(),
.AXI_W_INJECTDBITERR(),
.AXI_W_PROG_FULL_THRESH(),
.AXI_W_PROG_EMPTY_THRESH(),
.AXI_W_DATA_COUNT(),
.AXI_W_WR_DATA_COUNT(),
.AXI_W_RD_DATA_COUNT(),
.AXI_W_SBITERR(),
.AXI_W_DBITERR(),
.AXI_W_OVERFLOW(),
.AXI_W_UNDERFLOW(),
.AXI_B_INJECTSBITERR(),
.AXI_B_INJECTDBITERR(),
.AXI_B_PROG_FULL_THRESH(),
.AXI_B_PROG_EMPTY_THRESH(),
.AXI_B_DATA_COUNT(),
.AXI_B_WR_DATA_COUNT(),
.AXI_B_RD_DATA_COUNT(),
.AXI_B_SBITERR(),
.AXI_B_DBITERR(),
.AXI_B_OVERFLOW(),
.AXI_B_UNDERFLOW(),
.AXI_AR_INJECTSBITERR(),
.AXI_AR_INJECTDBITERR(),
.AXI_AR_PROG_FULL_THRESH(),
.AXI_AR_PROG_EMPTY_THRESH(),
.AXI_AR_DATA_COUNT(),
.AXI_AR_WR_DATA_COUNT(),
.AXI_AR_RD_DATA_COUNT(),
.AXI_AR_SBITERR(),
.AXI_AR_DBITERR(),
.AXI_AR_OVERFLOW(),
.AXI_AR_UNDERFLOW(),
.AXI_R_INJECTSBITERR(),
.AXI_R_INJECTDBITERR(),
.AXI_R_PROG_FULL_THRESH(),
.AXI_R_PROG_EMPTY_THRESH(),
.AXI_R_DATA_COUNT(),
.AXI_R_WR_DATA_COUNT(),
.AXI_R_RD_DATA_COUNT(),
.AXI_R_SBITERR(),
.AXI_R_DBITERR(),
.AXI_R_OVERFLOW(),
.AXI_R_UNDERFLOW(),
.AXIS_INJECTSBITERR(),
.AXIS_INJECTDBITERR(),
.AXIS_PROG_FULL_THRESH(),
.AXIS_PROG_EMPTY_THRESH(),
.AXIS_DATA_COUNT(),
.AXIS_WR_DATA_COUNT(),
.AXIS_RD_DATA_COUNT(),
.AXIS_SBITERR(),
.AXIS_DBITERR(),
.AXIS_OVERFLOW(),
.AXIS_UNDERFLOW()
);
// synthesis translate_on
endmodule
|
(*
Copyright 2014 Cornell University
This file is part of VPrl (the Verified Nuprl project).
VPrl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
VPrl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VPrl. If not, see <http://www.gnu.org/licenses/>.
Website: http://nuprl.org/html/verification/
Authors: Abhishek Anand & Vincent Rahli
*)
Require Export approx_star_props2.
Require Export computation6.
(** printing # $\times$ #×# *)
(** printing <=> $\Leftrightarrow$ #⇔# *)
(** printing $ $\times$ #×# *)
(** printing & $\times$ #×# *)
(* begin hide *)
Lemma range_utok_ren_nrut_subs_to_utok_ren {o} :
forall (sub1 sub2 : @Sub o) l1 l2,
nrut_sub l1 sub1
-> nrut_sub l2 sub2
-> length sub1 = length sub2
-> range_utok_ren (nrut_subs_to_utok_ren sub1 sub2)
= get_utokens_sub sub2.
Proof.
induction sub1; destruct sub2; introv nrut1 nrut2 len; simphyps; tcsp.
destruct a as [v1 t1]; destruct p as [v2 t2].
allrw @nrut_sub_cons; exrepnd; subst; allsimpl; cpx.
allrw @get_utokens_sub_cons; allsimpl.
erewrite IHsub1; eauto.
Qed.
Lemma dom_utok_ren_nrut_subs_to_utok_ren {o} :
forall (sub1 sub2 : @Sub o) l1 l2,
nrut_sub l1 sub1
-> nrut_sub l2 sub2
-> length sub1 = length sub2
-> dom_utok_ren (nrut_subs_to_utok_ren sub1 sub2)
= get_utokens_sub sub1.
Proof.
induction sub1; destruct sub2; introv nrut1 nrut2 len; simphyps; tcsp.
destruct a as [v1 t1]; destruct p as [v2 t2].
allrw @nrut_sub_cons; exrepnd; subst; allsimpl; cpx.
allrw @get_utokens_sub_cons; allsimpl.
erewrite IHsub1; eauto.
Qed.
Lemma approx_star_change_nrut_sub {o} :
forall lib (t1 t2 : @NTerm o) sub l sub' l',
nrut_sub l sub
-> nrut_sub l' sub'
-> dom_sub sub = dom_sub sub'
-> subset (get_utokens t1) l
-> subset (get_utokens t2) l
-> subset (get_utokens t1) l'
-> subset (get_utokens t2) l'
-> approx_star lib (lsubst t1 sub) (lsubst t2 sub)
-> approx_star lib (lsubst t1 sub') (lsubst t2 sub').
Proof.
introv nrut1 nrut2 eqdoms ss1 ss2 ss3 ss4 apr.
pose proof (length_dom sub) as len.
rw eqdoms in len; rw @length_dom in len.
pose proof (change_nr_ut_sub_in_lsubst_aux_approx_star
lib (lsubst t1 sub) (lsubst t2 sub)
(nrut_subs_to_utok_ren sub sub')) as h.
erewrite @range_utok_ren_nrut_subs_to_utok_ren in h; eauto.
erewrite @dom_utok_ren_nrut_subs_to_utok_ren in h; eauto.
repeat (autodimp h hyp); eauto 3 with slow.
- introv i j.
allrw in_diff; repnd.
apply get_utokens_lsubst in j0; allrw in_app_iff; repndors.
+ apply ss3 in j0.
unfold nrut_sub in nrut2; repnd.
apply nrut2 in j0; sp.
+ apply in_get_utokens_sub in j0; exrepnd.
apply in_sub_keep_first in j1; repnd.
apply sub_find_some in j2.
destruct j.
apply in_sub_eta in j2; repnd.
unfold get_utokens_sub; rw lin_flat_map.
eexists; dands; eauto.
- introv i j.
allrw in_diff; repnd.
apply get_utokens_lsubst in j0; allrw in_app_iff; repndors.
+ apply ss4 in j0.
unfold nrut_sub in nrut2; repnd.
apply nrut2 in j0; sp.
+ apply in_get_utokens_sub in j0; exrepnd.
apply in_sub_keep_first in j1; repnd.
apply sub_find_some in j2.
destruct j.
apply in_sub_eta in j2; repnd.
unfold get_utokens_sub; rw lin_flat_map.
eexists; dands; eauto.
- assert (disjoint (get_utokens_sub sub) (get_utokens t1)) as disj1.
{ introv i j.
apply ss1 in j; unfold nrut_sub in nrut1; repnd.
apply nrut1 in j; sp. }
assert (disjoint (get_utokens_sub sub) (get_utokens t2)) as disj2.
{ introv i j.
apply ss2 in j; unfold nrut_sub in nrut1; repnd.
apply nrut1 in j; sp. }
repeat (rw @lsubst_ren_utokens in h).
repeat (rw @ren_utokens_trivial in h;[|erewrite @dom_utok_ren_nrut_subs_to_utok_ren; eauto]).
erewrite @ren_utokens_sub_nrut_subs_to_utok_ren in h; eauto.
Qed.
Lemma alpha_eq_bterm_preserves_osize2 {p} :
forall bt1 bt2,
@alpha_eq_bterm p bt1 bt2
-> osize (get_nt bt1) = osize (get_nt bt2).
Proof.
introv Hal.
destruct bt1 as [lv1 nt1].
destruct bt2 as [lv2 nt2].
simpl; eapply alpha_eq_bterm_preserves_osize; eauto.
Qed.
Lemma lsubst_approx_star_congr_aux {p} :
forall lib b b' lvi lnta lnta',
approx_star lib b b'
-> length lvi = length lnta
-> length lvi = length lnta'
-> disjoint (bound_vars b ++ bound_vars b') (flat_map (@free_vars p) (lnta ++ lnta'))
-> bin_rel_nterm (approx_star lib) lnta lnta'
-> approx_star lib (lsubst_aux b (combine lvi lnta)) (lsubst_aux b' (combine lvi lnta')).
Proof.
nterm_ind1s b as [x|f ind|o lbt Hind] Case; introv Hap H1len H2len Hdis Hbin;
rw flat_map_app in Hdis; duplicate Hbin as Hbb;
apply @approx_rel_wf_sub with (lvi:=lvi) in Hbb; repnd.
- Case "vterm".
invertsn Hap. allsimpl.
dsub_find xa;
apply approx_open_lsubst_congr with (sub:= combine lvi lnta') in Hap;spcf;
lsubst_lsubst_aux_eq_hyp X99 Hap; simpl; simpl_vlist; clear X99;
lsubst_lsubst_aux_eq_hyp X99 Hap; simpl; simpl_vlist; clear X99;
allsimpl; revert Hap.
+ dsub_find xa'; [|provefalse; eauto with slow].
introv Hap. symmetry in Heqxa. symmetry in Heqxa'.
eapply sub_find_some2_first
in Heqxa; eauto. exrepnd. repnud Hbin. repnud Hbin.
dimp (Hbin n);[spc;fail|].
rewrite nth_indep with (d':= default_nterm) in Heqxa0; spc.
rewrite nth_indep with (d':= default_nterm) in Heqxa4; spc.
rw Heqxa0 in hyp.
rw Heqxa4 in hyp.
eapply approx_star_open_trans; eauto.
+ dsub_find xa'; [provefalse; eauto with slow | ].
introv. apply approx_open_implies_approx_star.
- Case "sterm".
allsimpl.
inversion Hap as [|? ? ? ? imp aop|]; subst; clear Hap.
econstructor; eauto.
apply (approx_open_lsubst_congr _ _ _ (combine lvi lnta')) in aop; eauto 3 with slow.
autorewrite with slow in *.
unfold lsubst in aop; boolvar; auto.
allrw disjoint_app_r; repnd.
allrw <- @sub_free_vars_is_flat_map_free_vars_range.
rw @sub_free_vars_combine in n; tcsp.
- Case "oterm".
allsimpl.
pose proof (approx_ot_change
lib
(flat_map free_vars lnta ++ flat_map free_vars lnta')
_ _ _ Hap) as Hao.
exrepnd.
rename lbtcv into lbt'. (* t' in paper *)
apply approx_open_lsubst_congr with (sub:= combine lvi lnta') in Hao0;spcf.
lsubst_lsubst_aux_eq_hyp X99 Hao0; simpl; simpl_vlist; clear X99;[].
lsubst_lsubst_aux_eq_hyp X99 Hao0; simpl; simpl_vlist; clear X99;[].
apply approx_star_open_trans with (b:=lsubst_aux (oterm o lbt') (combine lvi lnta'));spc;[].
allsimpl.
apply approx_open_relates_only_wf in Hao0. repnd.
apply approx_star_congruence2;spc;[].
clear Hao0 Hao4.
unfold approx_starbts, lblift_sub; allunfold @blift_sub;repeat(simpl_list).
dands; spcf.
exrepnd. GC.
introv Hlt. rw @selectbt_map;spc;[]. rw @selectbt_map;spc;[].
duplicate Hlt as Hlt99. apply Hao2 in Hlt.
destruct (dec_op_eq_fresh o) as [e|e].
+ pose proof (approx_star_btermd_fr
_ _ _ _
(flat_map free_vars lnta ++ flat_map free_vars lnta')
e
Hlt) as Hfb.
exrepnd.
exists lvn
(lsubst_aux nt1' (sub_filter (combine lvi lnta) lvn))
(lsubst_aux nt2' (sub_filter (combine lvi lnta') lvn)).
dimp (selectbt_in n lbt');spcf.
dimp (selectbt_in n lbt);spcf.
applydup @alpha_eq_bterm_preserves_osize2 in Hfb4.
(* needed to apply induction hyp later *)
apply (lsubst_alphabt_congr _ _ (combine lvi lnta'))
in Hfb5; [|allsimpl; spcls; disjoint_reasoningv;
apply disjoint_sym; eapply disjoint_flat_map_r in Hao1; eauto; fail].
apply (lsubst_alphabt_congr _ _ (combine lvi lnta))
in Hfb4; [|allsimpl; spcls; disjoint_reasoningv;
apply disjoint_sym in Hdis2;
eapply disjoint_flat_map_r in Hdis2; eauto with slow; fail].
dands; auto;[].
right.
pose proof (exists_nrut_sub
lvn
(get_utokens nt1'
++ get_utokens nt2'
++ flat_map get_utokens lnta
++ flat_map get_utokens lnta'))
as exnrut; exrepnd.
pose proof (approx_star_change_nrut_sub
lib nt1' nt2' sub (get_utokens nt1' ++ get_utokens nt2')
sub0
(get_utokens nt1'
++ get_utokens nt2'
++ flat_map get_utokens lnta
++ flat_map get_utokens lnta'))
as ch.
repeat (autodimp ch hh); tcsp; eauto 3 with slow.
destruct (selectbt lbt n) as [l1 t1].
destruct (selectbt lbt' n) as [l2 t2].
allsimpl.
pose proof (Hind t1 (lsubst nt1' sub0) l1) as h; repeat (autodimp h hh).
{ allrw; auto; rw @simple_osize_lsubst; eauto 3 with slow. }
pose proof (h (lsubst nt2' sub0) lvi lnta lnta') as q; clear h.
repeat (autodimp q hh).
{ repeat (rw @cl_lsubst_lsubst_aux; eauto 2 with slow).
repeat (erewrite bound_vars_lsubst_aux_nrut_sub; eauto).
rw flat_map_app; allrw disjoint_app_l; sp. }
repeat (rw @cl_lsubst_lsubst_aux in q; eauto 2 with slow).
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj nt1' sub0 (combine lvi lnta)) as e1.
rw @sub_free_vars_combine in e1; auto.
rw <- exnrut0 in e1.
erewrite sub_bound_vars_nrut_sub in e1; eauto.
erewrite sub_free_vars_nrut_sub in e1; eauto.
allrw disjoint_app_r; allrw disjoint_app_l; repnd.
repeat (autodimp e1 hh).
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj nt2' sub0 (combine lvi lnta')) as e2.
rw @sub_free_vars_combine in e2; auto.
rw <- exnrut0 in e2.
erewrite sub_bound_vars_nrut_sub in e2; eauto.
erewrite sub_free_vars_nrut_sub in e2; eauto.
allrw disjoint_app_r; allrw disjoint_app_l; repnd.
repeat (autodimp e2 hh).
rw @cl_lsubst_aux_sub_trivial in e1; eauto 2 with slow.
rw @cl_lsubst_aux_sub_trivial in e2; eauto 2 with slow.
rw <- e1 in q; rw <- e2 in q.
exists sub0; dands; auto.
{ repeat (rw @cl_lsubst_lsubst_aux; eauto 2 with slow). }
{ eapply nrut_sub_subset;[|exact exnrut1].
rw subset_app; dands; introv i; repeat (rw in_app_iff);
apply get_utokens_lsubst_aux in i; rw in_app_iff in i; repndors; tcsp;
apply in_get_utokens_sub in i; exrepnd; apply in_sub_keep_first in i0; repnd;
apply sub_find_some in i2; apply in_sub_filter in i2; repnd; apply in_combine in i3; repnd.
- right; right; left; rw lin_flat_map; eexists; dands; eauto.
- right; right; right; rw lin_flat_map; eexists; dands; eauto.
}
+ pose proof (approx_star_btermd
_ _ _ _
(flat_map free_vars lnta ++ flat_map free_vars lnta')
e
Hlt) as Hfb.
exrepnd.
exists lvn (lsubst_aux nt1' (sub_filter (combine lvi lnta) lvn))
(lsubst_aux nt2' (sub_filter (combine lvi lnta') lvn)).
dimp (selectbt_in n lbt');spcf.
dimp (selectbt_in n lbt);spcf.
applydup @alpha_eq_bterm_preserves_osize2 in Hfb2.
(* needed to apply induction hyp later *)
apply lsubst_alphabt_congr with (sub := (combine lvi lnta'))
in Hfb3; [| allsimpl; spcls; disjoint_reasoningv;
apply disjoint_sym; eapply disjoint_flat_map_r in Hao1; eauto; fail].
apply lsubst_alphabt_congr with (sub := (combine lvi lnta))
in Hfb2; [| allsimpl; spcls; disjoint_reasoningv;
apply disjoint_sym in Hdis2;
eapply disjoint_flat_map_r in Hdis2; eauto with slow; fail].
dands; auto;[].
left; dands; auto.
dimp (sub_filter_pair_dom lvn (approx_star lib) lvi lnta lnta' ); spcf.
exrepnd.
rename lnta'0 into lntf.
rename lntb' into lntf'.
rename lvi' into lvif.
rw hyp1.
rw hyp3.
destruct (selectbt lbt n) as [lv nt].
simpl in Hfb5.
eapply Hind with (nt:=nt); eauto; spc;[allrw; eauto 3 with slow|];[].
rw flat_map_app. disjoint_reasoningv; disjoint_sub_filter.
Qed.
Lemma get_utokens_sub_combine {o} :
forall vs (ts : list (@NTerm o)),
length vs = length ts
-> get_utokens_sub (combine vs ts) = flat_map get_utokens ts.
Proof.
induction vs; destruct ts; introv len; allsimpl; tcsp; cpx.
allrw @get_utokens_sub_cons.
rw IHvs; auto.
Qed.
Lemma change_dom_nrut_sub {o} :
forall (sub : @Sub o) l vs,
nrut_sub l sub
-> length vs = length sub
-> {sub' : Sub
& nrut_sub l sub'
# range sub = range sub'
# dom_sub sub' = vs }.
Proof.
introv nrut len.
exists (combine vs (range sub)).
rw @range_combine; allrw @length_range; auto.
rw @dom_sub_combine; allrw @length_range; auto.
dands; auto.
allunfold @nrut_sub; repnd.
rw @get_utokens_sub_combine; allrw @length_range; auto.
dands; auto.
introv i.
allapply in_combine; repnd.
apply in_range in i; exrepnd.
pose proof (nrut0 v0 t) as h; autodimp h hyp.
Qed.
Lemma cl_lsubst_approx_star_congr {o} :
forall lib (a b : @NTerm o) sub,
prog_sub sub
-> approx_star lib a b
-> approx_star lib (lsubst a sub) (lsubst_aux b sub).
Proof.
introv pr apr.
pose proof (lsubst_approx_star_congr_aux lib a b (dom_sub sub) (range sub) (range sub)) as h.
allrw @length_dom; allrw @length_range.
repeat (autodimp h hyp).
- rw flat_map_app.
allrw <- @sub_free_vars_is_flat_map_free_vars_range.
rw @sub_free_vars_if_cl_sub; simpl; eauto with slow.
- unfold bin_rel_nterm, binrel_list; dands; auto.
introv i.
apply approx_star_refl.
remember (nth n (range sub) default_nterm) as t.
assert (LIn t (range sub)) as k.
{ subst; apply nth_in; auto. }
apply in_range in k; exrepnd.
pose proof (pr v t) as h; autodimp h hyp.
destruct h as [c w]; auto.
- allrw <- @sub_eta; auto.
rw @cl_lsubst_lsubst_aux; eauto 2 with slow.
Qed.
(* we need it at least for subs with range as axiom for howe_lemma2 *)
Lemma approx_star_bterm_lsubst_congr {p} :
forall lib (bt1 bt2 : BTerm) sub op,
@prog_sub p sub
-> approx_star_bterm lib op bt1 bt2
-> approx_star_bterm
lib op
(lsubst_bterm_aux bt1 sub)
(lsubst_bterm_aux bt2 sub).
Proof.
introv Hpr Hs.
destruct (dec_op_eq_fresh op) as [d|d].
{
pose proof (approx_star_btermd_fr
_ _ _ _
(flat_map free_vars (range sub)) d Hs) as Hfb.
exrepnd.
allrw <- @sub_free_vars_is_flat_map_free_vars_range.
unfold approx_star_bterm, blift_sub.
exists lvn (lsubst nt1' (sub_filter sub lvn)) (lsubst nt2' (sub_filter sub lvn)).
dands; auto;
[|apply (lsubst_alphabt_congr _ _ sub) in Hfb4;
allsimpl; auto;
try (rw <- @cl_lsubst_lsubst_aux in Hfb4; eauto 3 with slow);
allrw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_if_cl_sub; eauto with slow
|apply (lsubst_alphabt_congr _ _ sub) in Hfb5;
allsimpl; auto;
try (rw <- @cl_lsubst_lsubst_aux in Hfb5; eauto 3 with slow);
allrw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_if_cl_sub; eauto with slow].
right.
pose proof (exists_nrut_sub
lvn
(get_utokens nt1'
++ get_utokens nt2'
++ get_utokens_sub sub))
as exnrut; exrepnd.
pose proof (approx_star_change_nrut_sub
lib nt1' nt2' sub0 (get_utokens nt1' ++ get_utokens nt2')
sub1
(get_utokens nt1'
++ get_utokens nt2'
++ get_utokens_sub sub))
as ch.
repeat (autodimp ch hh); tcsp; eauto 3 with slow.
destruct bt1 as [l1 t1].
destruct bt2 as [l2 t2].
allsimpl.
pose proof (cl_lsubst_approx_star_congr
lib (lsubst nt1' sub1) (lsubst nt2' sub1) sub) as q.
repeat (autodimp q hyp).
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj nt1' sub1 sub) as e1.
repeat (rw @sub_free_vars_if_cl_sub in e1; eauto with slow).
repeat (autodimp e1 hh).
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj nt2' sub1 sub) as e2.
repeat (rw @sub_free_vars_if_cl_sub in e2; eauto with slow).
repeat (autodimp e2 hh).
rw @cl_lsubst_aux_sub_trivial in e1; eauto 2 with slow.
rw @cl_lsubst_aux_sub_trivial in e2; eauto 2 with slow.
repeat (rw <- @cl_lsubst_lsubst_aux in e1; eauto with slow).
repeat (rw <- @cl_lsubst_lsubst_aux in e2; eauto with slow).
repeat (rw <- @cl_lsubst_lsubst_aux in q; eauto with slow).
rw <- e1 in q; rw <- e2 in q; clear e1 e2.
rw <- exnrut0 in q.
exists sub1; dands; auto.
{ eapply nrut_sub_subset;[|exact exnrut1].
rw subset_app; dands; introv i; repeat (rw in_app_iff);
apply get_utokens_lsubst in i; rw in_app_iff in i; repndors; tcsp;
apply in_get_utokens_sub in i; exrepnd; apply in_sub_keep_first in i0; repnd;
apply sub_find_some in i2; apply in_sub_filter in i2; repnd;
apply in_sub_eta in i3; repnd;
right; right; rw lin_flat_map; eexists; dands; eauto.
}
}
pose proof (approx_star_btermd
_ _ _ _
(flat_map free_vars (range sub)) d Hs) as Hfb.
exrepnd.
apply @lsubst_alphabt_congr with (sub := sub) in Hfb2;
[| change_to_lsubst_aux4; eauto; fail].
apply @lsubst_alphabt_congr with (sub := sub) in Hfb3;
[| change_to_lsubst_aux4; eauto; fail].
allsimpl.
exists lvn (lsubst_aux nt1' (sub_filter sub lvn))
(lsubst_aux nt2' (sub_filter sub lvn)).
dands; sp;[].
pose proof (sub_eta (sub_filter sub lvn)) as Xsfeta.
pose proof (sub_eta_length (sub_filter sub lvn)) as X1len.
remember (dom_sub (sub_filter sub lvn)) as lsvi.
remember (range (sub_filter sub lvn)) as lsnt.
rw Xsfeta.
left; dands; auto.
apply lsubst_approx_star_congr_aux;spc.
- rw flat_map_app.
(* the disjoint_sub_filter tactic needs the substitutions in eta form*)
pose proof (sub_eta sub ) as Xseta.
pose proof (sub_eta_length sub) as Xslen.
remember (dom_sub sub) as lvi.
remember (range sub) as lnt.
rw Xseta in Xsfeta.
disjoint_reasoningv; try disjoint_sub_filter.
- unfold bin_rel_nterm, binrel_list; dands; [sp | introv Hlt].
apply approx_star_refl. pose proof (nth_in _ _ _ default_nterm Hlt) as XX.
rw Heqlsnt in XX.
apply in_range in XX. exrepnd.
apply in_sub_filter in XX0. exrepnd.
apply Hpr in XX1.
rw Heqlsnt. inverts XX1. sp.
Qed.
(* end hide *)
(** %\noindent \\*% The following is a generalization of Howe's lemma 1 %\cite{Howe:1989}%.
He proved proved (needed) it for substitutions of length one.
We need it atleast for substitutions of length upto two because
the computation for [NSpread] performs a simultaneous subsitution
for two variables. We prove a more general version instead.
Apart from some uninteresting details about substitution, our
mechanized proof
is essentially the same as Howe's.
*)
Lemma lsubst_approx_star_congr {p} :
forall lib (t1 t2 : @NTerm p) (lvi : list NVar) (lnt1 lnt2 : list NTerm),
bin_rel_nterm (approx_star lib) lnt1 lnt2
-> length lvi = length lnt1
-> length lvi = length lnt2
-> approx_star lib t1 t2
-> approx_star lib (lsubst t1 (combine lvi lnt1)) (lsubst t2 (combine lvi lnt2)).
Proof.
introv Hsr H1l H2l Has.
pose proof (change_bvars_alpha_wspec
((flat_map free_vars lnt1)++(flat_map free_vars lnt2)) t1) as H1f.
exrepnd. rename ntcv into ct1.
pose proof (change_bvars_alpha_wspec
((flat_map free_vars lnt1)++(flat_map free_vars lnt2)) t2) as H2f.
exrepnd. rename ntcv into ct2.
assert (approx_star lib ct1 ct2) by eauto with slow. clear Has.
apply lsubst_alpha_congr2 with (sub:=(combine lvi lnt1)) in H1f0.
apply lsubst_alpha_congr2 with (sub:=(combine lvi lnt2)) in H2f0.
assert (approx_star lib (lsubst ct1 (combine lvi lnt1)) (lsubst ct2 (combine lvi lnt2)))
;[|eauto with slow; fail].
clear dependent t1. clear dependent t2.
change_to_lsubst_aux4; repeat(simpl_sub); disjoint_reasoningv.
apply lsubst_approx_star_congr_aux; spc;[].
spcls. rw flat_map_app. disjoint_reasoningv.
Qed.
(* begin hide *)
Lemma lsubst_approx_star_congr2 {p} : forall lib t1 t2 sub1 sub2,
sub_range_rel (@approx_star p lib) sub1 sub2
-> approx_star lib t1 t2
-> approx_star lib (lsubst t1 sub1) (lsubst t2 sub2).
Proof.
introv Hsr Has.
apply sub_range_rel_as_list in Hsr. exrepnd.
subst sub1. subst sub2.
apply lsubst_approx_star_congr; spc.
Qed.
(* weaker version than previous*)
Lemma lsubst_approx_star_congr3 {p} : forall lib t1 t2 sub,
@wf_sub p sub
-> approx_star lib t1 t2
-> approx_star lib (lsubst t1 sub) (lsubst t2 sub).
Proof.
introv Hw Has.
apply lsubst_approx_star_congr2; sp;[].
induction sub;allsimpl;spc.
- repnud Hw. repnud Hw. apply approx_star_refl. eapply Hw; left; eauto.
- apply IHsub. introv Hin. repnud Hw. repnud Hw. eapply Hw; right; eauto.
Qed.
Lemma approx_starbt_change {p} :
forall lib op bt1 bt2 (lvn : list NVar),
op <> NCan NFresh
-> approx_star_bterm lib op bt1 bt2
-> no_repeats lvn
-> length lvn = num_bvars bt1
-> disjoint lvn (free_vars_bterm bt1 ++ free_vars_bterm bt2)
-> {nt1',nt2' : @NTerm p
$ approx_star lib nt1' nt2'
# alpha_eq_bterm bt1 (bterm lvn nt1')
# alpha_eq_bterm bt2 (bterm lvn nt2')
(* # disjoint (lvn ++ (bound_vars nt1') ++ (bound_vars nt2')) lvn *)
}.
Proof.
introv d Hab Hnr Hlen Hdis.
invertsna Hab Hab.
exrepnd; repndors; exrepnd; tcsp; GC.
applydup @alphaeqbt_numbvars in Hab2.
allunfold @num_bvars. allsimpl.
dimp (alpha_bterm_pair_change3 _ _ _ _ _ lvn Hab2 Hab1); spcf;[].
exrepnd.
assert (approx_star lib nt1n nt2n) as XX by eauto with slow.
exists (lsubst nt1n (var_ren x lvn)).
exists (lsubst nt2n (var_ren x lvn)).
split; spc;[].
apply approx_star_lsubst_vars;spc.
Qed.
Lemma lsubst_aux_nest_same_str2 {p} :
forall t lvi lvio lnt lf,
length lvio=length lvi
-> length lvio=length lnt
-> no_repeats lvio
-> disjoint (lvio++(flat_map (@free_vars p) lnt)) (bound_vars t ++ lf)
-> disjoint lvio (remove_nvars lvi (free_vars t))
-> lsubst_aux (lsubst_aux t (filt_var_ren lvi lvio lf)) (filt_combine lvio lnt lf)
= lsubst_aux t (filt_combine lvi lnt lf).
Proof.
nterm_ind1s t as [v|f ind|o lbt Hind] Case;
introv Hl1 Hl2 Hnr Hdisb Hdisf; tcsp.
{ Case "vterm".
simpl. destructr (sub_find (@filt_var_ren p lvi lvio lf) v) as [s1st|n1n].
- apply symmetry in HeqHdeq. rename HeqHdeq into s1s.
apply sub_find_sub_filter_some in s1s. repnd.
apply sub_find_first in s1s0. exrepnd.
unfold var_ren in s1s1.
rewrite dom_sub_combine in s1s1;
[| rewrite map_length; congruence] .
unfold var_ren in s1s0.
rewrite length_combine_eq
in s1s0;[| rewrite map_length]; auto.
apply nth_var_ren_implies in s1s2;auto. exrepnd. rename vsr into vio.
simpl. rewrite s1s2. simpl.
destructr (sub_find (filt_combine lvio lnt lf) vio) as [s2st|n2n].
+ apply symmetry in HeqHdeq. rename HeqHdeq into s2s.
apply sub_find_sub_filter_some in s2s. repnd.
apply sub_find_first in s2s0. exrepnd.
unfold var_ren in s2s0. rewrite length_combine_eq
in s2s0;spc.
rw combine_nth in s2s2;spc. inverts s2s2 as s2s3 s2s4.
simpl. rewrite <- Hl1 in s1s0.
(** clear s2s1. it cannot rule out case when n>n0*)
pose proof (no_repeats_index_unique2
_ _ _ _ _ _ Hnr s1s0 s2s0 s1s4 s2s3) as X99.
destruct X99. GC. clear s1s2. clear s1st.
destructr (sub_find (filt_combine lvi lnt lf) v) as [s3st|n3n].
* apply symmetry in HeqHdeq. rename HeqHdeq into s3s.
apply sub_find_sub_filter_some in s3s. repnd.
apply sub_find_first in s3s0. exrepnd.
unfold var_ren in s3s0. rewrite length_combine_eq
in s3s0;spc.
rw combine_nth in s3s2;spc. inverts s3s2 as s3s3 s3s4.
simpl. rewrite Hl1 in s1s0.
allfold (@dom_sub p).
allunfold (@var_ren p). spcls.
assert (n0<n \/ n0=n \/ n<n0) as Htri by omega.
(dorn Htri);[|(dorn Htri)];
try (apply s1s1 in Htri); cpx;
try (apply s3s1 in Htri); cpx.
destruct Htri. GC. apply nth_select3 in s3s4;[| congruence].
apply nth_select3 in s2s4; congruence.
* rename HeqHdeq into n3n. symmetry in n3n.
apply sub_find_sub_filter_none in n3n. dorn n3n; [ |sp(**see s1s*)].
apply sub_find_none2 in n3n.
clear s1s1. apply nth_in2 in s1s3;[| congruence]. allunfold (@var_ren).
simpl. spcls. sp.
+ rename HeqHdeq into n2n. symmetry in n2n.
apply sub_find_sub_filter_none in n2n. dorn n2n.
* apply sub_find_none2 in n2n.
apply nth_in2 in s1s4;[| congruence]. allunfold (@var_ren).
simpl. spcls. sp.
* apply nth_in2 in s1s4;[| congruence].
assert (disjoint lvio lf) as X99 by disjoint_reasoningv.
apply X99 in s1s4; sp.
- allsimpl.
rw <- disjoint_remove_nvars_l in Hdisf.
apply disjoint_singleton_r in Hdisf.
allrw in_remove_nvars.
rw (not_over_and (LIn v lvio) (!LIn v lvi) (in_deq _ deq_nvar v lvio)) in Hdisf.
rw (not_over_not (LIn v lvi) (in_deq _ deq_nvar v lvi)) in Hdisf.
allfold @dom_sub.
assert ((dom_sub (combine lvi lnt)) = lvi) as Xrw by (spcls;sp).
rename HeqHdeq into n1n. symmetry in n1n.
unfold filt_var_ren in n1n.
unfold filt_combine.
allrw @sub_find_sub_filter_eq; boolvar; tcsp.
apply sub_find_none2 in n1n.
rw @dom_sub_var_ren in n1n; auto.
repndors; tcsp.
rw @sub_find_none_if;[|rw @dom_sub_combine; auto].
rw @sub_find_none_if;[|rw @dom_sub_combine; auto];tcsp.
}
{ Case "oterm". (**this part is easier!!*)
allsimpl. f_equal. rewrite map_map. eapply eq_maps; eauto.
intros bt Hinb. destruct bt as [lv nt].
unfold compose.
allsimpl. apply disjoint_app_r in Hdisb. repnd.
rename Hdisb into Hdisl.
rename Hdisb0 into Hdisb.
eapply disjoint_lbt_bt2 in Hdisb; eauto. repnd.
apply disjoint_app_l in Hdisb0. repnd.
simpl. f_equal.
unfold filt_var_ren. unfold filt_combine.
repeat(rewrite <- sub_filter_app_r).
eapply Hind; eauto 3 with slow;[disjoint_reasoningv|].
allrw <- disjoint_remove_nvars_l.
rw disjoint_flat_map_r in Hdisf. apply Hdisf in Hinb.
simpl in Hinb. rw <- disjoint_remove_nvars_l in Hinb.
apply remove_nvars_unchanged in Hdisb1.
rw remove_nvars_comm in Hinb.
rewrite Hdisb1 in Hinb. trivial.
}
Qed.
Lemma lsubst_nest_same_str2 {p} :
forall t lvi lvio lnt lf,
length lvio=length lvi
-> length lvio=length lnt
-> no_repeats lvio
-> disjoint (lvio++(flat_map (@free_vars p) lnt)) (bound_vars t ++ lf)
-> disjoint lvio (remove_nvars lvi (free_vars t))
-> lsubst (lsubst t (filt_var_ren lvi lvio lf)) (filt_combine lvio lnt lf)
= lsubst t (filt_combine lvi lnt lf).
Proof.
intros.
change_to_lsubst_aux4;
try(apply lsubst_aux_nest_same_str2;try(sp;fail));
apply disjoint_sym;
rw <- @disjoint_sub_as_flat_map;
try(apply sub_filter_sat).
- rw @disjoint_sub_as_flat_map; spcls; disjoint_reasoningv.
- rw @disjoint_sub_as_flat_map; spcls; disjoint_reasoningv.
- rw <- @lsubst_lsubst_aux; disjoint_reasoningv.
rw @boundvars_lsubst_vars2; spcls; disjoint_reasoningv.
+ rw @disjoint_sub_as_flat_map. spcls. sp.
+ apply allvars_sub_filter.
+ apply sub_filter_sat. rw @disjoint_sub_as_flat_map.
spcls. disjoint_reasoningv.
- rw @disjoint_sub_as_flat_map; spcls; disjoint_reasoningv.
Qed.
Lemma lsubst_nest_same2 {p} :
forall t lvi lvio lnt,
length lvio=length lvi
-> length lvio=length lnt
-> no_repeats lvio
-> disjoint (lvio++(flat_map (@free_vars p) lnt)) (bound_vars t)
-> disjoint lvio (remove_nvars lvi (free_vars t))
-> lsubst (lsubst t (var_ren lvi lvio)) (combine lvio lnt)
= lsubst t (combine lvi lnt).
Proof.
intros.
pose proof (sub_filter_nil_r (@var_ren p lvi lvio)) as K.
rewrite <- K. clear K.
pose proof (sub_filter_nil_r (combine lvio lnt)) as K.
rewrite <- K. clear K.
pose proof (sub_filter_nil_r (combine lvi lnt)) as K.
rewrite <- K. clear K.
apply lsubst_nest_same_str2; simpl; auto.
rewrite app_nil_r. auto.
Qed.
Lemma lsubst_nest_same_alpha2 {p} :
forall t lvi lvio lnt,
length lvio=length lvi
-> length lvio=length lnt
-> no_repeats lvio
-> disjoint lvio (remove_nvars lvi (free_vars t))
-> alpha_eq (lsubst (lsubst t (@var_ren p lvi lvio)) (combine lvio lnt))
(lsubst t (combine lvi lnt)).
Proof.
intros.
pose proof (change_bvars_alpha_wspec (lvio++(flat_map free_vars lnt)) t) as Hf.
exrepnd.
alpharws Hf0.
rw @lsubst_nest_same2;spc.
alpharws (alpha_eq_sym _ _ Hf0). sp.
Qed.
Lemma approx_starbt_change_fr {p} :
forall lib op bt1 bt2 (lvn : list NVar),
op = NCan NFresh
-> approx_star_bterm lib op bt1 bt2
-> no_repeats lvn
-> length lvn = num_bvars bt1
-> disjoint lvn (free_vars_bterm bt1 ++ free_vars_bterm bt2)
-> {sub : Sub
$ {nt1',nt2' : @NTerm p
$ approx_star lib (lsubst nt1' sub) (lsubst nt2' sub)
# nrut_sub (get_utokens nt1' ++ get_utokens nt2') sub
# lvn = dom_sub sub
# alpha_eq_bterm bt1 (bterm lvn nt1')
# alpha_eq_bterm bt2 (bterm lvn nt2')
(* # disjoint (lvn ++ (bound_vars nt1') ++ (bound_vars nt2')) lvn *)
}}.
Proof.
introv d Hab Hnr Hlen Hdis.
invertsna Hab Hab.
exrepnd; repndors; exrepnd; tcsp; GC.
applydup @alphaeqbt_numbvars in Hab2.
allunfold @num_bvars; allsimpl.
assert (length x = length sub) as len.
{ subst; allrw @length_dom; auto. }
dimp (alpha_bterm_pair_change3 _ _ _ _ _ lvn Hab2 Hab1); spcf;[].
exrepnd.
assert (approx_star lib (lsubst nt1n sub) (lsubst nt2n sub)) as XX by eauto with slow.
exists (combine lvn (range sub)).
exists (lsubst nt1n (var_ren x lvn)).
exists (lsubst nt2n (var_ren x lvn)).
rw @dom_sub_combine; allrw @length_range; auto; try omega.
subst; dands; tcsp.
- pose proof (lsubst_nest_same_alpha2 nt1n (dom_sub sub) lvn (range sub)) as nest1.
allrw @length_dom; allrw @length_range.
repeat (autodimp nest1 hyp); try omega.
{ apply alpha_eq_bterm_preserves_free_vars in Hab2; allsimpl.
rw disjoint_app_r in Hdis; repnd.
rw Hab2 in Hdis0.
apply alphaeq_preserves_free_vars in hyp0; rw <- hyp0; auto. }
rw <- @sub_eta in nest1.
pose proof (lsubst_nest_same_alpha2 nt2n (dom_sub sub) lvn (range sub)) as nest2.
allrw @length_dom; allrw @length_range.
repeat (autodimp nest2 hyp); try omega.
{ apply alpha_eq_bterm_preserves_free_vars in Hab1; allsimpl.
rw disjoint_app_r in Hdis; repnd.
rw Hab1 in Hdis.
apply alphaeq_preserves_free_vars in hyp2; rw <- hyp2; auto. }
rw <- @sub_eta in nest2.
pose proof (lsubst_alpha_congr2 nt1 nt1n sub hyp0) as as1.
pose proof (lsubst_alpha_congr2 nt2 nt2n sub hyp2) as as2.
eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact nest1].
eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact nest2].
eauto 3 with slow.
- apply alphaeq_preserves_utokens in hyp0.
apply alphaeq_preserves_utokens in hyp2.
repeat (rw @get_utokens_lsubst_allvars; eauto with slow).
rw <- hyp0; rw <- hyp2.
eapply nrut_sub_change_sub_same_range;[|exact Hab5].
rw @range_combine; auto; allrw @length_range; allrw @length_dom; auto; try omega.
Qed.
Lemma approx_star_open_bt_trans {pp} :
forall lib op (a b c : @BTerm pp),
approx_star_bterm lib op a b
-> approx_open_bterm lib b c
-> approx_star_bterm lib op a c.
Proof.
introv Has Hao.
applydup @blift_sub_numbvars in Has.
pose proof (fresh_vars
(num_bvars a)
(free_vars_bterm a ++ free_vars_bterm b ++ free_vars_bterm c))
as Hfr.
exrepnd.
destruct (dec_op_eq_fresh op) as [d|d].
- apply @approx_starbt_change_fr with (lvn:=lvn) in Has;exrepnd; spc;[| disjoint_reasoningv].
apply @approxbtd_change with (lvn:=lvn) in Hao;spc;[| disjoint_reasoningv].
assert (alpha_eq_bterm (bterm lvn nt1'0) (bterm lvn nt2')) as XX by eauto with slow.
apply alpha_eq_bterm_triv in XX.
unfold approx_open in p0.
rwhg XX p0.
fold (approx_open lib nt2' nt2'0) in p0.
dup p0 as ao.
pose proof (exists_nrut_sub
lvn
(get_utokens nt1'
++ get_utokens nt2'
++ get_utokens nt1'0
++ get_utokens nt2'0))
as exnrut; exrepnd.
pose proof (approx_star_change_nrut_sub
lib nt1' nt2' sub (get_utokens nt1' ++ get_utokens nt2')
sub0
(get_utokens nt1'
++ get_utokens nt2'
++ get_utokens nt1'0
++ get_utokens nt2'0))
as ch.
repeat (autodimp ch hh); tcsp; eauto 3 with slow.
apply (approx_open_lsubst_congr _ _ _ sub0) in p0; eauto 2 with slow.
eapply approx_star_open_trans in ch; eauto.
exists lvn nt1' nt2'0.
dands; tcsp.
right.
exists sub0; dands; tcsp.
eapply nrut_sub_subset;[|exact exnrut1]; eauto with slow.
- apply @approx_starbt_change with (lvn:=lvn) in Has;exrepnd; spc;[| disjoint_reasoningv].
apply @approxbtd_change with (lvn:=lvn) in Hao;spc;[| disjoint_reasoningv].
assert (alpha_eq_bterm (bterm lvn nt1'0) (bterm lvn nt2')) as XX by eauto with slow.
apply alpha_eq_bterm_triv in XX.
unfold approx_open in p0.
rwhg XX p0.
eapply approx_star_open_trans in Has1; eauto.
exists lvn nt1' nt2'0.
dands; tcsp.
Qed.
(* unlike lforall, this unfolds immediately to conjunctions
if the list is concrete. But, it might confuse tactics like eauto *)
Fixpoint lforall2 {T} (P : T -> [univ]) (l: list T) : [univ] :=
match l with
[] => True
| h::t => ((P h) # (lforall2 P t))
end.
Notation programs := (lforall2 isprogram).
(* end hide *)
(** %\noindent \\*% Howe implicitly uses the following lemma at least twice
in his proofs. It is essentially a more useful way
to eliminate (use/destruct) a hypothesis of the form
[approx_star (oterm o lbt) b].
The advantage here is that we additionally obtain the hypothesis
[isprogram (oterm o lbt')]. The [lbt'] that we obtain
by naive inductive destruction of [approx_star (oterm o lbt) b]
need not satisify this property. This additional property
simplifies many proofs. For example, in his proof of
Lemma 2 (shown below), when Howe says "by Lemma 1
and the definition of $\le$ on open terms, we may assume that
$\theta(\overline{t''})$ is closed", he is essentially using this lemma.
The proof of this lemma involves reasoning like that
used in the the proof
of [approx_open_trans].
Essentially, we substitute arbitrary closed terms for
free variables in [lbt'] obtained
by the inductive destruction so that it becomes closed and show that
this substitution has no effect when it gets applied to other terms
in the proof. %\\*%
*)
Lemma approx_star_otd {p} : forall lib o lbt b,
approx_star lib (oterm o lbt) b
-> isprogram b
-> isprogram (oterm o lbt) (* required near the end *)
-> {lbt' : (list (@BTerm p)) $ isprogram (oterm o lbt')
# approx_open lib (oterm o lbt') b
# length lbt = length lbt'
# approx_starbts lib o lbt lbt'}.
Proof.
introv Has Hisp Hispo.
invertsna Has Hapb.
rename lbt1' into lbt''. (* t'' in paper *)
unfold approx_open in Hapb1.
repnud Hapb1.
remember (oterm o lbt'') as tb.
pose proof (close_with_axiom tb Hapb2) as Hpr.
allsimpl. exrepnd.
dimp (Hapb1 (subst_axiom (free_vars tb))); spc;
eauto 2 with slow;[ |rw @lsubst_trivial2; auto].
remember (subst_axiom (free_vars tb)) as subc.
remember (lsubst tb subc) as tbc.
rw @lsubst_trivial2 in hyp; sp.
remember((fun t : BTerm =>
lsubst_bterm_aux t subc)) as fc.
exists (map fc lbt'').
lsubst_lsubst_aux_eq_hyp Heq Heqtbc.
rw Heqtbc in Hpr. subst tb.
simpl in Hpr.
rw <- Heqfc in Hpr.
dands; try( simpl_list); spc.
- apply approx_implies_approx_open. subst; spc.
- unfold approx_starbts; allunfold @lblift_sub; simpl_list; exrepnd.
dands; spcf. introv Hlt.
applydup Hapb0 in Hlt.
rw @selectbt_map; [| omega].
subst fc.
apply approx_star_bterm_lsubst_congr with (sub:=subc) in Hlt0; auto;[].
apply isprogram_ot_iff in Hispo. repnd.
apply selectbt_in in Hlt.
rw @lsubst_bterm_trivial in Hlt0; eauto with slow.
Qed.
Ltac prove_isprogram :=
match goal with
| [ |- isprogram _ ] =>
complete (repeat decomp_progh; show_hyps; eauto with extens;
repeat decomp_progc; eauto with extens)
| _ => idtac
end.
Lemma reduces_to_implies_approx_eauto {p} :
forall lib (t x : @NTerm p),
isprogram t -> reduces_to lib t x -> approx lib x t.
Proof.
introv Hp Hr.
apply reduces_to_implies_approx in Hr; sp.
Qed.
(** %\noindent \\* % We now prove Howe's lemma 2 %\cite{Howe:1989}%. Using the lemma
[approx_star_otd] above, this proof goes
pretty much exactly like Howe describes.
*)
Lemma howe_lemma2 {p} :
forall lib (c : CanonicalOp) (lbt : list BTerm) (b : @NTerm p),
let t:= oterm (Can c) lbt in
isprogram t
-> isprogram b
-> approx_star lib t b
-> {lbt' : (list BTerm)
& approx_starbts lib (Can c) lbt lbt'
# computes_to_value lib b (oterm (Can c) lbt')}.
Proof.
introv Hprt Hprb Hap.
apply approx_star_otd in Hap;spcf;[]. exrepnd.
rename lbt' into lbt''. (* t'' in paper *)
apply approx_open_approx in Hap2; spc.
invertsna Hap2 Hclose. repnud Hclose.
dimp (Hclose2 c lbt'');
eauto;[apply computes_to_value_isvalue_refl; constructor; eauto; fail|].
exrepnd.
apply clearbot_relbt in hyp0.
rename tr_subterms into lbt'. (*( t' in the paper proof *)
exists lbt'.
GC. (*clear Hclose*)
split; auto;[].
allunfold @lblift.
repeat (simpl_list). repnd. split; spcf;[].
introv Hlt.
applydup_clear Hap0 in Hlt.
dimp (hyp0 n); try omega;[].
clear hyp0.
eapply approx_star_open_bt_trans; eauto.
Qed.
Lemma howe_lemma2_seq {o} :
forall lib (f : @ntseq o) (b : @NTerm o),
isprogram (sterm f)
-> isprogram b
-> approx_star lib (sterm f) b
-> {f' : ntseq
& (forall n, alpha_eq (f n) (f' n))
# computes_to_seq lib b f'}.
Proof.
introv Hprt Hprb Hap.
inversion Hap as [|? ? ? ? imp aop|]; clear Hap; subst.
apply approx_open_approx in aop; eauto 3 with slow.
invertsna aop Hclose.
repnud Hclose.
dimp (Hclose4 f2); [apply reduces_to_symm|].
exrepnd.
eexists; dands;[|eauto].
introv; eauto 3 with slow.
Qed.
Lemma howe_lemma2_implies_iscan {p} :
forall lib (t b : @NTerm p),
isprogram t
-> iscan t
-> isprogram b
-> approx_star lib t b
-> {v : NTerm & iscan v # (b =v>(lib) v) # approx_star lib t v}.
Proof.
introv ispt isct ispb apr.
apply iscan_implies in isct; repndors; exrepnd; subst.
- apply howe_lemma2 in apr; auto.
exrepnd.
eexists; dands; eauto.
allunfold @approx_starbts.
apply (apso _ _ _ _ lbt'); auto.
{ allunfold @lblift_sub; repnd; auto. }
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram; eauto 3 with slow.
- apply howe_lemma2_seq in apr; auto.
exrepnd.
unfold computes_to_value.
unfold computes_to_seq in apr0.
eexists;dands;[|eauto| |]; simpl; eauto 3 with slow.
apply alpha_implies_approx_star; eauto 3 with slow.
Qed.
Lemma howe_lemma2_exc {p} :
forall lib a (e b : @NTerm p),
isprogram (mk_exception a e)
-> isprogram b
-> approx_star lib (mk_exception a e) b
-> { a' , e' : NTerm
$ approx_star lib a a'
# approx_star lib e e'
# computes_to_exception lib a' b e'}.
Proof.
introv Hprt Hprb Hap.
apply approx_star_otd in Hap;spcf;[]. exrepnd.
rename lbt' into lbt''. (* t'' in paper *)
apply approx_open_approx in Hap2; spc.
invertsna Hap2 Hclose. repnud Hclose.
allsimpl; cpx.
applydup @isprogram_exception_implies in Hap1; exrepnd; cpx.
dimp (Hclose3 a0 t); try (complete (apply computes_to_exception_refl; sp)); exrepnd.
apply remove_bot_approx in hyp2.
apply remove_bot_approx in hyp1.
exists a' e'; sp.
- inversion Hap0 as [? f]; allsimpl; GC.
generalize (f 0); clear f; intro k; autodimp k hyp.
unfold selectbt in k; simpl in k.
destruct k as [vs k]; exrepnd; repndors; exrepnd; ginv.
inversion k1; subst; allsimpl; cpx.
inversion k2; subst; allsimpl; cpx.
allunfold @var_ren; allsimpl.
allrw @lsubst_nil; GC.
apply @approx_star_alpha_fun_l with (nt1 := nt1); auto;
try (complete (apply alpha_eq_sym; auto)).
apply @approx_star_open_trans with (b := nt2); auto.
eapply approx_open_alpha_rw_l_aux; eauto.
apply approx_implies_approx_open; auto.
- inversion Hap0 as [? f]; allsimpl; GC.
generalize (f 1); clear f; intro k; autodimp k hyp.
unfold selectbt in k; simpl in k.
destruct k as [vs k]; exrepnd; repndors; exrepnd; ginv.
inversion k1; subst; allsimpl; cpx.
inversion k2; subst; allsimpl; cpx.
allunfold @var_ren; allsimpl.
allrw @lsubst_nil; GC.
apply @approx_star_alpha_fun_l with (nt1 := nt1); auto;
try (complete (apply alpha_eq_sym; auto)).
apply @approx_star_open_trans with (b := nt2); auto.
eapply approx_open_alpha_rw_l_aux; eauto.
apply approx_implies_approx_open; auto.
Qed.
(*
Lemma howe_lemma2_mrk {p} :
forall lib m (b : @NTerm p),
isprogram b
-> approx_star lib (mk_marker m) b
-> computes_to_marker lib b m.
Proof.
introv Hprb Hap.
apply approx_star_otd in Hap;spcf;[|repeat constructor; simpl; complete sp]; exrepnd.
allsimpl; cpx; fold_terms.
apply approx_open_approx in Hap2; spc.
invertsna Hap2 Hclose.
repnud Hclose.
dimp (Hclose m).
apply compute_to_marker_mrk.
Qed.
*)
(** Informally, [howe_lemma2] looks a lot like the definition of [close_comput].
The only difference is that [close_comput] was
preserved when computation happens on the LHS argument.
Recall the [approx] can be considered as a greatest fixed point
of [close_comput]. If we could prove that [approx_star] is preserved
when computation happens on the LHS argument, a simple coinductive
argument will prove that [approx_star] implies
[approx] on closed terms.
Formally, we only need to prove the following lemma
%\footnote{Howe did not explicitly call it Lemma 3. But he proves it
while proving his theorem 1}% :
[[
Lemma howe_lemma3 : forall (a a' b : NTerm),
isprogram a
-> isprogram a'
-> isprogram b
-> computes_to_value a a'
-> approx_star a b
-> approx_star a' b.
]]
This proof will proceed by the induction on the number of steps that
[a] took to compute to the value [a']. Since variables don't compute to
anything, [a] must be of the form [oterm o lbt]. The proof then proceeds
by case analysis on [o]. Unlike the previous proofs about [approx],
which were uniform w.r.t the [Opid]s in the language and
only assumed that the computation system was lazy, this proof
requires reasoning about each [Opid] in the language.
Howe abstracts the remainder of the proof of this lemma into the
following condition (called extensionality) that has to be proved
for each [Opid] in the language. The last hypothesis ([Hind], the big one)
in this definition is essentially the induction hypothesis
in the proof of [howe_lemma3].
*)
Definition extensional_op_ind {p} lib k :=
forall (u u' v : @NTerm p),
isprogram u
-> isprogram u'
-> isprogram v
-> computes_to_val_like_in_max_k_steps lib u u' k
-> approx_star lib u v
-> approx_star lib u' v.
Definition extensional_op {p} (o : @Opid p) :=
forall
(lib : library)
(lbt lbt' : list BTerm)
(a : NTerm)
(k : nat)
(Hpa : isprogram a)
(Hpt : isprogram (oterm o lbt))
(Hpt' : isprogram (oterm o lbt'))
(Hcv : computes_to_val_like_in_max_k_steps lib (oterm o lbt) a (S k))
(Has : lblift_sub o (approx_star lib) lbt lbt')
(Hind : @extensional_op_ind p lib k),
approx_star lib a (oterm o lbt').
(** %\noindent \\*% It is immediately clear that all the canonical [Opid]s of
a lazy computation
system are extensional. In this case, we have [(oterm o lbt)= a] and
the conclusion is an immediate consequence of congruence of [approx_star].
*)
Lemma nuprl_extensional_can {p} :
forall cop, extensional_op (@Can p cop).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
apply computes_to_val_like_in_max_k_steps_can in Hcv; subst.
apply approx_star_congruence2;sp; eauto with slow.
Qed.
Lemma nuprl_extensional_exc {p} :
extensional_op (@Exc p).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
apply computes_to_val_like_in_max_k_steps_exc in Hcv; subst.
apply approx_star_congruence2;sp; eauto with slow.
Qed.
(** %\noindent% The next definition
is just compact and equivalent
restatement of [extensional_op_val] for
the paper.
Please ignore if you are reading
the technical report. Sorry! *)
Definition extensional_opc {p} (o : @Opid p) :=
forall lib
(lbt lbt' : list BTerm)
(a : NTerm)
(k:nat),
programs [a,(oterm o lbt),(oterm o lbt')]
-> computes_to_value_in_max_k_steps lib (S k) (oterm o lbt) a
-> lblift_sub o (approx_star lib) lbt lbt'
-> (forall (u u' v : @NTerm p),
programs [u,u',v]
-> computes_to_value_in_max_k_steps lib k u u'
-> approx_star lib u v
-> approx_star lib u' v)
-> approx_star lib a (oterm o lbt').
(* begin hide *)
Lemma approx_star_bterm_nobnd2 {p} :
forall lib op a b,
approx_star_bterm lib op (bterm [] a) (@bterm p [] b)
-> approx_star lib a b.
Proof.
introv Has.
apply approx_star_bterm_nobnd in Has; exrepnd; subst; cpx.
inversion Has1; subst; sp.
Qed.
Lemma notTrue_btchange {p} : (forall lv nt lvn,
length lv = length lvn ->
alpha_eq_bterm (bterm lv nt) (bterm lvn (lsubst nt (@var_ren p lv lvn))))
-> False.
Proof.
introv Hc.
pose proof (Hc [nvarx,nvary] (oterm (NCan (NArithOp ArithOpAdd)) [(bterm [] (vterm nvarx)),(bterm [] (vterm nvary))])
[nvarz,nvarz] eq_refl) as XX.
clear Hc.
unfold mk_apply,lsubst, nobnd in XX.
simpl in XX.
Abort. (* apply both sides to [1,2] and compute 1 step to get sth which is not alpha equal*)
(* see btchange_alpha for the correct version*)
(*
Lemma approx_star_btermd_samevar {p} :
forall lib op a lv bt,
approx_star_bterm lib op (bterm lv a) bt
-> {b : @NTerm p
$ alpha_eq_bterm bt (bterm lv b)
# approx_star lib a b }.
Proof.
introv Has.
destruct bt as [lvb b']; allsimpl.
apply (approx_star_btermd _ _ _ (lv++lvb)) in Has.
exrepnd.
pose proof (change_bvars_alpha_wspec (lv++lvb) a) as Hfa.
exrepnd. rename ntcv into a'. duplicate Hfa0.
apply @alpha_eq_bterm_congr with (lv:=lv) in Hfa0.
assert (alpha_eq_bterm (bterm lv a') (bterm lvn nt1'))
as Xa by eauto with slow.
pose proof (change_bvars_alpha_wspec (lvb++lv) b') as Hfb.
exrepnd. rename ntcv into b.
apply @alpha_eq_bterm_congr with (lv:=lvb) in Hfb0.
assert (alpha_eq_bterm (bterm lvb b) (bterm lvn nt2'))
as Xb by eauto with slow.
invertsna Xa Hb.
invertsna Xb Ha.
apply lsubst_alpha_congr2 with (sub:=var_ren lv3 lv) in Ha3.
rw @lsubst_nest_vars_same in Ha3;spc; disjoint_reasoningv;[].
rw @lsubst_nest_vars_same in Ha3;spc; disjoint_reasoningv;[].
apply lsubst_alpha_congr2 with (sub:=var_ren lv0 lv) in Hb3.
rw @lsubst_nest_vars_same in Hb3;spc; disjoint_reasoningv;[].
rw @lsubst_nest_vars_same in Hb3;spc; disjoint_reasoningv;[].
assert (alpha_eq a' (lsubst nt1' (var_ren lvn lv))) as Xa by eauto with slow.
clear Hb3.
apply approx_star_lsubst_vars with (lvi:=lvn) (lvo:=lv) in Has1;spc;[].
exists (lsubst nt2' (var_ren lvn lv)).
dands.
Focus 2. eauto with slow; fail.
Abort. (* probably not true ... see above*)
*)
Lemma approx_star_btermd_1var {p} :
forall lib op v a bt,
approx_star_bterm lib op (bterm [v] a) bt
-> {vr : NVar
$ {b : @NTerm p
$ bt = bterm [vr] b
# approx_star_bterm lib op (bterm [v] a) (bterm [vr] b) }}.
Proof.
introv Hab.
destruct bt as [lvb b].
applydup @blift_sub_numbvars in Hab.
allunfold @num_bvars; allsimpl.
alphahypsd.
exrepnd.
eexists; eexists; dands; eauto.
Qed.
Lemma approx_star_btermd_2var {p} :
forall lib op v1 v2 a bt,
approx_star_bterm lib op (bterm [v1, v2] a) bt
-> {v1r,v2r : NVar
$ {b : @NTerm p $ bt=(bterm [v1r,v2r] b)
# approx_star_bterm lib op (bterm [v1,v2] a) (bterm [v1r,v2r] b)}}.
Proof.
introv Hab.
destruct bt as [lvb b].
applydup @blift_sub_numbvars in Hab.
allunfold @num_bvars.
allsimpl.
alphahypsd.
exrepnd.
eexists; eexists; dands; eauto.
Qed.
(*
Lemma compute_apply_decompose : forall k lbt a,
computes_to_value_in_max_k_steps (S k) (oterm (NCan NApply) lbt) a
-> {v : NVar $ {la b arg : NTerm $ lbt = [(bterm [] la), (bterm [] arg)
# computes_to_value_in_max_k_steps k la (mk_lambda v b)
# computes_to_value_in_max_k_steps k la (mk_lambda v b)
] }} *)
Hint Resolve computek_preserves_program : slow.
Ltac lsubst_nest_tac :=
let X99 := fresh "X438590348" in
repeat match goal with
| [ H : (approx_star ?lib (lsubst (lsubst ?t1 (var_ren ?lv1 ?lvn)) (combine ?lvn ?lnt1)) ?rhs) |- _ ]
=> dimp (lsubst_nest_same_alpha t1 lv1 lvn lnt1);
spc;
disjoint_reasoningv;
rename H into X99;
assert (approx_star lib (lsubst t1 (combine lv1 lnt1)) rhs)
as H by eauto with slow; clear X99
| [ H : (approx_star ?lib ?lhs (lsubst (lsubst ?t1 (var_ren ?lv1 ?lvn)) (combine ?lvn ?lnt1))) |- _ ]
=> dimp (lsubst_nest_same_alpha t1 lv1 lvn lnt1);
spc;
disjoint_reasoningv;
rename H into X99;
assert (approx_star lib lhs (lsubst t1 (combine lv1 lnt1)))
as H by eauto with slow; clear X99
end.
(* end hide *)
(** We now begin to prove that the non-canonical [Opid]s of Nuprl are extensional.
The following corollary of Howe's lemma 1 ([lsubst_approx_star_congr]) will
be very useful in of the proofs for the
[Opid]s [NApply, NCbv, NDecide, NSpread].
*)
Lemma apply_bterm_approx_star_congr {p} :
forall lib op bt1 bt2 lnt1 lnt2,
op <> NCan NFresh
-> approx_star_bterm lib op bt1 bt2
-> bin_rel_nterm (@approx_star p lib) lnt1 lnt2 (*enforces that the lengths are equal*)
-> length lnt1 = num_bvars bt1 (*only required for simplicity*)
-> length lnt1 = length lnt2 (*only required for simplicity*)
-> approx_star lib (apply_bterm bt1 lnt1) (apply_bterm bt2 lnt2).
Proof.
introv d Ha0 Hbr H1len H2len.
applydup @blift_sub_numbvars in Ha0. allunfold @num_bvars.
apply (approx_star_btermd _ _ _ _ ((flat_map free_vars lnt1) ++ (flat_map free_vars lnt2))) in Ha0; auto.
allunfold @apply_bterm. allsimpl. exrepnd.
destruct bt1 as [lv1 t1].
destruct bt2 as [lv2 t2]. rename nt1' into nt1. rename nt2' into nt2.
rename lvn into lv.
pose proof (fresh_vars (length lv1) (all_vars nt1 ++ all_vars nt2
++ all_vars t1 ++ all_vars t2)).
exrepnd. simpl in Ha1.
apply @alphabt_change_var with (lv:=lvn) in Ha4; spc; [| disjoint_reasoningv; fail].
apply @alphabt_change_var with (lv:=lvn) in Ha3; spc;[| disjoint_reasoningv];[].
apply approx_star_lsubst_vars with (lvi:=lv) (lvo:=lvn) in Ha0;spc;[].
apply alpha_eq_sym in Ha6.
apply alpha_eq_sym in Ha7.
assert (approx_star lib
(lsubst t1 (var_ren lv1 lvn)) (lsubst t2 (var_ren lv2 lvn)))
as XX by eauto with slow. (* alpha replacement *)
allsimpl. clear Ha0.
apply @lsubst_approx_star_congr with
(lvi:=lvn) (lnt1:=lnt1) (lnt2:=lnt2) in XX;spc;[].
lsubst_nest_tac.
sp.
Qed.
(* Howe proved the extensionality of the [NApply] [Opid].
Crary%\cite{Crary98}% proved it for many others. Our [NDecide] and
[NCbv] are exactly same as his case and let-binding constructs.
Our proofs of extensionality of these [Opid]s are quite close to
their descriptions. We will only describe the proofs for
We will now describe the proof for [NSpread]
%\footnote{Crary's language has $\pi _1$ and $\pi _2$ constructs}%.
*)
(* begin hide *)
Lemma blift_nobnd_congr {p} : forall R t1 t2,
R t1 t2
-> @blift p R (bterm [] t1) (bterm [] t2).
Proof.
introv Ht.
exists (@nil NVar) t1 t2.
dands; eauto with slow.
Qed.
Lemma blift_sub_nobnd_congr {p} :
forall R op t1 t2,
R t1 t2
-> @blift_sub p op R (bterm [] t1) (bterm [] t2).
Proof.
introv Ht.
exists (@nil NVar) t1 t2; dands; eauto with slow.
destruct (dec_op_eq_fresh op) as [d|d]; tcsp.
right; exists ([] : @Sub p); simpl; allrw @lsubst_nil; dands; eauto with slow.
Qed.
Hint Unfold lblift lblift_sub : slow.
Hint Resolve approx_star_congruence2 blift_nobnd_congr blift_sub_nobnd_congr : slow.
Theorem approx_star_congruence3 {p} : forall lib o lbt1 lbt2,
approx_starbts lib o lbt1 lbt2
-> @isprogram p (oterm o lbt2)
-> approx_star lib (oterm o lbt1) (oterm o lbt2).
Proof.
introv Haps Hnt.
apply approx_star_congruence2; sp.
eauto with slow.
Qed.
Ltac prove_approx_star := unfold mk_apply;
match goal with
| [ |- approx_star _ ?t ?t] => apply approx_star_refl
| [ |- approx_star _ (oterm ?o _) (oterm ?o _)] =>
apply approx_star_congruence3
| [ |- isprogram _] => repeat(decomp_progc); eauto with slow
| [ |- approx_starbts _ _ _ _ ] =>
(unfold approx_starbts, lblift_sub; simpl; dands;[spc|];
let Hlt := fresh "XXHlt" in
let n := fresh "XXn" in
intros n Hlt;
( let rnum := (get_lt_rhs Hlt) in
fail_if_not_number rnum; (*fail if not a normal form*)
repeat (destruct n; try omega); unfold selectbt; simpl; unfold nobnd
))
| [ |- approx_star_bterm _ _ (bterm [] ?t1) (bterm [] ?t2)] =>
apply blift_sub_nobnd_congr
| [ |- blift_sub _ (approx_star _) (bterm [] ?t1) (bterm [] ?t2)] =>
apply blift_sub_nobnd_congr
end.
Ltac duplicateas H newname :=
let name := fresh newname
in remember H as name;
clears_last.
Ltac approxrelbtd :=
match goal with
| [H: 0 = length _ |- _ ] => symmetry in H; apply length0 in H; subst
| [H: 1 = length _ |- _ ] => symmetry in H; apply length1 in H; exrepnd; subst
| [H: 2 = length _ |- _ ] => symmetry in H; apply length2 in H; exrepnd; subst
| [H: 3 = length _ |- _ ] => symmetry in H; apply length3 in H; exrepnd; subst
| [H: 4 = length _ |- _ ] => symmetry in H; apply length4 in H; exrepnd; subst
| [H: _ = S (length _) |- _ ] => inverts H as H
| [H: (forall _:nat, (_< ?m) -> blift_sub _ _ _ _) |- _ ] =>
fail_if_not_number m;
(let XXX:= fresh H "0bt" in
assert (0<m) as XXX by omega; apply H in XXX;
unfold selectbt in XXX; simpl in XXX);
try (let XXX:= fresh H "1bt" in
assert (1<m) as XXX by omega; apply H in XXX;
unfold selectbt in XXX; simpl in XXX);
try (let XXX:= fresh H "2bt" in
assert (2<m) as XXX by omega; apply H in XXX;
unfold selectbt in XXX; simpl in XXX);
try (let XXX:= fresh H "3bt" in
assert (3<m) as XXX by omega; apply H in XXX;
unfold selectbt in XXX; simpl in XXX); clear H
| [H: approx_star_bterm _ _ (bterm [] _) (bterm [] _) |- _] => hide_hyp H
| [H: blift_sub _ (approx_star _) (bterm [] _) (bterm [] _) |- _] => hide_hyp H
| [H: approx_star_bterm _ _ (bterm [_] _) (bterm [_] _) |- _] => hide_hyp H
| [H: blift_sub _ (approx_star _) (bterm [_] _) (bterm [_] _) |- _] => hide_hyp H
| [H: approx_star_bterm _ _ (bterm [_,_] _) (bterm [_,_] _) |- _] => hide_hyp H
| [H: blift_sub _ (approx_star _) (bterm [_,_] _) (bterm [_,_] _) |- _] => hide_hyp H
| [H: approx_star_bterm _ _ (bterm [] ?nt) _ |- _] =>
apply approx_star_bterm_nobnd in H;
let ntr := fresh nt "r" in
(destruct H as [ntr H]);
repnd; subst
| [H: blift_sub _ (approx_star _) (bterm [] ?nt) _ |- _] =>
apply approx_star_bterm_nobnd in H;
let ntr := fresh nt "r" in
(destruct H as [ntr H]);
repnd; subst
| [H: approx_star_bterm _ _ (bterm [?v] ?nt) _ |- _] =>
apply approx_star_btermd_1var in H;
let vr := fresh v "r" in
let ntr := fresh nt "r" in
(destruct H as [vr H]; destruct H as [ntr H]);
repnd; subst
| [H: blift_sub _ (approx_star _) (bterm [?v] ?nt) _ |- _] =>
apply approx_star_btermd_1var in H;
let vr := fresh v "r" in
let ntr := fresh nt "r" in
(destruct H as [vr H]; destruct H as [ntr H]);
repnd; subst
| [H: approx_star_bterm _ _ (bterm [?v1, ?v2] ?nt) _ |- _] =>
apply approx_star_btermd_2var in H;
let v1r := fresh v1 "r" in
let v2r := fresh v2 "r" in
let ntr := fresh nt "r" in
(destruct H as [v1r H]; destruct H as [v2r H]; destruct H as [ntr H]);
repnd; subst
| [H: blift_sub _ (approx_star _) (bterm [?v1, ?v2] ?nt) _ |- _] =>
apply approx_star_btermd_2var in H;
let v1r := fresh v1 "r" in
let v2r := fresh v2 "r" in
let ntr := fresh nt "r" in
(destruct H as [v1r H]; destruct H as [v2r H]; destruct H as [ntr H]);
repnd; subst
| [H : approx_star_bterm _ _ (bterm ?lv ?a) (bterm ?lv ?b) |- _ ] =>
apply approx_star_samevar in H; subst
| [H : blift (approx_star _) (bterm ?lv ?a) (bterm ?lv ?b) |- _ ] =>
apply approx_star_samevar in H; subst
| [H : blift _ _ _ |- _ ] => unfold blift in H; exrepnd
end.
Hint Resolve compute_max_steps_eauto compute_max_steps_eauto2: extens.
Lemma reduces_to_implies_approx_open {p} :
forall lib t x,
@isprogram p t
-> reduces_to lib t x
-> approx_open lib x t # approx_open lib t x.
Proof.
introv Hp Hr. apply reduces_to_implies_approx in Hr; auto. repnd.
split; apply approx_implies_approx_open; auto.
Qed.
(*
We begin by proving extensionality of the [NApply] [Opid].
Our proof essentially follows Howe's proof. We will, however
describe the proof to describe some details specific to our
formalization, and also sketch the general recipe for such proofs.
%\footnote {In hind-sight, it seems possible to write an
automated tactic that can finish these proofs}.%
Also, the shape of [bargs] has to be
the one that
[(map (fun x => 0) pargs ++ map num_bvars npargs) = OpBindings (NCan op)].
Morevover, the head [Opid] of this canonical form
([v]) should be compatiable with [op].
For example, if [op = NApply],
[c] must be [NLambda]. Similarly, if [op = NDecide], [c] must either
be [NInl] or [NInr]. For [NCbv], [c] can be canonical [Opid].
One can look at the definition of the [compute_step]
function to find out such relations.
Often, [op] is called the elim form of the intro form [c].
*)
Definition get_bterms {p} (nt:@NTerm p) : list BTerm :=
match nt with
| vterm v => []
| sterm _ => []
| oterm o lbt => lbt
end.
(* use this to typecheck all the composite terms in the long comment below*)
(*
Definition v := nvarx.
Definition v1 := nvarx.
Definition v2 := nvarx.
Definition b := (vterm nvarx).
Definition bl := (vterm nvarx).
Definition br := (vterm nvarx).
Definition pi1 := (vterm nvarx).
Definition arg := (vterm nvarx).
Definition pi2 := (vterm nvarx).
Definition lbt := @nil BTerm.
Definition lbtc := @nil BTerm.
Definition lbt' := @nil BTerm.
Definition bargs := @nil BTerm.
Definition bargs' := @nil BTerm.
Definition pnt := @nil NTerm.
Definition pnt' := @nil NTerm.
Definition pntc := @nil NTerm.
Definition pntc' := @nil NTerm.
Definition op := NFix.
Definition cc := NLambda.
Definition f := fun l: list BTerm => (vterm nvarx).
*)
(* end hide *)
(** Howe and Crary prove extensionality of many non-canonical [Opid]s.
Our computation system has some new ones and the operational
semantics of some earlier ones like [NFix] is different.
We have formally proved that all [Opid]s in our system are extensional.
Instead of describing these proofs separately, we will describe the
general recipe. A reader who
wishes to delve into very concrete details can walk through
the coq proof
scripts for the extensionality lemmas.
In general, whenever a computation in which an arbitrary non-cononical term
[(oterm (NCan op) lbt)] computes to a value [a], [lbt] can be expressed as
[(map (bterm []) pnt)++bargs], where [pnt] are the principal arguments of [op].
The length of [pargs] depends on [op].
For [NCompOp] and [NCanTest], it is 2 and it is 1 for the rest.
The [S k] steps of computation from [(oterm (NCan op) (map (bterm []) pnt ++ bargs))]
to the value [a] (see hypothesis [Hcv] in [extensional_op])
can be split into the following three parts
that happen one after the other.
- Each element of [pnt] converges to some canonical [NTerm].
At the end of this stage, the overall term is of the form
[(oterm (NCan op) ((map (bterm []) pntc)++bargs))] such that
elements of [pnt] converge respectively to canonical elements of [pntc].
- One interesting step of computation happens by the interaction of
the canonical [Opid]s in [pntc] and the corresponding non-canonical [Opid]
[op]. Let the overall term after this step
be [t]. Let [llbt] be [(bargs ++ (flat_map get_bterms pntc))].
For the proof of [extensional_op (NCan op)], the key property
here is that [t] can always be written as some [f llbt] such that
[forall lbt1 lbt2, approx_starbts lbt1 lbt2 -> approx_star (f lbt1) (f lbt2)].
The details of this depend on the specific [op].
We consider all cases
one by one. The reader might want to revisit the definition of [compute_step]
to understand the claims below. [op=]
-- [NApply] : In this case, [pntc] is of the form
[[oterm (Can NLambda) [(bterm [v] b)]]] and [bargs] is of the form
[[bterm [] arg]] and [t= apply_bterm (bterm [v] b) [arg]]. For this
and the next 4 cases, the required property of [f] is a direct consequence
of the lemma [apply_bterm_approx_star_congr] above.
-- [NCbv] : [pntc] is of the form [[oterm (Can cc) lbtc]] and
[bargs] is of the form [bterm [v] b].
[t= apply_bterm (bterm [v] b) [(oterm (Can cc) lbtc)]].
-- [NSpread] : [pntc] is of the form
[[oterm (Can NPair) [bterm [] pi1,bterm [] pi2]]]
and [bargs] is of the form [bterm [v1,v2] b].
[t= apply_bterm (bterm [v1,v2] b) [pi1,pi2]]
-- [NDecide] : [pntc] is of the form
[[oterm (Can NInl) [bterm [] arg]]] or [[oterm (Can NInr) [bterm [] arg]]]
and [bargs] is of the form [[bterm [v] bl,bterm [v] br]]
and [t= apply_bterm (bterm [v] bl) [arg]] or
[t= apply_bterm (bterm [v] br) [arg]] depending on [pntc].
-- [NArithOp] : [pntc] is of the form
[[oterm (Can (Nint n1)) [], oterm (Can (Nint n2)) []]]
and [bargs] is []. [t = oterm (Can (Nint (n1+n2))) []]
The [f] in this case does not depend on any [BTerm]s
(there aren't any in this case)
and is hence a constant function.
The same reason applies for the three cases below.
-- [NCompOp] : and [bargs] is of the form [arg3, arg4].
[t] is either [arg3] or [arg4] depending only on the
head canonical [Opid]s of the [NTerm]s in [pntc]
-- [NCanTest] : exactly same as above.
- t converges to a.
One key observation here is that the second part of this
3-way split consumes exactly one step. Hence the the first and last
parts consume at most [k] steps and hence [Hind] (in the definition
of [extensional_op]) can be applied to
both these parts.
To prove [extensional_op op], we use the hypothesis [Has] to infer
that [lbt'] can also be expressed as [(map (bterm []) pnt')++bargs']
(see the lemma [blift_numbvars]) such that we have
[Hasp : bin_rel_nterm approx_star pnt pnt']
Applying [Hind] along with [Hasp] to the first stage of computation where
[pnt] converges pointwise to [pntc],
and we get
[Haspc : bin_rel_nterm approx_star pntc pnt'].
Next, we apply
[howe_lemma2] pointwise to [Haspc](* make a corollary? *), we get [pntc']
such that elements of [pnt'] converges to [pntc'] respectively
such that we have [Haspcc : bin_rel_nterm approx_star pntc pntc']
Next, the second stage of computation happens and we get that
[oterm (NCan op) ((map (bterm []) pntc')++bargs')] computes to some
[t'] in exactly one step. By the property of this
one step function [f] that we described casewise above,
we get [Hapt : approx_star t t'].
Finally, we apply [Hind] to the third stage again to get
[Hapa : approx_star a t'].
Since [oterm (NCan op) ((map (bterm []) pnt')++bargs')] reduced to
[t'], we use the lemma [reduces_to_implies_approx_open] above to get
[Hao : approx_open t' (oterm (NCan op) ((map (bterm []) pnt')++bargs'))]
Now, we can use [approx_star_open_trans] on [Hapa] and [Hao] to get
the desired conclusion of [extensional_op op].
The concrete Coq proofs of the extensionality lemmas below follow this overall recipe.
*)
Ltac splr :=
first [ complete sp
| complete (left; sp; splr)
| complete (right; sp; splr)
].
Ltac make_red_val_or_exc H h :=
let hyp := fresh h in
let T := type of H in
match T with
| reduces_in_atmost_k_steps ?lib ?t1 ?t2 ?k =>
assert (computes_to_val_or_exc_in_max_k_steps lib t1 t2 k)
as hyp
by (split; [ complete eauto
| splr
]
)
end.
Ltac make_red_val_like H h :=
let hyp := fresh h in
let T := type of H in
match T with
| reduces_in_atmost_k_steps ?lib ?t1 ?t2 ?k =>
assert (computes_to_val_like_in_max_k_steps lib t1 t2 k)
as hyp
by (split; [ complete eauto
| splr
]
)
end.
Lemma approx_star_exception {p} :
forall lib (a1 a2 e1 e2 : @NTerm p),
approx_star lib a1 a2
-> approx_star lib e1 e2
-> approx_star lib (mk_exception a1 e1) (mk_exception a2 e2).
Proof.
introv ap1 ap2.
apply approx_star_congruence; simpl; sp.
unfold approx_starbts, lblift_sub; simpl; dands; auto; introv j.
repeat (destruct n; cpx);
unfold selectbt; simpl; unfold blift_sub.
- exists ([] : list NVar) a1 a2; dands; auto; left; dands; tcsp; intro i; ginv.
- exists ([] : list NVar) e1 e2; dands; auto; left; dands; tcsp; intro i; ginv.
Qed.
(*
(* !! MOVE to computation4 *)
Lemma reduces_to_primarg_marker {o} :
forall lib nc m (l bs : list (@BTerm o)) v,
reduces_to lib (oterm (NCan nc) (nobnd (oterm (Mrk m) l) :: bs)) v
-> v = oterm (NCan nc) (nobnd (oterm (Mrk m) l) :: bs).
Proof.
introv comp.
unfold reduces_to in comp; exrepnd.
allapply @reduces_in_atmost_k_steps_primarg_marker; subst; auto.
Qed.
(* !! MOVE to approx *)
Lemma approx_ncan_primarg_marker {o} :
forall lib ncan m l bs (t : @NTerm o),
isprogram (oterm (NCan ncan) (nobnd (oterm (Mrk m) l) :: bs))
-> isprogram t
-> approx lib (oterm (NCan ncan) (nobnd (oterm (Mrk m) l) :: bs)) t.
Proof.
introv isp1 isp2.
unfold approx.
constructor.
unfold close_comput; repnd; dands; auto.
- unfold close_compute_val; introv comp.
unfold computes_to_value in comp; repnd.
apply reduces_to_primarg_marker in comp0; ginv.
- unfold close_compute_exc; introv comp.
unfold computes_to_exception in comp; repnd.
apply reduces_to_primarg_marker in comp; ginv.
- unfold close_compute_mrk; introv comp.
unfold computes_to_marker in comp; repnd.
apply reduces_to_primarg_marker in comp; ginv.
Qed.
*)
Lemma approx_star_nat {p} :
forall lib (t : @NTerm p) n,
isprogram t
-> approx_star lib (mk_nat n) t
-> computes_to_value lib t (mk_nat n).
Proof.
introv isp apr.
apply howe_lemma2 in apr; fold_terms; eauto 3 with slow.
exrepnd.
unfold approx_starbts, lblift_sub in apr1; allsimpl; repnd; cpx.
Qed.
Lemma extensional_apply {p} : extensional_op (@NCan p NApply).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
apply isprogram_apply_implies in Hcv6; exrepnd; subst; cpx.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst.
{ csunf XX1; allsimpl.
apply compute_step_apply_success in XX1; repndors; exrepnd; subst; ginv.
+ (* destruct lhs for a bit so that the args of lambda show up*)
rename v into lamv.
rename b into lamb.
rename la into lamnt.
apply no_change_after_value_ra with (k2:=k) in Hcv3; auto.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := lamntr) in h; eauto; prove_isprogram.
apply howe_lemma2 in h; exrepnd; auto; prove_isprogram.
duplicate h1.
rename a into c.
unfold approx_starbts, lblift_sub in h1; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
apply apply_bterm_approx_star_congr with
(lnt1:= [arg]) (lnt2:= [argr]) in h10bt; tcsp;
try (complete (intro xx; ginv));
[|prove_bin_rel_nterm; fail].
apply no_change_after_val_like with (k2 := k) in XX0; auto.
repnud h0.
match goal with
[ |- approx_star _ _ (oterm (NCan ?no) _)] =>
let T := type of Has0 in
match T with
| lblift_sub _ (approx_star _) _ (_::?tr) =>
apply reduces_to_prinarg
with (lbt:= tr) (op:=no) in h1
end
end. (* this will be used later in this proof *)
pose proof (reduces_to_preserves_program _ _ _ h1 Hprt') as Hispr.
apply reduces_atmost_preserves_program in Hcv4; auto; try omega.
make_red_val_like XX0 hh.
let T:= type of h10bt in
match T with
| approx_star ?lib ?tl ?tr =>
assert (isprogram tl) by (apply (preserve_compute_step lib) with (t2:=tl) in Hcv4;sp);
assert(isprogram tr) by (apply (preserve_compute_step lib) with (t2:=tr) in Hispr;sp);
apply Hi with (v:=tr) in hh; auto;
apply approx_star_open_trans with (b:= tr); auto
end.
apply approx_implies_approx_open;
apply reduces_to_implies_approx_eauto;auto;
eapply reduces_to_if_split1; eauto.
+ apply no_change_after_value_ra with (k2:=k) in Hcv3; auto.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := lar) in h; eauto; prove_isprogram.
apply howe_lemma2 in h; exrepnd; auto; prove_isprogram.
unfold approx_starbts, lblift_sub in h1; repnd; allsimpl; cpx.
clear h1.
rename a into c.
apply no_change_after_val_like with (k2 := k) in XX0; auto.
repnud h0.
match goal with
[ |- approx_star _ _ (oterm (NCan ?no) _)] =>
let T := type of Has0 in
match T with
| lblift_sub _ (approx_star _) _ (_::?tr) =>
apply reduces_to_prinarg
with (lbt:= tr) (op:=no) in h1
end
end. (* this will be used later in this proof *)
pose proof (reduces_to_preserves_program _ _ _ h1 Hprt') as Hispr.
apply reduces_atmost_preserves_program in Hcv4; auto; try omega.
make_red_val_like XX0 hh.
allrw <- @isprogram_apply_iff; repnd.
pose proof (Hi (mk_apseq f arg) c (mk_apseq f argr)) as q.
repeat (autodimp q hyp); try (apply isprogram_apseq); auto.
{ apply approx_star_congruence3; try (apply isprogram_apseq); auto.
apply approx_starbts_cons; dands; eauto 3 with slow.
{ unfold nobnd; prove_approx_star; auto. }
{ unfold approx_starbts, lblift_sub; simpl; sp. }
}
eapply approx_star_open_trans;[exact q|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto;
allrw <- @isprogram_apply_iff; auto.
eapply reduces_to_if_split1; eauto.
}
{ allsimpl.
csunf XX1; allsimpl; ginv.
apply no_change_after_value_ra with (k2:=k) in Hcv3; eauto 2 with slow.
unfold lblift_sub in Has; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
allrw <- @isprogram_apply_iff; repnd.
fold_terms.
make_red_val_like Hcv3 h.
pose proof (Hi la (sterm f0) lar) as q.
repeat (autodimp q hyp).
apply howe_lemma2_seq in q; exrepnd; auto; prove_isprogram.
apply reduces_in_atmost_k_steps_eapply_sterm_to_isvalue_like in XX0; auto.
repndors; exrepnd.
- apply no_change_after_value_ra with (k2:=k) in XX2; eauto 2 with slow; try omega;[].
pose proof (Hi a0 (mk_nat n) a0r) as z.
make_red_val_like XX2 ca0.
repeat (autodimp z hyp); eauto 2 with slow;[].
apply approx_star_nat in z; auto.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
eapply approx_trans;
[apply reduces_to_implies_approx_eauto;[|eexists;exact XX1];eauto 3 with slow
|].
eapply approx_trans;
[|apply reduces_to_implies_approx_eauto;[|apply apply_sterm_nat_implies; eauto];
eauto 3 with slow].
apply alpha_implies_approx3; eauto 3 with slow.
- apply isexc_implies in XX1; auto; exrepnd; subst.
apply no_change_after_val_like with (k2:=k) in XX2; try splr; try omega.
make_red_val_like XX2 ca0.
pose proof (Hi a0 (mk_exception a1 e) a0r) as z.
repeat (autodimp z hyp); eauto 2 with slow;[].
apply howe_lemma2_exc in z; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply reduces_to_trans with (b := mk_apply (sterm f') a0r).
{ apply reduces_to_prinarg; auto. }
eapply apply_sterm_exception_implies; auto.
apply reduces_to_symm.
}
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
clear Hcv.
allrw @fold_exception.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl.
repeat(approxrelbtd). show_hyps.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := lar) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply reduces_to_trans with (b := mk_apply (mk_exception a' e') a0r).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma bin_rel_nterm_singleton {o} :
forall (a b : @NTerm o) R,
R a b -> bin_rel_nterm R [a] [b].
Proof.
introv h.
unfold bin_rel_nterm, binrel_list; dands; simpl; auto.
introv i; destruct n; try omega; auto.
Qed.
Hint Resolve bin_rel_nterm_singleton : slow.
Lemma extensional_eapply {p} : extensional_op (@NCan p NEApply).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
apply isprogram_eapply_implies in Hcv6; exrepnd; subst; cpx.
dorn Hcv0.
- apply no_change_after_value_ra with (k2:=k) in Hcv3; auto.
unfold lblift_sub in Has; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
make_red_val_like Hcv3 h.
pose proof (Hi la f lar) as q.
repeat (autodimp q hyp); prove_isprogram.
allrw <- @isprogram_eapply_iff; repnd.
apply iscan_implies in Hcv0; repndors; exrepnd; subst.
{ csunf XX1; allsimpl.
apply compute_step_eapply_success in XX1; exrepnd; allunfold @nobnd; ginv.
apply eapply_wf_def_oterm_implies in XX3; exrepnd; subst; ginv.
apply howe_lemma2 in q; exrepnd; auto.
unfold approx_starbts, lblift_sub in q1; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
fold_terms.
applydup @preserve_program in q0; auto.
repndors; exrepnd; subst; ginv.
- applydup @howe_lemma2_implies_iscan in Has1bt; auto; exrepnd.
applydup @preserve_program in Has1bt2; auto.
eapply approx_star_open_trans in Has1bt;
[|apply approx_implies_approx_open;
apply computes_to_value_implies_approx2;[|exact Has1bt2];
auto].
apply apply_bterm_approx_star_congr with
(lnt1:= [arg2]) (lnt2:= [v0]) in q10bt; simpl; tcsp; eauto 2 with slow;
try (complete (intro xx; ginv)).
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 w.
pose proof (Hi
(apply_bterm (bterm [v] t) [arg2])
a
(apply_bterm (bterm [vr] tr) [v0])) as z.
repeat (autodimp z hyp); prove_isprogram;
try (apply isprogram_bt_implies; simpl; auto; prove_isprogram;
try (apply implies_isprogram_bt_lam; auto);
introv i; repndors; subst; tcsp);[].
eapply approx_star_open_trans;[exact z|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply eapply_red_lam_val_implies; simpl; auto.
- apply isexc_implies in XX2; auto; exrepnd; subst.
apply reduces_in_atmost_k_steps_if_isvalue_like in XX0; eauto 2 with slow; subst.
apply howe_lemma2_exc in Has1bt; prove_isprogram; exrepnd.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
eapply eapply_lam_exception_implies; eauto.
- fold_terms.
apply reduces_in_atmost_k_steps_eapply_lam_to_isvalue_like in XX0; auto.
repndors; exrepnd.
+ apply no_change_after_val_like with (k2:=k) in XX2; eauto 2 with slow; try omega;[].
make_red_val_like XX2 cak.
applydup @preserve_compute_step in XX1; auto.
applydup @reduces_atmost_preserves_program in XX5; auto.
assert (reduces_in_atmost_k_steps lib arg2 c (S i)) as ra2.
{ rw @reduces_in_atmost_k_steps_S; eexists; dands; eauto. }
apply no_change_after_val_like with (k2:=k) in ra2; eauto 2 with slow; try omega;[].
make_red_val_like ra2 cck.
pose proof (Hi arg2 c a0r) as z.
repeat (autodimp z hyp); eauto 2 with slow;[].
applydup @howe_lemma2_implies_iscan in z; auto; exrepnd.
eapply approx_star_open_trans in z;
[|apply approx_implies_approx_open;
apply computes_to_value_implies_approx2;[|exact z2];
auto];[].
apply apply_bterm_approx_star_congr
with (lnt1:= [c]) (lnt2:= [v0]) in q10bt;
simpl; tcsp; eauto 2 with slow;
try (complete (intro xx; ginv));[].
allunfold @apply_bterm; allsimpl; allrw @fold_subst.
pose proof (Hi (subst t v c) a (subst tr vr v0)) as w.
repeat (autodimp w hyp); prove_isprogram;
try (try (apply isprogram_subst_if_bt);
try (apply isprogram_bt_implies);
try (apply implies_isprogram_bt_lam);
simpl; auto; prove_isprogram;
introv i; repndors; subst; tcsp).
eapply approx_star_open_trans;[exact w|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply eapply_red_lam_val_implies; simpl; auto.
+ apply isexc_implies in XX2; auto; exrepnd; subst.
assert (reduces_in_atmost_k_steps lib arg2 (mk_exception a0 e) (S j)) as ra2.
{ rw @reduces_in_atmost_k_steps_S; eexists; dands; eauto. }
apply no_change_after_val_like with (k2:=k) in ra2; try splr; try omega.
make_red_val_like ra2 ca0.
pose proof (Hi arg2 (mk_exception a0 e) a0r) as z.
repeat (autodimp z hyp); eauto 2 with slow;[].
apply howe_lemma2_exc in z; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
eapply eapply_lam_exception_implies; eauto.
}
{ allsimpl.
csunf XX1; allsimpl; ginv.
apply howe_lemma2_seq in q; exrepnd; auto; prove_isprogram.
apply compute_step_eapply_success in XX1; exrepnd; allunfold @nobnd; ginv.
applydup @reduces_to_preserves_program in q0; auto.
fold_terms.
repndors; exrepnd; subst.
- apply compute_step_eapply2_success in XX1; repnd; GC.
repndors; exrepnd; ginv.
apply approx_star_nat in Has1bt; auto.
apply no_change_after_val_like with (k2:=k) in XX0; eauto 2 with slow; try omega;[].
make_red_val_like XX0 ca0.
pose proof (Hi (f n) a (f' n)) as z.
repeat (autodimp z hyp); eauto 2 with slow;[|].
{ apply alpha_implies_approx_star; eauto 3 with slow. }
eapply approx_star_open_trans;[eauto|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply eapply_red_sterm_nat_implies; auto.
- apply isexc_implies in XX2; auto; exrepnd; subst.
apply reduces_in_atmost_k_steps_if_isvalue_like in XX0; eauto 2 with slow; subst.
apply howe_lemma2_exc in Has1bt; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
eapply eapply_red_sterm_exception_implies; eauto.
- apply reduces_in_atmost_k_steps_eapply_sterm_to_isvalue_like in XX0; auto.
repndors; exrepnd.
+ assert (reduces_in_atmost_k_steps lib arg2 (mk_nat n) (S i)) as ra2.
{ rw @reduces_in_atmost_k_steps_S; eexists; dands; eauto. }
apply no_change_after_value_ra with (k2:=k) in ra2; eauto 2 with slow; try omega;[].
pose proof (Hi arg2 (mk_nat n) a0r) as z.
make_red_val_like ra2 ca0.
repeat (autodimp z hyp); eauto 2 with slow;[].
apply approx_star_nat in z; auto.
apply no_change_after_val_like with (k2:=k) in XX2; eauto 2 with slow; try omega;[].
make_red_val_like XX2 caf.
pose proof (Hi (f0 n) a (f' n)) as w.
repeat (autodimp w hyp); eauto 2 with slow;[|].
{ apply alpha_implies_approx_star; eauto 3 with slow. }
eapply approx_star_open_trans;[eauto|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply eapply_red_sterm_nat_implies; auto.
+ apply isexc_implies in XX2; auto; exrepnd; subst.
assert (reduces_in_atmost_k_steps lib arg2 (mk_exception a0 e) (S j)) as ra2.
{ rw @reduces_in_atmost_k_steps_S; eexists; dands; eauto. }
apply no_change_after_val_like with (k2:=k) in ra2; try splr; try omega.
make_red_val_like ra2 ca0.
pose proof (Hi arg2 (mk_exception a0 e) a0r) as z.
repeat (autodimp z hyp); eauto 2 with slow;[].
apply howe_lemma2_exc in z; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
eapply eapply_red_sterm_exception_implies; eauto.
}
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
clear Hcv.
allrw @fold_exception.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl.
repeat(approxrelbtd). show_hyps.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := lar) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply reduces_to_trans with (b := mk_eapply (mk_exception a' e') a0r).
{ apply reduces_to_prinarg; auto. }
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_apseq {p} : forall s : nseq, extensional_op (@NCan p (NApseq s)).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_cbv_implies; exrepnd; subst; cpx.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst;
try (complete (csunf XX1; allsimpl; ginv));[].
csunf XX1; allsimpl.
apply compute_step_apseq_success in XX1; exrepnd; subst.
allrw <- @isprogram_apseq_iff.
apply reduces_in_atmost_k_steps_if_isvalue_like in XX0; eauto 2 with slow; subst.
apply no_change_after_value_ra with (k2:=k) in Hcv3; auto; [].
unfold lblift_sub in Has; repnd; allsimpl; cpx.
repeat(approxrelbtd); show_hyps.
allrw <- @isprogram_apseq_iff.
fold_terms.
make_red_val_like Hcv3 h.
pose proof (Hi la (mk_nat n) lar) as q.
repeat (autodimp q hyp).
apply howe_lemma2 in q; exrepnd; auto; prove_isprogram.
unfold approx_starbts, lblift_sub in q1; repnd; allsimpl; cpx.
clear q1.
fold_terms.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
unfold computes_to_value in q0; repnd.
eapply reduces_to_trans;[apply reduces_to_prinarg;exact q1|].
apply reduces_to_if_step; csunf; simpl.
rw @Znat.Nat2Z.id.
boolvar; try omega; auto.
- allapply @isprogram_apseq_implies; exrepnd; ginv.
apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
clear Hcv.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl.
repeat(approxrelbtd). show_hyps.
apply approx_star_bterm_nobnd2 in Has0bt.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := a2) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @fold_cbv.
allrw @computes_to_exception_as_reduces_to.
apply @reduces_to_trans with (b := mk_apseq s (mk_exception a' e')).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_fix {p} : extensional_op (@NCan p NFix).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m<= S k ) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_fix_implies; exrepnd; subst; cpx.
dorn Hcv0.
- unfold lblift_sub in Has; repnd; allsimpl; GC.
repeat(approxrelbtd). show_hyps.
apply approx_star_bterm_nobnd2 in Has0bt.
apply no_change_after_value_ra with (k2:=k) in Hcv3; auto.
make_red_val_like Hcv3 h.
apply iscan_implies in Hcv0; repndors; exrepnd; subst.
{ simpl in XX1; inversion XX1; subst; GC.
apply (Hi _ _ f0) in h; auto.
apply howe_lemma2 in h; exrepnd; auto.
repnud h0.
rename a into cc.
apply reduces_to_prinarg with (lbt:= []) (op:=NFix) in h2.
(* this will be used later in this proof *)
assert (approx_star
lib
(mk_apply (oterm (Can c) bterms)
(oterm (NCan NFix) [bterm [] (oterm (Can c) bterms)]))
(mk_apply (oterm (Can c) lbt')
(oterm (NCan NFix) [bterm [] (oterm (Can c) lbt')])))
as XXX.
{ repeat (prove_approx_star; auto; prove_isprogram). }
apply no_change_after_val_like with (k2:=k) in XX0; auto.
make_red_val_like XX0 h.
apply (Hi _ _ (mk_apply (oterm (Can c) lbt')
(oterm (NCan NFix) [bterm [] (oterm (Can c) lbt')])))
in h; auto; prove_isprogram.
match goal with
[ H : approx_star ?lib ?cc ?t2 |- approx_star ?lib ?cc ?t1] =>
apply (approx_star_open_trans lib) with (b:=t2) end; auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; try (rw <- @isprogram_fix_iff; auto).
eapply reduces_to_if_split1; eauto.
}
{ csunf XX1; allsimpl; ginv.
apply (Hi _ _ f0) in h; auto.
apply howe_lemma2_seq in h; exrepnd; auto.
apply no_change_after_val_like with (k2:=k) in XX0; auto.
make_red_val_like XX0 ca0.
apply (Hi _ _ (mk_apply (mk_ntseq f') (oterm (NCan NFix) [bterm [] (sterm f')]))) in ca0;
try prove_isprogram;
[|apply isprogram_apply; eauto 2 with slow;
apply isprogram_fix; eauto 2 with slow
|repeat (prove_approx_star; eauto 2 with slow; prove_isprogram);
try (apply alpha_implies_approx_star; eauto 3 with slow)];[].
eapply approx_star_open_trans;[exact ca0|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; try (rw <- @isprogram_fix_iff; auto).
eapply reduces_to_trans;
[apply reduces_to_prinarg;exact h0|].
eapply reduces_to_if_step.
csunf; simpl; auto.
}
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
clear Hcv.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl.
repeat(approxrelbtd). show_hyps.
apply approx_star_bterm_nobnd2 in Has0bt.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := f0) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e'); try (rw fold_fix).
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply reduces_to_trans with (b := mk_fix (mk_exception a' e')).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
(* !! Move to terms2 *)
Lemma isprogram_cbv_iff2 {p} :
forall (a : @NTerm p) v b,
isprogram (mk_cbv a v b)
<=> isprogram a # isprogram_bt (bterm [v] b).
Proof.
introv.
rw @isprogram_cbv_iff.
unfold isprogram_bt; simpl.
unfold closed_bt; simpl.
rw <- null_iff_nil.
rw null_remove_nvars.
rw subvars_prop.
split; intro k; repnd; dands; auto.
inversion k; sp.
Qed.
Lemma compute_step_cbv_iscan {o} :
forall lib (t : @NTerm o) v u,
iscan t
-> compute_step lib (mk_cbv t v u) = csuccess (subst u v t).
Proof.
introv isc.
apply iscan_implies in isc; repndors; exrepnd; subst; csunf; simpl;
unfold apply_bterm; simpl; auto.
Qed.
Lemma extensional_cbv {p} : extensional_op (@NCan p NCbv).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_cbv_implies; exrepnd; subst; cpx.
dorn Hcv0.
- unfold lblift_sub in Has; repnd; allsimpl; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply no_change_after_value_ra with (k2:=k) in Hcv3; auto; [].
make_red_val_like Hcv3 h.
apply (Hi _ _ t2) in h; auto; prove_isprogram;[].
applydup @howe_lemma2_implies_iscan in h; auto; exrepnd.
apply apply_bterm_approx_star_congr
with (lnt1:= [t1]) (lnt2:= [v1])
in Has1bt;
eauto 2 with slow;
try (complete (intro xx; ginv)).
allunfold @apply_bterm; allsimpl; allrw @fold_subst; fold_terms.
rw @compute_step_cbv_iscan in XX1; auto;[]; ginv.
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 hh.
apply (Hi _ _ (subst b0 v0 v1)) in hh; auto; prove_isprogram;
try (try (apply isprogram_subst_if_bt);
try (apply isprogram_bt_implies);
try (apply implies_isprogram_bt_lam);
simpl; auto; prove_isprogram;
introv i; repndors; subst; tcsp);[].
allunfold @computes_to_value; repnd.
eapply approx_star_open_trans;[eauto|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto;
try (apply isprogram_cbv_iff2;dands;auto).
eapply reduces_to_trans;[apply reduces_to_prinarg;eauto|]; fold_terms.
apply reduces_to_if_step.
rw @compute_step_cbv_iscan; auto.
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
clear Hcv.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
duplicate Has.
unfold lblift_sub in Has; repnd; allsimpl.
repeat(approxrelbtd). show_hyps.
apply approx_star_bterm_nobnd2 in Has0bt.
make_red_val_like Hcv3 h.
unfold extensional_op_ind in Hi.
apply Hi with (v := t2) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @fold_cbv.
allrw @computes_to_exception_as_reduces_to.
apply @reduces_to_trans with (b := mk_cbv (mk_exception a' e') v0 b0).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma reduces_to_implies_approx_open1 {o} :
forall lib (t x : @NTerm o),
isprogram t
-> reduces_to lib t x
-> approx_open lib x t.
Proof.
introv isp r.
apply reduces_to_implies_approx_open in r; sp.
Qed.
Lemma compute_step_try_iscan {o} :
forall lib (t : @NTerm o) n v u,
iscan t
-> compute_step lib (mk_try t n v u)
= csuccess (mk_atom_eq n n t mk_bot).
Proof.
introv isc.
apply iscan_implies in isc; repndors; exrepnd; subst; csunf; simpl;
unfold apply_bterm; simpl; auto.
Qed.
Lemma approx_star_mk_atom_eq {o} :
forall lib (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),
approx_star lib a1 a2
-> approx_star lib b1 b2
-> approx_star lib c1 c2
-> approx_star lib d1 d2
-> approx_star lib (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).
Proof.
introv apra aprb aprc aprd.
apply approx_star_congruence; simpl; unfold num_bvars; simpl; auto.
unfold approx_starbts, lblift_sub; simpl; dands; auto.
introv i.
unfold selectbt.
repeat (destruct n; simpl; try omega;
try (complete (apply blift_sub_nobnd_congr; auto))).
Qed.
Lemma extensional_trycatch {p} : extensional_op (@NCan p NTryCatch).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
repnud Hcv.
assert (m <= S k) as XX by omega.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_trycatch_implies; exrepnd; subst; cpx.
allrw @fold_try.
unfold lblift_sub in Has; repnd; simpl in Has0, Has; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
dorn Hcv0.
- apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
make_red_val_like Hcv3 h.
apply (Hi _ _ t2) in h; auto.
applydup @howe_lemma2_implies_iscan in h; auto; exrepnd.
allunfold @computes_to_value; repnd.
fold_terms.
rw @compute_step_try_iscan in XX1; ginv.
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 hh.
apply (Hi _ _ (mk_atom_eq a1 a1 v1 mk_bot)) in hh;
auto; prove_isprogram;
try (apply isprogram_mk_atom_eq; dands; auto);
eauto 2 with slow;
try (complete (apply approx_star_mk_atom_eq; auto;
apply approx_star_refl; eauto 3 with slow)).
eapply approx_star_open_trans;[eauto|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto;
try (apply isprogram_try_iff2;dands;auto);[].
eapply reduces_to_trans;[apply reduces_to_prinarg;eauto|]; fold_terms.
apply reduces_to_if_step.
rw @compute_step_try_iscan; auto.
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
applydup @isprogram_exception_iff in Hcv8.
csunf XX1; simpl in XX1; ginv.
apply no_change_after_val_like with (k2:=k) in Hcv3; try splr.
apply no_change_after_val_like with (k2:=k) in XX0; try splr.
unfold extensional_op_ind in Hi.
make_red_val_like Hcv3 h.
apply Hi with (v := t2) in h; auto; prove_isprogram.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
applydup @computes_to_exception_preserves_program in h1; auto.
apply apply_bterm_approx_star_congr
with (lnt1:=[e]) (lnt2:=[e']) in Has2bt;
auto;
try (complete (intro xx; ginv));
[|prove_bin_rel_nterm; prove_approx_star; auto; prove_isprogram].
unfold apply_bterm in Has1bt; simpl in Has1bt; repeat (rw fold_subst in Has1bt).
make_red_val_like XX0 hh.
apply Hi with (v := mk_atom_eq a1 a' (subst b0 v0 e') (mk_exception a' e')) in hh; auto; prove_isprogram;
try (apply isprogram_subst_if_bt; auto).
{
eapply approx_star_open_trans; eauto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram;
try (apply isprogram_try_iff2; sp).
apply (reduces_to_trans _ _ (mk_try (mk_exception a' e') a1 v0 b0)).
* apply reduces_to_prinarg; auto.
* apply reduces_to_if_step; csunf; simpl; boolvar; tcsp.
}
{
apply isprogram_mk_atom_eq; dands; auto.
apply isprogram_subst_if_bt; auto.
}
{
apply isprogram_mk_atom_eq; dands; auto; prove_isprogram.
- apply @preserve_program_exc2 in h1; sp.
- apply isprogram_subst_if_bt; auto.
- apply isprogram_exception; auto.
apply @preserve_program_exc2 in h1; sp.
}
{
apply approx_star_congruence3.
- unfold approx_starbts, lblift_sub; allsimpl; dands; auto.
introv i; repeat (destruct n; cpx); unfold selectbt; simpl;
apply blift_sub_nobnd_congr; auto.
apply approx_star_congruence3.
+ unfold approx_starbts, lblift_sub; allsimpl; dands; auto.
introv j; repeat (destruct n; cpx); unfold selectbt; simpl;
apply blift_sub_nobnd_congr; auto.
+ apply isprogram_exception; auto.
apply @preserve_program_exc2 in h1; sp.
- apply isprogram_mk_atom_eq; dands; auto; prove_isprogram.
+ apply @preserve_program_exc2 in h1; sp.
+ apply isprogram_subst_if_bt; auto.
+ apply isprogram_exception; auto.
apply @preserve_program_exc2 in h1; sp.
}
Qed.
Lemma extensional_spread {p} : extensional_op (@NCan p NSpread).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_spread_implies; exrepnd; subst; cpx.
allrw @fold_spread.
unfold lblift_sub in Has; repnd; simpl in Has, Has0; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
allsimpl; GC.
apply no_change_after_val_like with (k2:=k) in Hcv3;auto;[].
make_red_val_like Hcv3 h.
apply (Hi _ _ t2) in h; auto; prove_isprogram.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst;
csunf XX1; allsimpl; ginv;[].
apply compute_step_spread_success in XX1; exrepnd; subst; cpx; GC.
applydup @isprogram_pair_iff in Hcv8; repnd.
apply howe_lemma2 in h; exrepnd; auto; prove_isprogram.
unfold approx_starbts, lblift_sub in h1; simpl in h1; repnd.
repeat (destruct lbt'; simpl in h2; cpx); GC.
repeat(approxrelbtd); show_hyps.
applydup @computes_to_value_preserves_program in h0; auto.
applydup @isprogram_pair_iff in h1; repnd.
apply apply_bterm_approx_star_congr
with (lnt1:= [a0,b1]) (lnt2:= [a0r,b1r])
in Has1bt;
auto;
try (complete (intro xxx; ginv));
[|prove_bin_rel_nterm; prove_approx_star; auto; prove_isprogram].
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 hh.
apply (Hi _ _ (lsubst b0 [(v0,a0r),(v3,b1r)])) in hh; auto; prove_isprogram;
try (eapply isprogram_bt_implies_isprogram_lsubst; simpl;[reflexivity|idtac|auto];[];
introv i; repdors; cpx; auto).
apply approx_star_open_trans with (b := lsubst b0 [(v0, a0r), (v3, b1r)]); auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_spread (mk_pair a0r b1r) v0 v3 b0).
apply reduces_to_prinarg; auto; destruct h0; auto.
apply reduces_to_if_step; reflexivity.
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply @reduces_to_trans with (b := mk_spread (mk_exception a' e') v0 v3 b0).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_dsup {p} : extensional_op (@NCan p NDsup).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_dsup_implies; exrepnd; subst; cpx.
allrw @fold_spread.
unfold lblift_sub in Has; repnd; simpl in Has, Has0; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
allsimpl; GC.
apply no_change_after_val_like with (k2:=k) in Hcv3;auto;[].
make_red_val_like Hcv3 h.
apply (Hi _ _ t2) in h; auto; prove_isprogram.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst;
csunf XX1; allsimpl; ginv;[].
apply compute_step_dsup_success in XX1; exrepnd; subst; cpx; GC.
applydup @isprogram_sup_iff in Hcv8; repnd.
apply howe_lemma2 in h; exrepnd; auto; prove_isprogram.
unfold approx_starbts, lblift_sub in h1; simpl in h1; repnd.
repeat (destruct lbt'; simpl in h2; cpx); GC.
repeat(approxrelbtd); show_hyps.
applydup @computes_to_value_preserves_program in h0; auto.
applydup @isprogram_sup_iff in h1; repnd.
apply apply_bterm_approx_star_congr
with (lnt1:= [a0,b1]) (lnt2:= [a0r,b1r])
in Has1bt;
auto; try (complete (intro xxx; ginv));
[|prove_bin_rel_nterm; prove_approx_star; auto; prove_isprogram].
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 hh.
apply (Hi _ _ (lsubst b0 [(v0,a0r),(v3,b1r)])) in hh; auto; prove_isprogram;
try (eapply isprogram_bt_implies_isprogram_lsubst; simpl;[reflexivity|idtac|auto];[];
introv i; repdors; cpx; auto).
apply approx_star_open_trans with (b := lsubst b0 [(v0, a0r), (v3, b1r)]); auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_dsup (mk_sup a0r b1r) v0 v3 b0).
apply reduces_to_prinarg; auto; destruct h0; auto.
apply reduces_to_if_step; reflexivity.
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
apply howe_lemma2_exc in h; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply @reduces_to_trans with (b := mk_dsup (mk_exception a' e') v0 v3 b0).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_decide {p} : extensional_op (@NCan p NDecide).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_decide_implies; exrepnd; subst; cpx.
allrw @fold_decide.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply no_change_after_val_like with (k2:=k) in Hcv3;auto;[].
make_red_val_like Hcv3 hh.
apply (Hi _ _ t2) in hh; auto; prove_isprogram.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst;
csunf XX1; allsimpl; ginv;[].
apply compute_step_decide_success in XX1; exrepnd; subst; cpx; GC.
apply howe_lemma2 in hh; exrepnd; auto; prove_isprogram.
unfold approx_starbts, lblift_sub in hh1; simpl in hh1; repnd; cpx.
repeat(approxrelbtd); show_hyps.
applydup @computes_to_value_preserves_program in hh0; auto.
apply apply_bterm_approx_star_congr
with (lnt1:= [d]) (lnt2:= [dr])
in Has1bt;
auto; try (complete (intro xxx; ginv));
[|prove_bin_rel_nterm; prove_approx_star; auto; prove_isprogram].
apply apply_bterm_approx_star_congr
with (lnt1:= [d]) (lnt2:= [dr])
in Has2bt;
auto; try (complete (intro xxx; ginv));
[|prove_bin_rel_nterm; prove_approx_star; auto; prove_isprogram].
apply no_change_after_val_like with (k2 := k) in XX0; auto.
make_red_val_like XX0 hh.
destruct XX2 as [XX2|XX2]; repnd; subst.
+ applydup @isprogram_inl_iff in Hcv8; repnd.
applydup @isprogram_inl_iff in hh1; repnd.
apply (Hi _ _ (subst b0 v0 dr)) in hh; auto; prove_isprogram;
try (eapply isprogram_bt_implies_isprogram_lsubst; simpl;[reflexivity|idtac|auto];[];
introv i; repdors; cpx; auto).
apply approx_star_open_trans with (b := subst b0 v0 dr); auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_decide (mk_inl dr) v0 b0 v3 b3).
apply reduces_to_prinarg; auto; destruct hh0; auto.
apply reduces_to_if_step; reflexivity.
+ applydup @isprogram_inr_iff in Hcv8; repnd.
applydup @isprogram_inr_iff in hh1; repnd.
apply (Hi _ _ (subst b3 v3 dr)) in hh; auto; prove_isprogram;
try (eapply isprogram_bt_implies_isprogram_lsubst; simpl;[reflexivity|idtac|auto];[];
introv i; repdors; cpx; auto).
apply approx_star_open_trans with (b := subst b3 v3 dr); auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_decide (mk_inr dr) v0 b0 v3 b3).
apply reduces_to_prinarg; auto; destruct hh0; auto.
apply reduces_to_if_step; reflexivity.
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
apply howe_lemma2_exc in hh; exrepnd; auto; prove_isprogram.
apply approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply reduces_to_trans with (b := mk_decide (mk_exception a' e') v0 b0 v3 b3).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_arith {p} : forall a, extensional_op (@NCan p (NArithOp a)).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @isprogram_arithop_implies in Hprt; exrepnd; subst; cpx.
applydup @isprogram_arithop_implies in Hprt'; exrepnd; subst; cpx.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply computes_to_val_like_in_max_k_steps_arith_implies in Hcv;
[|eauto with slow|eauto with slow].
repndors; exrepnd; subst; GC.
- unfold extensional_op_ind in Hi.
unfold computes_to_value_in_max_k_steps in Hcv3; repnd.
unfold computes_to_value_in_max_k_steps in Hcv4; repnd.
apply @no_change_after_value_ra with (k2:=k) in Hcv0; auto; try omega; [].
apply @no_change_after_value_ra with (k2:=k) in Hcv5; auto; try omega; [].
make_red_val_like Hcv0 h1.
apply Hi with (v := a2) in h1; auto.
make_red_val_like Hcv5 h2.
apply Hi with (v := b0) in h2; auto.
apply howe_lemma2 in h1; auto; prove_isprogram.
apply howe_lemma2 in h2; auto; prove_isprogram.
exrepnd.
unfold approx_starbts, lblift_sub in h1; simpl in h1; repnd; cpx.
unfold approx_starbts, lblift_sub in h2; simpl in h2; repnd; cpx.
allrw @fold_integer.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NArithOp a))
[ bterm [] (mk_integer nv1),
bterm [] (mk_integer nv2)]).
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_if_step; reflexivity.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduce_to_prinargs_arith; eauto 3 with slow.
- unfold extensional_op_ind in Hi.
unfold computes_to_exception_in_max_k_steps in Hcv3; repnd.
apply @no_change_after_val_like with (k2:=k) in Hcv3; auto;
try omega; try (complete (unfold isvalue_like; simpl; sp)).
make_red_val_like Hcv3 h1.
apply Hi with (v := a2) in h1; auto.
apply howe_lemma2_exc in h1; auto; prove_isprogram.
exrepnd.
applydup @preserve_program_exc2 in h1; repnd; auto.
apply @approx_star_open_trans with (b := mk_exception a' e').
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NArithOp a))
[ bterm [] (mk_exception a' e'),
bterm [] b0]).
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
{ apply isprogram_arithop_iff.
eexists; eexists; dands; try reflexivity; auto;
rw @isprogram_exception_iff; tcsp.
}
apply reduces_to_if_step; reflexivity.
}
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_prinarg.
apply computes_to_exception_as_reduces_to; auto.
}
- unfold extensional_op_ind in Hi.
unfold computes_to_value_in_max_k_steps in Hcv3; repnd.
unfold computes_to_exception_in_max_k_steps in Hcv4; repnd.
applydup @reduces_atmost_preserves_program in Hcv2; auto.
assert (@isvalue p (mk_integer z)) as isvx by (apply isvalue_iff; sp).
apply @no_change_after_value_ra with (k2:=k) in Hcv2; auto; try omega; [].
apply @no_change_after_val_like with (k2:=k) in Hcv4; auto; try omega;
try (complete (unfold isvalue_like; simpl; sp)); [].
make_red_val_like Hcv2 h1.
apply Hi with (v := a2) in h1; auto.
make_red_val_like Hcv4 h2.
apply Hi with (v := b0) in h2; auto.
apply howe_lemma2_exc in h2; auto; prove_isprogram; exrepnd.
apply howe_lemma2 in h1; auto; prove_isprogram; exrepnd.
applydup @computes_to_value_preserves_program in h4; auto.
applydup @preserve_program_exc2 in h2; repnd; auto.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NArithOp a))
[ bterm [] (oterm (Can (Nint z)) lbt'),
bterm [] (mk_exception a' e')]).
{ apply reduces_to_implies_approx_eauto; prove_isprogram;[|].
{ apply isprogram_arithop_iff; eexists; eexists; dands; try reflexivity; auto.
rw @isprogram_exception_iff; auto. }
{ apply reduces_to_if_step.
csunf; simpl; dcwf h; simpl; auto;[].
allapply @isprogram_nat_implies; subst.
allunfold @ca_wf; ginv.
}
}
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduce_to_prinargs_arith; auto.
allapply @isprogram_nat_implies; subst.
fold_terms; eauto 3 with slow.
}
Qed.
Lemma extensional_ncomp {p} : forall a, extensional_op (@NCan p (NCompOp a)).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @isprogram_compop_implies in Hprt; exrepnd; subst; cpx.
applydup @isprogram_compop_implies in Hprt'; exrepnd; subst; cpx.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply computes_to_val_like_in_max_k_steps_comp_implies in Hcv;
try (complete (apply isprogram_implies_wf; auto)).
repndors; exrepnd; subst; GC.
- unfold extensional_op_ind in Hi.
unfold computes_to_can_in_max_k_steps in Hcv2; repnd.
unfold computes_to_can_in_max_k_steps in Hcv3; repnd.
applydup @reduces_atmost_preserves_program in Hcv6 as ispc1; auto.
applydup @reduces_atmost_preserves_program in Hcv7 as ispc2; auto.
assert (isvalue (pk2term pk1)) as isvc1 by (apply isvalue_iff; sp).
assert (isvalue (pk2term pk2)) as isvc2 by (apply isvalue_iff; sp).
apply @no_change_after_value_ra with (k2:=k) in Hcv6; auto; try omega; [].
apply @no_change_after_value_ra with (k2:=k) in Hcv7; auto; try omega; [].
applydup @reduces_atmost_preserves_program in Hcv6; auto.
applydup @reduces_atmost_preserves_program in Hcv7; auto.
make_red_val_like Hcv6 h1.
apply Hi with (v := a2) in h1; auto.
make_red_val_like Hcv7 h2.
apply Hi with (v := b0) in h2; auto.
allrw @pk2term_eq.
apply howe_lemma2 in h1; auto; prove_isprogram.
apply howe_lemma2 in h2; auto; prove_isprogram.
allrw <- @pk2term_eq.
exrepnd.
unfold approx_starbts, lblift_sub in h1; simpl in h1; repnd; cpx.
unfold approx_starbts, lblift_sub in h2; simpl in h2; repnd; cpx.
unfold computes_to_val_like_in_max_k_steps in Hcv5; repnd.
apply @no_change_after_val_like with (k2:=k) in Hcv10; auto; try omega; [].
make_red_val_like Hcv10 g.
apply Hi with (v := if d1 then c0 else d0) in g; auto;
try (complete (destruct d1; auto)).
apply @approx_star_open_trans with (b := if d1 then c0 else d0); auto.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NCompOp a))
[nobnd (pk2term pk1),
nobnd (pk2term pk2),
nobnd c0,
nobnd d0]).
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_if_step.
repndors; exrepnd; subst;
try (complete (csunf; simpl; dcwf h; simpl; unfold compute_step_comp; simpl; boolvar; tcsp));
try (complete (csunf; simpl; allrw @pk2term_eq; dcwf h; simpl;
unfold compute_step_comp; simpl; allrw @get_param_from_cop_pk2can;
boolvar; tcsp;
allunfold @co_wf; allsimpl; allrw @get_param_from_cop_pk2can; ginv)).
}
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
allrw <- @pk2term_eq.
apply reduce_to_prinargs_comp; auto.
{ repndors; exrepnd; subst; simpl; eauto 3 with slow. }
unfold computes_to_value in h0; sp.
}
- unfold extensional_op_ind in Hi.
unfold computes_to_exception_in_max_k_steps in Hcv3; repnd.
apply @no_change_after_val_like with (k2:=k) in Hcv3; auto;
try omega; try (unfold isvalue_like; allsimpl; sp).
make_red_val_like Hcv3 h1.
apply Hi with (v := a2) in h1; auto.
apply howe_lemma2_exc in h1; auto; prove_isprogram.
exrepnd.
applydup @preserve_program_exc2 in h1; repnd; auto.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NCompOp a))
[ nobnd (mk_exception a' e'),
nobnd b0,
nobnd c0,
nobnd d0]).
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
{ apply isprogram_compop_iff.
eexists; eexists; eexists; eexists; dands; try reflexivity; auto;
rw @isprogram_exception_iff; auto. }
{ apply reduces_to_if_step; reflexivity. }
}
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_prinarg.
apply computes_to_exception_as_reduces_to; auto.
}
- unfold extensional_op_ind in Hi.
unfold computes_to_can_in_max_k_steps in Hcv3; repnd.
unfold computes_to_exception_in_max_k_steps in Hcv4; repnd.
applydup @reduces_atmost_preserves_program in Hcv2 as ispx; auto.
assert (isvalue (pk2term pk)) as isvx by (apply isvalue_iff; sp).
apply @no_change_after_value_ra with (k2:=k) in Hcv2; auto; try omega; [].
apply @no_change_after_val_like with (k2:=k) in Hcv5; auto; try omega;
try (unfold isvalue_like; allsimpl; tcsp);[].
make_red_val_like Hcv2 h1.
apply Hi with (v := a2) in h1; auto.
make_red_val_like Hcv5 h2.
apply Hi with (v := b0) in h2; auto.
apply howe_lemma2_exc in h2; auto; prove_isprogram; exrepnd.
allrw @pk2term_eq.
apply howe_lemma2 in h1; auto; prove_isprogram; exrepnd.
applydup @computes_to_value_preserves_program in h4; auto.
applydup @preserve_program_exc2 in h2; repnd; auto.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NCompOp a))
[ nobnd (oterm (Can (pk2can pk)) lbt'),
nobnd (mk_exception a' e'),
nobnd c0,
nobnd d0]).
{ apply reduces_to_implies_approx_eauto; prove_isprogram;[|].
{ apply isprogram_compop_iff; eexists; eexists; eexists; eexists; dands; try reflexivity; auto.
rw @isprogram_exception_iff; auto. }
{ apply reduces_to_if_step.
csunf; simpl; dcwf h; simpl; auto;[].
allrw @isprogram_pk2can; subst; GC.
repndors; exrepnd; subst;
allunfold @co_wf; allrw @get_param_from_cop_pk2can; ginv.
}
}
{ apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduce_to_prinargs_comp; auto.
allrw @isprogram_pk2can; subst; GC.
repndors; exrepnd; subst;
allunfold @co_wf; allrw @get_param_from_cop_pk2can;
allsimpl; ginv; fold_terms; allrw <- @pk2term_eq; eauto 3 with slow.
}
Qed.
Lemma no_change_after_val_like3 {o} :
forall lib (t : @NTerm o) k1 v1 k2,
reduces_in_atmost_k_steps lib t v1 k1
-> isprogram v1
-> isvalue_like v1
-> k1 <= k2
-> reduces_in_atmost_k_steps lib t v1 k2.
Proof.
introv r isp isv leq.
eapply no_change_after_val_like; eauto.
Qed.
Ltac extensional_ind H k hyp :=
match type of H with
| reduces_in_atmost_k_steps ?lib ?t ?v ?n =>
apply (no_change_after_val_like3 lib t n v k) in H;
auto;
make_red_val_like H hyp
end.
Lemma extensional_cantest {p} : forall a, extensional_op (@NCan p (NCanTest a)).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
applydup @reduces_atmost_preserves_program in Hcv4; auto.
allapply @isprogram_cantest_implies; exrepnd; subst; cpx.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply no_change_after_val_like with (k2:=k) in Hcv3; auto; [].
make_red_val_like Hcv3 h1.
apply (Hi _ _ a2) in h1; auto; prove_isprogram;[].
extensional_ind XX0 k hh.
dorn Hcv0.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst;
csunf XX1; allsimpl; ginv.
{ apply (Hi _ _ (if canonical_form_test_for a c1 then b0 else c0)) in hh;
auto; prove_isprogram;
try (complete (destruct (canonical_form_test_for a c1); auto));
eauto 2 with slow.
apply howe_lemma2 in h1; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := if canonical_form_test_for a c1 then b0 else c0); auto.
apply approx_implies_approx_open.
apply @approx_trans with (b := oterm (NCan (NCanTest a)) [nobnd (oterm (Can c1) lbt'),nobnd b0,nobnd c0]).
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_if_step; reflexivity.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_prinarg; auto; destruct h0; auto.
}
{ apply howe_lemma2_seq in h1; exrepnd; auto.
apply (Hi _ _ c0) in hh; auto.
eapply approx_star_open_trans;[exact hh|clear hh].
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
eapply reduces_to_trans;[apply reduces_to_prinarg;eauto|].
apply reduces_to_if_step.
csunf; simpl; auto.
}
- apply isexc_implies in Hcv0; auto; exrepnd; subst.
csunf XX1; allsimpl; ginv.
apply reduces_atmost_exc in XX0; subst.
apply howe_lemma2_exc in h1; exrepnd; auto; prove_isprogram.
apply @approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply computes_to_exception_implies_approx; auto; prove_isprogram.
allrw @computes_to_exception_as_reduces_to.
apply @reduces_to_trans with (b := oterm (NCan (NCanTest a)) [nobnd (mk_exception a' e'),nobnd b0,nobnd c0]).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
(*
(* !! MOVE to computation4 *)
Lemma computes_to_val_like_in_max_k_steps_primarg_marker {o} :
forall (lib : @library o) k nc mrk l bs v,
computes_to_val_like_in_max_k_steps
lib
(oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs))
v k
-> False.
Proof.
introv h.
unfold computes_to_val_like_in_max_k_steps in h; repnd.
apply reduces_in_atmost_k_steps_primarg_marker in h0; subst.
dorn h; sp.
Qed.
*)
Lemma extensional_sleep {p} : extensional_op (@NCan p NSleep).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @isprogram_sleep_implies in Hprt; exrepnd; subst; cpx.
applydup @isprogram_sleep_implies in Hprt'; exrepnd; subst; cpx.
allrw @fold_sleep.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply computes_to_val_like_in_max_k_steps_sleep_implies in Hcv; exrepnd; cpx.
unfold extensional_op_ind in Hi.
applydup @computes_to_val_like_in_max_k_steps_preserves_program in Hcv2; auto.
apply Hi with (v := t0) in Hcv2; auto; clear Hi.
dorn Hcv1; exrepnd; subst.
- apply howe_lemma2 in Hcv2; auto; prove_isprogram; exrepnd.
unfold approx_starbts, lblift_sub in Hcv2; simpl in Hcv2; repnd; cpx.
allrw @fold_integer.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_sleep (mk_integer z)).
{ apply reduces_to_prinarg; auto.
destruct Hcv1; auto. }
{ apply reduces_to_if_step; reflexivity. }
- apply isexc_implies in Hcv3; auto; exrepnd; subst; GC.
apply howe_lemma2_exc in Hcv2; auto; exrepnd.
apply approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_sleep (mk_exception a' e')).
{ apply reduces_to_prinarg; auto. }
{ apply reduces_to_if_step; reflexivity. }
Qed.
Lemma extensional_tuni {p} : extensional_op (@NCan p NTUni).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @isprogram_tuni_implies in Hprt; exrepnd; subst; cpx.
applydup @isprogram_tuni_implies in Hprt'; exrepnd; subst; cpx.
allrw @fold_tuni.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
apply computes_to_val_like_in_max_k_steps_tuni_implies in Hcv; exrepnd; cpx.
unfold extensional_op_ind in Hi.
applydup @computes_to_val_like_in_max_k_steps_preserves_program in Hcv2; auto.
apply Hi with (v := t0) in Hcv2; auto; clear Hi.
destruct Hcv1 as [Hcv1|Hcv1]; exrepnd; subst.
- apply howe_lemma2 in Hcv2; auto; prove_isprogram; exrepnd.
unfold approx_starbts, lblift_sub in Hcv2; simpl in Hcv2; repnd; cpx.
allrw @fold_integer.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_tuni (mk_integer (Z.of_nat n))).
apply reduces_to_prinarg; auto.
destruct Hcv1; auto.
apply reduces_to_if_step.
csunf; simpl.
unfold compute_step_tuni; simpl.
destruct (Z_le_gt_dec 0 (Z.of_nat n)); try omega.
rw Znat.Nat2Z.id; sp.
- apply isexc_implies in Hcv3; auto; exrepnd; subst; GC.
apply howe_lemma2_exc in Hcv2; auto; exrepnd.
apply approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_tuni (mk_exception a' e')).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma extensional_minus {p} : extensional_op (@NCan p NMinus).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @isprogram_minus_implies in Hprt; exrepnd; subst; cpx.
applydup @isprogram_minus_implies in Hprt'; exrepnd; subst; cpx.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
repeat(approxrelbtd); show_hyps.
allapply @approx_star_bterm_nobnd2.
fold_terms.
allrw @fold_minus.
apply computes_to_val_like_in_max_k_steps_minus_implies in Hcv; exrepnd; cpx.
unfold extensional_op_ind in Hi.
applydup @computes_to_val_like_in_max_k_steps_preserves_program in Hcv2; auto.
apply Hi with (v := t0) in Hcv2; auto; clear Hi.
destruct Hcv1 as [Hcv1|Hcv1]; exrepnd; subst.
- apply howe_lemma2 in Hcv2; auto; prove_isprogram; exrepnd.
unfold approx_starbts, lblift_sub in Hcv2; simpl in Hcv2; repnd; cpx.
allrw @fold_integer.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_minus (mk_integer z)).
apply reduces_to_prinarg; auto.
destruct Hcv1; auto.
apply reduces_to_if_step.
simpl.
unfold compute_step_minus; simpl; auto.
- apply isexc_implies in Hcv3; auto; exrepnd; subst; GC.
apply howe_lemma2_exc in Hcv2; auto; exrepnd.
apply approx_star_open_trans with (b := mk_exception a' e').
apply approx_star_exception; auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_trans with (b := mk_minus (mk_exception a' e')).
apply reduces_to_prinarg; auto.
apply reduces_to_if_step; reflexivity.
Qed.
Lemma approx_star_bterm_numvars {o} :
forall lib op (b1 b2 : @BTerm o),
approx_star_bterm lib op b1 b2
-> num_bvars b1 = num_bvars b2.
Proof.
destruct b1, b2; introv ap.
unfold approx_star_bterm, blift_sub in ap; exrepnd.
inversion ap2; subst.
inversion ap0; subst.
unfold num_bvars; simpl; omega.
Qed.
Lemma approx_starbts_numvars {o} :
forall lib op (bs1 bs2 : list (@BTerm o)),
approx_starbts lib op bs1 bs2
-> map num_bvars bs1 = map num_bvars bs2.
Proof.
induction bs1; destruct bs2; intro ap; allsimpl; auto;
unfold approx_starbts, lblift_sub in ap; repnd; allsimpl; cpx.
pose proof (ap 0) as h; autodimp h hyp; [omega|].
unfold selectbt in h; allsimpl.
apply eq_cons; [ complete (eapply approx_star_bterm_numvars; eauto)|].
apply IHbs1.
unfold approx_starbts, lblift_sub; dands; auto; introv k.
pose proof (ap (S n)) as x; autodimp x hyp; omega.
Qed.
(*
Lemma lblift_approx_star_implies_sub_range_rel {o} :
forall lib (bs1 bs2 : list (@BTerm o)) vars,
lblift (approx_star lib) bs1 bs2
-> sub_range_rel
(approx_star lib)
(mk_abs_subst vars bs1)
(mk_abs_subst vars bs2).
Proof.
induction bs1; destruct bs2; introv ap; allsimpl; auto.
- rw @mk_abs_subst_nil_r; simpl; auto.
- unfold lblift in ap; cpx.
- unfold lblift in ap; cpx.
- destruct vars; simpl; auto.
destruct a as [l1 t1]; destruct b as [l2 t2].
unfold lblift in ap; simpl in ap; repnd; cpx.
pose proof (ap 0) as h; autodimp h hyp; [omega|].
unfold selectbt in h; simpl in h.
unfold blift in h; exrepnd.
inversion h2; inversion h0; subst; allsimpl; cpx; GC.
destruct l1; destruct l2; allsimpl; cpx; GC.
allunfold @var_ren; allsimpl.
allrw @lsubst_nil.
dands; eauto with slow.
apply IHbs1.
unfold lblift; dands; auto; introv k.
pose proof (ap (S n0)) as x; autodimp x hyp; omega.
Qed.
*)
(*
Inductive so_approx_star {o} :
@library o -> @SOTerm o -> @SOTerm o -> [univ] :=
| soapsv:
forall lib v t2,
so_approx_open lib (sovar v ts1) t2
-> so_approx_star lib (sovar v ts2) t2
| soapso:
forall lib
(op : Opid) (t2: NTerm)
(lbt1 lbt1' : list BTerm),
length lbt1 = length lbt1'
-> lblift (approx_star lib) lbt1 lbt1'
-> approx_open lib (oterm op lbt1') t2
-> approx_star lib (oterm op lbt1) t2.
*)
(* ====================================== *)
Definition approx_star_sk {o} lib op (sk1 sk2 : @sosub_kind o) :=
approx_star_bterm lib op (sk2bterm sk1) (sk2bterm sk2).
Lemma approx_star_sk_if_approx_star_sosub_find {o} :
forall lib op (vs : list NVar) (sks1 sks2 : list (@sosub_kind o)) (sk1 sk2 : sosub_kind) (sv : sovar_sig),
length vs = length sks1
-> length vs = length sks2
-> bin_rel_sk (approx_star_sk lib op) sks1 sks2
-> sosub_find (combine vs sks1) sv = Some sk1
-> sosub_find (combine vs sks2) sv = Some sk2
-> approx_star_sk lib op sk1 sk2.
Proof.
induction vs; introv len1 len2 aeq f1 f2; allsimpl; cpx.
destruct sks1, sks2; allsimpl; cpx.
apply binrel_list_cons in aeq; repnd.
destruct s, s0; boolvar; cpx.
- provefalse.
unfold approx_star_sk in aeq; simpl in aeq.
inversion aeq as [nvs h]; exrepnd.
inversion h1; inversion h2; subst.
destruct n1; f_equal; omega.
- provefalse.
unfold approx_star_sk in aeq; simpl in aeq.
inversion aeq as [nvs h]; exrepnd.
inversion h1; inversion h2; subst.
destruct n1; f_equal; omega.
- apply (IHvs sks1 sks2 sk1 sk2 sv); auto.
Qed.
Lemma approx_star_sk_is_approx_star_bterm {o} :
forall lib op (b1 b2 : @BTerm o),
approx_star_bterm lib op b1 b2
<=> approx_star_sk lib op (bterm2sk b1) (bterm2sk b2).
Proof.
introv.
unfold approx_star_sk; simpl.
destruct b1, b2; simpl; sp.
Qed.
Lemma false_if_approx_star_sk_sosub_find {o} :
forall lib op (vs : list NVar) (sks1 sks2 : list (@sosub_kind o)) (sk : sosub_kind) (sv : sovar_sig),
length vs = length sks1
-> length vs = length sks2
-> bin_rel_sk (approx_star_sk lib op) sks1 sks2
-> sosub_find (combine vs sks1) sv = Some sk
-> sosub_find (combine vs sks2) sv = None
-> False.
Proof.
induction vs; introv len1 len2 aeq f1 f2; allsimpl; cpx.
destruct sks1; destruct sks2; allsimpl; cpx.
destruct s, s0; boolvar; cpx;
apply binrel_list_cons in aeq; repnd.
- unfold approx_star_sk in aeq; simpl in aeq;
inversion aeq as [nvs h]; exrepnd;
inversion h1; inversion h2; subst;
destruct n1; f_equal; try omega.
- eapply IHvs in f1; eauto.
Qed.
Lemma false_if_approx_star_sk_sosub_find2 {o} :
forall lib op (vs : list NVar) (sks1 sks2 : list (@sosub_kind o)) (sk : sosub_kind) (sv : sovar_sig),
length vs = length sks1
-> length vs = length sks2
-> bin_rel_sk (approx_star_sk lib op) sks1 sks2
-> sosub_find (combine vs sks1) sv = None
-> sosub_find (combine vs sks2) sv = Some sk
-> False.
Proof.
induction vs; introv len1 len2 aeq f1 f2; allsimpl; cpx.
destruct sks1; destruct sks2; allsimpl; cpx.
destruct s, s0; boolvar; cpx;
apply binrel_list_cons in aeq; repnd.
- unfold approx_star_sk in aeq; simpl in aeq;
inversion aeq as [nvs h]; exrepnd;
inversion h1; inversion h2; subst;
destruct n1; f_equal; try omega.
- eapply IHvs in f1; eauto.
Qed.
Lemma approx_star_apply_list {o} :
forall lib ts1 ts2 (t1 t2 : @NTerm o),
approx_star lib t1 t2
-> bin_rel_nterm (approx_star lib) ts1 ts2
-> approx_star lib (apply_list t1 ts1) (apply_list t2 ts2).
Proof.
induction ts1; introv ap brel; destruct ts2; allsimpl; tcsp.
- unfold bin_rel_nterm, binrel_list in brel; repnd; allsimpl; cpx.
- unfold bin_rel_nterm, binrel_list in brel; repnd; allsimpl; cpx.
- apply binrel_list_cons in brel; repnd.
apply IHts1; auto.
apply approx_star_congruence; auto.
unfold approx_starbts, lblift_sub; simpl; dands; auto.
introv k.
destruct n0.
+ unfold selectbt; simpl; auto.
apply blift_sub_nobnd_congr; auto.
+ destruct n0; try omega.
unfold selectbt; simpl; auto.
apply blift_sub_nobnd_congr; auto.
Qed.
Lemma sosub_filter_if_approx_star_sk {o} :
forall lib op vs (sks1 sks2 : list (@sosub_kind o)) (l : list sovar_sig),
length vs = length sks1
-> length vs = length sks2
-> bin_rel_sk (approx_star_sk lib op) sks1 sks2
-> {vs' : list NVar
& {sks1' : list sosub_kind
& {sks2' : list sosub_kind
& sosub_filter (combine vs sks1) l = combine vs' sks1'
# sosub_filter (combine vs sks2) l = combine vs' sks2'
# bin_rel_sk (approx_star_sk lib op) sks1' sks2'
# subset (combine sks1' sks2') (combine sks1 sks2)
# subset vs' vs
# subset sks1' sks1
# subset sks2' sks2
# length vs' = length sks1'
# length vs' = length sks2'
# sodom (combine vs' sks1') = remove_so_vars l (sodom (combine vs sks1))
# sodom (combine vs' sks2') = remove_so_vars l (sodom (combine vs sks2)) }}}.
Proof.
induction vs; destruct sks1, sks2; introv len1 len2 ap; allsimpl; cpx.
- exists ([] : list NVar) ([] : list (@sosub_kind o)) ([] : list (@sosub_kind o));
sp; rw remove_so_vars_nil_r; rw combine_nil; sp.
- destruct s, s0; boolvar; tcsp.
+ apply binrel_list_cons in ap; repnd.
pose proof (IHvs sks1 sks2 l len1 len2 ap0) as h; exrepd.
exists vs' sks1' sks2'; dands; auto;
try (complete (apply subset_cons1; auto));
try (complete (rw remove_so_vars_cons_r; boolvar; tcsp)).
+ provefalse.
apply binrel_list_cons in ap; repnd.
inversion ap as [nvs h]; exrepnd; allsimpl.
inversion h1; subst.
inversion h2; subst.
assert (length l1 = length l0) as x by omega.
rw x in n1; sp.
+ provefalse.
apply binrel_list_cons in ap; repnd.
inversion ap as [nvs h]; exrepnd; allsimpl.
inversion h1; subst.
inversion h2; subst.
assert (length l1 = length l0) as x by omega.
rw x in l2; sp.
+ apply binrel_list_cons in ap; repnd.
pose proof (IHvs sks1 sks2 l len1 len2 ap0) as h; exrepd.
exists (a :: vs') (sosk l0 n :: sks1') (sosk l1 n0 :: sks2');
simpl; dands; tcsp;
try (complete (apply eq_cons; auto));
try (complete (apply subset_cons2; auto));
try (complete (rw remove_so_vars_cons_r; boolvar; tcsp; apply eq_cons; auto)).
apply binrel_list_cons; sp.
Qed.
(*
Lemma sosub_aux_approx_star_congr {p} :
forall lib opr (t : @SOTerm p) (vs : list NVar) (ts1 ts2 : list sosub_kind),
let sub1 := combine vs ts1 in
let sub2 := combine vs ts2 in
wf_soterm t
-> length vs = length ts1
-> length vs = length ts2
-> disjoint (free_vars_sosub sub1) (fo_bound_vars t)
-> disjoint (free_vars_sosub sub2) (fo_bound_vars t)
(* These 2 disjoints we can always assume because they are ensured by sosub *)
-> disjoint (bound_vars_sosub sub1) (free_vars_sosub sub1 ++ fovars t)
-> disjoint (bound_vars_sosub sub2) (free_vars_sosub sub2 ++ fovars t)
-> cover_so_vars t sub1
-> cover_so_vars t sub2
-> bin_rel_sk (approx_star_sk lib opr) ts1 ts2
-> approx_star lib (sosub_aux sub1 t) (sosub_aux sub2 t).
Proof.
soterm_ind1s t as [v ts ind|op lbt ind] Case; simpl;
introv wf len1 len2 d1 d2 d3 d4 cov1 cov2 ask.
- Case "sovar".
remember (sosub_find (combine vs ts1) (v, length ts)) as o;
destruct o; symmetry in Heqo;
remember (sosub_find (combine vs ts2) (v, length ts)) as q;
destruct q; symmetry in Heqq;
try (destruct s); try (destruct s0).
+ pose proof (apply_bterm_approx_star_congr
lib opr (bterm l n) (bterm l0 n0)
(map (sosub_aux (combine vs ts1)) ts)
(map (sosub_aux (combine vs ts2)) ts)
) as h.
repeat (autodimp h hyp).
* apply approx_star_sk_is_approx_star_bterm; simpl.
eapply approx_star_sk_if_approx_star_sosub_find;
[|idtac|exact ask|exact Heqo|exact Heqq]; auto.
* unfold bin_rel_nterm, binrel_list; allrw map_length; dands; auto.
introv i.
assert (@default_nterm p = sosub_aux (combine vs ts1) default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
assert (@default_nterm p = sosub_aux (combine vs ts2) default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
remember (nth n1 ts default_soterm) as t.
pose proof (nth_in _ n1 ts default_soterm i) as j.
rw <- Heqt in j; clear Heqt.
allrw disjoint_app_r; repnd.
assert (disjoint (bound_vars_sosub (combine vs ts1))
(flat_map fovars ts))
as disj1 by (boolvar; allrw disjoint_cons_r; sp).
assert (disjoint (bound_vars_sosub (combine vs ts2))
(flat_map fovars ts))
as disj2 by (boolvar; allrw disjoint_cons_r; sp).
allrw @wf_sovar.
apply ind; auto.
{ rw disjoint_flat_map_r in d1; apply d1; auto. }
{ rw disjoint_flat_map_r in d2; apply d2; auto. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj1; sp. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj2; sp. }
{ rw @cover_so_vars_sovar in cov1; sp. }
{ rw @cover_so_vars_sovar in cov2; sp. }
* allrw map_length; unfold num_bvars; simpl; auto.
allapply @sosub_find_some; sp.
* allrw map_length; unfold num_bvars; simpl; auto.
* unfold apply_bterm in h; simpl in h.
applydup @sosub_find_some in Heqo; repnd.
applydup @sosub_find_some in Heqq; repnd.
allrw @cover_so_vars_sovar; repnd.
revert h.
change_to_lsubst_aux4; auto; clear h;
try (complete (allrw disjoint_cons_r; repnd;
rw flat_map_map; unfold compose;
eapply disjoint_bound_vars_prop3; eauto)).
+ eapply false_if_approx_star_sk_sosub_find in Heqo; eauto; sp.
+ eapply false_if_approx_star_sk_sosub_find2 in Heqo; eauto; sp.
+ apply approx_star_apply_list; auto.
* apply approx_star_refl; auto.
* unfold bin_rel_nterm, binrel_list; allrw map_length; dands; auto.
introv i.
assert (@default_nterm p = sosub_aux (combine vs ts1) default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
assert (@default_nterm p = sosub_aux (combine vs ts2) default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
remember (nth n ts default_soterm) as t.
pose proof (nth_in _ n ts default_soterm i) as j.
rw <- Heqt in j; clear Heqt.
rw disjoint_flat_map_r in d1.
rw disjoint_flat_map_r in d2.
allrw disjoint_app_r; repnd.
assert (disjoint (bound_vars_sosub (combine vs ts1))
(flat_map fovars ts))
as disj1 by (boolvar; allrw disjoint_cons_r; sp).
assert (disjoint (bound_vars_sosub (combine vs ts2))
(flat_map fovars ts))
as disj2 by (boolvar; allrw disjoint_cons_r; sp).
allrw @wf_sovar.
apply ind; auto.
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj1; sp. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj2; sp. }
{ rw @cover_so_vars_sovar in cov1; sp. }
{ rw @cover_so_vars_sovar in cov2; sp. }
- Case "soterm".
allrw @wf_soterm_iff; repnd.
apply approx_star_congruence;
[|rw map_map; unfold compose; rw <- wf0;
apply eq_maps; introv k; destruct x;
unfold num_bvars; simpl; auto].
unfold approx_starbts, lblift; allrw map_length; dands; auto.
introv i.
unfold selectbt.
assert (@default_bt p = sosub_b_aux (combine vs ts1) default_sobterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_bt p).
assert (@default_bt p = sosub_b_aux (combine vs ts2) default_sobterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_bt p).
remember (nth n lbt default_sobterm) as bt.
pose proof (nth_in _ n lbt default_sobterm i) as j.
rw <- Heqbt in j; clear Heqbt.
rw disjoint_flat_map_r in d1.
rw disjoint_flat_map_r in d2.
allrw disjoint_app_r; repnd.
destruct bt; simpl.
pose proof (sosub_filter_if_approx_star_sk lib vs ts1 ts2 (vars2sovars l)) as h.
repeat (autodimp h hyp); exrepnd.
rw h1; rw h2.
unfold blift.
exists l (sosub_aux (combine vs' sks1') s) (sosub_aux (combine vs' sks2') s).
dands; auto.
eapply ind; eauto.
+ applydup d1 in j as k; simpl in k.
rw disjoint_app_r in k; repnd.
rw @free_vars_sosub_combine; auto.
rw @free_vars_sosub_combine in k; auto.
rw disjoint_flat_map_l; introv z.
rw disjoint_flat_map_l in k.
apply h6 in z.
applydup k in z; auto.
+ applydup d2 in j as k; simpl in k.
rw disjoint_app_r in k; repnd.
rw @free_vars_sosub_combine; auto.
rw @free_vars_sosub_combine in k; auto.
rw disjoint_flat_map_l; introv z.
rw disjoint_flat_map_l in k.
apply h7 in z.
applydup k in z; auto.
+ rw disjoint_app_r; dands.
* rw @bound_vars_sosub_combine; auto.
rw @free_vars_sosub_combine; auto.
rw @bound_vars_sosub_combine in d0; auto.
rw @free_vars_sosub_combine in d0; auto.
rw disjoint_flat_map_r; introv z.
rw disjoint_flat_map_l; introv y.
rw disjoint_flat_map_r in d0.
applydup h6 in z.
apply d0 in z0.
rw disjoint_flat_map_l in z0.
applydup h6 in y.
apply z0 in y0; auto.
* rw @bound_vars_sosub_combine; auto.
rw disjoint_flat_map_r in d3.
apply d3 in j; simpl in j; rw disjoint_app_r in j; repnd.
rw @bound_vars_sosub_combine in j; auto.
rw disjoint_flat_map_l in j.
rw disjoint_flat_map_l; introv z.
apply h6 in z.
apply j in z; auto.
+ rw disjoint_app_r; dands.
* rw @bound_vars_sosub_combine; auto.
rw @free_vars_sosub_combine; auto.
rw @bound_vars_sosub_combine in d5; auto.
rw @free_vars_sosub_combine in d5; auto.
rw disjoint_flat_map_r; introv z.
rw disjoint_flat_map_l; introv y.
rw disjoint_flat_map_r in d5.
applydup h7 in z.
apply d5 in z0.
rw disjoint_flat_map_l in z0.
applydup h7 in y.
apply z0 in y0; auto.
* rw @bound_vars_sosub_combine; auto.
rw disjoint_flat_map_r in d4.
apply d4 in j; simpl in j; rw disjoint_app_r in j; repnd.
rw @bound_vars_sosub_combine in j; auto.
rw disjoint_flat_map_l in j.
rw disjoint_flat_map_l; introv z.
apply h7 in z.
apply j in z; auto.
+ unfold cover_so_vars.
rw h10.
rw filter_out_fo_vars_remove_fo_vars; auto.
rw @cover_so_vars_soterm in cov1; eapply cov1; eauto.
+ unfold cover_so_vars.
rw h0.
rw filter_out_fo_vars_remove_fo_vars; auto.
rw @cover_so_vars_soterm in cov2; eapply cov2; eauto.
Qed.
*)
Definition approx_star_sosub {o} lib op (sub1 sub2 : @SOSub o) :=
bin_rel_sk (approx_star_sk lib op) (so_range sub1) (so_range sub2).
Lemma approx_star_sosub_implies_same_length {o} :
forall lib op (sub1 sub2 : @SOSub o),
approx_star_sosub lib op sub1 sub2 -> length sub1 = length sub2.
Proof.
introv ap.
unfold approx_star_sosub, bin_rel_sk, binrel_list in ap; repnd.
allrw @length_so_range; auto.
Qed.
(*
Lemma sosub_aux_approx_star_congr2 {o} :
forall lib (t : @SOTerm o) (sub1 sub2 : @SOSub o),
wf_soterm t
-> sodom sub1 = sodom sub2
-> disjoint (free_vars_sosub sub1) (fo_bound_vars t)
-> disjoint (free_vars_sosub sub2) (fo_bound_vars t)
-> disjoint (bound_vars_sosub sub1) (free_vars_sosub sub1 ++ fovars t)
-> disjoint (bound_vars_sosub sub2) (free_vars_sosub sub2 ++ fovars t)
-> cover_so_vars t sub1
-> cover_so_vars t sub2
-> approx_star_sosub lib sub1 sub2
-> approx_star lib (sosub_aux sub1 t) (sosub_aux sub2 t).
Proof.
introv wf e disj1 disj2 disj3 disj4 cov1 cov2 ap.
pose proof (sosub_aux_approx_star_congr
lib t
(so_dom sub1) (so_range sub1) (so_range sub2)) as h.
allrw <- @sosub_as_combine; allsimpl.
applydup @eq_sodoms_implies_eq_so_doms in e as e'.
repeat (autodimp h hyp).
- rw @length_so_dom; rw @length_so_range; auto.
- rw e'; rw @length_so_dom; rw @length_so_range; auto.
- rw e'; rw <- @sosub_as_combine; auto.
- rw e'; rw <- @sosub_as_combine; auto.
- rw e'; rw <- @sosub_as_combine; auto.
- rw e' in h; rw <- @sosub_as_combine in h; auto.
Qed.
*)
Lemma alphaeq_sosub_kind_if_alphaeq_sosub_find2 {o} :
forall (sub1 sub2 : @SOSub o) (sk1 sk2 : sosub_kind) (sv : sovar_sig),
alphaeq_sosub sub1 sub2
-> sosub_find sub1 sv = Some sk1
-> sosub_find sub2 sv = Some sk2
-> alphaeq_sk sk1 sk2.
Proof.
introv aeq f1 f2.
applydup @alphaeq_sosub_implies_eq_sodoms in aeq as eqdoms.
applydup @eq_sodoms_implies_eq_so_doms in eqdoms as eqdoms'.
apply (alphaeq_sosub_kind_if_alphaeq_sosub_find
(so_dom sub1) (so_range sub1) (so_range sub2) _ _ sv); auto.
- rw @length_so_dom; rw @length_so_range; auto.
- rw eqdoms'; rw @length_so_dom; rw @length_so_range; auto.
- apply alphaeq_sosub_implies_alphaeq_sk; auto.
- rw <- @sosub_as_combine; auto.
- rw eqdoms'; rw <- @sosub_as_combine; auto.
Qed.
Lemma approx_star_sk_if_approx_star_sosub_find2 {o} :
forall lib op (sub1 sub2 : @SOSub o) (sk1 sk2 : sosub_kind) (sv : sovar_sig),
so_dom sub1 = so_dom sub2
-> approx_star_sosub lib op sub1 sub2
-> sosub_find sub1 sv = Some sk1
-> sosub_find sub2 sv = Some sk2
-> approx_star_sk lib op sk1 sk2.
Proof.
introv e ap f1 f2.
applydup @approx_star_sosub_implies_same_length in ap.
apply (approx_star_sk_if_approx_star_sosub_find
lib op (so_dom sub1) (so_range sub1) (so_range sub2) _ _ sv); auto.
- rw @length_so_dom; rw @length_so_range; auto.
- rw @length_so_dom; rw @length_so_range; auto.
- rw <- @sosub_as_combine; auto.
- rw e; rw <- @sosub_as_combine; auto.
Qed.
Lemma false_if_approx_star_sosub_find {o} :
forall lib op (sub1 sub2 : @SOSub o) (sk : sosub_kind) (sv : sovar_sig),
so_dom sub1 = so_dom sub2
-> approx_star_sosub lib op sub1 sub2
-> sosub_find sub1 sv = Some sk
-> sosub_find sub2 sv = None
-> False.
Proof.
introv e ap f1 f2.
pose proof (false_if_approx_star_sk_sosub_find
lib op (so_dom sub1) (so_range sub1) (so_range sub2)
sk sv) as h.
allrw @length_so_dom.
allrw @length_so_range.
applydup @approx_star_sosub_implies_same_length in ap.
repeat (autodimp h hyp).
- rw <- @sosub_as_combine; auto.
- rw e; rw <- @sosub_as_combine; auto.
Qed.
Lemma false_if_approx_star_sosub_find2 {o} :
forall lib op (sub1 sub2 : @SOSub o) (sk : sosub_kind) (sv : sovar_sig),
so_dom sub1 = so_dom sub2
-> approx_star_sosub lib op sub1 sub2
-> sosub_find sub1 sv = None
-> sosub_find sub2 sv = Some sk
-> False.
Proof.
introv e ap f1 f2.
pose proof (false_if_approx_star_sk_sosub_find2
lib op (so_dom sub1) (so_range sub1) (so_range sub2)
sk sv) as h.
allrw @length_so_dom.
allrw @length_so_range.
applydup @approx_star_sosub_implies_same_length in ap.
repeat (autodimp h hyp).
- rw <- @sosub_as_combine; auto.
- rw e; rw <- @sosub_as_combine; auto.
Qed.
Lemma eq_maps_combine :
forall (A B C : tuniv)
(f : A -> B) (g : C -> B)
(la : list A) (lc : list C),
length la = length lc
-> (forall a c, LIn (a,c) (combine la lc) -> f a = g c)
-> map f la = map g lc.
Proof.
induction la; destruct lc; introv len imp; allsimpl; auto; cpx.
f_equal; sp.
Qed.
Lemma num_bvars_sosub_b_aux {o} :
forall (b : @SOBTerm o) sub,
num_bvars (sosub_b_aux sub b) = num_sobvars b.
Proof.
introv.
destruct b; simpl; unfold num_bvars; simpl; auto.
Qed.
Lemma so_alphaeq_vs_implies_eq_num_sobvars {o} :
forall (a b : @SOBTerm o) vs,
so_alphaeqbt_vs vs a b
-> num_sobvars a = num_sobvars b.
Proof.
introv aeq; inversion aeq; subst; simpl; omega.
Qed.
Lemma approx_starbts_map {o} :
forall lib A op (l1 l2 : list A) (f1 f2 : A -> @BTerm o),
length l1 = length l2
-> (forall a1 a2,
LIn (a1,a2) (combine l1 l2)
-> approx_star_bterm lib op (f1 a1) (f2 a2))
-> approx_starbts lib op (map f1 l1) (map f2 l2).
Proof.
induction l1; destruct l2; introv len imp; allsimpl; auto; cpx.
- unfold approx_starbts, lblift_sub; simpl; sp.
- rw @approx_starbts_cons; dands; auto.
Qed.
Lemma filter_out_fo_vars_swap_fo_vars :
forall vs1 vs2 vs,
filter_out_fo_vars (swap_fo_vars (mk_swapping vs1 vs2) vs)
= filter_out_fo_vars vs.
Proof.
induction vs; introv; simpl; auto.
destruct a; destruct n0; simpl; auto.
f_equal; auto.
Qed.
Lemma cover_so_vars_so_swap {o} :
forall (t : @SOTerm o) sub vs1 vs2,
no_repeats vs2
-> disjoint vs1 vs2
-> (cover_so_vars (so_swap (mk_swapping vs1 vs2) t) sub
<=> cover_so_vars t sub).
Proof.
introv norep disj.
unfold cover_so_vars.
rw @so_free_vars_so_swap; auto.
rw filter_out_fo_vars_swap_fo_vars; sp.
Qed.
Lemma cover_so_vars_sosub_filter_vars2sovars {o} :
forall (t : @SOTerm o) sub vs,
cover_so_vars t (sosub_filter sub (vars2sovars vs))
<=> cover_so_vars t sub.
Proof.
introv.
unfold cover_so_vars.
rw @sodom_sosub_filter.
rw filter_out_fo_vars_remove_fo_vars; sp.
Qed.
Lemma sosub_filter_if_not_in_dom {o} :
forall t (sub : @SOSub o) vs,
disjoint (sodom sub) vs
-> sosub_aux (sosub_filter sub vs) t = sosub_aux sub t.
Proof.
soterm_ind t as [v ts ind|op bs ind] Case; introv disj; allsimpl.
- Case "sovar".
destruct (in_deq sovar_sig sovar_sig_dec (v,length ts) vs) as [i|i].
+ rw disjoint_sym in disj; applydup disj in i.
remember (sosub_find (sosub_filter sub vs) (v,length ts)) as f1.
remember (sosub_find sub (v,length ts)) as f2.
symmetry in Heqf1; symmetry in Heqf2.
destruct f1; destruct f2.
* destruct s0.
apply sosub_find_some in Heqf2; repnd.
eapply in_sodom_if in Heqf0; eauto.
rw Heqf2 in Heqf0; sp.
* destruct s.
apply sosub_find_some in Heqf1; repnd.
eapply in_sodom_if in Heqf0; eauto.
rw Heqf1 in Heqf0.
rw @sodom_sosub_filter in Heqf0.
rw in_remove_so_vars in Heqf0; sp.
* destruct s.
apply sosub_find_some in Heqf2; repnd.
eapply in_sodom_if in Heqf0; eauto.
rw Heqf2 in Heqf0; sp.
* f_equal.
apply eq_maps; introv k.
apply ind; auto.
rw disjoint_sym; auto.
+ rw @sosub_find_sosub_filter; auto.
remember (sosub_find sub (v,length ts)) as f; symmetry in Heqf; destruct f.
* destruct s.
f_equal; f_equal.
apply eq_maps; introv k.
apply ind; auto.
* f_equal.
apply eq_maps; introv k.
apply ind; auto.
- Case "soterm".
f_equal.
apply eq_maps; introv i; destruct x as [l t]; simpl.
f_equal.
rw @sosub_filter_swap.
eapply ind; eauto.
rw @sodom_sosub_filter.
introv a b.
rw disjoint_sym in disj; apply disj in b.
allrw in_remove_so_vars; sp.
Qed.
Lemma if_disjoint_sovars2vars :
forall vs1 vs2,
disjoint (sovars2vars vs1) (sovars2vars vs2)
-> disjoint vs1 vs2.
Proof.
introv disj a b.
destruct t.
assert (LIn n (sovars2vars vs1)) as h by (apply in_sovars2vars; eexists; eauto).
apply disj in h.
rw in_sovars2vars in h.
destruct h; eexists; eauto.
Qed.
Lemma sovars2vars_vars2sovars :
forall vs, sovars2vars (vars2sovars vs) = vs.
Proof.
induction vs; simpl; allrw; sp.
Qed.
Lemma sovars2vars_sodom_is_so_dom {o} :
forall (sub : @SOSub o), sovars2vars (sodom sub) = so_dom sub.
Proof.
induction sub; simpl; auto.
destruct a; destruct s; simpl; allrw; sp.
Qed.
Lemma in_0_vars2sovars :
forall v vs, LIn (v, 0) (vars2sovars vs) <=> LIn v vs.
Proof.
introv; rw in_map_iff; split; intro k; exrepnd; allunfold var2sovar; cpx.
eexists; eauto.
Qed.
Lemma implies_disjoint_allvars {o} :
forall (t : @NTerm o) vs,
disjoint (free_vars t) vs
-> disjoint (bound_vars t) vs
-> disjoint (allvars t) vs.
Proof.
introv d1 d2.
apply disjoint_sym; apply disjoint_to_allvars_r.
rw disjoint_app_r; dands; apply disjoint_sym; auto.
Qed.
Lemma sosub_filter_r {o} :
forall (sub : @SOSub o) l1 l2,
sosub_filter (sosub_filter sub l1) l2
= sosub_filter sub (l1 ++ l2).
Proof.
induction sub; introv; simpl; auto.
destruct a; destruct s; simpl; boolvar; allrw in_app_iff; tcsp;
allrw not_over_or; repnd; tcsp; allsimpl; boolvar; tcsp.
rw IHsub; auto.
Qed.
Lemma vars2sovars_app :
forall vs1 vs2,
vars2sovars (vs1 ++ vs2) = vars2sovars vs1 ++ vars2sovars vs2.
Proof.
introv; unfold vars2sovars; rw map_app; auto.
Qed.
Lemma sosub_aux_sosub_filter_so_swap {o} :
forall (t : @SOTerm o) sub vs1 vs2 vs,
disjoint vs1 (free_vars_sosub sub)
-> disjoint vs1 (bound_vars_sosub sub)
-> disjoint vs2 (free_vars_sosub sub)
-> disjoint vs2 (bound_vars_sosub sub)
-> disjoint vs2 (all_fo_vars t)
-> disjoint vs1 vs2
-> disjoint vs vs2
-> no_repeats vs2
-> cover_so_vars t sub
-> subvars vs1 vs
-> length vs1 = length vs2
-> sosub_aux (sosub_filter sub (vars2sovars (swapbvars (mk_swapping vs1 vs2) vs)))
(so_swap (mk_swapping vs1 vs2) t)
= cswap (mk_swapping vs1 vs2)
(sosub_aux (sosub_filter sub (vars2sovars vs)) t).
Proof.
soterm_ind t as [v ts ind|op bs ind] Case;
introv disj1 disj2 disj3 disj4 disj5 disj6 disj7;
introv norep cov sv len; allsimpl.
- Case "sovar".
destruct (in_deq sovar_sig sovar_sig_dec (v,length ts) (vars2sovars vs)) as [i|i].
+ rw in_map_iff in i; exrepnd; destruct a; allsimpl; allunfold var2sovar; cpx.
destruct ts; allsimpl; cpx; GC; boolvar; cpx; GC; allsimpl.
allrw disjoint_singleton_r.
remember (sosub_find (sosub_filter sub (vars2sovars (swapbvars (mk_swapping vs1 vs2) vs)))
(swapvar (mk_swapping vs1 vs2) (nvar n), 0)) as f1.
symmetry in Heqf1; destruct f1.
* destruct s; apply sosub_find_some in Heqf1; repnd.
destruct l; allsimpl; cpx; GC.
apply in_sosub_filter in Heqf0; repnd; allsimpl.
destruct Heqf0.
rw in_map_iff; unfold var2sovar.
exists (swapvar (mk_swapping vs1 vs2) (nvar n)); dands; auto.
apply in_swapbvars; eexists; eauto.
* remember (sosub_find (sosub_filter sub (vars2sovars vs))
(nvar n, 0)) as f2.
symmetry in Heqf2; destruct f2; simpl; auto.
destruct s; apply sosub_find_some in Heqf2; repnd.
destruct l; allsimpl; cpx; GC.
apply in_sosub_filter in Heqf0; allsimpl; repnd.
destruct Heqf0.
rw in_map_iff; unfold var2sovar.
exists (nvar n); sp.
+ rw @sosub_find_sosub_filter; auto.
allrw @cover_so_vars_sovar; repnd.
allrw disjoint_cons_r; repnd.
boolvar.
* destruct ts; allsimpl; cpx; GC.
allrw in_0_vars2sovars.
rw @sosub_find_sosub_filter;
[|rw in_0_vars2sovars;auto; rw in_swapbvars; intro k; exrepnd;
apply swapvars_eq in k0; subst; complete sp].
destruct (in_deq NVar deq_nvar v vs1) as [j|j];
[rw subvars_prop in sv; apply sv in j; complete sp|].
rw swapvar_not_in;auto.
remember (sosub_find sub (v,0)) as f;
symmetry in Heqf; destruct f; allsimpl; auto.
{ destruct s; simpl.
apply sosub_find_some in Heqf; repnd.
destruct l; allsimpl; cpx; GC.
allrw @lsubst_aux_nil.
rw disjoint_flat_map_r in disj1; applydup disj1 in Heqf0 as h1.
rw disjoint_flat_map_r in disj3; applydup disj3 in Heqf0 as h2.
rw disjoint_flat_map_r in disj2; applydup disj2 in Heqf0 as h3.
rw disjoint_flat_map_r in disj4; applydup disj4 in Heqf0 as h4.
allsimpl.
allrw remove_nvars_nil_l.
rw @cswap_trivial; auto; apply implies_disjoint_allvars; eauto with slow. }
{ rw swapvar_not_in; auto. }
* autodimp cov0 hyp;[destruct ts; allsimpl; complete cpx|].
simpl; rw map_length.
rw @sosub_find_sosub_filter;
[|intro k; rw in_map_iff in k; exrepnd; allunfold var2sovar; cpx;
destruct ts; allsimpl; complete cpx].
remember (sosub_find sub (v, length ts)) as f;
symmetry in Heqf; destruct f;[|apply sosub_find_none in Heqf; complete sp].
destruct s; simpl.
allrw map_map; unfold compose.
rw @lsubst_aux_cswap_cswap; auto.
applydup @sosub_find_some in Heqf; repnd.
dup disj1 as d1; dup disj2 as d2; dup disj3 as d3; dup disj4 as d4.
rw disjoint_flat_map_r in disj1.
rw disjoint_flat_map_r in disj2.
rw disjoint_flat_map_r in disj3.
rw disjoint_flat_map_r in disj4.
applydup disj1 in Heqf1 as h1.
applydup disj2 in Heqf1 as h2.
applydup disj3 in Heqf1 as h3.
applydup disj4 in Heqf1 as h4.
allsimpl.
allrw disjoint_app_r; repnd.
assert (disjoint vs1 (free_vars n0))
as k1 by (introv a b; applydup h0 in a; applydup h1 in a;
allrw in_remove_nvars; sp).
assert (disjoint vs2 (free_vars n0))
as k2 by (introv a b; applydup h5 in a; applydup h3 in a;
allrw in_remove_nvars; sp).
rw @cswap_trivial;
try (complete (apply implies_disjoint_allvars; eauto with slow));[].
rw @cswap_sub_combine.
rw (swapbvars_trivial vs1 vs2 l); eauto with slow;[].
f_equal; f_equal.
allrw map_map; unfold compose.
apply eq_maps; introv j.
apply ind; auto.
rw disjoint_flat_map_r in disj0; apply disj0; sp.
- Case "soterm".
f_equal.
allrw map_map; unfold compose.
apply eq_maps; introv i.
destruct x as [l t].
simpl.
f_equal.
allrw @sosub_filter_r.
allrw <- vars2sovars_app.
allrw <- swapbvars_app.
rw disjoint_flat_map_r in disj5.
applydup disj5 in i as j; simpl in j; rw disjoint_app_r in j; repnd.
allrw @cover_so_vars_soterm.
applydup cov in i as c.
eapply ind; eauto.
+ rw disjoint_app_l; dands; eauto with slow.
+ apply subvars_app_weak_l; auto.
Qed.
Lemma subvars_swpbvars :
forall vs vs1 vs2,
subvars vs vs1
-> disjoint vs1 vs2
-> no_repeats vs2
-> length vs1 = length vs2
-> subvars (swapbvars (mk_swapping vs1 vs2) vs) vs2.
Proof.
introv sv disj norep len.
rw subvars_prop; introv i.
rw in_swapbvars in i; exrepnd; subst.
apply swapvar_implies3; auto.
rw subvars_prop in sv; apply sv; auto.
Qed.
Lemma btchange_alpha_cswap {o} :
forall (t : @NTerm o) l1 l2,
length l1 = length l2
-> no_repeats l2
-> disjoint l2 (allvars t)
-> disjoint l1 l2
-> alpha_eq_bterm (bterm l1 t) (bterm l2 (cswap (mk_swapping l1 l2) t)).
Proof.
introv len norep disj1 disj2.
apply alphaeqbt_eq.
pose proof (fresh_vars
(length l1)
(l1 ++ l2 ++ allvars t ++ allvars (cswap (mk_swapping l1 l2) t)))
as fv; exrepnd.
apply (aeqbt [] lvn); auto; try omega.
rw @cswap_cswap.
rw mk_swapping_app; auto.
allrw disjoint_app_r; repnd.
rw @cswap_disj_chain; auto; try omega;
allrw disjoint_app_r; dands; eauto with slow.
apply alphaeq_refl.
Qed.
(*
Lemma approx_star_sk_trans {o} :
forall lib (sk1 sk2 sk3 : @sosub_kind o),
approx_star_sk lib sk1 sk2
-> approx_star_sk lib sk2 sk3
-> approx_star_sk lib sk1 sk3.
Proof.
introv ap1 ap2.
allunfold @approx_star_sk.
destruct sk1, sk2, sk3; allsimpl.
allunfold @approx_star_bterm.
allunfold @blift; exrepnd.
pose proof (fresh_vars
(length l)
(l
++ lv0
++ l0
++ lv
++ l1
++ all_vars n
++ all_vars n0
++ all_vars n1
++ all_vars nt0
++ all_vars nt1
++ all_vars nt2
++ all_vars nt3)) as h; exrepnd.
applydup @alphaeqbt_numbvars in ap5 as len1; unfold num_bvars in len1; simpl in len1.
applydup @alphaeqbt_numbvars in ap4 as len2; unfold num_bvars in len2; simpl in len2.
applydup @alphaeqbt_numbvars in ap3 as len3; unfold num_bvars in len3; simpl in len3.
applydup @alphaeqbt_numbvars in ap0 as len4; unfold num_bvars in len4; simpl in len4.
apply alphaeq_bterm3_if with (lva := []) in ap5.
apply alphaeq_bterm3_if with (lva := []) in ap4.
apply alphaeq_bterm3_if with (lva := []) in ap3.
apply alphaeq_bterm3_if with (lva := []) in ap0.
allrw disjoint_app_r; repnd.
apply (alpha3bt_change_var _ _ _ _ lvn) in ap5; auto;
try (complete (allrw disjoint_app_r; auto)); try omega.
apply alpha_eq_if3 in ap5.
apply (alpha3bt_change_var _ _ _ _ lvn) in ap4; auto;
try (complete (allrw disjoint_app_r; auto)); try omega.
apply alpha_eq_if3 in ap4.
apply (alpha3bt_change_var _ _ _ _ lvn) in ap3; auto;
try (complete (allrw disjoint_app_r; auto)); try omega.
apply alpha_eq_if3 in ap3.
apply (alpha3bt_change_var _ _ _ _ lvn) in ap0; auto;
try (complete (allrw disjoint_app_r; auto)); try omega.
apply alpha_eq_if3 in ap0.
Abort.
*)
Lemma approx_star_sosub_cons {o} :
forall lib op v1 v2 sk1 sk2 (sub1 sub2 : @SOSub o),
approx_star_sosub lib op ((v1,sk1) :: sub1) ((v2,sk2) :: sub2)
<=> (approx_star_sk lib op sk1 sk2 # approx_star_sosub lib op sub1 sub2).
Proof.
introv.
unfold approx_star_sosub, bin_rel_sk, binrel_list; simpl.
allrw @length_so_range.
split; intro k; repnd; dands; auto; cpx.
- pose proof (k 0) as h; autodimp h hyp; omega.
- introv i.
pose proof (k (S n)) as h; autodimp h hyp; omega.
- introv i.
destruct n; cpx.
Qed.
Lemma approx_star_sk_alphaeq_l {o} :
forall lib op (sk1 sk2 sk3 : @sosub_kind o),
approx_star_sk lib op sk1 sk2
-> alphaeq_sk sk2 sk3
-> approx_star_sk lib op sk1 sk3.
Proof.
introv ap aeq.
allunfold @approx_star_sk.
allunfold @alphaeq_sk.
allrw @alphaeqbt_eq.
destruct sk1 as [l1 t1], sk2 as [l2 t2], sk3 as [l3 t3]; allsimpl.
eapply approx_star_bterm_alpha_fun_r; eauto.
Qed.
Lemma approx_star_sk_alphaeq_r {o} :
forall lib op (sk1 sk2 sk3 : @sosub_kind o),
alphaeq_sk sk1 sk2
-> approx_star_sk lib op sk2 sk3
-> approx_star_sk lib op sk1 sk3.
Proof.
introv aeq ap.
allunfold @approx_star_sk.
allunfold @alphaeq_sk.
allrw @alphaeqbt_eq.
destruct sk1 as [l1 t1], sk2 as [l2 t2], sk3 as [l3 t3]; allsimpl.
eapply approx_star_bterm_alpha_fun_l; eauto.
Qed.
Lemma approx_star_sosub_alphaeq_l {o} :
forall lib op (sub1 sub2 sub3 : @SOSub o),
approx_star_sosub lib op sub1 sub2
-> alphaeq_sosub sub2 sub3
-> approx_star_sosub lib op sub1 sub3.
Proof.
induction sub1; destruct sub2; destruct sub3; introv ap aeq; auto;
try (complete (inversion ap; allsimpl; cpx));
try (complete (inversion aeq)).
destruct p; destruct p0; destruct a.
inversion aeq; subst; clear aeq.
apply @approx_star_sosub_cons in ap; repnd.
apply @approx_star_sosub_cons.
dands.
- eapply approx_star_sk_alphaeq_l; eauto.
- eapply IHsub1; eauto.
Qed.
Lemma approx_star_sosub_alphaeq_r {o} :
forall lib op (sub1 sub2 sub3 : @SOSub o),
alphaeq_sosub sub1 sub2
-> approx_star_sosub lib op sub2 sub3
-> approx_star_sosub lib op sub1 sub3.
Proof.
induction sub1; destruct sub2; destruct sub3; introv aeq ap; auto;
try (complete (inversion ap; allsimpl; cpx));
try (complete (inversion aeq)).
destruct p; destruct p0.
inversion aeq; subst; clear aeq.
allapply @approx_star_sosub_cons; repnd.
apply @approx_star_sosub_cons; repnd.
dands.
- eapply approx_star_sk_alphaeq_r; eauto.
- eapply IHsub1; eauto.
Qed.
Lemma so_alphaeq_vs_preserves_wf {o} :
forall (t1 t2 : @SOTerm o) vs,
so_alphaeq_vs vs t1 t2
-> wf_soterm t1
-> wf_soterm t2.
Proof.
soterm_ind1s t1 as [v ts ind|op bs ind] Case; introv aeq wf; allsimpl.
- Case "sovar".
inversion aeq as [? ? ? len imp|]; subst; clear aeq.
allrw @wf_sovar; introv i.
pose proof (combine_in_right _ _ ts2 ts) as h; autodimp h hyp; try omega.
pose proof (h t i) as k; clear h; exrepnd.
applydup in_combine in k0; repnd.
apply imp in k0.
apply ind in k0; auto.
- Case "soterm".
inversion aeq as [|? ? ? len imp]; subst; clear aeq.
allrw @wf_soterm_iff; repnd; dands.
+ rw <- wf0.
apply eq_maps_combine; auto.
introv i.
apply in_combine_swap in i; auto.
apply imp in i.
destruct c as [l1 t1].
destruct a as [l2 t2].
inversion i; subst; simpl; omega.
+ introv i.
pose proof (combine_in_right _ _ bts2 bs) as h; autodimp h hyp; try omega.
pose proof (h (sobterm vs0 t) i) as k; clear h; exrepnd.
applydup in_combine in k0; repnd.
applydup imp in k0 as aeq.
inversion aeq as [? ? ? ? ? len1 len2 disj norep a]; subst; clear aeq.
pose proof (ind t1 (so_swap (mk_swapping vs2 vs1) t1) vs2 k2) as k; clear ind.
autodimp k hyp;[rw @sosize_so_swap; complete auto|].
pose proof (k (so_swap (mk_swapping vs0 vs1) t) vs a) as j; clear k.
autodimp j hyp.
* apply wf_soterm_so_swap; auto.
apply wf in k2; auto.
* apply wf_soterm_so_swap in j; auto.
Qed.
Lemma approx_starbts_implies_approx_star_sosub {o} :
forall lib op (bs1 bs2 : list (@BTerm o)) vars,
approx_starbts lib op bs1 bs2
-> approx_star_sosub lib op (mk_abs_subst vars bs1) (mk_abs_subst vars bs2).
Proof.
induction bs1; destruct bs2; destruct vars; introv ap; allsimpl; auto;
try (complete (inversion ap; allsimpl; cpx)).
- unfold approx_star_sosub, bin_rel_sk, binrel_list; simpl; sp.
- destruct s; unfold approx_star_sosub, bin_rel_sk, binrel_list; simpl; sp.
- unfold approx_star_sosub, bin_rel_sk, binrel_list; simpl; sp.
- rw @approx_starbts_cons in ap; repnd.
destruct s; destruct a, b; simpl; boolvar; simpl; tcsp.
+ apply approx_star_sosub_cons; dands; auto.
+ inversion ap0 as [vs x]; exrepnd.
inversion x2; subst.
inversion x1; subst.
provefalse.
destruct n3; omega.
+ inversion ap0 as [vs x]; exrepnd.
inversion x2; subst.
inversion x1; subst.
provefalse.
destruct n3; omega.
+ unfold approx_star_sosub, bin_rel_sk, binrel_list; simpl; sp.
Qed.
Lemma sosub_aux_approx_star_congr_al {p} :
forall lib (t1 t2 : @SOTerm p) (sub1 sub2 : SOSub) opr,
wf_soterm t1
-> wf_soterm t2
-> so_alphaeq t1 t2
-> sodom sub1 = sodom sub2
-> disjoint (free_vars_sosub sub1) (fo_bound_vars t1)
-> disjoint (free_vars_sosub sub2) (fo_bound_vars t2)
(* These 2 disjoints we can always assume because they are ensured by sosub *)
-> disjoint (bound_vars_sosub sub1) (free_vars_sosub sub1 ++ fovars t1)
-> disjoint (bound_vars_sosub sub2) (free_vars_sosub sub2 ++ fovars t2)
-> cover_so_vars t1 sub1
-> cover_so_vars t2 sub2
-> opr <> NCan NFresh
-> approx_star_sosub lib opr sub1 sub2
-> approx_star lib (sosub_aux sub1 t1) (sosub_aux sub2 t2).
Proof.
soterm_ind1s t1 as [v ts ind|op lbt ind] Case; simpl;
introv wf1 wf2 aeq eqdoms d1 d2 d3 d4 cov1 cov2; introv d ap.
- Case "sovar".
applydup @eq_sodoms_implies_eq_so_doms in eqdoms as eqdoms'.
inversion aeq as [? ? ? len imp|]; subst; clear aeq; allsimpl.
remember (sosub_find sub1 (v, length ts)) as o;
destruct o; symmetry in Heqo;
remember (sosub_find sub2 (v, length ts2)) as q;
destruct q; symmetry in Heqq;
try (destruct s); try (destruct s0).
+ pose proof (apply_bterm_approx_star_congr
lib opr (bterm l n) (bterm l0 n0)
(map (sosub_aux sub1) ts)
(map (sosub_aux sub2) ts2)
) as h.
repeat (autodimp h hyp); try (complete (intro xxx; ginv)).
* apply approx_star_sk_is_approx_star_bterm; simpl.
rw <- len in Heqq.
eapply approx_star_sk_if_approx_star_sosub_find2;
[exact eqdoms'|exact ap|exact Heqo|exact Heqq].
* unfold bin_rel_nterm, binrel_list; allrw map_length; dands; auto.
introv i.
assert (@default_nterm p = sosub_aux sub1 default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
assert (@default_nterm p = sosub_aux sub2 default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
remember (nth n1 ts default_soterm) as t1.
pose proof (nth_in _ n1 ts default_soterm i) as j1.
remember (nth n1 ts2 default_soterm) as t2.
dup i as i'; rw len in i'.
pose proof (nth_in _ n1 ts2 default_soterm i') as j2.
pose proof (imp t1 t2) as a;
autodimp a hyp;[subst; apply in_nth_combine; complete auto|].
rw <- Heqt1 in j1; clear Heqt1.
rw <- Heqt2 in j2; clear Heqt2.
allrw disjoint_app_r; repnd.
assert (disjoint (bound_vars_sosub sub1) (flat_map fovars ts))
as disj1 by (boolvar; allrw disjoint_cons_r; sp).
assert (disjoint (bound_vars_sosub sub2) (flat_map fovars ts2))
as disj2 by (boolvar; allrw disjoint_cons_r; sp).
allrw @wf_sovar.
eapply ind; eauto.
{ rw disjoint_flat_map_r in d1; apply d1; auto. }
{ rw disjoint_flat_map_r in d2; apply d2; auto. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj1; sp. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj2; sp. }
{ rw @cover_so_vars_sovar in cov1; sp. }
{ rw @cover_so_vars_sovar in cov2; sp. }
* allrw map_length; unfold num_bvars; simpl; auto.
allapply @sosub_find_some; sp.
* allrw map_length; unfold num_bvars; simpl; auto.
* unfold apply_bterm in h; simpl in h.
applydup @sosub_find_some in Heqo; repnd.
applydup @sosub_find_some in Heqq; repnd.
allrw @cover_so_vars_sovar; repnd.
revert h.
change_to_lsubst_aux4; auto; clear h;
try (complete (allrw disjoint_cons_r; repnd;
rw flat_map_map; unfold compose;
eapply disjoint_bound_vars_prop3; eauto)).
+ rw len in Heqo.
eapply false_if_approx_star_sosub_find in Heqo; eauto; sp.
+ rw len in Heqo.
eapply false_if_approx_star_sosub_find2 in Heqo; eauto; sp.
+ apply approx_star_apply_list; auto.
* apply approx_star_refl; auto.
* unfold bin_rel_nterm, binrel_list; allrw map_length; dands; auto.
introv i.
assert (@default_nterm p = sosub_aux sub1 default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
assert (@default_nterm p = sosub_aux sub2 default_soterm)
as e by auto.
rw e; rw map_nth; simpl; clear e; fold (@mk_axiom p); fold (@default_nterm p).
remember (nth n ts default_soterm) as t1.
remember (nth n ts2 default_soterm) as t2.
dup i as i'; rw len in i'.
pose proof (nth_in _ n ts default_soterm i) as j1.
pose proof (nth_in _ n ts2 default_soterm i') as j2.
pose proof (imp t1 t2) as a;
autodimp a hyp;[subst; apply in_nth_combine; complete auto|].
rw <- Heqt1 in j1; clear Heqt1.
rw <- Heqt2 in j2; clear Heqt2.
rw disjoint_flat_map_r in d1.
rw disjoint_flat_map_r in d2.
allrw disjoint_app_r; repnd.
assert (disjoint (bound_vars_sosub sub1) (flat_map fovars ts))
as disj1 by (boolvar; allrw disjoint_cons_r; sp).
assert (disjoint (bound_vars_sosub sub2) (flat_map fovars ts2))
as disj2 by (boolvar; allrw disjoint_cons_r; sp).
allrw @wf_sovar.
eapply ind; eauto.
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj1; sp. }
{ rw disjoint_app_r; dands; auto.
rw disjoint_flat_map_r in disj2; sp. }
{ rw @cover_so_vars_sovar in cov1; sp. }
{ rw @cover_so_vars_sovar in cov2; sp. }
- Case "soterm".
applydup @eq_sodoms_implies_eq_so_doms in eqdoms as eqdoms'.
inversion aeq as [|? ? ? len imp]; subst; clear aeq; allsimpl.
allrw disjoint_app_r; repnd.
allrw @wf_soterm_iff; repnd.
allrw @cover_so_vars_soterm.
apply approx_star_congruence;
[|rw map_map; unfold compose; rw <- wf0;
apply eq_maps_combine; auto; introv i;
apply in_combine_swap in i; auto;
apply imp in i;
rw @num_bvars_sosub_b_aux;
apply so_alphaeq_vs_implies_eq_num_sobvars in i; auto].
apply approx_starbts_map; auto.
introv i.
applydup imp in i as a.
destruct a1 as [l1 t1].
destruct a2 as [l2 t2].
applydup in_combine in i; repnd.
applydup wf1 in i1.
applydup wf2 in i0.
simpl.
apply (so_alphaeqbt_vs_implies_more
_ _ _ (free_vars_sosub sub1
++ so_dom sub1
++ so_dom sub2
++ free_vars_sosub sub2
++ bound_vars_sosub sub1
++ bound_vars_sosub sub2
++ allvars (sosub_aux (sosub_filter sub1 (vars2sovars l1)) t1)
++ allvars (sosub_aux (sosub_filter sub2 (vars2sovars l2)) t2)
)) in a; auto.
inversion a as [? ? ? u1 u2 len1 len2 disj norep ae]; subst; allsimpl; clear a.
apply so_alphaeq_vs_iff in ae.
allrw disjoint_app_r; repnd.
unfold approx_star_bterm, blift_sub.
exists vs
(sosub_aux sub1 (so_swap (mk_swapping l1 vs) t1))
(sosub_aux sub2 (so_swap (mk_swapping l2 vs) t2)).
dands; auto.
+ pose proof (ind t1 (so_swap (mk_swapping l1 vs) t1) l1) as h; clear ind.
rw @sosize_so_swap in h; auto.
repeat (autodimp h hyp).
pose proof (h (so_swap (mk_swapping l2 vs) t2) sub1 sub2 opr) as k; clear h.
allrw <- @wf_soterm_so_swap.
repeat (autodimp k hyp).
{ rw @fo_bound_var_so_swap.
rw disjoint_flat_map_r in d1; applydup d1 in i1 as k; simpl in k.
allrw disjoint_app_r; repnd.
apply disjoint_swapbvars; eauto with slow. }
{ rw @fo_bound_var_so_swap.
rw disjoint_flat_map_r in d2; applydup d2 in i0 as k; simpl in k.
allrw disjoint_app_r; repnd.
apply disjoint_swapbvars; eauto with slow. }
{ rw @fovars_so_swap.
rw disjoint_app_r; dands; auto.
apply disjoint_swapbvars; eauto 3 with slow.
{ rw disjoint_flat_map_r in d3; applydup d3 in i1 as k; simpl in k.
allrw disjoint_app_r; repnd; auto. }
{ rw disjoint_flat_map_r in d3; applydup d3 in i1 as k; simpl in k.
allrw disjoint_app_r; repnd; auto. }
}
{ rw @fovars_so_swap.
rw disjoint_app_r; dands; auto.
apply disjoint_swapbvars; eauto 3 with slow.
{ rw disjoint_flat_map_r in d4; applydup d4 in i0 as k; simpl in k.
allrw disjoint_app_r; repnd; auto. }
{ rw disjoint_flat_map_r in d4; applydup d4 in i0 as k; simpl in k.
allrw disjoint_app_r; repnd; auto. }
}
{ apply cover_so_vars_so_swap; eauto with slow. }
{ apply cover_so_vars_so_swap; eauto with slow. }
destruct (dec_op_eq_fresh op) as [df|df]; tcsp.
{
right.
pose proof (exists_nrut_sub
vs
(get_utokens (sosub_aux sub1 (so_swap (mk_swapping l1 vs) t1))
++
get_utokens (sosub_aux sub2 (so_swap (mk_swapping l2 vs) t2))))
as exnrut; exrepnd.
exists sub; dands; auto.
apply lsubst_approx_star_congr3; eauto with slow.
}
+ rw disjoint_flat_map_r in d1; applydup d1 in i1 as k; simpl in k.
rw disjoint_flat_map_r in d2; applydup d2 in i0 as j; simpl in j.
rw disjoint_flat_map_r in d3; applydup d3 in i1 as m; simpl in m.
rw disjoint_flat_map_r in d4; applydup d4 in i0 as n; simpl in n.
allrw disjoint_app_r; repnd; auto.
pose proof (subvars_swpbvars l1 l1 vs) as sv;
repeat (autodimp sv hyp); eauto 3 with slow;[].
pose proof (sosub_filter_if_not_in_dom
(so_swap (mk_swapping l1 vs) t1)
sub1
(vars2sovars (swapbvars (mk_swapping l1 vs) l1))) as h.
autodimp h hyp;
[apply if_disjoint_sovars2vars;
rw sovars2vars_vars2sovars;
rw @sovars2vars_sodom_is_so_dom; eauto with slow|].
rw <- h; clear h.
pose proof (sosub_aux_sosub_filter_so_swap
t1 sub1 l1 vs l1) as h;
repeat (autodimp h hyp); eauto 3 with slow;[].
rw h; clear h.
pose proof (btchange_alpha_cswap
(sosub_aux (sosub_filter sub1 (vars2sovars l1)) t1)
l1 vs) as e; repeat (autodimp e hyp); eauto 3 with slow.
+ rw disjoint_flat_map_r in d1; applydup d1 in i1 as k; simpl in k.
rw disjoint_flat_map_r in d2; applydup d2 in i0 as j; simpl in j.
rw disjoint_flat_map_r in d3; applydup d3 in i1 as m; simpl in m.
rw disjoint_flat_map_r in d4; applydup d4 in i0 as n; simpl in n.
allrw disjoint_app_r; repnd; auto.
pose proof (subvars_swpbvars l2 l2 vs) as sv;
repeat (autodimp sv hyp); eauto 3 with slow;[].
pose proof (sosub_filter_if_not_in_dom
(so_swap (mk_swapping l2 vs) t2)
sub2
(vars2sovars (swapbvars (mk_swapping l2 vs) l2))) as h.
autodimp h hyp;
[apply if_disjoint_sovars2vars;
rw sovars2vars_vars2sovars;
rw @sovars2vars_sodom_is_so_dom; eauto with slow|].
rw <- h; clear h.
pose proof (sosub_aux_sosub_filter_so_swap
t2 sub2 l2 vs l2) as h;
repeat (autodimp h hyp); eauto 3 with slow;[].
rw h; clear h.
pose proof (btchange_alpha_cswap
(sosub_aux (sosub_filter sub2 (vars2sovars l2)) t2)
l2 vs) as e; repeat (autodimp e hyp); eauto 3 with slow.
Qed.
Lemma sosub_approx_star_congr {p} :
forall (lib : library)
(opr : Opid)
(t : @SOTerm p)
(sub1 sub2 : SOSub),
wf_soterm t
-> sodom sub1 = sodom sub2
-> cover_so_vars t sub1
-> cover_so_vars t sub2
-> opr <> NCan NFresh
-> approx_star_sosub lib opr sub1 sub2
-> approx_star lib (sosub sub1 t) (sosub sub2 t).
Proof.
introv wf len cov1 cov2 d ap.
pose proof (fovars_subvars_all_fo_vars t) as sv.
pose proof (unfold_sosub sub1 t) as h; exrepnd.
rw h1; clear h1.
pose proof (unfold_sosub sub2 t) as k; exrepnd.
rw k1; clear k1.
applydup @alphaeq_sosub_implies_eq_sodoms in h0 as eqdoms1.
applydup @alphaeq_sosub_implies_eq_sodoms in k0 as eqdoms2.
pose proof (fovars_subvars_all_fo_vars t') as sv1.
pose proof (fovars_subvars_all_fo_vars t'0) as sv2.
pose proof (cover_so_vars_if_so_alphaeq t t' sub1 cov1 h2) as cov3; auto.
pose proof (cover_so_vars_if_alphaeq_sosub t' sub1 sub' cov3 h0) as cov4; auto.
pose proof (cover_so_vars_if_so_alphaeq t t'0 sub2 cov2 k2) as cov5; auto.
pose proof (cover_so_vars_if_alphaeq_sosub t'0 sub2 sub'0 cov5 k0) as cov6; auto.
eapply sosub_aux_approx_star_congr_al; eauto 3 with slow.
- apply so_alphaeq_vs_preserves_wf in h2; auto.
- apply so_alphaeq_vs_preserves_wf in k2; auto.
- allrw <-; auto.
- rw disjoint_app_r; dands; eauto with slow.
- rw disjoint_app_r; dands; eauto with slow.
- eapply approx_star_sosub_alphaeq_r;[apply alphaeq_sosub_sym;exact h0|].
eapply approx_star_sosub_alphaeq_l;[|exact k0];auto.
Qed.
Lemma mk_instance_approx_star_congr {p} :
forall (lib : library)
(opr : @Opid p)
(t : @SOTerm p)
(vars : list sovar_sig)
(bs1 bs2 : list BTerm),
wf_soterm t
-> socovered t vars
-> matching_bterms vars bs1
-> matching_bterms vars bs2
-> opr <> NCan NFresh
-> approx_starbts lib opr bs1 bs2
-> approx_star lib (mk_instance vars bs1 t) (mk_instance vars bs2 t).
Proof.
introv wf cov m1 m2 d ap.
unfold mk_instance.
eapply sosub_approx_star_congr; eauto.
- rw <- @mk_abs_subst_some_prop2; auto.
rw <- @mk_abs_subst_some_prop2; auto.
- apply socovered_implies_cover_so_vars; auto.
- apply socovered_implies_cover_so_vars; auto.
- apply approx_starbts_implies_approx_star_sosub; auto.
Qed.
Lemma nuprl_extensional_abs {p} :
forall x : opabs, @extensional_op p (Abs x).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
allfold (approx_starbts lib).
apply computes_to_val_like_in_max_k_steps_S in Hcv; exrepnd.
csunf Hcv1; allsimpl.
apply compute_step_lib_success in Hcv1; exrepnd; subst.
dup Hcv2 as fe1.
pose proof (approx_starbts_numvars lib (Abs x) lbt lbt' Has) as eqnum.
apply @found_entry_change_bs with (bs2 := lbt') in Hcv2; auto.
rename Hcv2 into fe2.
unfold extensional_op_ind in Hi.
apply Hi with (v := mk_instance vars lbt' rhs) in Hcv0; auto;
[ | complete (eapply isprogram_subst_lib; eauto;
apply isprogram_ot_iff in Hprt; repnd; auto)
| complete (eapply isprogram_subst_lib; eauto;
apply isprogram_ot_iff in Hprt'; repnd; auto)
| ]; clear Hi.
- apply @approx_star_open_trans with (b := mk_instance vars lbt' rhs); auto.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply reduces_to_if_step; simpl.
eapply compute_step_lib_success_change_bs; eauto.
- unfold correct_abs in correct;repnd.
eapply mk_instance_approx_star_congr; eauto; try (complete (intro xxx; ginv)).
+ apply found_entry_implies_matching_entry in fe1.
unfold matching_entry in fe1; sp.
+ apply found_entry_implies_matching_entry in fe2.
unfold matching_entry in fe2; sp.
Qed.
(*
Lemma computes_to_val_or_exc_in_max_k_steps_marker {o} :
forall lib (k : nat) mrk (l : list (@BTerm o)) (v : NTerm),
computes_to_val_or_exc_in_max_k_steps lib (oterm (Mrk mrk) l) v k
-> False.
Proof.
introv comp.
unfold computes_to_val_or_exc_in_max_k_steps in comp; repnd.
apply reduces_in_atmost_k_steps_marker in comp0; subst.
dorn comp; sp.
Qed.
*)
(*
Lemma computes_to_val_like_in_max_k_steps_marker {o} :
forall lib (k : nat) mrk (l : list (@BTerm o)) (v : NTerm),
computes_to_val_like_in_max_k_steps lib (oterm (Mrk mrk) l) v k
-> v = oterm (Mrk mrk) l.
Proof.
induction k; introv comp.
- rw @computes_to_val_like_in_max_k_steps_0 in comp; repnd; auto.
- rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.
simpl in comp1; ginv.
apply IHk in comp0; auto.
Qed.
Lemma nuprl_extensional_mrk {p} :
forall m : marker, @extensional_op p (Mrk m).
Proof.
introv.
unfold extensional_op.
introv isp1 isp2 isp3 comp ap ext.
apply computes_to_val_like_in_max_k_steps_marker in comp; subst.
apply ismrk_implies in isp2; tcsp; exrepnd.
inversion isp0; subst.
apply ismrk_implies in isp3; tcsp; exrepnd.
inversion isp2; subst; fold_terms.
apply (apso _ _ _ [] []); simpl; auto; fold_terms.
apply approx_implies_approx_open.
unfold approx; constructor.
unfold close_comput; dands; auto.
- unfold close_compute_val; introv comp.
unfold computes_to_value in comp; repnd.
apply reduces_to_marker in comp0; tcsp.
inversion comp0.
- unfold close_compute_exc; introv comp.
unfold computes_to_exception in comp; repnd.
apply reduces_to_marker in comp; tcsp.
inversion comp.
- unfold close_compute_mrk; introv comp.
unfold computes_to_marker in comp; repnd.
apply reduces_to_marker in comp; tcsp.
inversion comp; subst.
apply compute_to_marker_mrk.
Qed.
*)
Lemma isprog_vars_iff_isprogram_bt {o} :
forall vs (t : @NTerm o),
isprog_vars vs t <=> isprogram_bt (bterm vs t).
Proof.
introv.
rw @isprog_vars_eq.
unfold isprogram_bt; simpl.
rw @bt_wf_iff.
rw @closed_bt_bterm; sp.
Qed.
Lemma isprog_vars_implies_isprogram_bt {o} :
forall vs (t : @NTerm o),
isprog_vars vs t -> isprogram_bt (bterm vs t).
Proof.
introv isp.
apply isprog_vars_iff_isprogram_bt; auto.
Qed.
Hint Resolve isprog_vars_implies_isprogram_bt : slow.
Lemma alpha_eq_bterm_implies_eq_length {o} :
forall vs1 vs2 (t1 t2 : @NTerm o),
alpha_eq_bterm (bterm vs1 t1) (bterm vs2 t2)
-> length vs1 = length vs2.
Proof.
introv aeq.
inversion aeq; subst; auto.
Qed.
Lemma isprogram_lsubst_aux_implies {o} :
forall (t : @NTerm o) sub,
disjoint_bv_sub t sub
-> isprogram (lsubst_aux t sub)
-> isprogram_bt (bterm (dom_sub sub) t).
Proof.
introv d isp.
apply isprog_vars_iff_isprogram_bt.
apply isprog_vars_eq.
destruct isp as [c w].
apply lsubst_aux_nt_wf in w; dands; auto.
rw subvars_prop; introv i.
unfold closed in c.
rw <- null_iff_nil in c.
unfold null in c.
destruct (in_deq _ deq_nvar x (dom_sub sub)) as [j|j]; auto.
provefalse.
pose proof (c x) as h; destruct h.
pose proof (eqvars_free_vars_disjoint_aux2 t sub d) as h; auto.
rw eqvars_prop in h; apply h; clear h.
rw in_app_iff; rw in_remove_nvars; sp.
Qed.
Lemma isprogram_lsubst_implies {o} :
forall (t : @NTerm o) sub,
isprogram (lsubst t sub)
-> isprogram_bt (bterm (dom_sub sub) t).
Proof.
introv isp.
pose proof (unfold_lsubst sub t) as h; exrepnd; rw h0 in isp.
apply isprogram_lsubst_aux_implies in isp; auto.
- allunfold @isprogram_bt.
allunfold @closed_bt; allsimpl.
applydup @alphaeq_preserves_free_vars in h1 as fv.
rw fv; repnd; dands; auto.
allrw @bt_wf_iff.
apply alphaeq_preserves_wf in h1; apply h1; auto.
- unfold disjoint_bv_sub, sub_range_sat; introv i j k.
apply h2 in k; destruct k.
apply in_sub_free_vars_iff.
exists v t0; dands; auto.
Qed.
Lemma isprogram_subst_implies {o} :
forall (t : @NTerm o) (v : NVar) (a : NTerm),
isprogram (subst t v a)
-> isprogram_bt (bterm [v] t).
Proof.
introv isp.
apply isprogram_lsubst_implies in isp; allsimpl; auto.
Qed.
Definition get_op {o} (t : @NTerm o) : Opid :=
match t with
| vterm _ => Exc
| sterm _ => Exc
| oterm op _ => op
end.
Inductive same_value_like {o} : @NTerm o -> @NTerm o -> Type :=
| svl_c : forall c bs1 bs2, same_value_like (oterm (Can c) bs1) (oterm (Can c) bs2)
| svl_e : forall bs1 bs2, same_value_like (oterm Exc bs1) (oterm Exc bs2)
| svl_s :
forall f1 f2,
(forall n, alpha_eq (f1 n) (f2 n))
-> same_value_like (sterm f1) (sterm f2).
Hint Constructors same_value_like.
Lemma approx_starbts_nil {o} :
forall lib (op : @Opid o), approx_starbts lib op [] [].
Proof.
introv; unfold approx_starbts, lblift_sub; simpl; dands; tcsp.
Qed.
Hint Resolve approx_starbts_nil : slow.
Lemma howe_lemma2_implies_same_value_like {o} :
forall lib (t u : @NTerm o),
isprogram t
-> isprogram u
-> isvalue_like t
-> approx_star lib t u
-> {v : NTerm
& same_value_like t v
# approx_starbts lib (get_op t) (get_bterms t) (get_bterms v)
# reduces_to lib u v}.
Proof.
introv ispt ispu isv ap.
unfold isvalue_like in isv; repndors.
- apply iscan_implies in isv; repndors; exrepnd; subst.
+ pose proof (howe_lemma2 lib c bterms u) as h; simpl in h.
repeat (autodimp h hyp).
exrepnd.
exists (oterm (Can c) lbt'); dands; eauto.
unfold computes_to_value in h0; repnd; auto.
+ apply howe_lemma2_seq in ap; auto; exrepnd.
exists (sterm f'); dands; simpl; eauto 3 with slow; tcsp.
- apply isexc_implies2 in isv; exrepnd; subst.
applydup @isprogram_exception_implies in ispt; exrepnd; subst.
pose proof (howe_lemma2_exc lib a t u) as h; simpl in h.
repeat (autodimp h hyp).
exrepnd.
exists (oterm Exc [bterm [] a', bterm [] e']); simpl; dands; auto.
unfold approx_starbts, lblift_sub; simpl; dands; auto.
introv k; repeat (destruct n; cpx).
+ unfold selectbt; simpl; eauto with slow.
+ unfold selectbt; simpl; eauto with slow.
Qed.
Lemma same_value_like_alpha_eq_r {o} :
forall (t u v : @NTerm o),
same_value_like t u
-> alpha_eq u v
-> same_value_like t v.
Proof.
introv svl aeq.
inversion svl as [| |? ? imp1]; clear svl; subst;
inversion aeq as [|? ? imp2|]; clear aeq; subst; auto.
constructor; introv; eauto 3 with slow.
Qed.
Lemma same_value_like_alpha_eq_l {o} :
forall (t u v : @NTerm o),
same_value_like t u
-> alpha_eq t v
-> same_value_like v u.
Proof.
introv svl aeq.
inversion svl as [| |? ? imp1]; clear svl; subst;
inversion aeq as [|? ? imp2|]; clear aeq; subst; auto.
constructor; introv; eauto 3 with slow.
Qed.
Lemma approx_starbts_get_bterms_alpha_eq {o} :
forall lib op (t u v : @NTerm o),
approx_starbts lib op (get_bterms t) (get_bterms u)
-> alpha_eq u v
-> approx_starbts lib op (get_bterms t) (get_bterms v).
Proof.
introv ap aeq.
destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl; auto;
try (complete (inversion aeq; subst; allsimpl; tcsp)).
- unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.
inversion aeq; subst; allsimpl; cpx; auto.
unfold approx_starbts, lblift_sub; simpl; sp.
- unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.
inversion aeq; subst; allsimpl; cpx; auto.
unfold approx_starbts, lblift_sub; simpl; sp.
- inversion aeq as [|?|? ? ? len imp]; subst; simpl.
allunfold @approx_starbts.
allunfold @lblift_sub; repnd; dands; auto; try omega.
introv i.
pose proof (ap n) as h1; autodimp h1 hyp.
pose proof (imp n) as h2; autodimp h2 hyp; try omega.
eapply approx_star_bterm_alpha_fun_r; eauto.
Qed.
(*
Lemma approx_star_congruence_same_value_like {o} :
forall lib (t u : @NTerm o),
isprogram t
-> isprogram u
-> same_value_like t u
-> approx_starbts lib (get_op t) (get_bterms t) (get_bterms u)
-> approx_star lib t u.
Proof.
introv ispt ispu svl ap.
destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl;
try (complete (apply isprogram_vterm in ispt; sp));
try (complete (apply isprogram_vterm in ispu; sp));
try (complete (inversion svl)).
- apply (apss _ _ _ f2); eauto 3 with slow.
- inversion svl; subst; apply approx_star_congruence3; auto.
Qed.
*)
Lemma closed_axiom {o} :
@closed o mk_axiom.
Proof. sp. Qed.
Hint Resolve closed_axiom : slow.
Lemma alpha_eq_subst_utoken_not_in_implies2 {o} :
forall (t1 t2 : @NTerm o) v a,
!LIn a (get_utokens t1)
-> !LIn a (get_utokens t2)
-> alpha_eq (subst t1 v (mk_utoken a)) (subst t2 v (mk_utoken a))
-> alpha_eq t1 t2.
Proof.
introv ni1 ni2 aeq.
pose proof (change_bvars_alpha_wspec [v] t1) as k1.
pose proof (change_bvars_alpha_wspec [v] t2) as k2.
exrepnd.
allrw disjoint_singleton_l.
pose proof (lsubst_alpha_congr2 ntcv0 t1 [(v,mk_utoken a)]) as p1.
pose proof (lsubst_alpha_congr2 ntcv t2 [(v,mk_utoken a)]) as p2.
autodimp p1 hyp; autodimp p2 hyp; eauto 3 with slow.
allrw @fold_subst.
assert (alpha_eq (subst ntcv0 v (mk_utoken a)) (subst ntcv v (mk_utoken a))) as h' by eauto with slow.
apply alpha_eq_subst_utoken_not_in_implies in h'; eauto with slow.
{ intro j; destruct ni1; apply alphaeq_preserves_utokens in k3; rw k3; auto. }
{ intro j; destruct ni2; apply alphaeq_preserves_utokens in k0; rw k0; auto. }
Qed.
Lemma isprogram_pushdown_fresh {o} :
forall v (t : @NTerm o),
isprogram (pushdown_fresh v t) <=> isprog_vars [v] t.
Proof.
introv; split; intro k.
- destruct k as [c w].
rw @isprog_vars_eq.
apply nt_wf_pushdown_fresh in w; dands; auto.
unfold closed in c.
rw @free_vars_pushdown_fresh in c.
rw subvars_prop; introv i.
rw <- null_iff_nil in c.
rw null_remove_nvars in c; apply c in i; sp.
- rw @isprog_vars_eq in k; repnd.
split; allrw @nt_wf_pushdown_fresh; auto.
unfold closed; rw @free_vars_pushdown_fresh.
rw <- null_iff_nil.
rw null_remove_nvars; introv i.
rw subvars_prop in k0; apply k0; auto.
Qed.
Lemma same_value_like_implies_same_op {o} :
forall op1 op2 (bs1 bs2 : list (@BTerm o)),
same_value_like (oterm op1 bs1) (oterm op2 bs2)
-> op1 = op2.
Proof.
introv s; inversion s; auto.
Qed.
Lemma fresh_id_approx_any {o} :
forall lib (t : @NTerm o) x,
isprogram t
-> approx lib (mk_fresh x (mk_var x)) t.
Proof.
introv Hpr.
apply approx_assume_hasvalue; auto.
{ apply isprogram_fresh; apply isprog_vars_var. }
introv Hv.
unfold hasvalue_like in Hv; exrepnd.
apply (not_fresh_id_reduces_to_is_value_like _ _ x) in Hv1; tcsp.
Qed.
Lemma change_bvars_alpha_norep {o} :
forall (t : @NTerm o) (lv : list NVar),
{u : NTerm
$ disjoint lv (bound_vars u)
# alpha_eq t u
# no_repeats (bound_vars u)}.
Proof.
nterm_ind1s t as [v|f ind|op bs ind] Case; introv.
- Case "vterm".
exists (@mk_var o v); simpl; dands; auto.
- Case "sterm".
exists (sterm f); simpl; dands; eauto 3 with slow.
- Case "oterm".
assert (forall lv, {bs' : list BTerm
$ disjoint lv (bound_vars_bterms bs')
# alpha_eq_bterms bs bs'
# no_repeats (bound_vars_bterms bs') }) as ibs.
{ clear lv; induction bs; introv; allsimpl.
- exists ([] : list (@BTerm o)); simpl; dands; eauto with slow.
- autodimp IHbs hyp.
{ introv i s; eapply ind; eauto. }
pose proof (IHbs lv) as ibs; clear IHbs; exrepnd.
destruct a as [l t].
pose proof (fresh_vars (length l)
(lv ++ l
++ all_vars t
++ bound_vars_bterms bs'))
as fvs; exrepnd.
allrw disjoint_app_r; exrepnd.
pose proof (ind t (lsubst t (var_ren l lvn)) l) as ih; clear ind; repeat (autodimp ih hyp).
{ rw @lsubst_allvars_preserves_osize2; eauto 3 with slow. }
pose proof (ih (lv ++ lvn ++ bound_vars_bterms bs')) as ht; clear ih.
exrepnd.
allrw disjoint_app_l; repnd.
exists (bterm lvn u :: bs'); simpl.
allrw no_repeats_app.
allrw disjoint_app_l; allrw disjoint_app_r.
dands; eauto 3 with slow.
apply alpha_eq_bterms_cons; dands; auto.
eapply alpha_eq_bterm_trans;[|apply alpha_eq_bterm_congr;exact ht2].
apply alpha_bterm_change; auto.
allrw disjoint_app_l; dands; eauto with slow.
}
pose proof (ibs lv) as h; clear ibs; exrepnd.
exists (oterm op bs'); simpl; dands; auto.
apply alpha_eq_oterm_combine; auto.
Qed.
Lemma blift_sub_diff {o} :
forall vs lib op (b1 b2 : @BTerm o),
blift_sub op (approx_star lib) b1 b2
-> {lv : list NVar
$ {nt1,nt2 : NTerm
$ (
(op <> NCan NFresh # approx_star lib nt1 nt2)
[+]
{sub : Sub
& op = NCan NFresh
# approx_star lib (lsubst nt1 sub) (lsubst nt2 sub)
# nrut_sub (get_utokens nt1 ++ get_utokens nt2) sub
# lv = dom_sub sub}
)
# alpha_eq_bterm b1 (bterm lv nt1)
# alpha_eq_bterm b2 (bterm lv nt2)
# disjoint vs lv
# disjoint vs (bound_vars nt1)
# disjoint vs (bound_vars nt2)
# disjoint lv (bound_vars nt1)
# disjoint lv (bound_vars nt2)
# no_repeats lv
# no_repeats (bound_vars nt1)
# no_repeats (bound_vars nt2) }}.
Proof.
introv bl.
unfold blift_sub in bl; exrepnd.
pose proof (alpha_bterm_pair_change b1 b2 lv nt1 nt2 vs) as h.
repeat (autodimp h hyp); exrepnd.
allrw disjoint_app_r; allrw disjoint_app_l; repnd.
pose proof (change_bvars_alpha_norep nt1n (vs ++ lvn)) as ch1; exrepnd.
assert (alpha_eq nt1 u) as h2' by eauto with slow.
assert (alpha_eq_bterm b1 (bterm lvn (lsubst u (var_ren lv lvn)))) as h4'.
{ eapply alpha_eq_bterm_trans;[exact h4|].
apply alpha_eq_bterm_congr.
apply lsubst_alpha_congr2; auto. }
allrw disjoint_app_l; repnd.
rename ch3 into h9'.
rename ch1 into h13'.
clear dependent nt1n.
rename h2' into h2; rename h4' into h4; rename h9' into h9; rename h13' into h13.
rename u into nt1n.
pose proof (change_bvars_alpha_norep nt2n (vs ++ lvn)) as ch'1; exrepnd.
assert (alpha_eq nt2 u) as h3' by eauto with slow.
assert (alpha_eq_bterm b2 (bterm lvn (lsubst u (var_ren lv lvn)))) as h5'.
{ eapply alpha_eq_bterm_trans;[exact h5|].
apply alpha_eq_bterm_congr.
apply lsubst_alpha_congr2; auto. }
allrw disjoint_app_l; repnd.
rename ch'3 into h0'.
rename ch'1 into h7'.
clear dependent nt2n.
rename h3' into h3; rename h5' into h5; rename h7' into h7; rename h0' into h0.
rename u into nt2n.
exists lvn (lsubst nt1n (var_ren lv lvn)) (lsubst nt2n (var_ren lv lvn)).
dands; eauto 3 with slow; try (complete (rw @boundvars_lsubst_vars; auto)).
repndors; exrepnd.
- left; dands; auto.
apply approx_star_lsubst_vars; eauto 3 with slow.
- right.
exists (combine lvn (range sub)); dands; auto.
+ pose proof (lsubst_nest_same_alpha2 nt1n lv lvn (range sub)) as nest1.
allrw @length_dom; allrw @length_range.
repeat (autodimp nest1 hyp); try omega; eauto 3 with slow.
{ subst; allrw @length_dom; auto. }
{ apply alphaeq_preserves_free_vars in h2; rw <- h2.
apply disjoint_remove_nvars_weak_r; auto. }
eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact nest1].
pose proof (lsubst_nest_same_alpha2 nt2n lv lvn (range sub)) as nest2.
allrw @length_dom; allrw @length_range.
repeat (autodimp nest2 hyp); try omega; eauto 3 with slow.
{ subst; allrw @length_dom; auto. }
{ apply alphaeq_preserves_free_vars in h3; rw <- h3.
apply disjoint_remove_nvars_weak_r; auto. }
eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact nest2].
subst.
rw <- @sub_eta; auto.
apply (lsubst_alpha_congr2 _ _ sub) in h2.
apply (lsubst_alpha_congr2 _ _ sub) in h3.
eauto with slow.
+ repeat (rw @get_utokens_lsubst_allvars; eauto with slow).
apply alphaeq_preserves_utokens in h2.
apply alphaeq_preserves_utokens in h3.
rw <- h2; rw <- h3.
eapply nrut_sub_change_sub_same_range;[|exact bl5].
rw @range_combine; auto.
rw @length_range; auto.
subst; allrw @length_dom; auto.
+ rw @dom_sub_combine; auto.
rw @length_range; auto.
subst; allrw @length_dom; auto.
Qed.
Lemma bt_wf_mk_fresh_bterm_if {o} :
forall (b : @BTerm o) v,
bt_wf b
-> bt_wf (mk_fresh_bterm v b).
Proof.
introv wf.
destruct b as [l t]; allsimpl.
allrw @bt_wf_iff.
apply nt_wf_fresh; auto.
Qed.
Lemma alpha_eq_bterm_ren_1side {o} :
forall (t1 t2 : @NTerm o) l1 l2,
disjoint l1 (bound_vars t1)
-> disjoint l1 (bound_vars t2)
-> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)
-> alpha_eq_bterm (bterm l1 t1) (bterm l1 (lsubst t2 (var_ren l2 l1))).
Proof.
introv disj1 disj2 aeq.
inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; subst.
apply (lsubst_alpha_congr2 _ _ (var_ren lv l1)) in a.
allrw disjoint_app_r; repnd.
pose proof (lsubst_nest_vars_same t1 l1 lv l1) as h1.
allrw disjoint_app_l.
repeat (autodimp h1 hyp); dands; eauto 3 with slow.
rw h1 in a.
pose proof (lsubst_nest_vars_same t2 l2 lv l1) as h2.
allrw disjoint_app_l.
repeat (autodimp h2 hyp); dands; try omega; eauto 3 with slow.
rw h2 in a.
pose proof (lsubst_trivial_alpha t1 l1) as h.
eauto with slow.
Qed.
Lemma alpha_eq_bterm_ren_1side2 {o} :
forall (t1 t2 : @NTerm o) l1 l2,
disjoint l1 (bound_vars t1)
-> disjoint l1 (bound_vars t2)
-> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)
-> alpha_eq t1 (lsubst t2 (var_ren l2 l1)).
Proof.
introv disj1 disj2 aeq.
inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; subst.
apply (lsubst_alpha_congr2 _ _ (var_ren lv l1)) in a.
allrw disjoint_app_r; repnd.
pose proof (lsubst_nest_vars_same t1 l1 lv l1) as h1.
allrw disjoint_app_l.
repeat (autodimp h1 hyp); dands; eauto 3 with slow.
rw h1 in a.
pose proof (lsubst_nest_vars_same t2 l2 lv l1) as h2.
allrw disjoint_app_l.
repeat (autodimp h2 hyp); dands; try omega; eauto 3 with slow.
rw h2 in a.
pose proof (lsubst_trivial_alpha t1 l1) as h.
eauto with slow.
Qed.
Lemma alpha_eq_lsubst_aux_pull_out_token {o} :
forall (t : @NTerm o) l sub t',
disjoint (dom_sub sub) (bound_vars t)
-> disjoint (dom_sub sub) (bound_vars t')
-> disjoint (bound_vars t) (bound_vars t')
-> no_repeats (bound_vars t)
-> nrut_sub l sub
-> subset (get_utokens t') l
-> no_repeats (dom_sub sub)
-> wf_term t
-> alpha_eq t (lsubst_aux t' sub)
-> {u : NTerm $ t = lsubst_aux u sub # disjoint (get_utokens u) (get_utokens_sub sub)}.
Proof.
nterm_ind t as [x|f ind|op bs ind] Case;
introv disj1 disj2 disj3 norep nrut ss nrs wf aeq;
allsimpl; GC.
- Case "vterm".
destruct t' as [z|f|op' bs']; allsimpl;
try (complete (inversion aeq)).
remember (sub_find sub z) as sf; symmetry in Heqsf; destruct sf.
+ apply sub_find_some in Heqsf.
eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst; inversion aeq.
+ inversion aeq; subst.
exists (@mk_var o z); simpl; boolvar; tcsp.
rw Heqsf; auto.
- Case "sterm".
exists (sterm f); simpl; dands; auto.
- Case "oterm".
destruct t' as [z|f|op' bs']; allsimpl; try (complete (inversion aeq)).
+ remember (sub_find sub z) as sf; symmetry in Heqsf; destruct sf;
try (complete (inversion aeq)).
apply sub_find_some in Heqsf.
eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst; inversion aeq; subst.
allsimpl; cpx; allsimpl; fold_terms.
pose proof (in_nrut_sub_or l a sub) as ora.
repeat (autodimp ora hyp); repndors; exrepnd.
{ exists (@mk_var o v); simpl; allrw; dands; auto. }
{ exists (mk_utoken a); simpl; auto.
rw disjoint_singleton_l; dands; auto. }
+ allrw @alpha_eq_oterm_combine2; repnd; subst.
allrw map_length.
rw @wf_oterm_iff in wf; repnd.
assert {bs'' : list BTerm
& bs = lsubst_bterms_aux bs'' sub
# disjoint (get_utokens_bs bs'') (get_utokens_sub sub)} as hbs.
{ clear wf0.
revert dependent bs'.
revert dependent bs.
induction bs as [|b bs]; introv ind disj1 norep wf disj2 disj3 ss len imp; allsimpl; cpx; GC.
- exists ([] : list (@BTerm o)); simpl; auto.
- destruct bs' as [|b' bs']; allsimpl; cpx.
allrw in_app_iff; allrw not_over_or; repnd.
allrw no_repeats_app; repnd.
allrw disjoint_app_r; allrw disjoint_app_l; repnd.
repeat (autodimp IHbs hyp).
{ introv i j k; eapply ind; eauto. }
pose proof (IHbs bs') as ih; clear IHbs.
repeat (autodimp ih IHbs); exrepnd.
{ allrw subset_app; repnd; dands; auto. }
pose proof (imp b (lsubst_bterm_aux b' sub)) as h.
repeat (autodimp h hyp).
destruct b as [l1 t1].
destruct b' as [l2 t2].
allsimpl; allrw in_app_iff; allrw not_over_or; repnd.
allrw disjoint_app_l; repnd.
allrw no_repeats_app; repnd.
allrw disjoint_app_r; allrw disjoint_app_l; repnd.
applydup @alpha_eq_bterm_lenbvars in h.
apply alpha_eq_bterm_ren_1side2 in h; auto;
[|introv i j; apply subset_bound_vars_lsubst_aux in j; allsimpl;
allrw in_app_iff; repndors; tcsp;
[apply disj8 in i; sp|];
rw (sub_bound_vars_nrut_sub (sub_filter sub l2) l) in j; allsimpl; tcsp;
complete (eauto with slow)].
pose proof (ind t1 l1) as k; clear ind; autodimp k hyp.
rw @lsubst_lsubst_aux in h;
[|rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_var_ren; auto;
introv i j; apply subset_bound_vars_lsubst_aux in i; allsimpl;
allrw in_app_iff; applydup disj8 in j; repndors; tcsp;
apply subset_sub_bound_vars_sub_filter in i;
erewrite sub_bound_vars_nrut_sub in i; eauto].
rw (sub_filter_disjoint1 sub) in h; eauto 3 with slow.
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj
t2 sub (var_ren l2 l1)) as e.
allsimpl; rw @sub_free_vars_var_ren in e; auto.
rw (sub_bound_vars_nrut_sub sub l) in e; eauto 3 with slow.
rw (sub_free_vars_nrut_sub sub l) in e; eauto 3 with slow.
rw @cl_lsubst_aux_sub_trivial in e; eauto 3 with slow.
repeat (autodimp e hyp); eauto with slow.
rw <- e in h; clear e.
pose proof (k l sub (lsubst_aux t2 (sub_filter (var_ren l2 l1) (dom_sub sub))))
as ih; clear k.
repeat (autodimp ih hyp); eauto 3 with slow.
{ introv i j; apply subset_bound_vars_lsubst_aux in j.
rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.
allrw app_nil_r; apply disj7 in i; sp. }
{ introv i j; apply subset_bound_vars_lsubst_aux in j.
rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.
allrw app_nil_r; apply disj5 in i; sp. }
{ allrw subset_app; repnd; rw @get_utokens_lsubst_aux_allvars; eauto 3 with slow. }
{ pose proof (wf (bterm l1 t1)) as w; autodimp w hyp. }
exrepnd.
exists (bterm l1 u :: bs''); simpl.
allrw disjoint_app_l; dands; eauto 3 with slow.
f_equal; auto.
f_equal; auto.
rw (sub_filter_disjoint1 sub); eauto 3 with slow.
}
exrepnd.
remember (get_utok op') as guo; symmetry in Heqguo; destruct guo.
{ apply get_utok_some in Heqguo; subst; allsimpl.
destruct bs''; allsimpl; cpx; GC; fold_terms.
allrw subset_cons_l; repnd; allsimpl.
exists (mk_utoken g); simpl; fold_terms; rw disjoint_singleton_l; dands; auto.
unfold nrut_sub in nrut; repnd.
apply nrut in ss0; sp.
}
{ exists (oterm op' bs''); simpl; subst.
allrw subset_app; repnd.
allrw disjoint_app_l; dands; eauto 3 with slow.
unfold lsubst_bterms_aux; auto.
destruct op'; allsimpl; tcsp.
destruct c; allsimpl; tcsp.
}
Qed.
Lemma alpha_eq_subst_bterm_aux_pull_out_token {o} :
forall b v a l (t : @NTerm o),
!LIn v l
-> !LIn v (bound_vars t)
-> disjoint l (bound_vars t)
-> no_repeats (bound_vars t)
-> !LIn a (get_utokens_b b)
-> wf_term t
-> alpha_eq_bterm (subst_bterm_aux b v (mk_utoken a)) (bterm l t)
-> {u : NTerm & t = subst u v (mk_utoken a) # !LIn a (get_utokens u)}.
Proof.
introv ni1 ni2 disj1 norep niab wf aeq.
pose proof (ex_change_bvars_bterm_alpha (v :: l ++ bound_vars t) b) as ch; exrepnd.
allrw disjoint_cons_l; allrw disjoint_app_l; repnd.
pose proof (lsubst_aux_alphabt_congr_cl b bt' [(v,mk_utoken a)] [(v,mk_utoken a)]) as aeqb.
repeat (autodimp aeqb hyp); eauto with slow.
eapply alpha_eq_bterm_trans in aeq;[|apply alpha_eq_bterm_sym; exact aeqb].
assert (!LIn a (get_utokens_b bt')) as niabt'.
{ apply alpha_eq_bterm_preserves_utokens in ch0; rw <- ch0; auto. }
clear dependent b; rename bt' into b.
rename ch3 into disj2; rename ch2 into disj3; rename ch1 into ni3; rename niabt' into niab.
destruct b as [l1 u1]; allsimpl.
allrw disjoint_app_r; repnd.
allunfold @subst_bterm_aux; allsimpl; boolvar.
- allrw @lsubst_aux_nil.
exists t.
applydup @alpha_eq_bterm_preserves_utokens in aeq as eu; allsimpl; rw <- eu.
apply alpha_eq_bterm_preserves_free_vars in aeq; allsimpl.
rw @cl_subst_trivial; eauto with slow.
introv i.
assert (LIn v (remove_nvars l (free_vars t))) as j.
{ rw in_remove_nvars; sp. }
rw <- aeq in j.
rw in_remove_nvars in j; sp.
- (* change the l1 into l when inverting aeq *)
apply alpha_eq_bterm_sym in aeq.
applydup @alpha_eq_bterm_lenbvars in aeq.
apply alpha_eq_bterm_ren_1side2 in aeq; auto;
[|introv i j; apply subset_bound_vars_lsubst_aux in j; allsimpl;
allrw app_nil_r; apply disj2 in i; sp].
rw @lsubst_lsubst_aux in aeq;
[|rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_var_ren; auto;
introv i j; apply subset_bound_vars_lsubst_aux in i; allsimpl;
allrw app_nil_r; apply disj2 in j; sp].
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj u1 [(v,mk_utoken a)] (var_ren l1 l)) as h.
allsimpl.
rw @sub_free_vars_var_ren in h; auto.
allrw disjoint_singleton_l; fold_terms.
repeat (autodimp h hyp); eauto 3 with slow.
rw <- h in aeq; clear h.
pose proof (alpha_eq_lsubst_aux_pull_out_token
t (get_utokens u1) [(v,mk_utoken a)]
(lsubst_aux u1 (sub_filter (var_ren l1 l) [v]))) as h.
allsimpl; allrw disjoint_singleton_l.
repeat (autodimp h hyp); eauto 3 with slow.
{ intro i; apply subset_bound_vars_lsubst_aux in i; allrw in_app_iff.
rw @sub_bound_vars_allvars_sub in i; eauto 3 with slow.
allsimpl; repndors; tcsp. }
{ introv i j; apply subset_bound_vars_lsubst_aux in j; allrw in_app_iff.
rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.
allsimpl; repndors; tcsp.
apply disj3 in i; sp. }
{ apply nrut_sub_cons; eexists; simpl; dands; eauto; tcsp; eauto with slow. }
{ rw @get_utokens_lsubst_aux_allvars; eauto with slow. }
exrepnd; allsimpl.
unfold get_utokens_sub in h0; allsimpl; allrw disjoint_singleton_r.
exists u.
unfsubst; dands; auto.
Qed.
Lemma alpha_eq_bterm_ren_1side3 {o} :
forall (t1 t2 : @NTerm o) l1 l2,
disjoint l1 (all_vars t2)
-> length l1 = length l2
-> no_repeats l1
-> alpha_eq t1 (lsubst t2 (var_ren l2 l1))
-> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2).
Proof.
introv disj1 len norep aeq.
pose proof (fresh_vars (length l1) (l1 ++ l2
++ all_vars t1
++ all_vars t2))
as fvs; exrepnd; allrw disjoint_app_r; repnd.
apply (al_bterm _ _ lvn); allrw disjoint_app_r; auto.
apply (lsubst_alpha_congr2 _ _ (var_ren l1 lvn)) in aeq.
pose proof (lsubst_nest_vars_same t2 l2 l1 lvn) as h.
repeat (autodimp h hyp); allrw disjoint_app_l; dands; auto.
rw h in aeq; eauto with slow.
Qed.
Definition maybe_new_var_b {o} (v : NVar) (b : @BTerm o) :=
match b with
| bterm l t => maybe_new_var v l t
end.
Lemma in_nrut_sub_eq {o} :
forall (sub: @Sub o) v1 v2 t l,
nrut_sub l sub
-> LIn (v1, t) sub
-> LIn (v2, t) sub
-> v1 = v2.
Proof.
induction sub; introv nrut ni1 ni2; allsimpl; tcsp.
destruct a as [v u].
allrw @nrut_sub_cons; exrepnd; subst.
repndors; subst; tcsp; cpx.
- destruct nrut2; rw lin_flat_map.
apply in_sub_eta in ni1; repnd.
eexists; dands; eauto; simpl; tcsp.
- destruct nrut2; rw lin_flat_map.
apply in_sub_eta in ni2; repnd.
eexists; dands; eauto; simpl; tcsp.
- eapply IHsub; eauto.
Qed.
Lemma eqset_preserves_null {T} :
forall (s1 s2 : list T),
eqset s1 s2
-> null s1
-> null s2.
Proof.
introv eqs n i.
apply eqs in i.
apply n in i; sp.
Qed.
Lemma null_get_utokens_sub_keep_first_free_vars_eq {o} :
forall l (t : @NTerm o) sub,
nrut_sub l sub
-> null (get_utokens_sub (sub_keep_first sub (free_vars t)))
-> lsubst_aux t sub = t.
Proof.
nterm_ind t as [v|f ind|op bs ind] Case; introv nrut nu; allsimpl; auto.
- Case "vterm".
remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; auto.
unfold get_utokens_sub in nu.
allrw @null_flat_map.
applydup @sub_find_some in Heqsf.
pose proof (nu n) as h; clear nu.
eapply in_nrut_sub in nrut; eauto; exrepnd; subst; allsimpl.
autodimp h hyp.
+ apply in_range_iff; exists v.
apply in_sub_keep_first; simpl; tcsp.
+ pose proof (h a) as q; allsimpl; destruct q; tcsp.
- Case "oterm".
f_equal.
apply eq_map_l; introv i.
destruct x as [vs t]; allsimpl.
f_equal.
eapply ind;[eauto| |]; eauto 3 with slow.
introv j.
allrw @in_get_utokens_sub; exrepnd.
allrw @in_sub_keep_first; repnd.
allrw @sub_find_sub_filter_eq; boolvar; ginv.
destruct (nu x).
apply in_get_utokens_sub.
exists v t0; dands; auto.
apply in_sub_keep_first; dands; auto.
apply lin_flat_map.
eexists; dands; eauto.
simpl; rw in_remove_nvars; sp.
Qed.
Lemma alpha_eq_lsubst_aux_nrut_sub_implies {o} :
forall (t1 t2 : @NTerm o) sub l,
nrut_sub l sub
-> subset (get_utokens t1) l
-> subset (get_utokens t2) l
-> disjoint (dom_sub sub) (bound_vars t1)
-> disjoint (dom_sub sub) (bound_vars t2)
-> alpha_eq (lsubst_aux t1 sub) (lsubst_aux t2 sub)
-> alpha_eq t1 t2.
Proof.
nterm_ind1s t1 as [v1|f1 ind1|op1 bs1 ind1] Case;
introv nrut ss1 ss2 disj1 disj2 aeq; allsimpl.
- Case "vterm".
remember (sub_find sub v1) as sf; symmetry in Heqsf; destruct sf.
+ apply sub_find_some in Heqsf.
dup Heqsf as i.
eapply in_nrut_sub in i; eauto; exrepnd; subst.
destruct t2 as [v2|f2|op2 bs2]; allsimpl;
try (complete (inversion aeq)).
* remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.
{ apply sub_find_some in Heqsf'.
dup Heqsf' as j.
eapply in_nrut_sub in j; eauto; exrepnd; subst.
inversion aeq; subst; allsimpl; GC.
apply (in_nrut_sub_eq sub v1 v2 (mk_utoken a0) l) in nrut; auto; subst; auto. }
{ inversion aeq. }
* inversion aeq; subst; allsimpl; cpx; destruct bs2; allsimpl; cpx; GC; fold_terms.
allrw singleton_subset; tcsp.
+ apply sub_find_none2 in Heqsf.
destruct t2 as [v2|f2|op2 bs2]; allsimpl;
try (complete (inversion aeq)).
remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.
{ apply sub_find_some in Heqsf'.
dup Heqsf' as j.
eapply in_nrut_sub in j; eauto; exrepnd; subst.
inversion aeq. }
{ inversion aeq; subst; auto. }
- Case "sterm".
applydup @alphaeq_preserves_utokens in aeq; allsimpl.
symmetry in aeq0; apply null_iff_nil in aeq0.
eapply eqset_preserves_null in aeq0;[|apply get_utokens_lsubst_aux].
allrw @null_app; repnd.
erewrite null_get_utokens_sub_keep_first_free_vars_eq in aeq; eauto.
- Case "oterm".
allrw subset_app; repnd.
destruct t2 as [v2|f2|op2 bs2]; allsimpl; try (complete (inversion aeq)).
+ remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.
{ apply sub_find_some in Heqsf'.
dup Heqsf' as j.
eapply in_nrut_sub in j; eauto; exrepnd; subst.
inversion aeq; subst; allsimpl; destruct bs1; allsimpl; cpx; GC; fold_terms.
allrw singleton_subset; tcsp. }
{ inversion aeq. }
+ apply alpha_eq_oterm_combine2 in aeq; allrw map_length; repnd; subst.
apply alpha_eq_oterm_combine; dands; auto.
introv i.
pose proof (aeq (lsubst_bterm_aux b1 sub) (lsubst_bterm_aux b2 sub)) as aeqb; clear aeq.
rw <- @map_combine in aeqb.
rw in_map_iff in aeqb.
autodimp aeqb hyp.
{ eexists; dands; eauto. }
applydup in_combine in i; repnd; disj_flat_map.
destruct b1 as [l1 t1]; destruct b2 as [l2 t2]; allsimpl.
allrw disjoint_app_r; repnd.
allrw subset_app; repnd.
repeat (rw @sub_filter_disjoint1 in aeqb; eauto 3 with slow).
pose proof (fresh_vars
(length l1)
(all_vars (lsubst_aux t1 sub)
++ all_vars (lsubst_aux t2 sub)
++ dom_sub sub
++ bound_vars t1
++ bound_vars t2
++ free_vars t1
++ free_vars t2))
as fvs; exrepnd; allrw disjoint_app_r; repnd.
pose proof (alphabt_change_var_aux
(lsubst_aux t1 sub) (lsubst_aux t2 sub) l1 l2) lvn
as a.
allrw disjoint_app_r; repeat (autodimp a hyp); dands; eauto 3 with slow.
repnd.
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj
t1 sub (var_ren l1 lvn)) as e1.
rw @sub_free_vars_var_ren in e1; auto.
rw @cl_lsubst_aux_sub_trivial in e1; eauto 3 with slow.
erewrite sub_bound_vars_nrut_sub in e1; eauto 3 with slow.
erewrite sub_free_vars_nrut_sub in e1; eauto 3 with slow.
rw @sub_filter_disjoint1 in e1;[|rw @dom_sub_var_ren; eauto with slow]; auto.
repeat (autodimp e1 hyp); eauto 3 with slow.
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj
t2 sub (var_ren l2 lvn)) as e2.
rw @sub_free_vars_var_ren in e2; auto; try omega.
rw @cl_lsubst_aux_sub_trivial in e2; eauto 3 with slow.
erewrite sub_bound_vars_nrut_sub in e2; eauto 3 with slow.
erewrite sub_free_vars_nrut_sub in e2; eauto 3 with slow.
rw @sub_filter_disjoint1 in e2;[|rw @dom_sub_var_ren; eauto with slow]; auto; try omega.
repeat (autodimp e2 hyp); eauto 3 with slow.
rw <- e1 in a0; rw <- e2 in a0; clear e1 e2.
pose proof (ind1 t1 (lsubst_aux t1 (var_ren l1 lvn)) l1) as q; clear ind1.
repeat (autodimp q hyp).
{ rw @lsubst_aux_allvars_preserves_osize2; eauto 2 with slow. }
pose proof (q (lsubst_aux t2 (var_ren l2 lvn)) sub l) as ih; clear q.
repeat (rw @get_utokens_lsubst_aux_allvars in ih; eauto 3 with slow).
repeat (rw @boundvars_lsubst_aux_vars in ih; auto; try omega).
repeat (autodimp ih hyp); eauto 3 with slow.
{ introv z1; apply ss1; rw lin_flat_map; eexists; dands; eauto. }
{ introv z1; apply ss2; rw lin_flat_map; eexists; dands; eauto. }
apply (al_bterm _ _ lvn); allrw disjoint_app_r; dands; auto.
repeat (rw @lsubst_lsubst_aux); auto;
rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @computation2.sub_free_vars_var_ren; eauto 3 with slow; try omega.
Qed.
Lemma alpha_eq_bterm_mk_fresh_bterm_berm {o} :
forall (b : @BTerm o) v a l t,
disjoint l (all_vars_bterm b)
-> disjoint l (bound_vars t)
-> !LIn v l
-> !LIn (maybe_new_var_b v b) l
-> no_repeats l
-> !LIn a (get_utokens t)
-> !LIn a (get_utokens_b b)
-> alpha_eq_bterm (subst_bterm_aux b v (mk_utoken a))
(bterm l (subst t v (mk_utoken a)))
-> alpha_eq_bterm (mk_fresh_bterm v b) (bterm l (mk_fresh v t)).
Proof.
introv disj1 disj2 ni1 ni2 norep nia1 nia2 aeqb.
destruct b as [l' t'].
unfold mk_fresh_bterm.
apply alpha_eq_bterm_sym.
allsimpl; allrw disjoint_app_r; repnd.
applydup @alphaeqbt_numbvars in aeqb as len.
unfold num_bvars in len; allsimpl.
apply alpha_eq_bterm_sym in aeqb.
unfold subst_bterm_aux in aeqb; allsimpl.
apply alpha_eq_bterm_ren_1side2 in aeqb;
[|unfold subst; rw @cl_lsubst_lsubst_aux; eauto 3 with slow;
rw (@bound_vars_lsubst_aux_nrut_sub o t [(v,mk_utoken a)] []);
eauto 3 with slow;
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp
|boolvar; allrw @lsubst_aux_nil; auto;
rw (@bound_vars_lsubst_aux_nrut_sub o t' [(v,mk_utoken a)] []);
eauto 3 with slow;
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp].
apply alpha_eq_bterm_ren_1side3; auto.
{ unfold all_vars; simpl; allrw app_nil_r.
allrw disjoint_app_r; allrw disjoint_cons_r; dands; auto.
apply disjoint_remove_nvars_weak_r; auto. }
rw @lsubst_lsubst_aux; simpl; fold_terms;
[|rw app_nil_r; rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_var_ren; auto;
apply disjoint_cons_l; dands; complete (eauto with slow)].
allunfold @maybe_new_var.
boolvar.
- allrw @lsubst_aux_nil.
assert (!LIn v (free_vars t)) as nivt.
{ intro i; apply alphaeq_preserves_utokens in aeqb.
rw (get_utokens_lsubst_allvars t') in aeqb; eauto 3 with slow.
rw <- aeqb in nia2; destruct nia2.
apply get_utokens_lsubst; rw in_app_iff; sp; simpl.
boolvar; tcsp. }
rw @cl_subst_trivial in aeqb; eauto 3 with slow.
rw @lsubst_aux_sub_filter_aux; simpl;
[|introv i j; repndors; tcsp; subst;
rw @dom_sub_var_ren; auto;
apply newvar_prop in i; complete sp].
dup aeqb as aeq.
apply (implies_alpha_eq_mk_fresh v) in aeqb.
rw <- @lsubst_lsubst_aux;
[|rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_var_ren; complete (eauto with slow)].
eapply alpha_eq_trans;[exact aeqb|].
pose proof (ex_fresh_var (all_vars (lsubst t' (var_ren l' l)))) as fv; exrepnd.
apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; allrw not_over_or; repnd; tcsp.
repeat (rw (lsubst_trivial3 (lsubst t' (var_ren l' l)))); auto.
{ introv i; apply in_var_ren in i; allsimpl; exrepnd; repndors; tcsp; subst; allsimpl.
rw disjoint_singleton_l; dands; auto.
intro j.
pose proof (eqvars_free_vars_disjoint t' (var_ren l' l)) as e.
rw eqvars_prop in e; apply e in j; clear e.
rw @dom_sub_var_ren in j; auto.
rw in_app_iff in j; rw in_remove_nvars in j; repndors; exrepnd; tcsp.
- apply newvar_prop in j0; sp.
- apply in_sub_free_vars in j; exrepnd.
apply in_sub_keep_first in j0; repnd.
apply sub_find_some in j2.
apply in_var_ren in j2; exrepnd; subst; allsimpl; repndors; tcsp; subst; tcsp.
}
{ introv i; apply in_var_ren in i; allsimpl; exrepnd; repndors; tcsp; subst; allsimpl.
rw disjoint_singleton_l; dands; auto.
intro j.
pose proof (eqvars_free_vars_disjoint t' (var_ren l' l)) as e.
rw eqvars_prop in e; apply e in j; clear e.
rw @dom_sub_var_ren in j; auto.
rw in_app_iff in j; rw in_remove_nvars in j; repndors; exrepnd; tcsp.
apply in_sub_free_vars in j; exrepnd.
apply in_sub_keep_first in j0; repnd.
apply sub_find_some in j2.
apply in_var_ren in j2; exrepnd; subst; allsimpl; repndors; tcsp; subst; tcsp.
}
- rw @lsubst_lsubst_aux in aeqb;
[|rw <- @sub_free_vars_is_flat_map_free_vars_range;
rw @sub_free_vars_var_ren; try (complete (eauto 3 with slow));
rw (@bound_vars_lsubst_aux_nrut_sub o t' [(v,mk_utoken a)] []);
eauto 3 with slow;
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp].
pose proof (simple_lsubst_aux_lsubst_aux_sub_disj
t' [(v,mk_utoken a)] (var_ren l' l)) as e; allsimpl.
allrw disjoint_singleton_l.
rw @sub_free_vars_var_ren in e; try (complete (eauto 3 with slow)).
repeat (autodimp e hyp); eauto 2 with slow; fold_terms.
rw <- e in aeqb; clear e.
apply implies_alpha_eq_mk_fresh.
remember (lsubst_aux t' (sub_filter (var_ren l' l) [v])) as t''.
unfold subst in aeqb; rw @cl_lsubst_lsubst_aux in aeqb; eauto 2 with slow.
assert (!LIn a (get_utokens t'')) as niat''.
{ subst; intro i.
apply get_utokens_lsubst_aux in i; allrw in_app_iff; repndors; tcsp.
rw @get_utokens_sub_allvars_sub in i; allsimpl; eauto with slow.
}
clear Heqt''.
pose proof (change_bvars_alpha_wspec [v] t) as aeqt; exrepnd.
pose proof (change_bvars_alpha_wspec [v] t'') as aeqt'; exrepnd.
allrw disjoint_singleton_l.
assert (alpha_eq (lsubst_aux t [(v, mk_utoken a)])
(lsubst_aux ntcv [(v, mk_utoken a)])) as aeq1.
{ apply computation2.lsubst_aux_alpha_congr_same_cl_sub; eauto 3 with slow. }
assert (alpha_eq (lsubst_aux t'' [(v, mk_utoken a)])
(lsubst_aux ntcv0 [(v, mk_utoken a)])) as aeq2.
{ apply computation2.lsubst_aux_alpha_congr_same_cl_sub; eauto 3 with slow. }
assert (alpha_eq (lsubst_aux ntcv [(v, mk_utoken a)])
(lsubst_aux ntcv0 [(v, mk_utoken a)])) as aeq3.
{ eapply alpha_eq_trans;[apply alpha_eq_sym; exact aeq1|].
eapply alpha_eq_trans;[exact aeqb|].
eauto with slow. }
clear aeq1 aeq2.
assert (alpha_eq ntcv ntcv0) as aeq;[|eauto 4 with slow];[].
apply (alpha_eq_lsubst_aux_nrut_sub_implies
_ _ _ (get_utokens ntcv ++ get_utokens ntcv0)) in aeq3;
simpl; eauto 3 with slow; allrw disjoint_singleton_l; auto.
apply alphaeq_preserves_utokens in aeqt0.
apply alphaeq_preserves_utokens in aeqt'0.
rw aeqt0 in nia1.
rw aeqt'0 in niat''.
apply nrut_sub_cons; eexists; dands; simpl; eauto; tcsp; eauto 3 with slow.
rw in_app_iff; tcsp.
Qed.
Lemma alpha_eq_bterm_preserves_isprog_vars {o} :
forall l1 l2 (t1 t2 : @NTerm o),
alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)
-> isprog_vars l1 t1
-> isprog_vars l2 t2.
Proof.
introv aeq isp.
allrw @isprog_vars_eq; repnd.
applydup @alphaeqbt_preserves_nt_wf in aeq as w.
rw w; dands; auto.
apply alphaeqbt_preserves_fvars in aeq; allsimpl.
rw eqvars_prop in aeq.
allrw subvars_prop.
introv i.
destruct (in_deq _ deq_nvar x l2) as [d|d]; auto.
assert (LIn x (remove_nvars l2 (free_vars t2))) as j.
{ rw in_remove_nvars; sp. }
apply aeq in j.
rw in_remove_nvars in j; repnd.
apply isp0 in j0; sp.
Qed.
Lemma approx_starbts_get_bterms_alpha_eq_l {o} :
forall lib op (t u v : @NTerm o),
approx_starbts lib op (get_bterms t) (get_bterms u)
-> alpha_eq t v
-> approx_starbts lib op (get_bterms v) (get_bterms u).
Proof.
introv ap aeq.
destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl; auto;
try (complete (inversion aeq; subst; allsimpl; auto)).
- unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.
inversion aeq; subst; allsimpl; cpx; auto.
unfold approx_starbts, lblift_sub; simpl; sp.
- unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.
inversion aeq; subst; allsimpl; cpx; auto.
unfold approx_starbts, lblift_sub; simpl; sp.
- inversion aeq as [|?|? ? ? len imp]; subst; simpl.
allunfold @approx_starbts.
allunfold @lblift_sub; repnd; dands; auto; try omega.
introv i.
pose proof (ap n) as h1; autodimp h1 hyp; try omega.
pose proof (imp n) as h2; autodimp h2 hyp; try omega.
eapply approx_star_bterm_alpha_fun_l;[apply alpha_eq_bterm_sym; exact h2|]; auto.
Qed.
Lemma subst_sterm {o} :
forall (f : @ntseq o) v t,
subst (sterm f) v t = sterm f.
Proof.
introv; unfold subst; autorewrite with slow; auto.
Qed.
Hint Rewrite @subst_sterm : slow.
Lemma same_value_like_sterm_implies_approx_star {o} :
forall lib (f1 f2 : @ntseq o),
nt_wf (sterm f2)
-> same_value_like (sterm f1) (sterm f2)
-> approx_star lib (sterm f1) (sterm f2).
Proof.
introv wf svl.
inversion svl; subst; clear svl.
econstructor; eauto.
apply approx_open_refl; auto.
Qed.
Hint Resolve same_value_like_sterm_implies_approx_star : slow.
Lemma approx_star_pushdown_fresh_if_subst {o} :
forall lib (t1 t2 : @NTerm o) v1 v2 a,
!LIn a (get_utokens t1)
-> !LIn a (get_utokens t2)
-> isprog_vars [v1] t1
-> isprog_vars [v2] t2
-> same_value_like (subst t1 v1 (mk_utoken a)) (subst t2 v2 (mk_utoken a))
-> approx_starbts lib (get_op t1) (get_bterms (subst t1 v1 (mk_utoken a))) (get_bterms (subst t2 v2 (mk_utoken a)))
-> approx_star lib (pushdown_fresh v1 t1) (pushdown_fresh v2 t2).
Proof.
introv ni1 ni2 isp1 isp2 svl ap.
pose proof (ex_fresh_var (all_vars t1
++ all_vars t2))
as fv; exrepnd.
allrw in_app_iff; allrw not_over_or; repnd.
pose proof (alpha_bterm_change
(bterm [v1] t1) [v1] t1 [v]) as aeqbt1.
allrw disjoint_singleton_r.
allrw in_app_iff; allrw not_over_or.
allsimpl.
repeat (autodimp aeqbt1 hyp).
pose proof (alpha_bterm_change
(bterm [v2] t2) [v2] t2 [v]) as aeqbt2.
allrw disjoint_singleton_r.
allrw in_app_iff; allrw not_over_or.
allsimpl.
repeat (autodimp aeqbt2 hyp).
remember (lsubst t1 (var_ren [v1] [v])) as nt1.
remember (lsubst t2 (var_ren [v2] [v])) as nt2.
applydup @alpha_eq_bterm_preserves_utokens in aeqbt1 as ut1; allsimpl.
rw ut1 in ni1.
applydup @alpha_eq_bterm_preserves_utokens in aeqbt2 as ut2; allsimpl.
rw ut2 in ni2.
pose proof (lsubst_alpha_congr4 [v1] [v] t1 nt1 [(v1,mk_utoken a)] [(v,mk_utoken a)]) as c1.
allsimpl.
repeat (autodimp c1 hyp); eauto 3 with slow.
pose proof (lsubst_alpha_congr4 [v2] [v] t2 nt2 [(v2,mk_utoken a)] [(v,mk_utoken a)]) as c2.
allsimpl.
repeat (autodimp c2 hyp); eauto 3 with slow.
allrw @fold_subst.
eapply same_value_like_alpha_eq_r in svl;[|exact c2].
eapply same_value_like_alpha_eq_l in svl;[|exact c1].
eapply alpha_eq_bterm_preserves_isprog_vars in isp1;[|exact aeqbt1].
eapply alpha_eq_bterm_preserves_isprog_vars in isp2;[|exact aeqbt2].
assert (get_op t1 = get_op nt1) as go.
{ subst; rw @lsubst_lsubst_aux; allrw <- @sub_free_vars_is_flat_map_free_vars_range;
allsimpl; allrw disjoint_singleton_r; auto.
destruct t1; simpl; boolvar; simpl; tcsp. }
rw go in ap.
eapply approx_starbts_get_bterms_alpha_eq in ap;[|exact c2].
eapply approx_starbts_get_bterms_alpha_eq_l in ap;[|exact c1].
applydup @implies_alpha_eq_pushdown_fresh in aeqbt1 as apf1.
applydup @implies_alpha_eq_pushdown_fresh in aeqbt2 as apf2.
eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact apf1].
eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact apf2].
clear dependent t1.
clear dependent t2.
rename nt1 into t1.
rename nt2 into t2.
repeat (unfsubst in svl); repeat (unfsubst in ap); allsimpl.
destruct t1 as [x|f|op bs]; allsimpl; tcsp; GC.
- boolvar.
+ apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply (approx_trans _ _ (mk_fresh x (mk_var x))).
* apply reduces_to_implies_approx2.
{ apply isprogram_fresh.
apply isprog_vars_var. }
apply reduces_to_if_step.
csunf; simpl; boolvar; auto.
* apply fresh_id_approx_any.
apply isprogram_pushdown_fresh; auto.
+ inversion svl.
- autorewrite with slow in *.
destruct t2 as [v2|f2|op bs]; allsimpl; boolvar; allsimpl;
try (complete (inversion svl)); eauto 4 with slow.
- allsimpl.
destruct t2 as [x|f|op' bs']; allsimpl; GC; try (complete (inversion svl)).
+ boolvar; try (complete (inversion svl)).
inversion svl; subst; allsimpl.
allrw not_over_or; sp.
+ applydup @same_value_like_implies_same_op in svl; subst.
assert (length bs = length bs') as e.
{ unfold approx_starbts, lblift_sub in ap; repnd; allrw map_length.
unfold mk_fresh_bterms; allrw map_length; auto. }
apply (apso _ _ _ _ (mk_fresh_bterms v bs')); auto;
try (apply approx_open_refl);
[unfold mk_fresh_bterms; allrw map_length; auto
|idtac
|apply isprog_vars_eq in isp2; repnd;
allrw @nt_wf_oterm_iff; repnd;
rw <- isp3;
unfold mk_fresh_bterms; allrw map_map; unfold compose; dands;
[ apply eq_maps; introv i; destruct x; unfold num_bvars; simpl; auto|];
introv i; allrw in_map_iff; exrepnd; subst;
apply isp2 in i1; apply bt_wf_mk_fresh_bterm_if; complete auto].
unfold lblift_sub, mk_fresh_bterms; dands; allrw map_length; auto.
introv i.
repeat (rw @selectbt_map; auto; try omega).
unfold approx_starbts, lblift_sub in ap; repnd; allrw map_length; GC.
pose proof (ap n i) as k; clear ap.
repeat (rw @selectbt_map in k; auto; try omega).
allunfold @selectbt.
pose proof (in_nth_combine _ _ bs bs' n default_bt default_bt) as h.
repeat (autodimp h hyp).
remember (nth n bs default_bt) as b1; clear Heqb1.
remember (nth n bs' default_bt) as b2; clear Heqb2.
allrw in_app_iff; allrw not_over_or; repnd.
applydup in_combine in h; repnd.
assert (!LIn a (get_utokens_b b1)) as niab1.
{ introv q; destruct ni1; rw lin_flat_map; eexists; dands; eauto. }
assert (!LIn a (get_utokens_b b2)) as niab2.
{ introv q; destruct ni2; rw lin_flat_map; eexists; dands; eauto. }
(* new stuff *)
apply (blift_sub_diff (v :: maybe_new_var_b v b1
:: maybe_new_var_b v b2
:: all_vars_bterm b1
++ all_vars_bterm b2)) in k; exrepnd.
allrw disjoint_cons_r; allrw disjoint_cons_l; allrw disjoint_app_r; allrw disjoint_app_l; repnd.
assert (wf_term nt1) as wfnt1.
{ repndors; exrepnd.
- allapply @approx_star_relates_only_wf; repnd; eauto 2 with slow.
- allapply @approx_star_relates_only_wf; repnd.
allapply @lsubst_nt_wf; eauto with slow. }
assert (wf_term nt2) as wfnt2.
{ repndors; exrepnd.
- allapply @approx_star_relates_only_wf; repnd; eauto 2 with slow.
- allapply @approx_star_relates_only_wf; repnd.
allapply @lsubst_nt_wf; eauto with slow. }
pose proof (alpha_eq_subst_bterm_aux_pull_out_token b1 v a lv nt1) as exs1.
repeat (autodimp exs1 hyp); exrepnd.
subst nt1.
rename u into nt1.
pose proof (alpha_eq_subst_bterm_aux_pull_out_token b2 v a lv nt2) as exs2.
repeat (autodimp exs2 hyp); exrepnd.
subst nt2.
rename u into nt2.
assert (disjoint lv (bound_vars nt1)) as disjlvnt1.
{ introv i1 i2; apply k7 in i1; destruct i1.
unfsubst.
rw (bound_vars_lsubst_aux_nrut_sub nt1 [(v,mk_utoken a)] []); auto.
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp. }
assert (disjoint lv (bound_vars nt2)) as disjlvnt2.
{ introv i1 i2; apply k8 in i1; destruct i1.
unfsubst.
rw (bound_vars_lsubst_aux_nrut_sub nt2 [(v,mk_utoken a)] []); auto.
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp. }
unfold blift_sub.
pose proof (alpha_eq_bterm_mk_fresh_bterm_berm b1 v a lv nt1) as e1.
repeat (autodimp e1 hyp); eauto 3 with slow.
pose proof (alpha_eq_bterm_mk_fresh_bterm_berm b2 v a lv nt2) as e2.
repeat (autodimp e2 hyp); eauto 3 with slow.
exists lv (mk_fresh v nt1) (mk_fresh v nt2); dands; auto.
(* here comes trouble! *)
repndors;[left|right].
* repnd; dands; auto.
apply (apso _ _ _ _ [bterm [v] nt2]); allsimpl; auto; fold_terms;
[|apply approx_open_refl; allrw <- @nt_wf_eq;
allapply @lsubst_nt_wf; apply nt_wf_fresh; auto].
unfold lblift_sub; simpl; dands; auto; introv q; destruct n0; cpx.
unfold selectbt; simpl.
unfold blift_sub.
exists [v] nt1 nt2; dands; auto.
right.
exists [(v,mk_utoken a)]; simpl; dands; auto.
apply nrut_sub_cons; simpl; eexists; dands; eauto with slow; tcsp.
rw in_app_iff; sp.
* exrepnd.
pose proof (exists_nrut_sub
(dom_sub sub)
(a :: get_utokens (subst nt1 v (mk_utoken a))
++ get_utokens (subst nt2 v (mk_utoken a))))
as ens; exrepnd.
pose proof (approx_star_change_nrut_sub
lib
(subst nt1 v (mk_utoken a))
(subst nt2 v (mk_utoken a))
sub
(get_utokens (subst nt1 v (mk_utoken a)) ++ get_utokens (subst nt2 v (mk_utoken a)))
sub0
(a :: get_utokens (subst nt1 v (mk_utoken a)) ++ get_utokens (subst nt2 v (mk_utoken a))))
as aps; repeat (autodimp aps hyp); eauto 3 with slow.
exists sub0; dands; auto; simpl; allrw app_nil_r;
try (complete (subst; auto));
[|eapply nrut_sub_subset;[|exact ens1]; apply subset_cons1;
apply subset_app_lr; introv z;
apply get_utokens_subst; boolvar; simpl;
repeat (rw app_nil_r); repeat (rw in_app_iff); complete sp].
repeat (rw @cl_lsubst_lsubst_aux; eauto 2 with slow); simpl; fold_terms.
apply (apso _ _ _ _ [bterm [v] (lsubst_aux nt2 (sub_filter sub0 [v]))]); allsimpl; auto; fold_terms;
[|apply approx_open_refl; allrw <- @nt_wf_eq;
allapply @lsubst_nt_wf; apply nt_wf_fresh; auto;
apply implies_wf_lsubst_aux; eauto 3 with slow];[].
unfold lblift_sub; simpl; dands; auto; introv q; destruct n0; cpx.
unfold selectbt; simpl.
unfold blift_sub.
allunfold @subst.
rw (cl_lsubst_swap_sub_filter nt1) in aps; eauto 3 with slow.
rw (cl_lsubst_swap_sub_filter nt2) in aps; eauto 3 with slow.
allsimpl.
assert (!LIn a (get_utokens_sub sub0)) as niasub.
{ intro z; unfold nrut_sub in ens1; repnd; allrw disjoint_cons_l; sp. }
exists [v] (lsubst_aux nt1 (sub_filter sub0 [v])) (lsubst_aux nt2 (sub_filter sub0 [v])); dands; auto.
right.
exists [(v,mk_utoken a)]; simpl; dands; auto.
{ repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow). }
apply nrut_sub_cons; simpl; eexists; dands; eauto with slow; tcsp.
rw in_app_iff; rw not_over_or; dands; intro z;
apply get_utokens_lsubst_aux_subset in z; rw in_app_iff in z; repndors; tcsp;
apply get_utokens_sub_filter_subset in z; tcsp.
Qed.
Lemma alpha_eq_lsubst_nrut_sub_implies {o} :
forall (t1 t2 : @NTerm o) sub l,
nrut_sub l sub
-> subset (get_utokens t1) l
-> subset (get_utokens t2) l
-> alpha_eq (lsubst t1 sub) (lsubst t2 sub)
-> alpha_eq t1 t2.
Proof.
introv nrut ss1 ss2 aeq.
pose proof (unfold_lsubst sub t1) as p; destruct p as [t1']; repnd.
pose proof (unfold_lsubst sub t2) as q; destruct q as [t2']; repnd.
rw p in aeq; rw p2 in aeq.
pose proof (change_bvars_alpha_wspec (dom_sub sub) t1') as h; destruct h as [t1'']; repnd.
pose proof (change_bvars_alpha_wspec (dom_sub sub) t2') as k; destruct k as [t2'']; repnd.
dup p5 as a1.
apply (computation2.lsubst_aux_alpha_congr_same_cl_sub _ _ sub) in a1; eauto 2 with slow.
dup p7 as a2.
apply (computation2.lsubst_aux_alpha_congr_same_cl_sub _ _ sub) in a2; eauto 2 with slow.
assert (alpha_eq (lsubst_aux t1'' sub) (lsubst_aux t2'' sub)) as aeq2 by eauto 4 with slow.
pose proof (alpha_eq_lsubst_aux_nrut_sub_implies t1'' t2'' sub l) as a.
repeat (autodimp a hyp).
- apply alphaeq_preserves_utokens in p5; rw <- p5.
apply alphaeq_preserves_utokens in p0; rw <- p0; auto.
- apply alphaeq_preserves_utokens in p7; rw <- p7.
apply alphaeq_preserves_utokens in p3; rw <- p3; auto.
- assert (alpha_eq t1 t1'') as aeq11 by eauto with slow.
assert (alpha_eq t2 t2'') as aeq22 by eauto with slow.
eauto with slow.
Qed.
Lemma reduces_in_atmost_k_steps_mk_fresh_id {o} :
forall (lib : @library o) v k u,
reduces_in_atmost_k_steps lib (mk_fresh v (vterm v)) u k
-> u = mk_fresh v (vterm v).
Proof.
induction k; introv r.
- allrw @reduces_in_atmost_k_steps_0; auto.
- allrw @reduces_in_atmost_k_steps_S; exrepnd.
csunf r1; allsimpl; boolvar; ginv.
apply IHk in r0; auto.
Qed.
Lemma reduces_in_atmost_k_steps_mk_fresh_id2 {o} :
forall (lib : @library o) v k,
reduces_in_atmost_k_steps lib (mk_fresh v (vterm v)) (mk_fresh v (vterm v)) k.
Proof.
induction k; introv.
- allrw @reduces_in_atmost_k_steps_0; auto.
- allrw @reduces_in_atmost_k_steps_S; exrepnd.
exists (@mk_fresh o v (vterm v)); dands; auto.
csunf; simpl; boolvar; auto.
Qed.
Lemma isprog_vars_implies_nt_wf {o} :
forall (t : @NTerm o) l, isprog_vars l t -> nt_wf t.
Proof.
introv isp.
rw @isprog_vars_eq in isp; sp.
Qed.
Hint Resolve isprog_vars_implies_nt_wf : slow.
Lemma extensional_fresh {p} : @extensional_op p (NCan NFresh).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
applydup @compute_decompose_aux in Hcv; auto; exrepnd.
repndors; exrepnd; allsimpl; repnd; subst; GC;
[apply isprogram_fresh_implies in Hprt; exrepnd; complete ginv|].
fold_terms.
assert (m <= S k) as XX by omega.
repnud Hcv.
eapply reduces_atmost_split in XX; eauto.
remember (S k - m) as skm.
destruct skm; [omega|].
assert (skm <= k) as lek by (subst; omega).
apply reduces_atmost_S in XX; exrepnd.
apply isprogram_fresh in Hprt.
applydup @reduces_atmost_preserves_program in Hcv4; auto;
[|apply isprogram_subst_if_bt; eauto 3 with slow].
duplicate Has.
unfold lblift_sub in Has; repnd.
simpl in Has, Has1; cpx; GC.
repeat(approxrelbtd); show_hyps.
fold_terms.
applydup @alpha_eq_preserves_isvalue_like in Hcv8; auto.
unfold mk_fresh in XX1.
rw @compute_step_fresh_if_isvalue_like2 in XX1; auto; ginv.
assert (isvalue_like (subst u v (mk_utoken (get_fresh_atom t)))) as isv.
{ apply isvalue_like_subst; auto. }
assert (isvalue_like x) as isvx.
{ apply alpha_eq_sym in Hcv5; apply alpha_eq_preserves_isvalue_like in Hcv5; auto. }
remember (get_fresh_atom t) as ua.
apply isprogram_fresh in Hprt'.
pose proof (fresh_atom p (get_utokens (mk_pair t tr))) as fa.
destruct fa as [ua' fa]; allsimpl; allrw app_nil_r.
allrw in_app_iff; allrw not_over_or; repnd.
pose proof (get_fresh_atom_prop t) as gfu; rw <- Hequa in gfu.
apply no_change_after_val_like with (k2 := k) in Hcv4; auto.
pose proof (reduces_in_atmost_k_steps_change_utok_sub
lib k t x [(v,mk_utoken ua)] [(v,mk_utoken ua')]) as comp.
repeat (autodimp comp hyp); eauto 2 with slow.
{ unfold get_utokens_sub; simpl; rw disjoint_singleton_l; auto. }
{ unfold get_utokens_sub; simpl; rw disjoint_singleton_l; auto. }
exrepnd; allrw @fold_subst.
unfold get_utokens_sub in comp2; simpl in comp2; allrw disjoint_singleton_l.
assert (isprogram (subst w0 v (mk_utoken ua))) as ispsw0.
{ apply alphaeq_preserves_program in comp0; apply comp0; auto. }
assert (isprogram s) as isps.
{ apply alpha_eq_sym in comp1; apply alphaeq_preserves_program in comp1; apply comp1.
apply isprogram_subst_if_bt; eauto 2 with slow.
apply isprogram_subst_implies in ispsw0; auto. }
assert (!LIn ua (get_utokens u)) as niu.
{ intro i; apply Hcv6 in i; sp. }
assert (alpha_eq u w0) as aeq0.
{ assert (alpha_eq (subst u v (mk_utoken ua)) (subst w0 v (mk_utoken ua))) as h by eauto with slow.
pose proof (change_bvars_alpha_wspec [v] u) as k1.
pose proof (change_bvars_alpha_wspec [v] w0) as k2.
exrepnd.
allrw disjoint_singleton_l.
pose proof (lsubst_alpha_congr2 ntcv0 u [(v,mk_utoken ua)]) as p1.
pose proof (lsubst_alpha_congr2 ntcv w0 [(v,mk_utoken ua)]) as p2.
autodimp p1 hyp; autodimp p2 hyp; eauto 3 with slow.
allrw @fold_subst.
assert (alpha_eq (subst ntcv0 v (mk_utoken ua)) (subst ntcv v (mk_utoken ua))) as h' by eauto with slow.
apply alpha_eq_subst_utoken_not_in_implies in h'; eauto with slow.
{ intro j; destruct niu; apply alphaeq_preserves_utokens in k3; rw k3; auto. }
{ intro j; destruct comp2; apply alphaeq_preserves_utokens in k0; rw k0; auto. }
}
assert (isvalue_like w0) as isvw0.
{ apply alpha_eq_preserves_isvalue_like in aeq0; auto. }
assert (isvalue_like s) as isvs.
{ apply alpha_eq_sym in comp1; apply alpha_eq_preserves_isvalue_like in comp1; auto.
apply isvalue_like_subst; auto. }
make_red_val_like comp5 h.
pose proof (Hi (subst t v (mk_utoken ua')) s (subst tr vr (mk_utoken ua'))) as h'.
repeat (autodimp h' hyp).
{ apply isprogram_subst_if_bt; eauto with slow. }
{ apply isprogram_subst_if_bt; eauto with slow. }
{ unfold approx_star_bterm, blift_sub in Has0bt; exrepnd; repndors; exrepnd; tcsp; GC.
applydup @alpha_eq_bterm_implies_eq_length in Has0bt2.
allsimpl; destruct lv as [|v']; allsimpl; tcsp.
destruct lv; allsimpl; tcsp; GC; try omega.
pose proof (lsubst_alpha_congr4 [v] [v'] t nt1 [(v,mk_utoken ua')] [(v',mk_utoken ua')]) as aeq1.
repeat (autodimp aeq1 hyp); simpl; eauto 2 with slow.
pose proof (lsubst_alpha_congr4 [vr] [v'] tr nt2 [(vr,mk_utoken ua')] [(v',mk_utoken ua')]) as aeq2.
repeat (autodimp aeq2 hyp); simpl; eauto 2 with slow.
allrw @fold_subst.
eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact aeq1].
eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact aeq2].
pose proof (approx_star_change_nrut_sub
lib nt1 nt2 sub
(get_utokens nt1 ++ get_utokens nt2)
[(v',mk_utoken ua')]
(get_utokens nt1 ++ get_utokens nt2)) as q.
allsimpl; repeat (autodimp q hyp); eauto 3 with slow.
apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp.
apply alpha_eq_bterm_preserves_utokens in Has0bt2.
apply alpha_eq_bterm_preserves_utokens in Has0bt0.
allsimpl; rw <- Has0bt2; rw <- Has0bt0; rw in_app_iff; sp.
}
pose proof (approx_star_alpha_fun_l lib s (subst tr vr (mk_utoken ua')) (subst u v (mk_utoken ua'))) as ap1.
repeat (autodimp ap1 hyp).
{ eapply alpha_eq_trans;[exact comp1|].
unfold subst; apply lsubst_alpha_congr2; eauto with slow. }
apply reduces_in_atmost_k_steps_if_isvalue_like in XX0; subst; eauto 2 with slow.
assert (alpha_eq (pushdown_fresh v w) (pushdown_fresh v u)) as aeq.
{ apply implies_alpha_eq_pushdown_fresh.
apply alpha_eq_bterm_congr; eauto with slow. }
eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact aeq].
assert (isprog_vars [v] u) as ispu.
{ apply alphaeq_preserves_program in Hcv5.
apply Hcv5 in Hcv3.
apply isprogram_subst_implies in Hcv3.
apply isprog_vars_iff_isprogram_bt; auto. }
pose proof (howe_lemma2_implies_same_value_like
lib
(subst u v (mk_utoken ua'))
(subst tr vr (mk_utoken ua'))) as ap2.
repeat (autodimp ap2 hyp); eauto 2 with slow.
{ apply isprogram_subst_if_bt; eauto 2 with slow. }
{ apply isprogram_subst_if_bt; eauto 2 with slow. }
exrepnd.
unfold reduces_to in ap0; exrepnd.
pose proof (reduces_in_atmost_k_steps_change_utok_sub
lib k0 tr v0 [(vr,mk_utoken ua')] [(vr,mk_utoken ua')]) as comp'.
allrw @fold_subst.
repeat (autodimp comp' hyp); eauto 2 with slow;
try (unfold get_utokens_sub; simpl; apply disjoint_singleton_l; complete sp).
exrepnd.
clear dependent s0.
allunfold @get_utokens_sub; allsimpl; allrw disjoint_singleton_l.
allrw @fold_subst.
eapply same_value_like_alpha_eq_r in ap2;[|exact comp'0].
eapply approx_starbts_get_bterms_alpha_eq in ap3;[|exact comp'0].
assert (isprog_vars [vr] w1) as ispw1.
{ apply reduces_atmost_preserves_program in ap4.
- apply alphaeq_preserves_program in comp'0; apply comp'0 in ap4.
apply isprogram_subst_implies in ap4.
apply isprog_vars_iff_isprogram_bt; auto.
- apply isprogram_subst_if_bt; eauto with slow. }
assert (!LIn ua' (get_utokens u)) as niua'u.
{ intro i; apply Hcv6 in i; sp. }
assert (get_op (subst u v (mk_utoken ua')) = get_op u) as gopu.
{ unfsubst; unfold isvalue_like in Hcv0; repndors.
- apply iscan_implies in Hcv0; repndors; exrepnd; subst; simpl; auto.
- apply isexc_implies2 in Hcv0; exrepnd; subst; simpl; auto. }
rw gopu in ap3.
pose proof (approx_star_pushdown_fresh_if_subst lib u w1 v vr ua') as apspf.
repeat (autodimp apspf hyp).
eapply approx_star_open_trans;[exact apspf|].
apply approx_implies_approx_open.
remember (get_fresh_atom tr) as a.
pose proof (reduces_in_atmost_k_steps_change_utok_sub
lib k0 tr v0 [(vr,mk_utoken ua')] [(vr,mk_utoken a)]) as r.
allsimpl; allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allrw app_nil_r.
allsimpl; allrw disjoint_singleton_l.
repeat (autodimp r hyp); eauto 3 with slow.
{ apply nr_ut_sub_cons; eauto with slow; intro xx; subst; apply get_fresh_atom_prop. }
{ subst; apply get_fresh_atom_prop. }
exrepnd.
allrw @fold_subst.
pose proof (alpha_eq_lsubst_nrut_sub_implies
w1 w2 [(vr,mk_utoken ua')]
(get_utokens w1 ++ get_utokens w2)) as aeqws.
repeat (autodimp aeqws hyp); eauto 3 with slow.
{ apply nrut_sub_cons; simpl; eexists; dands; eauto with slow; tcsp; rw in_app_iff; sp. }
applydup @approx_starbt_relates_only_wf in Has0bt as wf; repnd.
allrw @bt_wf_iff.
allrw @nt_wf_eq.
pose proof (reduces_to_fresh lib tr s0 vr) as rf; simpl in rf.
rw <- Heqa in rf.
repeat (autodimp rf hyp).
{ exists k0; auto. }
exrepnd.
assert (alpha_eq s0 (subst w1 vr (mk_utoken a))) as aeq1.
{ eapply alpha_eq_trans;[exact r1|].
apply lsubst_alpha_congr2; eauto with slow. }
assert (alpha_eq z (subst_utokens (subst w1 vr (mk_utoken a)) [(a,mk_var vr)])) as aeq2.
{ eapply alpha_eq_trans;[exact rf0|].
apply alpha_eq_subst_utokens; eauto with slow. }
assert (!LIn a (get_utokens w1)) as niaw1.
{ intro xx.
apply alphaeq_preserves_utokens in aeqws; rw aeqws in xx; apply r4 in xx.
subst; apply get_fresh_atom_prop in xx; tcsp. }
pose proof (simple_alphaeq_subst_utokens_subst w1 vr a niaw1) as aeq3.
assert (alpha_eq z w1) as aeq4 by eauto 3 with slow.
apply (approx_trans _ _ (mk_fresh vr z));
[|apply reduces_to_implies_approx_eauto; auto;
apply isprogram_fresh; complete auto].
eapply approx_alpha_rw_r_aux;
[apply alpha_eq_sym; apply implies_alpha_eq_mk_fresh; exact aeq4|].
assert (isvalue_like w1) as isvlw1.
{ repeat (rw @cl_subst_subst_aux in ap2; eauto 2 with slow).
unfold subst_aux in ap2.
inversion ap2 as [? ? ? e1 e2| ? ? e1 e2|].
- destruct u as [z11|f11|op11 bs11]; allsimpl; boolvar; tcsp; ginv.
+ repeat (rw @cl_subst_subst_aux in gopu; eauto 2 with slow); allunfold @subst_aux; allsimpl; boolvar; allsimpl;
try (complete (inversion gopu)).
+ repeat (rw @cl_subst_subst_aux in gopu; eauto 2 with slow); allunfold @subst_aux; allsimpl; boolvar; allsimpl;
try (complete (inversion gopu)); ginv.
destruct w1 as [z22|f22|op22 bs22]; allsimpl; boolvar; GC; tcsp; ginv; eauto 3 with slow.
inversion e2; subst; allsimpl; fold_terms; GC.
allrw subset_cons_l; repnd; tcsp.
- destruct u as [z11|f11|op11 bs11]; allsimpl; boolvar; tcsp; ginv.
destruct w1 as [z22|f22|op22 bs22]; allsimpl; boolvar; GC; tcsp; ginv; eauto 3 with slow.
- destruct u as [z11|f11|op11 bs11]; allsimpl; boolvar; tcsp; ginv.
destruct w1 as [z22|f22|op22 bs22]; allsimpl; boolvar; GC; tcsp; ginv; eauto 3 with slow.
}
pose proof (compute_step_fresh_if_isvalue_like lib vr w1 isvlw1) as comp.
apply reduces_to_implies_approx_eauto;
[apply isprogram_fresh; complete auto|].
apply reduces_to_if_step; auto.
Qed.
Lemma computes_to_val_like_in_max_k_steps_parallel_implies2 {o} :
forall lib k (bs : list (@BTerm o)) v,
computes_to_val_like_in_max_k_steps lib (oterm (NCan NParallel) bs) v k
-> {x : NTerm
& {u : NTerm
& {bs' : list BTerm
& {m : nat
& k = S m
# bs = nobnd u :: bs'
# computes_to_val_like_in_max_k_steps lib u x m
# {c : CanonicalOp & {bs : list BTerm & x = oterm (Can c) bs # v = mk_axiom}}
[+]
(isexc x # x = v)}}}}.
Proof.
induction k; introv comp; simpl.
- allunfold @computes_to_val_like_in_max_k_steps.
rw @reduces_in_atmost_k_steps_0 in comp; repnd; subst.
unfold isvalue_like in comp; allsimpl; sp.
- rw @computes_to_val_like_in_max_k_steps_S in comp; exrepnd.
csunf comp1; allsimpl.
destruct bs as [|b bs]; ginv.
destruct b as [l t].
destruct l; ginv.
destruct t as [z|f|op bts]; ginv;[].
dopid op as [can|ncan|exc|abs] Case; ginv.
+ Case "Can".
apply compute_step_parallel_success in comp1; subst.
apply computes_to_val_like_in_max_k_steps_can_iff in comp0; subst.
exists (oterm (Can can) bts) (oterm (Can can) bts) bs k; dands; auto.
{ apply computes_to_val_like_in_max_k_steps_can_iff; sp. }
left; eexists; eexists; dands; eauto.
+ Case "NCan".
remember (compute_step lib (oterm (NCan ncan) bts)) as comp'; destruct comp'; ginv.
apply IHk in comp0; clear IHk; exrepnd; subst; allunfold @nobnd; ginv.
exists x (oterm (NCan ncan) bts) bs' (S m); dands; auto.
rw @computes_to_val_like_in_max_k_steps_S.
exists u; auto.
+ Case "Exc".
apply computes_to_val_like_in_max_k_steps_exc in comp0; subst.
exists (oterm Exc bts) (oterm Exc bts) bs k; dands; auto.
apply computes_to_val_like_in_max_k_steps_exc_iff; sp.
+ Case "Abs".
remember (compute_step lib (oterm (Abs abs) bts)) as comp'; destruct comp'; ginv.
apply IHk in comp0; clear IHk; exrepnd; subst.
allunfold @nobnd; ginv.
exists x (oterm (Abs abs) bts) bs' (S m); dands; auto.
rw @computes_to_val_like_in_max_k_steps_S.
exists u; auto.
Qed.
Lemma extensional_parallel {p} : extensional_op (@NCan p NParallel).
Proof.
introv Hpra Hprt Hprt' Hcv Has Hi.
apply computes_to_val_like_in_max_k_steps_parallel_implies2 in Hcv; exrepnd; ginv.
unfold lblift_sub in Has; simpl in Has; repnd; GC.
destruct lbt'; allsimpl; cpx.
pose proof (Has 0) as h; autodimp h hyp; try omega.
unfold selectbt in h; allsimpl.
unfold blift_sub in h; exrepnd; destruct h1 as [h1|h1]; exrepnd; ginv.
allapply @alpha_eq_bterm_nobnd; exrepnd; allunfold @nobnd; ginv.
destruct b as [l t].
apply alpha_eq_bterm_sym in h0; allapply @alpha_eq_bterm_nobnd; exrepnd; allunfold @nobnd; ginv.
apply isprogram_parallel_implies in Hprt; exrepnd; ginv; allsimpl; cpx.
apply isprogram_parallel_implies in Hprt'; exrepnd; ginv.
applydup @computes_to_val_like_in_max_k_steps_preserves_program in Hcv3; auto.
applydup @alphaeq_preserves_program in h2 as isp1.
applydup @alphaeq_preserves_program in h4 as isp2.
applydup isp1 in Hprt'2.
applydup isp2 in Hprt2.
pose proof (Hi a0 x nt2) as q.
repeat (autodimp q hyp).
{ eauto 3 with slow. }
assert (approx_star lib x a1) as apr by eauto 3 with slow.
repndors; exrepnd; subst; allsimpl.
- apply howe_lemma2 in apr; auto; exrepnd.
apply approx_open_implies_approx_star.
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply (reduces_to_trans _ _ (mk_parallel (oterm (Can c) lbt') b0)).
{ apply reduces_to_prinarg; auto; destruct apr0; auto. }
{ apply reduces_to_if_step; reflexivity. }
- apply isexc_implies in Hcv2; auto; exrepnd; subst; GC.
apply howe_lemma2_exc in apr; auto; exrepnd.
apply (approx_star_open_trans _ _ (mk_exception a' e')).
{ apply approx_star_exception; auto. }
apply approx_implies_approx_open.
apply reduces_to_implies_approx_eauto; prove_isprogram.
apply (reduces_to_trans _ _ (mk_parallel (mk_exception a' e') b0)).
{ apply reduces_to_prinarg; auto. }
{ apply reduces_to_if_step; reflexivity. }
Qed.
Theorem nuprl_extensional {p} : forall op, @extensional_op p op.
(* begin show *)
Proof.
intro op. destruct op.
- apply nuprl_extensional_can.
- dopid_noncan n Case.
+ Case "NApply"; apply extensional_apply.
+ Case "NEApply"; apply extensional_eapply.
+ Case "NApseq"; apply extensional_apseq.
+ Case "NFix"; apply extensional_fix.
+ Case "NSpread"; apply extensional_spread.
+ Case "NDsup"; apply extensional_dsup.
+ Case "NDecide"; apply extensional_decide.
+ Case "NCbv"; apply extensional_cbv.
+ Case "NSleep"; apply extensional_sleep.
+ Case "NTUni"; apply extensional_tuni.
+ Case "NMinus"; apply extensional_minus.
+ Case "NFresh"; apply extensional_fresh.
+ Case "NTryCatch"; apply extensional_trycatch.
+ Case "NParallel"; apply extensional_parallel.
+ Case "NCompOp"; apply extensional_ncomp.
+ Case "NArithOp"; apply extensional_arith.
+ Case "NCanTest"; apply extensional_cantest.
- apply nuprl_extensional_exc.
- apply nuprl_extensional_abs.
Qed.
(* end show *)
(** %\noindent \\*% As we mentioned above, Howe
abstracted the extensionality condition above out
of the proof of the following lemma.
Hence its proof follows directly
from the lemma [nuprl_extensional].
*)
Lemma howe_lemma3 {p} : forall lib (a a' b : @NTerm p),
isprogram a
-> isprogram a'
-> isprogram b
-> computes_to_val_like lib a a'
-> approx_star lib a b
-> approx_star lib a' b.
Proof.
introv Hpra Hpra' Hprb Hc Hs.
repnud Hc; exrepnd.
revert a a' b Hpra Hpra' Hprb Hc0 Hs.
induction k as [| k Hind]; introv Hpra Hpra' Hprb comp ap.
- unfold computes_to_val_like_in_max_k_steps, reduces_in_atmost_k_steps in comp; repnd.
simpl in comp0; inversion comp0; subst; auto.
- destruct a as [|f|o lba]; [inversion Hpra as [c w]; inversion c| |].
+ apply howe_lemma2_seq in ap; auto; exrepnd.
apply computes_to_val_like_in_max_k_steps_if_isvalue_like in comp;
eauto 2 with slow; subst.
econstructor;[eauto|].
apply approx_implies_approx_open.
apply reduces_to_implies_approx1; auto.
+ pose proof (@nuprl_extensional p) as Hex.
applydup @approx_star_otd in ap; auto; []; exrepnd.
unfold extensional_op in Hex.
apply Hex with (lbt' := lbt') in comp; auto.
eapply approx_star_open_trans; eauto.
Qed.
Lemma howe_lemma3_val {p} :
forall lib (a a' b : @NTerm p),
isprogram a
-> isprogram a'
-> isprogram b
-> computes_to_value lib a a'
-> approx_star lib a b
-> approx_star lib a' b.
Proof.
introv ispa ispa' ispb comp ap.
apply @howe_lemma3 with (a := a); auto.
apply computes_to_value_implies_val_like; auto.
Qed.
(*
(* !! MOVE to computation4 *)
Lemma computes_to_marker_implies_val_like {p} :
forall lib (a : @NTerm p) m,
computes_to_marker lib a m
-> computes_to_val_like lib a (mk_marker m).
Proof.
introv comp.
unfold computes_to_val_like, computes_to_val_like_in_max_k_steps.
unfold computes_to_marker, reduces_to in comp.
exrepnd.
exists k; dands; auto.
right.
constructor.
Qed.
*)
Lemma howe_lemma3_exc {p} :
forall lib en (a a' b : @NTerm p),
isprogram en
-> isprogram a
-> isprogram a'
-> isprogram b
-> computes_to_exception lib en a a'
-> approx_star lib a b
-> approx_star lib (mk_exception en a') b.
Proof.
introv ispa ispa' ispb comp ap.
apply @howe_lemma3 with (a := a); auto.
apply isprogram_exception; auto.
apply computes_to_exception_implies_val_like; auto.
Qed.
Lemma computes_to_seq_implies_computes_to_val_like {o} :
forall lib (a : @NTerm o) f,
(a =s>(lib) f)
-> computes_to_val_like lib a (sterm f).
Proof.
introv comp.
unfold computes_to_seq, reduces_to in comp; exrepnd.
unfold computes_to_val_like.
exists k.
unfold computes_to_val_like_in_max_k_steps; dands; eauto 3 with slow.
Qed.
Hint Resolve computes_to_seq_implies_computes_to_val_like : slow.
Lemma howe_lemma3_seq {o} :
forall lib (a b : @NTerm o) f,
isprogram a
-> isprogram b
-> isprogram (sterm f)
-> (a =s>(lib) f)
-> approx_star lib a b
-> approx_star lib (sterm f) b.
Proof.
introv ispa ispa' ispb comp ap.
apply @howe_lemma3 with (a := a); eauto 3 with slow.
Qed.
(*
Lemma howe_lemma3_mrk {p} :
forall lib (a b : @NTerm p) m,
isprogram a
-> isprogram b
-> computes_to_marker lib a m
-> approx_star lib a b
-> approx_star lib (mk_marker m) b.
Proof.
introv ispa ispb comp ap.
apply @howe_lemma3 with (a := a); auto; [apply isprogram_marker|].
apply computes_to_marker_implies_val_like; auto.
Qed.
*)
(* begin hide *)
Lemma alphaeq_preserves_wf_r_eauto {p} :
forall t1 t2 : @NTerm p, alpha_eq t1 t2 -> nt_wf t1 -> nt_wf t2.
Proof.
introv Hal Hw. apply alphaeq_preserves_wf in Hal.
destruct Hal.
auto.
Qed.
Lemma alphaeqbt_preserves_prog_r_eauto {p} :
forall t1 t2 : @BTerm p, alpha_eq_bterm t1 t2 -> isprogram_bt t1 -> isprogram_bt t2.
Proof.
introv Hal Hw. allunfold @isprogram_bt. allunfold @closed_bt. exrepnd. dands.
- apply alphaeqbt_preserves_fvars in Hal. rw Hw0 in Hal.
apply eq_vars_nil in Hal; sp.
- apply alphaeqbt_preserves_wf in Hal; destruct Hal. sp.
Qed.
Hint Resolve alphaeqbt_preserves_prog_r_eauto : slow.
Lemma isprogam_bt_nt_wf_eauto {p} :
forall (lv : list NVar) (nt : @NTerm p), isprogram_bt (bterm lv nt) -> nt_wf nt.
Proof.
introv Hb.
repnud Hb.
apply bt_wf_iff in Hb; sp.
Qed.
Theorem howetheorem1_aux {p}:
forall lib,
(fun a b => @approx_star p lib a b # isprogram a # isprogram b)
=2> (approx lib).
Proof.
intro lib.
apply approx_acc.
introv Cb Cih. intros a b Has.
exrepnd.
constructor.
unfold close_comput.
dands; spcf.
- introv hcv.
applydup @preserve_program in hcv; sp;[].
apply @howe_lemma3_val with (b:=b) in hcv; sp;[].
apply howe_lemma2 in hcv;exrepnd; spc;[].
exists lbt'; dands;sp.
unfold approx_starbts in hcv2.
allunfold @lblift_sub.
exrepnd.
split; spcf.
introv Hlt.
applydup hcv2 in Hlt.
unfold blift.
invertsna Hlt0 Hbas.
exrepnd; repndors; exrepnd; ginv.
exists x nt1 nt2.
dands; sp.
unfold olift.
applydup @preserve_program in hcv1;spcf;[].
applydup @isprogram_ot_iff in hcv4.
applydup @isprogram_ot_iff in hcv0.
exrepnd. clear hcv8 hcv7.
Hint Resolve selectbt_in alphaeq_preserves_wf_r_eauto isprogam_bt_nt_wf_eauto : slow.
assert (n < length lbt') as X99 by omega.
dands; spcf; try (apply isprogam_bt_nt_wf_eauto with (lv:=x); eauto with slow);[].
introv Hw Hpa Hpb.
right.
apply Cih;sp.
apply lsubst_approx_star_congr3;sp.
- introv comp.
applydup @preserve_program_exc2 in comp; sp;[].
apply @howe_lemma3_exc with (b:=b) in comp; sp;[].
apply howe_lemma2_exc in comp; auto;
try (apply isprogram_exception; auto); exrepnd;[].
applydup @preserve_program_exc2 in comp3; auto; repnd.
exists a' e'; dands; auto; tcsp.
- introv comp.
applydup @reduces_to_preserves_program in comp; auto.
eapply howe_lemma3_seq in Has0; eauto.
apply howe_lemma2_seq in Has0; auto; exrepnd.
eexists; dands; eauto.
Qed.
(* end hide *)
(** %\noindent \\*%
Now Howe uses a simple coindiuctive argument to show that
[approx_star] implies [approx] on closed terms.
*)
Theorem howetheorem1 {p} :
forall lib a b,
@approx_star p lib a b
-> isprogram a
-> isprogram b
-> approx lib a b.
Proof.
intros. apply howetheorem1_aux;sp.
Qed.
(** %\noindent \\*%
There are many useful Corollaries of the above theorem.
*)
Corollary approx_star_implies_approx_open {p} :
forall lib (t1 t2 : @NTerm p), approx_star lib t1 t2 -> approx_open lib t1 t2.
Proof.
introv Has.
applydup @approx_star_relates_only_wf in Has. repnd.
unfold approx_open, olift. dands; spcf. introv Hw Hpa Hpb.
apply howetheorem1;sp.
apply lsubst_approx_star_congr3;sp.
Qed.
Corollary approx_star_iff_approx_open {p} :
forall lib (t1 t2 : @NTerm p), approx_star lib t1 t2 <=> approx_open lib t1 t2.
Proof.
split; introv hyp.
- apply approx_star_implies_approx_open;sp.
- apply approx_open_implies_approx_star;sp.
Qed.
Lemma le_blift_sub {p} :
forall op (R1 R2 : bin_rel (@NTerm p)),
le_bin_rel R1 R2 -> le_bin_rel (blift_sub op R1) (blift_sub op R2).
Proof.
unfold le_bin_rel.
intros R1 R2 Hle a b Hrel.
allunfold @blift_sub.
sp.
- exists lv nt1 nt2; split; eauto.
- exists lv nt1 nt2; split; eauto.
subst; right; exists sub; subst; split; eauto.
Defined.
Hint Resolve le_blift_sub : slow.
Lemma le_blift_sub2 {p} :
forall op (R1 R2 : bin_rel (@NTerm p)),
(le_bin_rel R1 R2)
-> forall a b, (blift_sub op R1 a b) -> (blift_sub op R2 a b).
Proof.
intros op R1 R2 n H.
fold (@le_bin_rel (BTerm ) (blift_sub op R1) (blift_sub op R2)).
apply le_blift_sub.
auto.
Defined.
Hint Resolve le_blift_sub2 : slow.
Lemma le_lblift_sub {p} :
forall op (R1 R2 : bin_rel (@NTerm p)),
(le_bin_rel R1 R2)
-> le_bin_rel (lblift_sub op R1) (lblift_sub op R2).
Proof.
unfold lblift_sub; sp.
unfold le_bin_rel; sp.
generalize (X0 n); sp.
apply @le_blift_sub2 with (R1 := R1); sp.
Defined.
Lemma le_lblift_sub2 {p} :
forall op (R1 R2 : bin_rel (@NTerm p)),
(le_bin_rel R1 R2)
-> forall a b, (lblift_sub op R1 a b) -> (lblift_sub op R2 a b).
Proof.
intros op R1 R2 H.
fold (@le_bin_rel (list BTerm) (lblift_sub op R1) (lblift_sub op R2)).
apply le_lblift_sub. auto.
Defined.
Corollary approx_open_congruence_sub {p} :
forall lib (o : Opid) (lbt1 lbt2 : list (@BTerm p)),
lblift_sub o (approx_open lib) lbt1 lbt2
-> nt_wf (oterm o lbt2)
-> approx_open lib (oterm o lbt1) (oterm o lbt2).
Proof.
introv Haps Hnt.
apply (le_lblift_sub2 _ _ _ (approx_open_implies_approx_star lib)) in Haps.
apply approx_star_implies_approx_open.
apply approx_star_congruence2; sp.
Qed.
Corollary approx_open_congruence {p} :
forall lib (o : Opid) (lbt1 lbt2 : list (@BTerm p)),
lblift (approx_open lib) lbt1 lbt2
-> nt_wf (oterm o lbt2)
-> approx_open lib (oterm o lbt1) (oterm o lbt2).
Proof.
introv Haps Hnt.
apply (le_lblift2 _ _ (approx_open_implies_approx_star lib)) in Haps.
apply approx_star_implies_approx_open.
apply approx_star_congruence2; sp.
unfold approx_starbts, lblift_sub.
unfold lblift in Haps; repnd; dands; auto.
introv i; applydup Haps in i as b.
unfold blift in b; unfold blift_sub; exrepnd.
exists lv nt1 nt2; dands; auto.
destruct (dec_op_eq_fresh o) as [d|d]; tcsp.
right.
pose proof (exists_nrut_sub
lv
(get_utokens nt1 ++ get_utokens nt2))
as exnrut; exrepnd.
exists sub; dands; auto.
apply lsubst_approx_star_congr3; eauto with slow.
Qed.
Corollary approx_congruence_sub {p} : forall lib o lbt1 lbt2,
lblift_sub o (approx_open lib) lbt1 lbt2
-> @isprogram p (oterm o lbt1)
-> isprogram (oterm o lbt2)
-> approx lib (oterm o lbt1) (oterm o lbt2).
Proof.
introv Haps H1p H2p.
apply approx_open_approx;sp.
apply approx_open_congruence_sub;sp.
eauto with slow.
Qed.
Corollary approx_congruence {p} : forall lib o lbt1 lbt2,
lblift (approx_open lib) lbt1 lbt2
-> @isprogram p (oterm o lbt1)
-> isprogram (oterm o lbt2)
-> approx lib (oterm o lbt1) (oterm o lbt2).
Proof.
introv Haps H1p H2p.
apply approx_open_approx;sp.
apply approx_open_congruence;sp.
eauto with slow.
Qed.
(* begin hide *)
Ltac prove_approx_lblift :=
unfold lblift; simpl; dands;[spc|];
let Hlt := fresh "XXHlt" in
let n := fresh "XXn" in
intros n Hlt;
( let rnum := (get_lt_rhs Hlt) in
fail_if_not_number rnum; (*fail if not a normal form*)
repeat (destruct n; try omega); unfold selectbt; simpl; unfold nobnd
).
Ltac prove_approx_lblift_sub :=
unfold lblift_sub; simpl; dands;[spc|];
let Hlt := fresh "XXHlt" in
let n := fresh "XXn" in
intros n Hlt;
( let rnum := (get_lt_rhs Hlt) in
fail_if_not_number rnum; (*fail if not a normal form*)
repeat (destruct n; try omega); unfold selectbt; simpl; unfold nobnd
).
Ltac prove_approx :=
unfold_all_mk;
match goal with
| [ |- approx _ ?t ?t] => apply approx_refl
| [ |- approx_open _ ?t ?t] => apply approx_open_refl
| [ |- approx_open _ ?t1 ?t2] => apply approx_implies_approx_open
| [ |- approx _ (oterm ?o _) (oterm ?o _)] => apply approx_congruence
| [ |- isprogram _] => repeat(decomp_progh); show_hyps; repeat(decomp_progc); sp
(* blift *)
| [ |- lblift (olift approx) _ ] => prove_approx_lblift
| [ |- lblift (olift approx) _ _ ] => prove_approx_lblift
| [ |- lblift (approx_open _) _ _ ] => prove_approx_lblift
| [ |- lblift (olift approx) _ _ _ ] => prove_approx_lblift
| [ |- lblift (olift approx) _ _ _ _ ] => prove_approx_lblift
| [ |- blift (olift approx) (bterm [] ?t1) (bterm [] ?t2)] => apply blift_nobnd_congr
| [ |- blift (approx_open _) (bterm [] ?t1) (bterm [] ?t2)] => apply blift_nobnd_congr
(* lblift *)
| [ |- lblift_sub _ (olift approx) _ ] => prove_approx_lblift_sub
| [ |- lblift_sub _ (olift approx) _ _ ] => prove_approx_lblift_sub
| [ |- lblift_sub _ (approx_open _) _ _ ] => prove_approx_lblift_sub
| [ |- lblift_sub _ (olift approx) _ _ _ ] => prove_approx_lblift_sub
| [ |- lblift_sub _ (olift approx) _ _ _ _ ] => prove_approx_lblift_sub
| [ |- blift_sub _ (olift approx) (bterm [] ?t1) (bterm [] ?t2)] => apply blift_nobnd_congr
| [ |- blift_sub _ (approx_open _) (bterm [] ?t1) (bterm [] ?t2)] => apply blift_nobnd_congr
end.
Lemma le_bin_rel_approx1_eauto {p} :
forall lib, le_bin_rel (approx lib) (@approx_star p lib).
Proof.
introv Has.
eauto with slow.
apply approx_star_iff_approx_open.
apply approx_implies_approx_open.
auto.
Qed.
Lemma le_bin_rel_approx2_eauto {p} :
forall lib, le_bin_rel (@approx p lib) (indep_bin_rel isprogram isprogram).
Proof.
introv Has. unfolds_base.
apply approx_relates_only_progs in Has;sp.
Qed.
(* end hide *)
Corollary lsubst_approx_congr {p} : forall lib t1 t2 sub1 sub2,
sub_range_rel (@approx p lib) sub1 sub2
-> approx_open lib t1 t2
-> isprogram (lsubst t1 sub1)
-> isprogram (lsubst t2 sub2)
-> approx lib (lsubst t1 sub1) (lsubst t2 sub2).
Proof.
introv Hsr Hao H1p H2p.
apply (le_sub_range_rel _ _ (le_bin_rel_approx1_eauto lib)) in Hsr.
apply howetheorem1; auto.
apply approx_open_implies_approx_star in Hao.
apply lsubst_approx_star_congr2; auto.
Qed.
(* begin hide *)
Lemma approxbtd_change3 {p} : forall lib bt1 bt2 (lvn: list NVar),
approx_open_bterm lib bt1 bt2
-> no_repeats lvn
-> length lvn = num_bvars bt1
-> disjoint lvn (free_vars_bterm bt1 ++ free_vars_bterm bt2)
-> approx_open lib (apply_bterm bt1 (map vterm lvn))
(apply_bterm bt2 (map (@vterm p) lvn)).
Proof.
introv Hao Hnr Hlen Hdis.
destruct bt1 as [lv1 nt1].
destruct bt2 as [lv2 nt2].
applydup @blift_numbvars in Hao.
apply @approxbtd_change with (lvn:=lvn) in Hao; auto;[].
exrepnd.
unfold apply_bterm. allsimpl.
allrw @fold_var_ren.
allunfold @num_bvars. allsimpl.
apply apply_bterm_alpha_congr2 with (lnt := map vterm lvn) in Hao3; spcls; try congruence;[].
apply apply_bterm_alpha_congr2 with (lnt := map vterm lvn) in Hao4; spcls;
unfold num_bvars; simpl; try congruence;[].
allunfold @apply_bterm.
allsimpl.
allrw (@fold_var_ren).
pose proof (lsubst_trivial_alpha nt2' lvn) as zz.
pose proof (lsubst_trivial_alpha nt1' lvn) as zzz.
assert (alpha_eq nt1' (lsubst nt1 (var_ren lv1 lvn))) as r1 by eauto with slow.
assert (alpha_eq nt2' (lsubst nt2 (var_ren lv2 lvn))) as r2 by eauto with slow.
clear zzz zz Hao0 Hdis Hlen Hnr Hao2 Hao4 Hao3.
eapply approx_open_alpha_rw_lr in Hao1; eauto with slow.
Qed.
Lemma implies_approx_fix {p} :
forall lib a b,
@approx p lib a b
-> approx lib (mk_fix a) (mk_fix b).
Proof.
introv ap.
applydup @approx_relates_only_progs in ap.
repnd.
repeat (prove_approx);sp.
Qed.
Lemma implies_approx_apseq {p} :
forall lib f a b,
@approx p lib a b
-> approx lib (mk_apseq f a) (mk_apseq f b).
Proof.
introv ap.
applydup @approx_relates_only_progs in ap.
repnd.
repeat (prove_approx);sp.
Qed.
Lemma implies_approx_apply {p} :
forall lib f g a b,
approx lib f g
-> @approx p lib a b
-> approx lib (mk_apply f a) (mk_apply g b).
Proof.
introv H1p H2p.
applydup @approx_relates_only_progs in H1p.
applydup @approx_relates_only_progs in H2p.
repnd.
repeat (prove_approx);sp.
Qed.
(*
(* !! MOVE to computation4 *)
Lemma if_computes_to_marker_apply {p} :
forall lib (f a : @NTerm p) m,
isprogram f
-> isprogram a
-> computes_to_marker lib (mk_apply f a) m
-> {v : NVar & {b : NTerm & reduces_to lib f (mk_lam v b)}}.
Proof.
introv.
unfold computes_to_marker, reduces_to.
introv ispf ispa comp; exrepnd.
revert f a ispf ispa comp0.
induction k; simpl; introv ispf ispa comp.
- inversion comp; subst; GC.
- apply reduces_in_atmost_k_steps_S in comp; exrepnd.
simpl in comp1.
destruct f; try (complete (inversion comp1)).
dopid o as [can|ncan|exc|abs] Case; try (complete (inversion comp1)).
+ Case "Can".
csunf comp1; allsimpl.
apply compute_step_apply_success in comp1; exrepnd; subst; cpx; GC.
exists v b 0; sp.
+ Case "NCan".
unfold mk_apply, nobnd in comp1; rw @compute_step_ncan_ncan in comp1.
remember (compute_step lib (oterm (NCan ncan) l)); destruct c; inversion comp1; subst; GC.
symmetry in Heqc.
applydup @preserve_compute_step in Heqc; auto.
apply IHk in comp0; auto.
exrepnd.
exists v b (S k0).
rw @reduces_in_atmost_k_steps_S.
exists n; sp.
+ Case "Exc".
csunf comp1; simpl in comp1; ginv.
apply reduces_atmost_exc in comp0; ginv.
+ Case "Abs".
unfold mk_apply, nobnd in comp1; rw @compute_step_ncan_abs in comp1.
remember (compute_step_lib lib abs l); destruct c; inversion comp1; subst; GC.
symmetry in Heqc.
applydup @isprogram_compute_step_lib in Heqc; auto.
apply IHk in comp0; auto; exrepnd.
exists v b (S k0).
rw @reduces_in_atmost_k_steps_S.
exists n; sp.
Qed.
*)
Lemma hasvalue_like_implies_or {o} :
forall lib (t : @NTerm o),
isprogram t
-> hasvalue_like lib t
-> hasvalue lib t
[+] raises_exception lib t.
Proof.
introv isp hv.
unfold hasvalue_like in hv; exrepnd.
applydup @reduces_to_preserves_program in hv1; auto.
dorn hv0.
- left.
exists v.
unfold computes_to_value; dands; auto.
- right.
apply isexc_implies in hv0; exrepnd; subst; auto.
exists a e; auto.
Qed.
Lemma fix_unfold_approx_fix {p} : forall lib f,
@isprogram p f
-> approx lib (mk_apply f (mk_fix f)) (mk_fix f).
Proof.
introv Hpr.
apply approx_assume_hasvalue;
try match goal with [|- isprogram _] => eauto with slow; fail end.
introv Hv.
apply hasvalue_like_implies_or in Hv;
[|apply isprogram_apply; auto; apply isprogram_fix; complete auto].
dorn Hv.
- unfold hasvalue in Hv; exrepnd.
applydup @if_computes_to_value_apply in Hv0; auto;
allrw @isprog_eq; auto; try (apply isprogram_fix; auto).
repndors; exrepnd.
{ clear Hv1.
applydup @computes_to_value_preserves_program in Hv2; auto.
apply @approx_trans with (b := mk_fix (mk_lam v b)).
+ apply @approx_trans with (b := mk_apply (mk_lam v b) (mk_fix (mk_lam v b))); auto.
* apply implies_approx_apply.
apply reduces_to_implies_approx2; auto.
destruct Hv2; auto.
apply implies_approx_fix.
apply reduces_to_implies_approx2; auto.
destruct Hv2; auto.
* apply reduces_to_implies_approx1; auto.
apply isprogram_fix; auto.
apply reduces_to_if_step; reflexivity.
+ apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram.
destruct Hv2; auto.
}
{ apply @approx_trans with (b := mk_fix (mk_nseq s)).
+ apply @approx_trans with (b := mk_apply (mk_nseq s) (mk_fix (mk_nseq s))); auto.
* apply implies_approx_apply.
{ apply reduces_to_implies_approx2; auto.
destruct Hv1; auto. }
{ apply implies_approx_fix.
apply reduces_to_implies_approx2; auto.
destruct Hv1; auto. }
* apply reduces_to_implies_approx1; auto; prove_isprogram.
apply reduces_to_if_step; reflexivity.
+ apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram.
destruct Hv1; auto.
}
{ apply @approx_trans with (b := mk_fix (mk_ntseq s)).
+ apply @approx_trans with (b := mk_apply (mk_ntseq s) (mk_fix (mk_ntseq s))); auto.
* apply implies_approx_apply.
{ apply reduces_to_implies_approx2; auto.
destruct Hv1; auto. }
{ apply implies_approx_fix.
apply reduces_to_implies_approx2; auto.
destruct Hv1; auto. }
* apply reduces_to_implies_approx1; auto; prove_isprogram.
apply reduces_to_if_step; reflexivity.
+ apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram.
destruct Hv1; auto.
}
- repnud Hv; exrepnd.
applydup @isprogram_fix in Hpr.
apply if_computes_to_exception_apply in Hv1; auto.
repndors; exrepnd.
+ applydup @reduces_to_preserves_program in Hv1; auto.
apply @approx_trans with (b := mk_fix (mk_lam v b)).
* apply @approx_trans with (b := mk_apply (mk_lam v b) (mk_fix (mk_lam v b))); auto.
apply implies_approx_apply.
apply reduces_to_implies_approx2; auto.
apply implies_approx_fix.
apply reduces_to_implies_approx2; auto.
apply reduces_to_implies_approx1; auto.
apply isprogram_fix; auto.
apply reduces_to_if_step; reflexivity.
* apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram; auto.
+ apply @approx_trans with (b := mk_fix (mk_nseq s)).
* apply @approx_trans with (b := mk_apply (mk_nseq s) (mk_fix (mk_nseq s))); auto.
{ apply implies_approx_apply.
{ apply reduces_to_implies_approx2; auto. }
{ apply implies_approx_fix.
apply reduces_to_implies_approx2; auto. }
}
{ apply reduces_to_implies_approx1; auto.
{ apply isprogram_fix; eauto 3 with slow. }
{ apply reduces_to_if_step; reflexivity. }
}
* apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram; auto.
+ apply @approx_trans with (b := mk_fix (mk_ntseq s)).
* apply @approx_trans with (b := mk_apply (mk_ntseq s) (mk_fix (mk_ntseq s))); auto.
{ apply implies_approx_apply.
{ apply reduces_to_implies_approx2; auto. }
{ apply implies_approx_fix.
apply reduces_to_implies_approx2; auto. }
}
{ apply reduces_to_implies_approx1; auto.
{ apply isprogram_fix; eauto 3 with slow. }
{ apply reduces_to_if_step; reflexivity. }
}
* apply implies_approx_fix; auto.
apply reduces_to_implies_approx_eauto; prove_isprogram; auto.
+ applydup @preserve_program_exc2 in Hv1; repnd; auto.
apply approx_trans with (b := mk_apply (mk_exception a e) (mk_fix f)).
* apply implies_approx_apply; auto; try (apply approx_refl; auto).
apply computes_to_exception_implies_approx; auto.
* applydup (isprogram_exception a) in Hv0; auto.
apply approx_trans with (b := mk_fix (mk_exception a e)).
apply approx_trans with (b := mk_exception a e).
apply reduces_to_implies_approx2; auto.
apply isprogram_apply; auto.
apply reduces_to_if_step; reflexivity.
apply reduces_to_implies_approx1; auto.
apply isprogram_fix; auto.
apply reduces_to_if_step; reflexivity.
apply implies_approx_fix.
apply reduces_to_implies_approx1; auto.
Qed.
|
`default_nettype none
//---------------------------------------------------------------------
//-- --
//-- Company: University of Bonn --
//-- Engineer: John Bieling --
//-- --
//---------------------------------------------------------------------
//-- --
//-- Copyright (C) 2015 John Bieling --
//-- --
//-- This program is free software; you can redistribute it and/or --
//-- modify it under the terms of the GNU General Public License as --
//-- published by the Free Software Foundation; either version 3 of --
//-- the License, or (at your option) any later version. --
//-- --
//-- This program is distributed in the hope that it will be useful, --
//-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
//-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
//-- GNU General Public License for more details. --
//-- --
//-- You should have received a copy of the GNU General Public --
//-- License along with this program; if not, see --
//-- <http://www.gnu.org/licenses>. --
//-- --
//---------------------------------------------------------------------
//-- The module can be configured with these parameters (defaults given in braces):
//--
//-- width(1) : BRAM is 36Bit wide. The width parameter defines how many of them
//-- should be used parallel to build the TDC
module BRAMTDC_256_SWITCHING (d, q, tdc_event, tdc_readnext, tdc_switch, CLK, tdc_request, data_size);
parameter width = 1;
output wire [(width*36)-1:0] q;
input wire [(width*36)-1:0] d;
input wire CLK;
input wire tdc_event;
input wire tdc_readnext;
input wire tdc_switch;
input wire tdc_request;
output reg [7:0] data_size;
wire [31:0] data_size_counter;
slimfast_multioption_counter #(.clip_count(0)) DATASIZE_COUNTER (
.countClock(CLK),
.count(tdc_event == 1'b1 && data_size_counter[7:0] != 8'b1111_1111),
.reset(tdc_request),
.countout(data_size_counter));
always@(posedge CLK)
begin
//the stored data_size is without the trigger, so a size of "2" are 3 events
if (tdc_switch == 1'b1) data_size <= data_size_counter[7:0];
end
genvar k;
generate
for (k=0; k < width; k=k+1) begin : TDCS
(* EQUIVALENT_REGISTER_REMOVAL="NO" *) reg area = 1'b0;
wire [31:0] a_write_counter;
wire [7:0] a_read_counter;
wire [7:0] a_write = a_write_counter[7:0];
wire [7:0] a_read = a_read_counter[7:0];
//he will complain about "Property EQUIVALENT REGISTER REMOVAL not applicable on a instance", but it works
(* EQUIVALENT_REGISTER_REMOVAL="NO" *) slimfast_multioption_counter #(.clip_count(0)) WRITE_ADDR_COUNTER (
.countClock(CLK),
.count(tdc_event),
.reset(1'b0),
.countout(a_write_counter));
//he will complain about "Property EQUIVALENT REGISTER REMOVAL not applicable on a instance", but it works
(* EQUIVALENT_REGISTER_REMOVAL="NO" *) loadable_downcounter8 READ_ADDR_COUNTER (
.countClock(CLK),
.count(tdc_readnext),
.loadvalue(a_write),
.load(tdc_switch),
.countout(a_read_counter));
always@(posedge CLK)
begin
if (tdc_switch == 1'b1) area <= ~area;
end
RAMB16_S36_S36 #(
.INIT_A(36'h000000000), // Value of output RAM registers on Port A at startup
.INIT_B(36'h000000000), // Value of output RAM registers on Port B at startup
.SRVAL_A(36'h000000000), // Port A output value upon SSR assertion
.SRVAL_B(36'h000000000), // Port B output value upon SSR assertion
.WRITE_MODE_A("WRITE_FIRST"), // WRITE_FIRST, READ_FIRST or NO_CHANGE
.WRITE_MODE_B("WRITE_FIRST"), // WRITE_FIRST, READ_FIRST or NO_CHANGE
.SIM_COLLISION_CHECK("ALL"), // "NONE", "WARNING_ONLY", "GENERATE_X_ONLY", "ALL"
// The following INIT_xx declarations specify the initial contents of the RAM
// Address 0 to 127
.INIT_00(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_01(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_02(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_03(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_04(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_05(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_06(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_07(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_08(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_09(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0A(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0B(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0C(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0D(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0E(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_0F(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
// Address 128 to 255
.INIT_10(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_11(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_12(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_13(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_14(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_15(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_16(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_17(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_18(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_19(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1A(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1B(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1C(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1D(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1E(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_1F(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
// Address 256 to 383
.INIT_20(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_21(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_22(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_23(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_24(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_25(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_26(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_27(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_28(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_29(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2A(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2B(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2C(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2D(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2E(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_2F(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
// Address 384 to 511
.INIT_30(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_31(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_32(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_33(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_34(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_35(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_36(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_37(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_38(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_39(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3A(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3B(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3C(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3D(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3E(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
.INIT_3F(256'h00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000),
// The next set of INITP_xx are for the parity bits
// Address 0 to 127
.INITP_00(256'h0000000000000000000000000000000000000000000000000000000000000000),
.INITP_01(256'h0000000000000000000000000000000000000000000000000000000000000000),
// Address 128 to 255
.INITP_02(256'h0000000000000000000000000000000000000000000000000000000000000000),
.INITP_03(256'h0000000000000000000000000000000000000000000000000000000000000000),
// Address 256 to 383
.INITP_04(256'h0000000000000000000000000000000000000000000000000000000000000000),
.INITP_05(256'h0000000000000000000000000000000000000000000000000000000000000000),
// Address 384 to 511
.INITP_06(256'h0000000000000000000000000000000000000000000000000000000000000000),
.INITP_07(256'h0000000000000000000000000000000000000000000000000000000000000000)
) RAMB_TDC (
.DIA(d[k*36+31:k*36]), // Port A 32-bit Data Input
.DIPA(d[k*36+35:k*36+32]), // Port A 4-bit parity Input
.DOA(), // Port A 32-bit Data Output
.DOPA(), // Port A 4-bit Parity Output
.ADDRA({area,a_write}), // Port B 9-bit Address Input
.CLKA(CLK), // Port A Clock
.WEA(1'b1), // Port A Write Enable Input
.ENA(1'b1), // Port A RAM Enable Input
.SSRA(1'b0), // Port A Synchronous Set/Reset Input
.DIB(32'b0), // Port B 32-bit Data Input
.DIPB(4'b0), // Port-B 4-bit parity Input
.DOB(q[k*36+31:k*36]), // Port B 32-bit Data Output
.DOPB(q[k*36+35:k*36+32]), // Port B 4-bit Parity Output
.ADDRB({~area,a_read}), // Port A 9-bit Address Input
.CLKB(CLK), // Port B Clock
.ENB(1'b1), // Port B RAM Enable Input
.SSRB(1'b0), // Port B Synchronous Set/Reset Input
.WEB(1'b0) // Port B Write Enable Input
);
end
endgenerate
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_MS__NAND4B_FUNCTIONAL_PP_V
`define SKY130_FD_SC_MS__NAND4B_FUNCTIONAL_PP_V
/**
* nand4b: 4-input NAND, first input inverted.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_ms__udp_pwrgood_pp_pg.v"
`celldefine
module sky130_fd_sc_ms__nand4b (
Y ,
A_N ,
B ,
C ,
D ,
VPWR,
VGND,
VPB ,
VNB
);
// Module ports
output Y ;
input A_N ;
input B ;
input C ;
input D ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
// Local signals
wire not0_out ;
wire nand0_out_Y ;
wire pwrgood_pp0_out_Y;
// Name Output Other arguments
not not0 (not0_out , A_N );
nand nand0 (nand0_out_Y , D, C, B, not0_out );
sky130_fd_sc_ms__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_Y, nand0_out_Y, VPWR, VGND);
buf buf0 (Y , pwrgood_pp0_out_Y );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_MS__NAND4B_FUNCTIONAL_PP_V |
/*
* Copyright (c) 2013 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
module top(
//////// CLOCK //////////
input CLOCK_50,
//input CLOCK2_50,
//input CLOCK3_50,
//input ENETCLK_25,
//////// Sma //////////
//input SMA_CLKIN,
//output SMA_CLKOUT,
//////// LED //////////
output [8:0] LEDG,
output [17:0] LEDR,
//////// KEY //////////
input [3:0] KEY,
//////// SW //////////
input [17:0] SW,
//////// SEG7 //////////
output [6:0] HEX0,
output [6:0] HEX1,
output [6:0] HEX2,
output [6:0] HEX3,
output [6:0] HEX4,
output [6:0] HEX5,
output [6:0] HEX6,
output [6:0] HEX7,
//////// LCD //////////
//output LCD_BLON,
//inout [7:0] LCD_DATA,
//output LCD_EN,
//output LCD_ON,
//output LCD_RS,
//output LCD_RW,
//////////// RS232 //////////
//output UART_CTS,
//input UART_RTS,
input UART_RXD,
output UART_TXD,
//////////// PS2 //////////
//inout PS2_CLK,
//inout PS2_DAT,
//inout PS2_CLK2,
//inout PS2_DAT2,
//////////// SDCARD //////////
//output SD_CLK,
//inout SD_CMD,
//inout [3:0] SD_DAT,
//input SD_WP_N,
//////////// VGA //////////
//output [7:0] VGA_B,
//output VGA_BLANK_N,
//output VGA_CLK,
//output [7:0] VGA_G,
//output VGA_HS,
//output [7:0] VGA_R,
//output VGA_SYNC_N,
//output VGA_VS,
//////////// Audio //////////
//input AUD_ADCDAT,
//inout AUD_ADCLRCK,
//inout AUD_BCLK,
//output AUD_DACDAT,
//inout AUD_DACLRCK,
//output AUD_XCK,
//////////// I2C for EEPROM //////////
//output EEP_I2C_SCLK,
//inout EEP_I2C_SDAT,
//////////// I2C for Audio and Tv-Decode //////////
//output I2C_SCLK,
//inout I2C_SDAT,
//////////// Ethernet 0 //////////
//output ENET0_GTX_CLK,
//input ENET0_INT_N,
//output ENET0_MDC,
//inout ENET0_MDIO,
//output ENET0_RST_N,
//input ENET0_RX_CLK,
//input ENET0_RX_COL,
//input ENET0_RX_CRS,
//input [3:0] ENET0_RX_DATA,
//input ENET0_RX_DV,
//input ENET0_RX_ER,
//input ENET0_TX_CLK,
//output [3:0] ENET0_TX_DATA,
//output ENET0_TX_EN,
//output ENET0_TX_ER,
//input ENET0_LINK100,
//////////// Ethernet 1 //////////
//output ENET1_GTX_CLK,
//input ENET1_INT_N,
//output ENET1_MDC,
//inout ENET1_MDIO,
//output ENET1_RST_N,
//input ENET1_RX_CLK,
//input ENET1_RX_COL,
//input ENET1_RX_CRS,
//input [3:0] ENET1_RX_DATA,
//input ENET1_RX_DV,
//input ENET1_RX_ER,
//input ENET1_TX_CLK,
//output [3:0] ENET1_TX_DATA,
//output ENET1_TX_EN,
//output ENET1_TX_ER,
//input ENET1_LINK100,
//////////// TV Decoder 1 //////////
//input TD_CLK27,
//input [7:0] TD_DATA,
//input TD_HS,
//output TD_RESET_N,
//input TD_VS,
//////////// USB OTG controller //////////
//inout [15:0] OTG_DATA,
//output [1:0] OTG_ADDR,
//output OTG_CS_N,
//output OTG_WR_N,
//output OTG_RD_N,
//input [1:0] OTG_INT,
//output OTG_RST_N,
//input [1:0] OTG_DREQ,
//output [1:0] OTG_DACK_N,
//inout OTG_FSPEED,
//inout OTG_LSPEED,
//////////// IR Receiver //////////
//input IRDA_RXD,
//////////// SDRAM //////////
//output [12:0] DRAM_ADDR,
//output [1:0] DRAM_BA,
//output DRAM_CAS_N,
//output DRAM_CKE,
//output DRAM_CLK,
//output DRAM_CS_N,
//inout [31:0] DRAM_DQ,
//output [3:0] DRAM_DQM,
//output DRAM_RAS_N,
//output DRAM_WE_N,
//////////// SRAM //////////
//output [19:0] SRAM_ADDR,
//output SRAM_CE_N,
//inout [15:0] SRAM_DQ,
//output SRAM_LB_N,
//output SRAM_OE_N,
//output SRAM_UB_N,
//output SRAM_WE_N,
//////////// Flash //////////
//output [22:0] FL_ADDR,
//output FL_CE_N,
//inout [7:0] FL_DQ,
//output FL_OE_N,
//output FL_RST_N,
//input FL_RY,
//output FL_WE_N,
//output FL_WP_N,
//////////// GPIO //////////
inout [35:0] GPIO,
//////////// HSMC (LVDS) //////////
//input HSMC_CLKIN_N1,
//input HSMC_CLKIN_N2,
//input HSMC_CLKIN_P1,
//input HSMC_CLKIN_P2,
//input HSMC_CLKIN0,
//output HSMC_CLKOUT_N1,
//output HSMC_CLKOUT_N2,
//output HSMC_CLKOUT_P1,
//output HSMC_CLKOUT_P2,
//output HSMC_CLKOUT0,
//inout [3:0] HSMC_D,
//input [16:0] HSMC_RX_D_N,
//input [16:0] HSMC_RX_D_P,
//output [16:0] HSMC_TX_D_N,
//output [16:0] HSMC_TX_D_P,
//////// EXTEND IO //////////
//inout [6:0] EX_IO,
/* put a dummy input here to satisfy the apparent requirement that there be something immediately before ); */
input _DUMMY
);
/* global regs */
reg rst;
reg halt;
initial begin
rst <= 0;
halt <= 0;
end
always @(posedge fastclk)
begin
rst = !KEY[0];
end
wire fastclk = CLOCK_50;
/* latch halt on the negedge of the main clock to keep it from glitching the clock
if you hit the key in the middle of an up phase */
always @(negedge fastclk)
begin
if (!KEY[1]) begin
halt <= 1;
end else begin
halt <= 0;
end
end
/* clock generation */
wire slowclk = !halt ? fastclk : 1'b0;
/* instantiate the cpu */
wire cpu_re;
wire cpu_we;
wire [29:0] memaddr;
wire [31:0] rmemdata;
wire [31:0] wmemdata;
wire [31:0] cpudebugout;
cpu cpu0(
.clk(slowclk),
.rst(rst),
.mem_re(cpu_re),
.mem_we(cpu_we),
.memaddr(memaddr),
.rmemdata(rmemdata),
.wmemdata(wmemdata),
.debugout(cpudebugout)
);
/* main memory */
wire mem_re = cpu_re && (memaddr[29] == 0);
wire mem_we = cpu_we && (memaddr[29] == 0);
syncmem mem0(
.clk(slowclk),
.re(mem_re),
.we(mem_we),
.addr(memaddr),
.rdata(rmemdata),
.wdata(wmemdata)
);
/* uart */
wire uart_re = cpu_re && (memaddr[29:14] == 16'b1000000000000000);
wire uart_we = cpu_we && (memaddr[29:14] == 16'b1000000000000000);
uart uart0(
.clk(slowclk),
.rst(rst),
.hwtx(UART_TXD),
.hwrx(UART_RXD),
.addr(memaddr[0]),
.re(uart_re),
.we(uart_we),
.wdata(wmemdata),
.rdata(rmemdata),
.rxchar(),
.rxvalid()
);
/* debug register */
wire debuglatch_we = cpu_we && (memaddr[29:14] == 16'b1000000000000001);
reg[31:0] debuglatch;
always @(posedge slowclk) begin
if (debuglatch_we) begin
debuglatch <= wmemdata;
end
end
//`define WITH_SRAM
`ifdef WITH_SRAM
assign SRAM_UB_N = 0;
assign SRAM_LB_N = 0;
wire read_sync;
wire write_sync;
integer addr;
reg [1:0] retest;
always @(negedge slowclk) begin
retest <= retest + 1;
end
always @(posedge read_sync or posedge write_sync) begin
addr <= addr + 1;
end
sramcontroller sram(
.clk(slowclk),
.addr(addr),
.indata(0),
.re(retest[1]),
.we(retest[0]),
.read_sync(read_sync),
.write_sync(write_sync),
.memclk(memclk),
.sram_addr(SRAM_ADDR),
.sram_data(SRAM_DQ),
.sram_ce(SRAM_CE_N),
.sram_re(SRAM_OE_N),
.sram_we(SRAM_WE_N)
);
`endif
reg[31:0] debugreg;
always @*
begin
if (SW[1]) begin
debugreg = cpudebugout;
end else if (SW[1]) begin
debugreg = rmemdata[31:0];
end else if (SW[0]) begin
debugreg = debuglatch[31:0];
end else begin
debugreg = memaddr[29:0];
end
end
/* debug info */
seven_segment seg0(debugreg[3:0], HEX0);
seven_segment seg1(debugreg[7:4], HEX1);
seven_segment seg2(debugreg[11:8], HEX2);
seven_segment seg3(debugreg[15:12], HEX3);
seven_segment seg4(debugreg[19:16], HEX4);
seven_segment seg5(debugreg[23:20], HEX5);
seven_segment seg6(debugreg[27:24], HEX6);
seven_segment seg7(debugreg[31:28], HEX7);
assign LEDG[0] = rst;
assign LEDG[1] = slowclk;
assign LEDG[2] = mem_re;
assign LEDG[3] = mem_we;
assign LEDG[8:4] = 0;
assign LEDR = 0;
assign GPIO = 0;
//assign GPIO_1[0] = slowclk;
//assign GPIO_1[1] = mem_re;
//assign GPIO_1[2] = mem_we;
//assign GPIO_1[7:3] = memaddr[4:0];
//assign GPIO_1[15:8] = wmemdata[7:0];
//assign GPIO_1[8] = memclk;
//assign GPIO_1[9] = read_sync;
//assign GPIO_1[10] = write_sync;
//assign GPIO_1[11] = SRAM_CE_N;
//assign GPIO_1[12] = SRAM_OE_N;
//assign GPIO_1[15:13] = SRAM_ADDR[2:0];
//assign GPIO_1[0] = UART_TXD;
//assign GPIO_1[1] = UART_RXD;
endmodule
module syncmem(
input clk,
input re,
input we,
input [29:0] addr,
output reg [31:0] rdata,
input [31:0] wdata
);
reg [31:0] mem [0:4096];
initial begin
$readmemh("../test/test2.asm.hex", mem);
end
always @(posedge clk) begin
if (re)
rdata <= mem[addr];
else
rdata <= 32'bzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz;
if (we)
mem[addr] <= wdata;
end
endmodule
|
`timescale 1ns/1ps
module dv_elink_tb();
parameter AW=32;
parameter DW=32;
parameter PW=104;
parameter CW=2; //number of clocks to send int
parameter MW=104;
parameter MAW=10;
parameter MD=1<<MAW;//limit test to 1K transactions
//TODO:generealize
/* verilator lint_off STMTDLY */
/* verilator lint_off UNOPTFLAT */
//REGS
reg clk;
reg reset=1'b0;
reg go;
reg [1:0] datamode;
reg ext_access;
reg ext_write;
reg [1:0] ext_datamode;
reg [3:0] ext_ctrlmode;
reg [31:0] ext_dstaddr;
reg [31:0] ext_data;
reg [31:0] ext_srcaddr;
reg ext_wr_wait;
reg ext_rd_wait;
wire [PW-1:0] ext_packet;
reg init;
reg [MW-1:0] stimarray[MD-1:0];
reg [MW-1:0] transaction;
reg [MAW-1:0] stim_addr;
reg [1:0] state;
reg [31:0] count;
reg start;
integer i;
`ifdef MANUAL
//TODO: make test name a parameter, fancify,...
initial
begin
for(i=0;i<MD;i++)
stimarray[i]='d0;
//$readmemh(`TESTNAME,stimarray,0,`TRANS-1);//How to?
$readmemh("test.memh",stimarray,0,`TRANS-1);
end
`endif
//Forever clock
always
#5 clk = ~clk; //system clock (100MHz)
wire clkstim = clk;
//Reset
initial
begin
#10
reset = 1'b1; // reset is active
start = 1'b0;
clk = 1'b0;
#1000
`ifdef AUTO
//clock config (fast /2)
dv_elink.elink.ecfg.ecfg_clk_reg[15:0] = 16'h0113;
//tx config (enable)
dv_elink.elink.ecfg.ecfg_tx_reg[8:0] = 9'h001;
//rx config (enable)
dv_elink.elink.ecfg.ecfg_rx_reg[4:0] = 5'h01;
`endif
reset = 1'b0; // at time 100 release reset
#4000
start = 1'b1;
#10000
$finish;
end
`define IDLE 2'b00
`define DONE 2'b10
`define GO 2'b01
always @ (posedge clk or posedge reset)
if(reset)
state[1:0] <= `IDLE;//not started
else if(start & (state[1:0]==`IDLE))
state[1:0] <= `GO;//going
else if( ~(|count) & (state[1:0]==`GO))
state[1:0] <= `DONE;//gone
//Notes:The testbench
// connects a 64 bit master to a 32 bit slave
//To make this work, we limit the addresses to 64 bit aligned
//Stimulus Driver
always @ (posedge clkstim)
if(reset)
begin
ext_access <= 1'b0; //empty
ext_write <= 1'b0;
ext_datamode[1:0] <= 2'b0;
ext_ctrlmode[3:0] <= 4'b0;
ext_data[31:0] <= 32'b0;
ext_dstaddr[31:0] <= 32'b0;
ext_srcaddr[31:0] <= 32'b0;
ext_rd_wait <= 1'b0;
ext_wr_wait <= 1'b0;
stim_addr[MAW-1:0] <= 'd0;
transaction[MW-1:0] <= 'd0;
count <= `TRANS;
end
else if ((state[1:0]==`GO) & ~(dut_wr_wait|dut_rd_wait))
begin
transaction[MW-1:0] <= stimarray[stim_addr];
ext_access <= transaction[0];
ext_write <= transaction[1];
ext_datamode[1:0] <= transaction[3:2];
ext_ctrlmode[3:0] <= transaction[7:4];
ext_dstaddr[31:0] <= transaction[39:8];
ext_data[31:0] <= transaction[71:40];
ext_srcaddr[31:0] <= transaction[103:72];
stim_addr[MAW-1:0] <= stim_addr[MAW-1:0] + 1'b1;
count <= count - 1'b1;
end
else
ext_access <= 1'b0;
//Waveform dump
`ifndef TARGET_VERILATOR
initial
begin
$dumpfile("test.vcd");
$dumpvars(0, dv_elink_tb);
end
`endif
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
wire dut_access; // From dv_elink of dv_elink.v
wire dut_failed; // From dv_elink of dv_elink.v
wire [PW-1:0] dut_packet; // From dv_elink of dv_elink.v
wire dut_passed; // From dv_elink of dv_elink.v
wire dut_rd_wait; // From dv_elink of dv_elink.v
wire dut_wr_wait; // From dv_elink of dv_elink.v
// End of automatics
emesh2packet e2p (
// Outputs
.packet_out (ext_packet[PW-1:0]),
// Inputs
.access_in (ext_access),
.write_in (ext_write),
.datamode_in (ext_datamode[1:0]),
.ctrlmode_in (ext_ctrlmode[3:0]),
.dstaddr_in (ext_dstaddr[AW-1:0]),
.data_in (ext_data[DW-1:0]),
.srcaddr_in (ext_srcaddr[AW-1:0]));
//dut
dv_elink dv_elink(/*AUTOINST*/
// Outputs
.dut_passed (dut_passed),
.dut_failed (dut_failed),
.dut_rd_wait (dut_rd_wait),
.dut_wr_wait (dut_wr_wait),
.dut_access (dut_access),
.dut_packet (dut_packet[PW-1:0]),
// Inputs
.clk (clk),
.reset (reset),
.ext_access (ext_access),
.ext_packet (ext_packet[PW-1:0]),
.ext_rd_wait (ext_rd_wait),
.ext_wr_wait (ext_wr_wait));
endmodule // dv_elink_tb
// Local Variables:
// verilog-library-directories:("." "../../emesh/hdl")
// End:
/*
Copyright (C) 2014 Adapteva, Inc.
Contributed by Andreas Olofsson <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.This program is distributed in the hope
that it will be useful,but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have received a copy
of the GNU General Public License along with this program (see the file
COPYING). If not, see <http://www.gnu.org/licenses/>.
*/
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 15:42:20 10/14/2015
// Design Name:
// Module Name: rotator
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Rotator(
input[31:0] RotatorIn,
input[4:0] RotatorBitNum,
input[1:0] RotatorOp,
output[31:0] RotatorOut
);
/*
reg[31:0] RotatorIn;
reg[4:0] RotatorBitNum;
reg[1:0] RotatorOp;
initial begin
RotatorIn = 32'h00001998;
RotatorBitNum = 5'b11001;
RotatorOp = 0;
#100
RotatorOp = 2;
#100
RotatorOp = 3;
end*/
assign RotatorOut =
{32{RotatorOp==2'b00}} & (RotatorIn[31:0] << {1'b0,RotatorBitNum[4:0]}) |
{32{RotatorOp==2'b10}} & ({32'h0,RotatorIn[31:0]} >> {1'b0,RotatorBitNum[4:0]}) |
{32{RotatorOp==2'b11}} & ({{32{RotatorIn[31]}}, RotatorIn[31:0]} >> {1'b0,RotatorBitNum[4:0]}) ;
endmodule
|
// (c) Copyright 1995-2016 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: xilinx.com:ip:axi_protocol_converter:2.1
// IP Revision: 8
`timescale 1ns/1ps
(* DowngradeIPIdentifiedWarnings = "yes" *)
module design_1_auto_pc_1 (
aclk,
aresetn,
s_axi_awid,
s_axi_awaddr,
s_axi_awlen,
s_axi_awsize,
s_axi_awburst,
s_axi_awlock,
s_axi_awcache,
s_axi_awprot,
s_axi_awqos,
s_axi_awvalid,
s_axi_awready,
s_axi_wid,
s_axi_wdata,
s_axi_wstrb,
s_axi_wlast,
s_axi_wvalid,
s_axi_wready,
s_axi_bid,
s_axi_bresp,
s_axi_bvalid,
s_axi_bready,
s_axi_arid,
s_axi_araddr,
s_axi_arlen,
s_axi_arsize,
s_axi_arburst,
s_axi_arlock,
s_axi_arcache,
s_axi_arprot,
s_axi_arqos,
s_axi_arvalid,
s_axi_arready,
s_axi_rid,
s_axi_rdata,
s_axi_rresp,
s_axi_rlast,
s_axi_rvalid,
s_axi_rready,
m_axi_awaddr,
m_axi_awprot,
m_axi_awvalid,
m_axi_awready,
m_axi_wdata,
m_axi_wstrb,
m_axi_wvalid,
m_axi_wready,
m_axi_bresp,
m_axi_bvalid,
m_axi_bready,
m_axi_araddr,
m_axi_arprot,
m_axi_arvalid,
m_axi_arready,
m_axi_rdata,
m_axi_rresp,
m_axi_rvalid,
m_axi_rready
);
(* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 CLK CLK" *)
input wire aclk;
(* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 RST RST" *)
input wire aresetn;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWID" *)
input wire [11 : 0] s_axi_awid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWADDR" *)
input wire [31 : 0] s_axi_awaddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWLEN" *)
input wire [3 : 0] s_axi_awlen;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWSIZE" *)
input wire [2 : 0] s_axi_awsize;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWBURST" *)
input wire [1 : 0] s_axi_awburst;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWLOCK" *)
input wire [1 : 0] s_axi_awlock;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWCACHE" *)
input wire [3 : 0] s_axi_awcache;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWPROT" *)
input wire [2 : 0] s_axi_awprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWQOS" *)
input wire [3 : 0] s_axi_awqos;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWVALID" *)
input wire s_axi_awvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI AWREADY" *)
output wire s_axi_awready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WID" *)
input wire [11 : 0] s_axi_wid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WDATA" *)
input wire [31 : 0] s_axi_wdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WSTRB" *)
input wire [3 : 0] s_axi_wstrb;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WLAST" *)
input wire s_axi_wlast;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WVALID" *)
input wire s_axi_wvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI WREADY" *)
output wire s_axi_wready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI BID" *)
output wire [11 : 0] s_axi_bid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI BRESP" *)
output wire [1 : 0] s_axi_bresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI BVALID" *)
output wire s_axi_bvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI BREADY" *)
input wire s_axi_bready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARID" *)
input wire [11 : 0] s_axi_arid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARADDR" *)
input wire [31 : 0] s_axi_araddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARLEN" *)
input wire [3 : 0] s_axi_arlen;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARSIZE" *)
input wire [2 : 0] s_axi_arsize;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARBURST" *)
input wire [1 : 0] s_axi_arburst;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARLOCK" *)
input wire [1 : 0] s_axi_arlock;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARCACHE" *)
input wire [3 : 0] s_axi_arcache;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARPROT" *)
input wire [2 : 0] s_axi_arprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARQOS" *)
input wire [3 : 0] s_axi_arqos;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARVALID" *)
input wire s_axi_arvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI ARREADY" *)
output wire s_axi_arready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RID" *)
output wire [11 : 0] s_axi_rid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RDATA" *)
output wire [31 : 0] s_axi_rdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RRESP" *)
output wire [1 : 0] s_axi_rresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RLAST" *)
output wire s_axi_rlast;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RVALID" *)
output wire s_axi_rvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 S_AXI RREADY" *)
input wire s_axi_rready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI AWADDR" *)
output wire [31 : 0] m_axi_awaddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI AWPROT" *)
output wire [2 : 0] m_axi_awprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI AWVALID" *)
output wire m_axi_awvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI AWREADY" *)
input wire m_axi_awready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI WDATA" *)
output wire [31 : 0] m_axi_wdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI WSTRB" *)
output wire [3 : 0] m_axi_wstrb;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI WVALID" *)
output wire m_axi_wvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI WREADY" *)
input wire m_axi_wready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI BRESP" *)
input wire [1 : 0] m_axi_bresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI BVALID" *)
input wire m_axi_bvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI BREADY" *)
output wire m_axi_bready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI ARADDR" *)
output wire [31 : 0] m_axi_araddr;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI ARPROT" *)
output wire [2 : 0] m_axi_arprot;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI ARVALID" *)
output wire m_axi_arvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI ARREADY" *)
input wire m_axi_arready;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI RDATA" *)
input wire [31 : 0] m_axi_rdata;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI RRESP" *)
input wire [1 : 0] m_axi_rresp;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI RVALID" *)
input wire m_axi_rvalid;
(* X_INTERFACE_INFO = "xilinx.com:interface:aximm:1.0 M_AXI RREADY" *)
output wire m_axi_rready;
axi_protocol_converter_v2_1_8_axi_protocol_converter #(
.C_FAMILY("zynq"),
.C_M_AXI_PROTOCOL(2),
.C_S_AXI_PROTOCOL(1),
.C_IGNORE_ID(0),
.C_AXI_ID_WIDTH(12),
.C_AXI_ADDR_WIDTH(32),
.C_AXI_DATA_WIDTH(32),
.C_AXI_SUPPORTS_WRITE(1),
.C_AXI_SUPPORTS_READ(1),
.C_AXI_SUPPORTS_USER_SIGNALS(0),
.C_AXI_AWUSER_WIDTH(1),
.C_AXI_ARUSER_WIDTH(1),
.C_AXI_WUSER_WIDTH(1),
.C_AXI_RUSER_WIDTH(1),
.C_AXI_BUSER_WIDTH(1),
.C_TRANSLATION_MODE(2)
) inst (
.aclk(aclk),
.aresetn(aresetn),
.s_axi_awid(s_axi_awid),
.s_axi_awaddr(s_axi_awaddr),
.s_axi_awlen(s_axi_awlen),
.s_axi_awsize(s_axi_awsize),
.s_axi_awburst(s_axi_awburst),
.s_axi_awlock(s_axi_awlock),
.s_axi_awcache(s_axi_awcache),
.s_axi_awprot(s_axi_awprot),
.s_axi_awregion(4'H0),
.s_axi_awqos(s_axi_awqos),
.s_axi_awuser(1'H0),
.s_axi_awvalid(s_axi_awvalid),
.s_axi_awready(s_axi_awready),
.s_axi_wid(s_axi_wid),
.s_axi_wdata(s_axi_wdata),
.s_axi_wstrb(s_axi_wstrb),
.s_axi_wlast(s_axi_wlast),
.s_axi_wuser(1'H0),
.s_axi_wvalid(s_axi_wvalid),
.s_axi_wready(s_axi_wready),
.s_axi_bid(s_axi_bid),
.s_axi_bresp(s_axi_bresp),
.s_axi_buser(),
.s_axi_bvalid(s_axi_bvalid),
.s_axi_bready(s_axi_bready),
.s_axi_arid(s_axi_arid),
.s_axi_araddr(s_axi_araddr),
.s_axi_arlen(s_axi_arlen),
.s_axi_arsize(s_axi_arsize),
.s_axi_arburst(s_axi_arburst),
.s_axi_arlock(s_axi_arlock),
.s_axi_arcache(s_axi_arcache),
.s_axi_arprot(s_axi_arprot),
.s_axi_arregion(4'H0),
.s_axi_arqos(s_axi_arqos),
.s_axi_aruser(1'H0),
.s_axi_arvalid(s_axi_arvalid),
.s_axi_arready(s_axi_arready),
.s_axi_rid(s_axi_rid),
.s_axi_rdata(s_axi_rdata),
.s_axi_rresp(s_axi_rresp),
.s_axi_rlast(s_axi_rlast),
.s_axi_ruser(),
.s_axi_rvalid(s_axi_rvalid),
.s_axi_rready(s_axi_rready),
.m_axi_awid(),
.m_axi_awaddr(m_axi_awaddr),
.m_axi_awlen(),
.m_axi_awsize(),
.m_axi_awburst(),
.m_axi_awlock(),
.m_axi_awcache(),
.m_axi_awprot(m_axi_awprot),
.m_axi_awregion(),
.m_axi_awqos(),
.m_axi_awuser(),
.m_axi_awvalid(m_axi_awvalid),
.m_axi_awready(m_axi_awready),
.m_axi_wid(),
.m_axi_wdata(m_axi_wdata),
.m_axi_wstrb(m_axi_wstrb),
.m_axi_wlast(),
.m_axi_wuser(),
.m_axi_wvalid(m_axi_wvalid),
.m_axi_wready(m_axi_wready),
.m_axi_bid(12'H000),
.m_axi_bresp(m_axi_bresp),
.m_axi_buser(1'H0),
.m_axi_bvalid(m_axi_bvalid),
.m_axi_bready(m_axi_bready),
.m_axi_arid(),
.m_axi_araddr(m_axi_araddr),
.m_axi_arlen(),
.m_axi_arsize(),
.m_axi_arburst(),
.m_axi_arlock(),
.m_axi_arcache(),
.m_axi_arprot(m_axi_arprot),
.m_axi_arregion(),
.m_axi_arqos(),
.m_axi_aruser(),
.m_axi_arvalid(m_axi_arvalid),
.m_axi_arready(m_axi_arready),
.m_axi_rid(12'H000),
.m_axi_rdata(m_axi_rdata),
.m_axi_rresp(m_axi_rresp),
.m_axi_rlast(1'H1),
.m_axi_ruser(1'H0),
.m_axi_rvalid(m_axi_rvalid),
.m_axi_rready(m_axi_rready)
);
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_HD__LPFLOW_ISOBUFSRCKAPWR_16_V
`define SKY130_FD_SC_HD__LPFLOW_ISOBUFSRCKAPWR_16_V
/**
* lpflow_isobufsrckapwr: Input isolation, noninverted sleep on
* keep-alive power rail.
*
* X = (!A | SLEEP)
*
* Verilog wrapper for lpflow_isobufsrckapwr with size of 16 units.
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
`include "sky130_fd_sc_hd__lpflow_isobufsrckapwr.v"
`ifdef USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hd__lpflow_isobufsrckapwr_16 (
X ,
SLEEP,
A ,
KAPWR,
VPWR ,
VGND ,
VPB ,
VNB
);
output X ;
input SLEEP;
input A ;
input KAPWR;
input VPWR ;
input VGND ;
input VPB ;
input VNB ;
sky130_fd_sc_hd__lpflow_isobufsrckapwr base (
.X(X),
.SLEEP(SLEEP),
.A(A),
.KAPWR(KAPWR),
.VPWR(VPWR),
.VGND(VGND),
.VPB(VPB),
.VNB(VNB)
);
endmodule
`endcelldefine
/*********************************************************/
`else // If not USE_POWER_PINS
/*********************************************************/
`celldefine
module sky130_fd_sc_hd__lpflow_isobufsrckapwr_16 (
X ,
SLEEP,
A
);
output X ;
input SLEEP;
input A ;
// Voltage supply signals
supply1 KAPWR;
supply1 VPWR ;
supply0 VGND ;
supply1 VPB ;
supply0 VNB ;
sky130_fd_sc_hd__lpflow_isobufsrckapwr base (
.X(X),
.SLEEP(SLEEP),
.A(A)
);
endmodule
`endcelldefine
/*********************************************************/
`endif // USE_POWER_PINS
`default_nettype wire
`endif // SKY130_FD_SC_HD__LPFLOW_ISOBUFSRCKAPWR_16_V
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__A21OI_FUNCTIONAL_PP_V
`define SKY130_FD_SC_LP__A21OI_FUNCTIONAL_PP_V
/**
* a21oi: 2-input AND into first input of 2-input NOR.
*
* Y = !((A1 & A2) | B1)
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
// Import user defined primitives.
`include "../../models/udp_pwrgood_pp_pg/sky130_fd_sc_lp__udp_pwrgood_pp_pg.v"
`celldefine
module sky130_fd_sc_lp__a21oi (
Y ,
A1 ,
A2 ,
B1 ,
VPWR,
VGND,
VPB ,
VNB
);
// Module ports
output Y ;
input A1 ;
input A2 ;
input B1 ;
input VPWR;
input VGND;
input VPB ;
input VNB ;
// Local signals
wire and0_out ;
wire nor0_out_Y ;
wire pwrgood_pp0_out_Y;
// Name Output Other arguments
and and0 (and0_out , A1, A2 );
nor nor0 (nor0_out_Y , B1, and0_out );
sky130_fd_sc_lp__udp_pwrgood_pp$PG pwrgood_pp0 (pwrgood_pp0_out_Y, nor0_out_Y, VPWR, VGND);
buf buf0 (Y , pwrgood_pp0_out_Y );
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_LP__A21OI_FUNCTIONAL_PP_V |
// File: BDCLed_TBV.v
// Generated by MyHDL 0.10
// Date: Mon Aug 20 12:45:05 2018
`timescale 1ns/10ps
module BDCLed_TBV (
);
// myHDL -> Verilog Testbench for `BDCLed`
reg clk = 0;
wire [1:0] sw;
reg [3:0] led = 0;
wire [7:0] BDCLed0_0_duty_led;
reg [7:0] BDCLed0_0_counter = 0;
assign sw = 2'd0;
assign BDCLed0_0_duty_led = 8'd8;
always @(led, sw, clk) begin: BDCLED_TBV_PRINT_DATA
$write("%h", sw);
$write(" ");
$write("%h", clk);
$write(" ");
$write("%h", led);
$write("\n");
end
always @(posedge clk) begin: BDCLED_TBV_BDCLED0_0_LOGIC
BDCLed0_0_counter <= (BDCLed0_0_counter + 1);
if ((BDCLed0_0_counter < BDCLed0_0_duty_led)) begin
led <= 15;
end
else begin
led <= 0;
end
end
initial begin: BDCLED_TBV_CLK_SIGNAL
while (1'b1) begin
clk <= (!clk);
# 1;
end
end
initial begin: BDCLED_TBV_STIMULES
integer i;
i = 0;
while (1'b1) begin
if ((i == 1000)) begin
$finish;
end
i = i + 1;
@(posedge clk);
end
end
endmodule
|
/*
** -----------------------------------------------------------------------------**
** twelve_ios.v
**
** GPIO control
**
** Copyright (C) 2005-2007 Elphel, Inc
**
** -----------------------------------------------------------------------------**
** This file is part of X353
** X353 is free software - hardware description language (HDL) code.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
** -----------------------------------------------------------------------------**
**
*/
// update to eliminate need for a shadow register
// each pair of data bits at write cycle control the data and enable in the following way:
// bit 1 bit 0 dibit enable data
// 0 0 0 - no change -
// 0 1 1 1 0
// 1 0 2 1 1
// 1 1 3 0 0
//Unified IO control for the 6 pins that are connected from the FPGA to the inter-board 16-pin connector
// those pins were controlled (in models 303, 313, 323 and earlier 333) by the control register, status was
// read through the status register.
// Now each pin will be controlled by 2 bits (data+enable), total 12 bits that will come from one of 4 sources
// selected by bits [13:12] of the new control word:
// 0 - use bits [11:0] of the control word
// 1 - use channel A (USB)?
// 2 - use channel B (tbd)
// 3 - use channel C (tbd)
// Updating logic
// global enable signals (disabled channel will not compete for per-biot access)
// next 4 enable signals are controlled by bit pairs (0X - don't change, 10 - disable, 11 - enable)
// bit [25:24] - enable software bits (contolled by bits [23:0] (on at powerup)
// bit [27:26] - enable chn. A
// bit [29:28] - enable chn. B
// bit [31:30] - enable chn. C
// Enabled bits will be priority encoded (C - highest, software - lowest)
module twelve_ios (sclk, // @negedge
pre_wen, // 1 cycle ahead of write data
di, // [15:0] data in
io_do, // [5:0] data to I/O pins
io_t, // [5:0] tristate I/O pins
da, // [5:0] data from port A (USB?)
da_en, // [5:0] data enable from port A (USB?)
db, // [5:0] data from port B
db_en, // [5:0] data enable from port B
dc, // [5:0] data from port C
dc_en); // [5:0] data enable from port C
input sclk;
input pre_wen;
input [15:0] di;
output [11:0] io_do;
output [11:0] io_t;
input [11:0] da;
input [11:0] da_en;
input [11:0] db;
input [11:0] db_en;
input [11:0] dc;
input [11:0] dc_en;
// wire [23:0] cr; // control register - reset at powerup
wire [11:0] ds; // "software" data (programmed by lower 24 bits)
wire [11:0] ds_en; // "software" data enable (programmed by lower 24 bits)
wire [ 3:0] ch_en; // channel enable
reg pre_wen_d;
reg cr_wen;
reg [31:0] did; // registered (dealyed by 1 clock) version of di[25:0]
wire [11:0] ds_en_m;
wire [11:0] da_en_m;
wire [11:0] db_en_m;
wire [11:0] dc_en_m;
assign dc_en_m[11:0]= dc_en[11:0] & {12{ch_en[3]}};
assign db_en_m[11:0]= db_en[11:0] & {12{ch_en[2]}} & ~dc_en_m[11:0];
assign da_en_m[11:0]= da_en[11:0] & {12{ch_en[1]}} & ~dc_en_m[11:0] & ~db_en_m[11:0];
assign ds_en_m[11:0]= ds_en[11:0] & {12{ch_en[0]}} & ~dc_en_m[11:0] & ~db_en_m[11:0] & ~da_en_m[11:0];
assign io_do[11:0]=(dc_en_m[11:0] & dc[11:0]) |
(db_en_m[11:0] & db[11:0]) |
(da_en_m[11:0] & da[11:0]) |
(ds_en_m[11:0] & ds[11:0]);
assign io_t[11:0]=~(dc_en_m[11:0] | db_en_m[11:0] | da_en_m[11:0] | ds_en_m[11:0]);
// 0 0 0 - no change -
// 0 1 1 1 0
// 1 0 2 1 1
// 1 1 3 0 0
FDE_1 i_ds_0 (.C(sclk), .CE(cr_wen & (did[ 0] | did[ 1])), .D( ~did[ 0] ), .Q(ds[ 0]));
FDE_1 i_ds_1 (.C(sclk), .CE(cr_wen & (did[ 2] | did[ 3])), .D( ~did[ 2] ), .Q(ds[ 1]));
FDE_1 i_ds_2 (.C(sclk), .CE(cr_wen & (did[ 4] | did[ 5])), .D( ~did[ 4] ), .Q(ds[ 2]));
FDE_1 i_ds_3 (.C(sclk), .CE(cr_wen & (did[ 6] | did[ 7])), .D( ~did[ 6] ), .Q(ds[ 3]));
FDE_1 i_ds_4 (.C(sclk), .CE(cr_wen & (did[ 8] | did[ 9])), .D( ~did[ 8] ), .Q(ds[ 4]));
FDE_1 i_ds_5 (.C(sclk), .CE(cr_wen & (did[10] | did[11])), .D( ~did[10] ), .Q(ds[ 5]));
FDE_1 i_ds_6 (.C(sclk), .CE(cr_wen & (did[12] | did[13])), .D( ~did[12] ), .Q(ds[ 6]));
FDE_1 i_ds_7 (.C(sclk), .CE(cr_wen & (did[14] | did[15])), .D( ~did[14] ), .Q(ds[ 7]));
FDE_1 i_ds_8 (.C(sclk), .CE(cr_wen & (did[16] | did[17])), .D( ~did[16] ), .Q(ds[ 8]));
FDE_1 i_ds_9 (.C(sclk), .CE(cr_wen & (did[18] | did[19])), .D( ~did[18] ), .Q(ds[ 9]));
FDE_1 i_ds_10 (.C(sclk), .CE(cr_wen & (did[20] | did[21])), .D( ~did[20] ), .Q(ds[10]));
FDE_1 i_ds_11 (.C(sclk), .CE(cr_wen & (did[22] | did[23])), .D( ~did[22] ), .Q(ds[11]));
FDE_1 i_ds_en_0 (.C(sclk), .CE(cr_wen & (did[ 0] | did[ 1])), .D(~(did[ 1] & did[ 0])), .Q(ds_en[ 0]));
FDE_1 i_ds_en_1 (.C(sclk), .CE(cr_wen & (did[ 2] | did[ 3])), .D(~(did[ 3] & did[ 2])), .Q(ds_en[ 1]));
FDE_1 i_ds_en_2 (.C(sclk), .CE(cr_wen & (did[ 4] | did[ 5])), .D(~(did[ 5] & did[ 4])), .Q(ds_en[ 2]));
FDE_1 i_ds_en_3 (.C(sclk), .CE(cr_wen & (did[ 6] | did[ 7])), .D(~(did[ 7] & did[ 6])), .Q(ds_en[ 3]));
FDE_1 i_ds_en_4 (.C(sclk), .CE(cr_wen & (did[ 8] | did[ 9])), .D(~(did[ 9] & did[ 8])), .Q(ds_en[ 4]));
FDE_1 i_ds_en_5 (.C(sclk), .CE(cr_wen & (did[10] | did[11])), .D(~(did[11] & did[10])), .Q(ds_en[ 5]));
FDE_1 i_ds_en_6 (.C(sclk), .CE(cr_wen & (did[12] | did[13])), .D(~(did[13] & did[12])), .Q(ds_en[ 6]));
FDE_1 i_ds_en_7 (.C(sclk), .CE(cr_wen & (did[14] | did[15])), .D(~(did[15] & did[14])), .Q(ds_en[ 7]));
FDE_1 i_ds_en_8 (.C(sclk), .CE(cr_wen & (did[16] | did[17])), .D(~(did[17] & did[16])), .Q(ds_en[ 8]));
FDE_1 i_ds_en_9 (.C(sclk), .CE(cr_wen & (did[18] | did[19])), .D(~(did[19] & did[18])), .Q(ds_en[ 9]));
FDE_1 i_ds_en_10 (.C(sclk), .CE(cr_wen & (did[20] | did[21])), .D(~(did[21] & did[20])), .Q(ds_en[10]));
FDE_1 i_ds_en_11 (.C(sclk), .CE(cr_wen & (did[22] | did[23])), .D(~(did[23] & did[22])), .Q(ds_en[11]));
FDE_1 #(.INIT(1'b1)) i_ch_en_0 (.C(sclk), .CE(cr_wen & did[25]), .D(did[24]), .Q(ch_en[ 0]));
FDE_1 #(.INIT(1'b0)) i_ch_en_1 (.C(sclk), .CE(cr_wen & did[27]), .D(did[26]), .Q(ch_en[ 1]));
FDE_1 #(.INIT(1'b0)) i_ch_en_2 (.C(sclk), .CE(cr_wen & did[29]), .D(did[28]), .Q(ch_en[ 2]));
FDE_1 #(.INIT(1'b0)) i_ch_en_3 (.C(sclk), .CE(cr_wen & did[31]), .D(did[30]), .Q(ch_en[ 3]));
always @ (negedge sclk) begin
pre_wen_d <= pre_wen;
cr_wen <=pre_wen_d;
if (pre_wen) did[15: 0] <= di[15:0];
if (pre_wen_d) did[31:16] <= di[15:0];
end
endmodule
|
// ======================================================================
// UARTDeepSleepWakeUp.v generated from TopDesign.cysch
// 11/18/2017 at 13:31
// This file is auto generated. ANY EDITS YOU MAKE MAY BE LOST WHEN THIS FILE IS REGENERATED!!!
// ======================================================================
`define CYDEV_CHIP_FAMILY_UNKNOWN 0
`define CYDEV_CHIP_MEMBER_UNKNOWN 0
`define CYDEV_CHIP_FAMILY_PSOC3 1
`define CYDEV_CHIP_MEMBER_3A 1
`define CYDEV_CHIP_REVISION_3A_PRODUCTION 3
`define CYDEV_CHIP_REVISION_3A_ES3 3
`define CYDEV_CHIP_REVISION_3A_ES2 1
`define CYDEV_CHIP_REVISION_3A_ES1 0
`define CYDEV_CHIP_FAMILY_PSOC4 2
`define CYDEV_CHIP_MEMBER_4G 2
`define CYDEV_CHIP_REVISION_4G_PRODUCTION 17
`define CYDEV_CHIP_REVISION_4G_ES 17
`define CYDEV_CHIP_REVISION_4G_ES2 33
`define CYDEV_CHIP_MEMBER_4U 3
`define CYDEV_CHIP_REVISION_4U_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4E 4
`define CYDEV_CHIP_REVISION_4E_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4O 5
`define CYDEV_CHIP_REVISION_4O_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4N 6
`define CYDEV_CHIP_REVISION_4N_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4D 7
`define CYDEV_CHIP_REVISION_4D_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4J 8
`define CYDEV_CHIP_REVISION_4J_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4K 9
`define CYDEV_CHIP_REVISION_4K_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4H 10
`define CYDEV_CHIP_REVISION_4H_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4A 11
`define CYDEV_CHIP_REVISION_4A_PRODUCTION 17
`define CYDEV_CHIP_REVISION_4A_ES0 17
`define CYDEV_CHIP_MEMBER_4F 12
`define CYDEV_CHIP_REVISION_4F_PRODUCTION 0
`define CYDEV_CHIP_REVISION_4F_PRODUCTION_256K 0
`define CYDEV_CHIP_REVISION_4F_PRODUCTION_256DMA 0
`define CYDEV_CHIP_MEMBER_4F 13
`define CYDEV_CHIP_REVISION_4F_PRODUCTION 0
`define CYDEV_CHIP_REVISION_4F_PRODUCTION_256K 0
`define CYDEV_CHIP_REVISION_4F_PRODUCTION_256DMA 0
`define CYDEV_CHIP_MEMBER_4M 14
`define CYDEV_CHIP_REVISION_4M_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4L 15
`define CYDEV_CHIP_REVISION_4L_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4I 16
`define CYDEV_CHIP_REVISION_4I_PRODUCTION 0
`define CYDEV_CHIP_MEMBER_4C 17
`define CYDEV_CHIP_REVISION_4C_PRODUCTION 0
`define CYDEV_CHIP_FAMILY_PSOC5 3
`define CYDEV_CHIP_MEMBER_5B 18
`define CYDEV_CHIP_REVISION_5B_PRODUCTION 0
`define CYDEV_CHIP_REVISION_5B_ES0 0
`define CYDEV_CHIP_MEMBER_5A 19
`define CYDEV_CHIP_REVISION_5A_PRODUCTION 1
`define CYDEV_CHIP_REVISION_5A_ES1 1
`define CYDEV_CHIP_REVISION_5A_ES0 0
`define CYDEV_CHIP_FAMILY_USED 2
`define CYDEV_CHIP_MEMBER_USED 13
`define CYDEV_CHIP_REVISION_USED 0
// Component: cy_virtualmux_v1_0
`ifdef CY_BLK_DIR
`undef CY_BLK_DIR
`endif
`ifdef WARP
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\cy_virtualmux_v1_0"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\cy_virtualmux_v1_0\cy_virtualmux_v1_0.v"
`else
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\cy_virtualmux_v1_0"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\cy_virtualmux_v1_0\cy_virtualmux_v1_0.v"
`endif
// Component: ZeroTerminal
`ifdef CY_BLK_DIR
`undef CY_BLK_DIR
`endif
`ifdef WARP
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\ZeroTerminal"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\ZeroTerminal\ZeroTerminal.v"
`else
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\ZeroTerminal"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\ZeroTerminal\ZeroTerminal.v"
`endif
// Component: or_v1_0
`ifdef CY_BLK_DIR
`undef CY_BLK_DIR
`endif
`ifdef WARP
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\or_v1_0"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\or_v1_0\or_v1_0.v"
`else
`define CY_BLK_DIR "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\or_v1_0"
`include "C:\Program Files (x86)\Cypress\PSoC Creator\3.3\PSoC Creator\psoc\content\cyprimitives\CyPrimitives.cylib\or_v1_0\or_v1_0.v"
`endif
// SCB_P4_v3_20(ApplySbClockParam=false, BitWidthReplacementStringRx=uint8, BitWidthReplacementStringTx=uint8, BufNum=1, Cond=#, DBGW_SCB_IP_V0=false, DBGW_SCB_IP_V1=false, DBGW_SCB_IP_V2=true, DW_Hide_i2c=true, DW_Hide_Scbv0Feature=true, DW_Hide_Scbv2Feature=false, DW_Hide_Spi=true, DW_Hide_Uart=false, DW_Hide_UartFlowControl=false, DW_INTR_SPI_EC=, DW_INTR_SPI_EC_MASK=, DW_INTR_SPI_EC_MASKED=, DW_SPI_CTRL=, DW_SPI_STATUS=, DW_UART_CTRL=UART_SCB__UART_CTRL, DW_UART_FLOW_CTRL=UART_SCB__UART_FLOW_CTRL, DW_UART_RX_CTRL=UART_SCB__UART_RX_CTRL, DW_UART_TX_CTRL=UART_SCB__UART_TX_CTRL, EndCond=#endif, EzI2cBitWidthReplacementString=uint16, EzI2cBusVoltage=3.3, EzI2cByteModeEnable=false, EzI2cClkFreqDes=1550, EzI2cClockFromTerm=false, EzI2cClockStretching=true, EzI2cDataRate=100, EzI2cIsPrimarySlaveAddressHex=true, EzI2cIsSecondarySlaveAddressHex=true, EzI2cMedianFilterEnable=true, EzI2cNumberOfAddresses=0, EzI2cOvsFactor=16, EzI2cPrimarySlaveAddress=8, EzI2cSecondarySlaveAddress=9, EzI2cSlaveAddressMask=254, EzI2cSlewRate=0, EzI2cSubAddressSize=0, EzI2cWakeEnable=false, I2cAcceptAddress=false, I2cAcceptGeneralCall=false, I2cBusVoltage=3.3, I2cBusVoltageLevel=, I2cByteModeEnable=false, I2cClkFreqDes=1550, I2cClockFromTerm=false, I2cDataRate=100, I2cExternIntrHandler=false, I2cIsSlaveAddressHex=true, I2cIsSlaveAddressMaskHex=true, I2cManualOversampleControl=true, I2cMedianFilterEnable=true, I2cMode=1, I2cOvsFactor=16, I2cOvsFactorHigh=8, I2cOvsFactorLow=8, I2cSlaveAddress=8, I2cSlaveAddressMask=254, I2cSlewRate=0, I2cSlewRateSettings=0, I2cWakeEnable=false, PinLocationP4A=false, PinName0Unconfig=uart_rx_i2c_sda_spi_mosi, PinName0UnconfigWake=uart_rx_wake_i2c_sda_spi_mosi, PinName1Unconfig=uart_tx_i2c_scl_spi_miso, PinName2Unconfig=uart_cts_spi_sclk, PinName3Unconfig=uart_rts_spi_ss0, Pn0Unconfig=RX_SDA_MOSI, Pn0UnconfigWake=RX_WAKE_SDA_MOSI, Pn1Unconfig=TX_SCL_MISO, Pn2Unconfig=CTS_SCLK, Pn3Unconfig=RTS_SS0, RemoveI2cPins=true, RemoveMisoSdaTx=true, RemoveMosiSclRx=true, RemoveMosiSclRxWake=true, RemoveScbClk=false, RemoveScbIrq=true, RemoveSpiMasterMiso=true, RemoveSpiMasterMosi=true, RemoveSpiMasterPins=true, RemoveSpiMasterSclk=true, RemoveSpiMasterSs0Pin=true, RemoveSpiMasterSs1Pin=true, RemoveSpiMasterSs2Pin=true, RemoveSpiMasterSs3Pin=true, RemoveSpiSclk=true, RemoveSpiSlaveMiso=true, RemoveSpiSlaveMosi=true, RemoveSpiSlavePins=true, RemoveSpiSs0=true, RemoveSpiSs1=true, RemoveSpiSs2=true, RemoveSpiSs3=true, RemoveUartCtsPin=true, RemoveUartRtsPin=true, RemoveUartRxPin=true, RemoveUartRxTxPin=true, RemoveUartRxWake=false, RemoveUartRxWakeupIrq=false, RemoveUartTxPin=false, RxTriggerOutputEnable=false, ScbClkFreqDes=134.4, ScbClkMinusTolerance=5, ScbClkPlusTolerance=5, ScbClockSelect=1, ScbClockTermEnable=false, ScbCustomIntrHandlerEnable=true, ScbInterruptTermEnable=true, ScbMisoSdaTxEnable=true, ScbMode=4, ScbModeHw=2, ScbMosiSclRxEnable=true, ScbRxWakeIrqEnable=false, ScbSclkEnable=false, ScbSs0Enable=false, ScbSs1Enable=false, ScbSs2Enable=false, ScbSs3Enable=false, ScbSymbolVisibility=0, SpiBitRate=1000, SpiBitsOrder=1, SpiByteModeEnable=false, SpiClkFreqDes=16000, SpiClockFromTerm=false, SpiFreeRunningSclk=false, SpiInterruptMode=0, SpiIntrMasterSpiDone=false, SpiIntrRxFull=false, SpiIntrRxNotEmpty=false, SpiIntrRxOverflow=false, SpiIntrRxTrigger=false, SpiIntrRxUnderflow=false, SpiIntrSlaveBusError=false, SpiIntrTxEmpty=false, SpiIntrTxNotFull=false, SpiIntrTxOverflow=false, SpiIntrTxTrigger=false, SpiIntrTxUnderflow=false, SpiLateMisoSampleEnable=false, SpiManualOversampleControl=true, SpiMasterMode=false, SpiMedianFilterEnable=false, SpimMisoTermEnable=false, SpimMosiTermEnable=false, SpiMode=0, SpimSclkTermEnable=false, SpimSs0TermEnable=false, SpimSs1TermEnable=false, SpimSs2TermEnable=false, SpimSs3TermEnable=false, SpiNumberOfRxDataBits=8, SpiNumberOfSelectLines=1, SpiNumberOfTxDataBits=8, SpiOvsFactor=16, SpiRemoveMiso=false, SpiRemoveMosi=false, SpiRemoveSclk=false, SpiRxBufferSize=8, SpiRxIntrMask=0, SpiRxOutputEnable=false, SpiRxTriggerLevel=7, SpiSclkMode=0, SpiSlaveMode=false, SpiSmartioEnable=false, SpisMisoTermEnable=false, SpisMosiTermEnable=false, SpiSs0Polarity=0, SpiSs1Polarity=0, SpiSs2Polarity=0, SpiSs3Polarity=0, SpisSclkTermEnable=false, SpisSsTermEnable=false, SpiSubMode=0, SpiTransferSeparation=1, SpiTxBufferSize=8, SpiTxIntrMask=0, SpiTxOutputEnable=false, SpiTxTriggerLevel=0, SpiWakeEnable=false, TermMode_clock=0, TermMode_interrupt=0, TermVisibility_clock=false, TermVisibility_interrupt=true, TriggerOutputEnable=false, TxTriggerOutputEnable=false, UartByteModeEnable=false, UartClkFreqDes=134.4, UartClockFromTerm=false, UartCtsEnable=false, UartCtsPolarity=0, UartCtsTermEnable=false, UartDataRate=9600, UartDirection=3, UartDropOnFrameErr=false, UartDropOnParityErr=false, UartInterruptMode=2, UartIntrRxFrameErr=false, UartIntrRxFull=false, UartIntrRxNotEmpty=true, UartIntrRxOverflow=false, UartIntrRxParityErr=false, UartIntrRxTrigger=false, UartIntrRxUnderflow=false, UartIntrTxEmpty=false, UartIntrTxNotFull=false, UartIntrTxOverflow=false, UartIntrTxTrigger=false, UartIntrTxUartDone=false, UartIntrTxUartLostArb=false, UartIntrTxUartNack=false, UartIntrTxUnderflow=false, UartIrdaLowPower=false, UartIrdaPolarity=0, UartMedianFilterEnable=false, UartMpEnable=false, UartMpRxAcceptAddress=false, UartMpRxAddress=2, UartMpRxAddressMask=255, UartNumberOfDataBits=8, UartNumberOfStopBits=2, UartOvsFactor=14, UartParityType=2, UartRtsEnable=false, UartRtsPolarity=0, UartRtsTermEnable=false, UartRtsTriggerLevel=4, UartRxBufferSize=8, UartRxEnable=true, UartRxIntrMask=4, UartRxOutputEnable=false, UartRxTermEnable=false, UartRxTriggerLevel=7, UartSmartioEnable=false, UartSmCardRetryOnNack=false, UartSubMode=0, UartTxBufferSize=8, UartTxEnable=true, UartTxIntrMask=0, UartTxOutputEnable=false, UartTxTermEnable=false, UartTxTriggerLevel=0, UartWakeEnable=true, CY_API_CALLBACK_HEADER_INCLUDE=#include "cyapicallbacks.h", CY_COMPONENT_NAME=SCB_P4_v3_20, CY_CONTROL_FILE=<:default:>, CY_DATASHEET_FILE=<:default:>, CY_FITTER_NAME=UART, CY_INSTANCE_SHORT_NAME=UART, CY_MAJOR_VERSION=3, CY_MINOR_VERSION=20, CY_REMOVE=false, CY_SUPPRESS_API_GEN=false, CY_VERSION=PSoC Creator 3.3 CP3, INSTANCE_NAME=UART, )
module SCB_P4_v3_20_0 (
interrupt,
clock,
rx_tr_out,
tx_tr_out,
s_mosi,
s_sclk,
s_ss,
m_miso,
m_mosi,
m_sclk,
m_ss0,
m_ss1,
m_ss2,
m_ss3,
s_miso,
rx_in,
cts_in,
tx_out,
rts_out);
output interrupt;
input clock;
output rx_tr_out;
output tx_tr_out;
input s_mosi;
input s_sclk;
input s_ss;
input m_miso;
output m_mosi;
output m_sclk;
output m_ss0;
output m_ss1;
output m_ss2;
output m_ss3;
output s_miso;
input rx_in;
input cts_in;
output tx_out;
output rts_out;
wire uncfg_rx_irq;
wire sclk_m_wire;
wire Net_1264;
wire Net_1258;
wire rx_irq;
wire [3:0] select_m_wire;
wire Net_1099;
wire Net_1090;
wire Net_467;
wire Net_1316;
wire Net_252;
wire Net_1089;
wire Net_1320;
wire Net_1257;
wire sclk_s_wire;
wire Net_1268;
wire Net_1297;
wire Net_547;
wire Net_1001;
wire mosi_s_wire;
wire rts_wire;
wire mosi_m_wire;
wire Net_891;
wire Net_1263;
wire miso_s_wire;
wire cts_wire;
wire Net_899;
wire tx_wire;
wire Net_1028;
wire rx_wire;
wire Net_916;
wire Net_1000;
wire scl_wire;
wire miso_m_wire;
wire Net_1172;
wire Net_1170;
wire select_s_wire;
wire sda_wire;
wire Net_847;
cy_clock_v1_0
#(.id("43ec2fa1-bf22-4b71-9477-b6ca7b97f0b0/2dc2d7a8-ce2b-43c7-af4a-821c8cd73ccf"),
.source_clock_id(""),
.divisor(0),
.period("7440476190.47619"),
.is_direct(0),
.is_digital(0))
SCBCLK
(.clock_out(Net_847));
// select_s_VM (cy_virtualmux_v1_0)
assign select_s_wire = s_ss;
// rx_VM (cy_virtualmux_v1_0)
assign rx_wire = Net_1172;
wire [0:0] tmpOE__rx_wake_net;
wire [0:0] tmpIO_0__rx_wake_net;
electrical [0:0] tmpSIOVREF__rx_wake_net;
cy_psoc3_pins_v1_10
#(.id("43ec2fa1-bf22-4b71-9477-b6ca7b97f0b0/e9408829-61ce-4f43-b0c1-855b87d0fbdc"),
.drive_mode(3'b001),
.ibuf_enabled(1'b1),
.init_dr_st(1'b0),
.input_clk_en(0),
.input_sync(1'b0),
.input_sync_mode(1'b0),
.intr_mode(2'b10),
.invert_in_clock(0),
.invert_in_clock_en(0),
.invert_in_reset(0),
.invert_out_clock(0),
.invert_out_clock_en(0),
.invert_out_reset(0),
.io_voltage(""),
.layout_mode("CONTIGUOUS"),
.oe_conn(1'b0),
.oe_reset(0),
.oe_sync(1'b0),
.output_clk_en(0),
.output_clock_mode(1'b0),
.output_conn(1'b0),
.output_mode(1'b0),
.output_reset(0),
.output_sync(1'b0),
.pa_in_clock(-1),
.pa_in_clock_en(-1),
.pa_in_reset(-1),
.pa_out_clock(-1),
.pa_out_clock_en(-1),
.pa_out_reset(-1),
.pin_aliases(""),
.pin_mode("I"),
.por_state(4),
.sio_group_cnt(0),
.sio_hyst(1'b1),
.sio_ibuf(""),
.sio_info(2'b00),
.sio_obuf(""),
.sio_refsel(""),
.sio_vtrip(""),
.sio_hifreq(""),
.sio_vohsel(""),
.slew_rate(1'b0),
.spanning(0),
.use_annotation(1'b0),
.vtrip(2'b00),
.width(1),
.ovt_hyst_trim(1'b0),
.ovt_needed(1'b0),
.ovt_slew_control(2'b00),
.input_buffer_sel(2'b00))
rx_wake
(.oe(tmpOE__rx_wake_net),
.y({1'b0}),
.fb({Net_1172}),
.io({tmpIO_0__rx_wake_net[0:0]}),
.siovref(tmpSIOVREF__rx_wake_net),
.interrupt({rx_irq}),
.in_clock({1'b0}),
.in_clock_en({1'b1}),
.in_reset({1'b0}),
.out_clock({1'b0}),
.out_clock_en({1'b1}),
.out_reset({1'b0}));
assign tmpOE__rx_wake_net = (`CYDEV_CHIP_MEMBER_USED == `CYDEV_CHIP_MEMBER_3A && `CYDEV_CHIP_REVISION_USED < `CYDEV_CHIP_REVISION_3A_ES3) ? ~{1'b1} : {1'b1};
// rx_wake_VM (cy_virtualmux_v1_0)
assign Net_1257 = rx_irq;
cy_isr_v1_0
#(.int_type(2'b10))
RX_WAKEUP_IRQ
(.int_signal(Net_1257));
// clock_VM (cy_virtualmux_v1_0)
assign Net_1170 = Net_847;
// sclk_s_VM (cy_virtualmux_v1_0)
assign sclk_s_wire = s_sclk;
// mosi_s_VM (cy_virtualmux_v1_0)
assign mosi_s_wire = s_mosi;
// miso_m_VM (cy_virtualmux_v1_0)
assign miso_m_wire = m_miso;
wire [0:0] tmpOE__tx_net;
wire [0:0] tmpFB_0__tx_net;
wire [0:0] tmpIO_0__tx_net;
wire [0:0] tmpINTERRUPT_0__tx_net;
electrical [0:0] tmpSIOVREF__tx_net;
cy_psoc3_pins_v1_10
#(.id("43ec2fa1-bf22-4b71-9477-b6ca7b97f0b0/23b8206d-1c77-4e61-be4a-b4037d5de5fc"),
.drive_mode(3'b110),
.ibuf_enabled(1'b0),
.init_dr_st(1'b1),
.input_clk_en(0),
.input_sync(1'b0),
.input_sync_mode(1'b0),
.intr_mode(2'b00),
.invert_in_clock(0),
.invert_in_clock_en(0),
.invert_in_reset(0),
.invert_out_clock(0),
.invert_out_clock_en(0),
.invert_out_reset(0),
.io_voltage(""),
.layout_mode("CONTIGUOUS"),
.oe_conn(1'b0),
.oe_reset(0),
.oe_sync(1'b0),
.output_clk_en(0),
.output_clock_mode(1'b0),
.output_conn(1'b1),
.output_mode(1'b0),
.output_reset(0),
.output_sync(1'b0),
.pa_in_clock(-1),
.pa_in_clock_en(-1),
.pa_in_reset(-1),
.pa_out_clock(-1),
.pa_out_clock_en(-1),
.pa_out_reset(-1),
.pin_aliases(""),
.pin_mode("B"),
.por_state(4),
.sio_group_cnt(0),
.sio_hyst(1'b1),
.sio_ibuf(""),
.sio_info(2'b00),
.sio_obuf(""),
.sio_refsel(""),
.sio_vtrip(""),
.sio_hifreq(""),
.sio_vohsel(""),
.slew_rate(1'b0),
.spanning(0),
.use_annotation(1'b0),
.vtrip(2'b00),
.width(1),
.ovt_hyst_trim(1'b0),
.ovt_needed(1'b0),
.ovt_slew_control(2'b00),
.input_buffer_sel(2'b00))
tx
(.oe(tmpOE__tx_net),
.y({tx_wire}),
.fb({tmpFB_0__tx_net[0:0]}),
.io({tmpIO_0__tx_net[0:0]}),
.siovref(tmpSIOVREF__tx_net),
.interrupt({tmpINTERRUPT_0__tx_net[0:0]}),
.in_clock({1'b0}),
.in_clock_en({1'b1}),
.in_reset({1'b0}),
.out_clock({1'b0}),
.out_clock_en({1'b1}),
.out_reset({1'b0}));
assign tmpOE__tx_net = (`CYDEV_CHIP_MEMBER_USED == `CYDEV_CHIP_MEMBER_3A && `CYDEV_CHIP_REVISION_USED < `CYDEV_CHIP_REVISION_3A_ES3) ? ~{1'b1} : {1'b1};
ZeroTerminal ZeroTerminal_7 (
.z(Net_1099));
assign Net_1258 = Net_847 | Net_1099;
// cts_VM (cy_virtualmux_v1_0)
assign cts_wire = cts_in;
cy_m0s8_scb_v2_0 SCB (
.rx(rx_wire),
.miso_m(miso_m_wire),
.select_m(select_m_wire[3:0]),
.sclk_m(sclk_m_wire),
.mosi_s(mosi_s_wire),
.select_s(select_s_wire),
.sclk_s(sclk_s_wire),
.mosi_m(mosi_m_wire),
.scl(scl_wire),
.sda(sda_wire),
.tx(tx_wire),
.miso_s(miso_s_wire),
.interrupt(interrupt),
.cts(cts_wire),
.rts(rts_wire),
.tx_req(tx_tr_out),
.rx_req(rx_tr_out),
.clock(Net_1170));
defparam SCB.scb_mode = 2;
// Device_VM4 (cy_virtualmux_v1_0)
assign uncfg_rx_irq = Net_1000;
assign m_mosi = mosi_m_wire;
assign m_sclk = sclk_m_wire;
assign m_ss0 = select_m_wire[0];
assign m_ss1 = select_m_wire[1];
assign m_ss2 = select_m_wire[2];
assign m_ss3 = select_m_wire[3];
assign s_miso = miso_s_wire;
assign tx_out = tx_wire;
assign rts_out = rts_wire;
endmodule
// top
module top ;
wire Net_3491;
wire Net_3490;
wire Net_3489;
wire Net_3488;
wire Net_3487;
wire Net_3486;
wire Net_3485;
wire Net_3484;
wire Net_3483;
wire Net_3482;
wire Net_3481;
wire Net_3480;
wire Net_3479;
wire Net_3478;
wire Net_3477;
wire Net_3476;
wire Net_3475;
wire Net_3474;
wire Net_3473;
wire Net_3450;
wire [0:0] tmpOE__LED_G_net;
wire [0:0] tmpFB_0__LED_G_net;
wire [0:0] tmpIO_0__LED_G_net;
wire [0:0] tmpINTERRUPT_0__LED_G_net;
electrical [0:0] tmpSIOVREF__LED_G_net;
cy_psoc3_pins_v1_10
#(.id("e851a3b9-efb8-48be-bbb8-b303b216c393"),
.drive_mode(3'b110),
.ibuf_enabled(1'b1),
.init_dr_st(1'b1),
.input_clk_en(0),
.input_sync(1'b1),
.input_sync_mode(1'b0),
.intr_mode(2'b00),
.invert_in_clock(0),
.invert_in_clock_en(0),
.invert_in_reset(0),
.invert_out_clock(0),
.invert_out_clock_en(0),
.invert_out_reset(0),
.io_voltage(""),
.layout_mode("CONTIGUOUS"),
.oe_conn(1'b0),
.oe_reset(0),
.oe_sync(1'b0),
.output_clk_en(0),
.output_clock_mode(1'b0),
.output_conn(1'b0),
.output_mode(1'b0),
.output_reset(0),
.output_sync(1'b0),
.pa_in_clock(-1),
.pa_in_clock_en(-1),
.pa_in_reset(-1),
.pa_out_clock(-1),
.pa_out_clock_en(-1),
.pa_out_reset(-1),
.pin_aliases(""),
.pin_mode("O"),
.por_state(4),
.sio_group_cnt(0),
.sio_hyst(1'b1),
.sio_ibuf(""),
.sio_info(2'b00),
.sio_obuf(""),
.sio_refsel(""),
.sio_vtrip(""),
.sio_hifreq(""),
.sio_vohsel(""),
.slew_rate(1'b0),
.spanning(0),
.use_annotation(1'b0),
.vtrip(2'b10),
.width(1),
.ovt_hyst_trim(1'b0),
.ovt_needed(1'b0),
.ovt_slew_control(2'b00),
.input_buffer_sel(2'b00))
LED_G
(.oe(tmpOE__LED_G_net),
.y({1'b0}),
.fb({tmpFB_0__LED_G_net[0:0]}),
.io({tmpIO_0__LED_G_net[0:0]}),
.siovref(tmpSIOVREF__LED_G_net),
.interrupt({tmpINTERRUPT_0__LED_G_net[0:0]}),
.in_clock({1'b0}),
.in_clock_en({1'b1}),
.in_reset({1'b0}),
.out_clock({1'b0}),
.out_clock_en({1'b1}),
.out_reset({1'b0}));
assign tmpOE__LED_G_net = (`CYDEV_CHIP_MEMBER_USED == `CYDEV_CHIP_MEMBER_3A && `CYDEV_CHIP_REVISION_USED < `CYDEV_CHIP_REVISION_3A_ES3) ? ~{1'b1} : {1'b1};
wire [0:0] tmpOE__LED_R_net;
wire [0:0] tmpFB_0__LED_R_net;
wire [0:0] tmpIO_0__LED_R_net;
wire [0:0] tmpINTERRUPT_0__LED_R_net;
electrical [0:0] tmpSIOVREF__LED_R_net;
cy_psoc3_pins_v1_10
#(.id("46bcb939-fabe-42b9-90af-3e1c6577dc70"),
.drive_mode(3'b110),
.ibuf_enabled(1'b1),
.init_dr_st(1'b1),
.input_clk_en(0),
.input_sync(1'b1),
.input_sync_mode(1'b0),
.intr_mode(2'b00),
.invert_in_clock(0),
.invert_in_clock_en(0),
.invert_in_reset(0),
.invert_out_clock(0),
.invert_out_clock_en(0),
.invert_out_reset(0),
.io_voltage(""),
.layout_mode("CONTIGUOUS"),
.oe_conn(1'b0),
.oe_reset(0),
.oe_sync(1'b0),
.output_clk_en(0),
.output_clock_mode(1'b0),
.output_conn(1'b0),
.output_mode(1'b0),
.output_reset(0),
.output_sync(1'b0),
.pa_in_clock(-1),
.pa_in_clock_en(-1),
.pa_in_reset(-1),
.pa_out_clock(-1),
.pa_out_clock_en(-1),
.pa_out_reset(-1),
.pin_aliases(""),
.pin_mode("O"),
.por_state(4),
.sio_group_cnt(0),
.sio_hyst(1'b1),
.sio_ibuf(""),
.sio_info(2'b00),
.sio_obuf(""),
.sio_refsel(""),
.sio_vtrip(""),
.sio_hifreq(""),
.sio_vohsel(""),
.slew_rate(1'b0),
.spanning(0),
.use_annotation(1'b0),
.vtrip(2'b10),
.width(1),
.ovt_hyst_trim(1'b0),
.ovt_needed(1'b0),
.ovt_slew_control(2'b00),
.input_buffer_sel(2'b00))
LED_R
(.oe(tmpOE__LED_R_net),
.y({1'b0}),
.fb({tmpFB_0__LED_R_net[0:0]}),
.io({tmpIO_0__LED_R_net[0:0]}),
.siovref(tmpSIOVREF__LED_R_net),
.interrupt({tmpINTERRUPT_0__LED_R_net[0:0]}),
.in_clock({1'b0}),
.in_clock_en({1'b1}),
.in_reset({1'b0}),
.out_clock({1'b0}),
.out_clock_en({1'b1}),
.out_reset({1'b0}));
assign tmpOE__LED_R_net = (`CYDEV_CHIP_MEMBER_USED == `CYDEV_CHIP_MEMBER_3A && `CYDEV_CHIP_REVISION_USED < `CYDEV_CHIP_REVISION_3A_ES3) ? ~{1'b1} : {1'b1};
cy_isr_v1_0
#(.int_type(2'b10))
WDT_isr
(.int_signal(Net_3450));
cy_gsref_v1_0
#(.guid("1563FAA8-0748-4a1c-9785-CED309984BE3"))
WDT
(.sig_out(Net_3450));
SCB_P4_v3_20_0 UART (
.cts_in(1'b0),
.tx_out(Net_3474),
.rts_out(Net_3475),
.interrupt(Net_3476),
.clock(1'b0),
.rx_tr_out(Net_3478),
.tx_tr_out(Net_3479),
.s_mosi(1'b0),
.s_sclk(1'b0),
.s_ss(1'b0),
.m_miso(1'b0),
.m_mosi(Net_3484),
.m_sclk(Net_3485),
.m_ss0(Net_3486),
.m_ss1(Net_3487),
.m_ss2(Net_3488),
.m_ss3(Net_3489),
.s_miso(Net_3490),
.rx_in(1'b0));
wire [0:0] tmpOE__LED_B_net;
wire [0:0] tmpFB_0__LED_B_net;
wire [0:0] tmpIO_0__LED_B_net;
wire [0:0] tmpINTERRUPT_0__LED_B_net;
electrical [0:0] tmpSIOVREF__LED_B_net;
cy_psoc3_pins_v1_10
#(.id("3b8d3c3c-27ec-4327-b3ef-9251ee2d52b4"),
.drive_mode(3'b110),
.ibuf_enabled(1'b1),
.init_dr_st(1'b1),
.input_clk_en(0),
.input_sync(1'b1),
.input_sync_mode(1'b0),
.intr_mode(2'b00),
.invert_in_clock(0),
.invert_in_clock_en(0),
.invert_in_reset(0),
.invert_out_clock(0),
.invert_out_clock_en(0),
.invert_out_reset(0),
.io_voltage(""),
.layout_mode("CONTIGUOUS"),
.oe_conn(1'b0),
.oe_reset(0),
.oe_sync(1'b0),
.output_clk_en(0),
.output_clock_mode(1'b0),
.output_conn(1'b0),
.output_mode(1'b0),
.output_reset(0),
.output_sync(1'b0),
.pa_in_clock(-1),
.pa_in_clock_en(-1),
.pa_in_reset(-1),
.pa_out_clock(-1),
.pa_out_clock_en(-1),
.pa_out_reset(-1),
.pin_aliases(""),
.pin_mode("O"),
.por_state(4),
.sio_group_cnt(0),
.sio_hyst(1'b1),
.sio_ibuf(""),
.sio_info(2'b00),
.sio_obuf(""),
.sio_refsel(""),
.sio_vtrip(""),
.sio_hifreq(""),
.sio_vohsel(""),
.slew_rate(1'b0),
.spanning(0),
.use_annotation(1'b0),
.vtrip(2'b10),
.width(1),
.ovt_hyst_trim(1'b0),
.ovt_needed(1'b0),
.ovt_slew_control(2'b00),
.input_buffer_sel(2'b00))
LED_B
(.oe(tmpOE__LED_B_net),
.y({1'b0}),
.fb({tmpFB_0__LED_B_net[0:0]}),
.io({tmpIO_0__LED_B_net[0:0]}),
.siovref(tmpSIOVREF__LED_B_net),
.interrupt({tmpINTERRUPT_0__LED_B_net[0:0]}),
.in_clock({1'b0}),
.in_clock_en({1'b1}),
.in_reset({1'b0}),
.out_clock({1'b0}),
.out_clock_en({1'b1}),
.out_reset({1'b0}));
assign tmpOE__LED_B_net = (`CYDEV_CHIP_MEMBER_USED == `CYDEV_CHIP_MEMBER_3A && `CYDEV_CHIP_REVISION_USED < `CYDEV_CHIP_REVISION_3A_ES3) ? ~{1'b1} : {1'b1};
cy_isr_v1_0
#(.int_type(2'b10))
UART_isr
(.int_signal(Net_3476));
endmodule
|
/*
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LP__DECAPKAPWR_BEHAVIORAL_V
`define SKY130_FD_SC_LP__DECAPKAPWR_BEHAVIORAL_V
/**
* decapkapwr: Decoupling capacitance filler on keep-alive rail.
*
* Verilog simulation functional model.
*/
`timescale 1ns / 1ps
`default_nettype none
`celldefine
module sky130_fd_sc_lp__decapkapwr ();
// Module supplies
supply1 KAPWR;
supply1 VPWR ;
supply0 VGND ;
supply1 VPB ;
supply0 VNB ;
// No contents.
endmodule
`endcelldefine
`default_nettype wire
`endif // SKY130_FD_SC_LP__DECAPKAPWR_BEHAVIORAL_V |
/******************************************************************************
* License Agreement *
* *
* Copyright (c) 1991-2009 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Any megafunction design, and related net list (encrypted or decrypted), *
* support information, device programming or simulation file, and any other *
* associated documentation or information provided by Altera or a partner *
* under Altera's Megafunction Partnership Program may be used only to *
* program PLD devices (but not masked PLD devices) from Altera. Any other *
* use of such megafunction design, net list, support information, device *
* programming or simulation file, or any other related documentation or *
* information is prohibited for any other purpose, including, but not *
* limited to modification, reverse engineering, de-compiling, or use with *
* any other silicon devices, unless such use is explicitly licensed under *
* a separate agreement with Altera or a megafunction partner. Title to *
* the intellectual property, including patents, copyrights, trademarks, *
* trade secrets, or maskworks, embodied in any such megafunction design, *
* net list, support information, device programming or simulation file, or *
* any other related documentation or information provided by Altera or a *
* megafunction partner, remains with Altera, the megafunction partner, or *
* their respective licensors. No other licenses, including any licenses *
* needed under any third party's intellectual property, are provided herein.*
* Copying or modifying any file, or portion thereof, to which this notice *
* is attached violates this copyright. *
* *
* THIS FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THIS FILE OR THE USE OR OTHER DEALINGS *
* IN THIS FILE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
/******************************************************************************
* *
* This module sends and receives data to/from the DE1's audio and TV *
* peripherals' control registers. *
* *
******************************************************************************/
module Altera_UP_I2C (
// Inputs
clk,
reset,
clear_ack,
clk_400KHz,
start_and_stop_en,
change_output_bit_en,
send_start_bit,
send_stop_bit,
data_in,
transfer_data,
read_byte,
num_bits_to_transfer,
// Bidirectionals
i2c_sdata,
// Outputs
i2c_sclk,
i2c_scen,
enable_clk,
ack,
data_from_i2c,
transfer_complete
);
/*****************************************************************************
* Parameter Declarations *
*****************************************************************************/
parameter I2C_BUS_MODE = 1'b0;
/*****************************************************************************
* Port Declarations *
*****************************************************************************/
// Inputs
input clk;
input reset;
input clear_ack;
input clk_400KHz;
input start_and_stop_en;
input change_output_bit_en;
input send_start_bit;
input send_stop_bit;
input [7:0] data_in;
input transfer_data;
input read_byte;
input [2:0] num_bits_to_transfer;
// Bidirectionals
inout i2c_sdata; // I2C Data
// Outputs
output i2c_sclk; // I2C Clock
output reg i2c_scen;
output enable_clk;
output reg ack;
output reg [7:0] data_from_i2c;
output transfer_complete;
/*****************************************************************************
* Constant Declarations *
*****************************************************************************/
// states
localparam I2C_STATE_0_IDLE = 3'h0,
I2C_STATE_1_PRE_START = 3'h1,
I2C_STATE_2_START_BIT = 3'h2,
I2C_STATE_3_TRANSFER_BYTE = 3'h3,
I2C_STATE_4_TRANSFER_ACK = 3'h4,
I2C_STATE_5_STOP_BIT = 3'h5,
I2C_STATE_6_COMPLETE = 3'h6;
/*****************************************************************************
* Internal wires and registers Declarations *
*****************************************************************************/
// Internal Wires
// Internal Registers
reg [2:0] current_bit;
reg [7:0] current_byte;
// State Machine Registers
reg [2:0] ns_i2c_transceiver;
reg [2:0] s_i2c_transceiver;
/*****************************************************************************
* Finite State Machine(s) *
*****************************************************************************/
always @(posedge clk)
begin
if (reset == 1'b1)
s_i2c_transceiver <= I2C_STATE_0_IDLE;
else
s_i2c_transceiver <= ns_i2c_transceiver;
end
always @(*)
begin
// Defaults
ns_i2c_transceiver = I2C_STATE_0_IDLE;
case (s_i2c_transceiver)
I2C_STATE_0_IDLE:
begin
if ((send_start_bit == 1'b1) && (clk_400KHz == 1'b0))
ns_i2c_transceiver = I2C_STATE_1_PRE_START;
else if (send_start_bit == 1'b1)
ns_i2c_transceiver = I2C_STATE_2_START_BIT;
else if (send_stop_bit == 1'b1)
ns_i2c_transceiver = I2C_STATE_5_STOP_BIT;
else if (transfer_data == 1'b1)
ns_i2c_transceiver = I2C_STATE_3_TRANSFER_BYTE;
else
ns_i2c_transceiver = I2C_STATE_0_IDLE;
end
I2C_STATE_1_PRE_START:
begin
if (start_and_stop_en == 1'b1)
ns_i2c_transceiver = I2C_STATE_2_START_BIT;
else
ns_i2c_transceiver = I2C_STATE_1_PRE_START;
end
I2C_STATE_2_START_BIT:
begin
if (change_output_bit_en == 1'b1)
begin
if ((transfer_data == 1'b1) && (I2C_BUS_MODE == 1'b0))
ns_i2c_transceiver = I2C_STATE_3_TRANSFER_BYTE;
else
ns_i2c_transceiver = I2C_STATE_6_COMPLETE;
end
else
ns_i2c_transceiver = I2C_STATE_2_START_BIT;
end
I2C_STATE_3_TRANSFER_BYTE:
begin
if ((current_bit == 3'h0) && (change_output_bit_en == 1'b1))
begin
if ((I2C_BUS_MODE == 1'b0) || (num_bits_to_transfer == 3'h6))
ns_i2c_transceiver = I2C_STATE_4_TRANSFER_ACK;
else
ns_i2c_transceiver = I2C_STATE_6_COMPLETE;
end
else
ns_i2c_transceiver = I2C_STATE_3_TRANSFER_BYTE;
end
I2C_STATE_4_TRANSFER_ACK:
begin
if (change_output_bit_en == 1'b1)
ns_i2c_transceiver = I2C_STATE_6_COMPLETE;
else
ns_i2c_transceiver = I2C_STATE_4_TRANSFER_ACK;
end
I2C_STATE_5_STOP_BIT:
begin
if (start_and_stop_en == 1'b1)
ns_i2c_transceiver = I2C_STATE_6_COMPLETE;
else
ns_i2c_transceiver = I2C_STATE_5_STOP_BIT;
end
I2C_STATE_6_COMPLETE:
begin
if (transfer_data == 1'b0)
ns_i2c_transceiver = I2C_STATE_0_IDLE;
else
ns_i2c_transceiver = I2C_STATE_6_COMPLETE;
end
default:
begin
ns_i2c_transceiver = I2C_STATE_0_IDLE;
end
endcase
end
/*****************************************************************************
* Sequential logic *
*****************************************************************************/
// Output Registers
always @(posedge clk)
begin
if (reset == 1'b1)
i2c_scen <= 1'b1;
else if (change_output_bit_en & (s_i2c_transceiver == I2C_STATE_2_START_BIT))
i2c_scen <= 1'b0;
else if (s_i2c_transceiver == I2C_STATE_5_STOP_BIT)
i2c_scen <= 1'b1;
end
always @(posedge clk)
begin
if (reset == 1'b1)
ack <= 1'b0;
else if (clear_ack == 1'b1)
ack <= 1'b0;
else if (start_and_stop_en & (s_i2c_transceiver == I2C_STATE_4_TRANSFER_ACK))
ack <= i2c_sdata ^ I2C_BUS_MODE;
end
always @(posedge clk)
begin
if (reset == 1'b1)
data_from_i2c <= 8'h00;
else if (start_and_stop_en & (s_i2c_transceiver == I2C_STATE_3_TRANSFER_BYTE))
data_from_i2c <= {data_from_i2c[6:0], i2c_sdata};
end
// Internal Registers
always @(posedge clk)
begin
if (reset == 1'b1)
current_bit <= 3'h0;
else if ((s_i2c_transceiver == I2C_STATE_3_TRANSFER_BYTE) &&
(change_output_bit_en == 1'b1))
current_bit <= current_bit - 3'h1;
else if (s_i2c_transceiver != I2C_STATE_3_TRANSFER_BYTE)
current_bit <= num_bits_to_transfer;
end
always @(posedge clk)
begin
if (reset == 1'b1)
current_byte <= 8'h00;
else if ((s_i2c_transceiver == I2C_STATE_0_IDLE) ||
(s_i2c_transceiver == I2C_STATE_2_START_BIT))
current_byte <= data_in;
end
/*****************************************************************************
* Combinational logic *
*****************************************************************************/
assign i2c_sclk = (I2C_BUS_MODE == 1'b0) ?
clk_400KHz :
((s_i2c_transceiver == I2C_STATE_3_TRANSFER_BYTE) |
(s_i2c_transceiver == I2C_STATE_4_TRANSFER_ACK)) ?
clk_400KHz :
1'b0;
assign i2c_sdata =
(s_i2c_transceiver == I2C_STATE_2_START_BIT) ? 1'b0 :
(s_i2c_transceiver == I2C_STATE_5_STOP_BIT) ? 1'b0 :
((s_i2c_transceiver == I2C_STATE_4_TRANSFER_ACK) & read_byte) ? 1'b0 :
((s_i2c_transceiver == I2C_STATE_3_TRANSFER_BYTE) & ~read_byte) ?
current_byte[current_bit]
: 1'bz;
assign enable_clk = ~(s_i2c_transceiver == I2C_STATE_0_IDLE) &&
~(s_i2c_transceiver == I2C_STATE_6_COMPLETE);
assign transfer_complete =
(s_i2c_transceiver == I2C_STATE_6_COMPLETE) ? 1'b1 : 1'b0;
/*****************************************************************************
* Internal Modules *
*****************************************************************************/
endmodule
|
/*module xor3(input a ,input b,input c,output x);
assign x=a^b^c;
endmodule
module alu2(input wire [31:0] srca,input wire [31:0]srcb,
input wire [1:0] alucontrol,
output reg[31:0] aluresult,output reg[3:0]aluflags);
reg [31:0]sum;
reg cout;
wire [31:0]srcbc=~srcb;
wire xa;
xor3 aa(alucontrol[0],srca[31],srca[31],xa);
always@(*)
begin
if(alucontrol[0]) {cout,sum}=srca+srcbc+1;
else {cout,sum}=srca+srcb;
case (alucontrol)
2'b00: aluresult=sum;
2'b01: aluresult=sum;
2'b10: aluresult=srca & srcb;
2'b11: aluresult=srca | srcb;
endcase
aluflags[3:2]={aluresult[31],aluresult==0}; //n,z flags
aluflags[1]= cout & ~alucontrol[1]; //carry out flag c
aluflags[0]= xa & (~alucontrol[1] & (aluresult[31] ^ srca[31]) ); //overflow flag v
end
endmodule*/
module alu2(input wire [31:0] srca,input wire [31:0]srcb,
input wire [1:0] alucontrol,
output reg[31:0] aluresult,output wire[3:0]aluflags);
reg [31:0]sum;
reg cout;
wire [31:0]srcbc=~srcb;
always@(*) begin
if(alucontrol[0]) {cout,sum}=srca+srcbc+1;
else {cout,sum}=srca+srcb;
case (alucontrol)
2'b00: aluresult=sum;
2'b01: aluresult=sum;
2'b10: aluresult=srca & srcb;
2'b11: aluresult=srca | srcb;
endcase
end
assign aluflags[3:2]={aluresult[31],aluresult==0}; //n,z flags
assign aluflags[1]= cout & ~alucontrol[1]; //carry out flag c
assign aluflags[0]= (~(alucontrol[0]^srca[31]^srca[31])) & (~alucontrol[1]) & (aluresult[31] ^ srca[31]) ; //overflow flag v
endmodule |
//==============================================================================
// File: $URL$
// Version: $Revision$
// Author: Jose Renau (http://masc.cse.ucsc.edu/)
// Copyright: Copyright 2011 UC Santa Cruz
//==============================================================================
//==============================================================================
// Section: License
//==============================================================================
// SCOORE: Santa Cruz Out-of-order Risc Engine
// Copyright (C) 2004 University of California, Santa Cruz.
// All rights reserved.
//
// This file is part of SCOORE.
//
// SCOORE is free software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later version.
//
// SCOORE is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// SCOORE; see the file COPYING. If not, write to the Free Software Foundation,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// - Neither the name of the University of California, Santa Cruz nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==============================================================================
/****************************************************************************
Description:
Register file structure. Instantiates the optimal module based on the number
of rd/wr ports.
NOTE:
This module does not have reset. Tables can be too big, the state machine to
clear datas should be handled outside (if necessary).
****************************************************************************/
`include "logfunc.h"
module async_ram_1port
#(parameter Width = 64, Size=128)
( input [`log2(Size)-1:0] p0_pos
,input p0_enable
,input [Width-1:0] p0_in_data
,output reg [Width-1:0] p0_out_data
);
reg [Width-1:0] data [Size-1:0]; // synthesis syn_ramstyle = "block_ram"
reg [Width-1:0] d0;
always_comb begin
if (p0_enable) begin
d0 = 'b0;
end else begin
d0 = data[p0_pos];
end
end
always @(p0_pos or p0_in_data or p0_enable) begin
if (p0_enable) begin
data[p0_pos] = p0_in_data;
end
end
always_comb begin
p0_out_data = d0;
end
endmodule
|
/**
* Copyright 2020 The SkyWater PDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
`ifndef SKY130_FD_SC_LS__O21BAI_PP_BLACKBOX_V
`define SKY130_FD_SC_LS__O21BAI_PP_BLACKBOX_V
/**
* o21bai: 2-input OR into first input of 2-input NAND, 2nd iput
* inverted.
*
* Y = !((A1 | A2) & !B1_N)
*
* Verilog stub definition (black box with power pins).
*
* WARNING: This file is autogenerated, do not modify directly!
*/
`timescale 1ns / 1ps
`default_nettype none
(* blackbox *)
module sky130_fd_sc_ls__o21bai (
Y ,
A1 ,
A2 ,
B1_N,
VPWR,
VGND,
VPB ,
VNB
);
output Y ;
input A1 ;
input A2 ;
input B1_N;
input VPWR;
input VGND;
input VPB ;
input VNB ;
endmodule
`default_nettype wire
`endif // SKY130_FD_SC_LS__O21BAI_PP_BLACKBOX_V
|
module note2dds(CLK, NOTE, ADDER);
input wire CLK;
input wire [6:0] NOTE;
output [31:0] ADDER;
reg [31:0] ADDER_tbl [15:0];
reg [3:0] addr;
reg [3:0] divider;
// note div 12 ( * 0,08333333333333333333333333333333)
//; Add input / 16 to accumulator
//; Add input / 64 to accumulator
initial begin
addr <= 4'd0;
divider <= 4'd0;
ADDER_tbl[ 4'd0] <= 32'd0359575;
ADDER_tbl[ 4'd1] <= 32'd0380957;
ADDER_tbl[ 4'd2] <= 32'd0403610;
ADDER_tbl[ 4'd3] <= 32'd0427610;
ADDER_tbl[ 4'd4] <= 32'd0453037;
ADDER_tbl[ 4'd5] <= 32'd0479976;
ADDER_tbl[ 4'd6] <= 32'd0508516;
ADDER_tbl[ 4'd7] <= 32'd0538754;
ADDER_tbl[ 4'd8] <= 32'd0570790;
ADDER_tbl[ 4'd9] <= 32'd0604731;
ADDER_tbl[4'd10] <= 32'd0640691;
ADDER_tbl[4'd11] <= 32'd0678788;
ADDER_tbl[4'd12] <= 32'd0;
ADDER_tbl[4'd13] <= 32'd0;
ADDER_tbl[4'd14] <= 32'd0;
ADDER_tbl[4'd15] <= 32'd0;
end
assign ADDER = ADDER_tbl[addr] >> divider;
wire [3:0] diap = (NOTE < 12) ? 4'd00 :
(NOTE < 24) ? 4'd01 :
(NOTE < 36) ? 4'd02 :
(NOTE < 48) ? 4'd03 :
(NOTE < 60) ? 4'd04 :
(NOTE < 72) ? 4'd05 :
(NOTE < 84) ? 4'd06 :
(NOTE < 96) ? 4'd07 :
(NOTE < 108) ? 4'd08 :
(NOTE < 120) ? 4'd09 : 4'd010 ;
wire [6:0] c_addr = NOTE - (diap * 4'd012);
always @ (posedge CLK) begin
addr <= c_addr[3:0];
divider <= 4'd010 - diap;
end
endmodule
|
// ========== Copyright Header Begin ==========================================
//
// OpenSPARC T1 Processor File: bw_r_rf16x32.v
// Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
//
// The above named program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License version 2 as published by the Free Software Foundation.
//
// The above named program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this work; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// ========== Copyright Header End ============================================
////////////////////////////////////////////////////////////////////////
/*
// Module Name: bw_r_rf16x32
// Description:
// 1r1w array for icache and dcache valid bits.
// Modified to conform to naming convention
// Added 16 bit wr en
// Made bit_wen and din flopped inputs
// So all inputs are setup to flops in the stage before memory
// access. The data output is available one cycle later (same
// stage as mem access)
//
// IMPORTANT NOTE: This block has to work even in the case where
// there is contention between a read and write operation for the
// same address. Based on ease of implementation, the behavior
// during contention is defined as follows.
// -- write always succeeds
// -- read data is (array_data & write_data)
// (i.e. old_data & new_data)
//
// So read 0 always succeeds. read 1 succeeds if the data being
// written is also a 1. Otherwise it fails.
//
// new_data = 1, old_data = 0, does not give the expected or
// predictable result in post layout, so the code has been modified
// to be
// old new rd_data
// --- --- -------
// 0 0 0
// 0 1 X
// 1 0 0
// 1 1 1
//
// **The write still succeeds in ALL cases**
*/
////////////////////////////////////////////////////////////////////////
// Global header file includes
////////////////////////////////////////////////////////////////////////
//`include "sys.h" // system level definition file which contains the
// time scale definition
//`include "iop.h"
////////////////////////////////////////////////////////////////////////
// Local header file includes / local defines
////////////////////////////////////////////////////////////////////////
//FPGA_SYN enables all FPGA related modifications
`ifdef FPGA_SYN
`define FPGA_SYN_IDCT
`endif
module bw_r_rf16x32 (/*AUTOARG*/
// Outputs
dout, so,
// Inputs
rclk, se, si, reset_l, sehold, rst_tri_en, rd_adr1, rd_adr2,
rd_adr1_sel, rd_en, wr_adr, wr_en, bit_wen, din
);
input rclk;
input se;
input si;
input reset_l;
input sehold; // scan enable hold
input rst_tri_en;
// 11:5(I);10:4(D)
input [6:0] rd_adr1 ; // rd address-1
input [6:0] rd_adr2 ; // rd address-2
input rd_adr1_sel ; // sel rd addr 1
input rd_en ; // rd enable
// 11:7(I);10:6(D)
input [6:2] wr_adr ; // wr address
input wr_en ; // wr enable
input [15:0] bit_wen ; // write enable with bit select
input din ; // write data
output [3:0] dout ; // valid bits for tag compare
output so;
wire clk;
assign clk = rclk;
//----------------------------------------------------------------------
// Declarations
//----------------------------------------------------------------------
// local signals
wire [6:0] rd_index ;
// 512 bit array
`ifdef FPGA_SYN_IDCT
reg [31:0] idcv_ary_0000;
reg [31:0] idcv_ary_0001;
reg [31:0] idcv_ary_0010;
reg [31:0] idcv_ary_0011;
reg [31:0] idcv_ary_0100;
reg [31:0] idcv_ary_0101;
reg [31:0] idcv_ary_0110;
reg [31:0] idcv_ary_0111;
reg [31:0] idcv_ary_1000;
reg [31:0] idcv_ary_1001;
reg [31:0] idcv_ary_1010;
reg [31:0] idcv_ary_1011;
reg [31:0] idcv_ary_1100;
reg [31:0] idcv_ary_1101;
reg [31:0] idcv_ary_1110;
reg [31:0] idcv_ary_1111;
`else
reg [511:0] idcv_ary;
`endif
reg [3:0] vbit,
vbit_sa;
reg [6:2] wr_index_d1;
reg [6:0] rd_index_d1;
reg rdreq_d1,
wrreq_d1;
reg [15:0] bit_wen_d1;
reg din_d1;
reg [4:0] index;
wire rst_all;
//----------------------------------------------------------------------
// Code Begins Here
//----------------------------------------------------------------------
assign rst_all = rst_tri_en | ~reset_l;
// mux merged with flop on index
assign rd_index = rd_adr1_sel ? rd_adr1:rd_adr2 ;
// input flops
always @ (posedge clk)
begin
if (~sehold)
begin
rdreq_d1 <= rd_en ;
wrreq_d1 <= wr_en ;
rd_index_d1 <= rd_index;
wr_index_d1 <= wr_adr;
bit_wen_d1 <= bit_wen;
din_d1 <= din;
end
end
//----------------------------------------------------------------------
// Read Operation
//----------------------------------------------------------------------
`ifdef FPGA_SYN_IDCT
always @(/*AUTOSENSE*/
idcv_ary_0000 or idcv_ary_0001 or idcv_ary_0010 or idcv_ary_0011 or
idcv_ary_0100 or idcv_ary_1001 or idcv_ary_1010 or idcv_ary_0111 or
idcv_ary_1000 or idcv_ary_0101 or idcv_ary_0110 or idcv_ary_1011 or
idcv_ary_1100 or idcv_ary_1101 or idcv_ary_1110 or idcv_ary_1111 or rd_index_d1 or rdreq_d1)
`else
always @(/*AUTOSENSE*/idcv_ary or rd_index_d1 or rdreq_d1)
`endif
begin
if (rdreq_d1) // should work even if there is read
// write conflict. Data can be latest
// or previous but should not be x
begin
`ifdef FPGA_SYN_IDCT
case(rd_index_d1[1:0])
2'b00: begin
vbit[0] = idcv_ary_0000[{rd_index_d1[6:2]}];
vbit[1] = idcv_ary_0001[{rd_index_d1[6:2]}];
vbit[2] = idcv_ary_0010[{rd_index_d1[6:2]}];
vbit[3] = idcv_ary_0011[{rd_index_d1[6:2]}];
end
2'b01: begin
vbit[0] = idcv_ary_0100[{rd_index_d1[6:2]}];
vbit[1] = idcv_ary_0101[{rd_index_d1[6:2]}];
vbit[2] = idcv_ary_0110[{rd_index_d1[6:2]}];
vbit[3] = idcv_ary_0111[{rd_index_d1[6:2]}];
end
2'b10: begin
vbit[0] = idcv_ary_1000[{rd_index_d1[6:2]}];
vbit[1] = idcv_ary_1001[{rd_index_d1[6:2]}];
vbit[2] = idcv_ary_1010[{rd_index_d1[6:2]}];
vbit[3] = idcv_ary_1011[{rd_index_d1[6:2]}];
end
2'b11: begin
vbit[0] = idcv_ary_1100[{rd_index_d1[6:2]}];
vbit[1] = idcv_ary_1101[{rd_index_d1[6:2]}];
vbit[2] = idcv_ary_1110[{rd_index_d1[6:2]}];
vbit[3] = idcv_ary_1111[{rd_index_d1[6:2]}];
end
endcase
`else
vbit[0] = idcv_ary[{rd_index_d1, 2'b00}]; // way 0
vbit[1] = idcv_ary[{rd_index_d1, 2'b01}]; // way 1
vbit[2] = idcv_ary[{rd_index_d1, 2'b10}]; // way 2
vbit[3] = idcv_ary[{rd_index_d1, 2'b11}]; // way 3
`endif
end // if (rdreq_d1)
else // i/dcache disabled or rd disabled
begin
vbit[3:0] = 4'bx;
end // else: !if(rdreq_d1)
end // always @ (...
// r-w conflict case, returns old_data & new_data
// 12/06 modified to be
// 0 0 0
// 0 1 X
// 1 0 0
// 1 1 1
`ifdef FPGA_SYN_IDCT
initial
begin
for(index = 5'h0; index < 5'h1f; index = index+1)
begin
idcv_ary_0000[index] = 1'b0;
idcv_ary_0001[index] = 1'b0;
idcv_ary_0010[index] = 1'b0;
idcv_ary_0011[index] = 1'b0;
idcv_ary_0100[index] = 1'b0;
idcv_ary_0101[index] = 1'b0;
idcv_ary_0110[index] = 1'b0;
idcv_ary_0111[index] = 1'b0;
idcv_ary_1000[index] = 1'b0;
idcv_ary_1001[index] = 1'b0;
idcv_ary_1010[index] = 1'b0;
idcv_ary_1011[index] = 1'b0;
idcv_ary_1100[index] = 1'b0;
idcv_ary_1101[index] = 1'b0;
idcv_ary_1110[index] = 1'b0;
idcv_ary_1111[index] = 1'b0;
end
end
`endif
reg [3:0] wr_data;
always @ (/*AUTOSENSE*/bit_wen_d1 or rd_index_d1 or rst_all
or wr_index_d1 or wrreq_d1)
begin
if (rd_index_d1[6:2] == wr_index_d1[6:2])
case (rd_index_d1[1:0])
2'b00: wr_data = bit_wen_d1[3:0] & {4{wrreq_d1 & ~rst_all}};
2'b01: wr_data = bit_wen_d1[7:4] & {4{wrreq_d1 & ~rst_all}};
2'b10: wr_data = bit_wen_d1[11:8] & {4{wrreq_d1 & ~rst_all}};
default: wr_data = bit_wen_d1[15:12] & {4{wrreq_d1 & ~rst_all}};
endcase // case(rd_index_d1[1:0])
else
wr_data = 4'b0;
end
`ifdef FPGA_SYN_IDCT
assign dout[3:0] = (~reset_l | ~rdreq_d1) ? 4'b0000 :
(~wr_data & vbit | wr_data & {4{din_d1}} & vbit);
`else
// SA latch -- to make 0in happy
always @ (/*AUTOSENSE*/clk or din_d1 or vbit or wr_data)
begin
if (clk)
begin
vbit_sa <= (~wr_data & vbit |
wr_data & {4{din_d1}} & (vbit | 4'bxxxx));
end
end
// bug:2776 - remove holding the last read value
// reset_l rdreq_d1 dout
// 0 - 0
// 1 0 0
// 1 1 vbit_sa
assign dout[3:0] = (~reset_l | ~rdreq_d1) ? 4'b0000 : vbit_sa[3:0] ;
`endif
//----------------------------------------------------------------------
// Write Operation
//----------------------------------------------------------------------
// Invalidate/Write occurs on 16B boundary.
// For this purpose, 4x4 write-enables are required.
// Index thus corresponds to 11:7,6:5,w[1:0], where w=way (ICache)
// Index thus corresponds to 10:6,5:4,w[1:0], where w=way (DCache)
// Thru data-in, vld bit can be set or cleared.
always @ (negedge clk)
begin
if (wrreq_d1 & ~rst_all) // should work even if rd-wr conflict
begin
// line 0 (5:4=00)
`ifdef FPGA_SYN_IDCT
if (bit_wen_d1[0]) idcv_ary_0000[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[1]) idcv_ary_0001[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[2]) idcv_ary_0010[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[3]) idcv_ary_0011[{wr_index_d1[6:2]}] = din_d1;
`else
if (bit_wen_d1[0])
idcv_ary[{wr_index_d1[6:2],2'b00,2'b00}] = din_d1;
if (bit_wen_d1[1])
idcv_ary[{wr_index_d1[6:2],2'b00,2'b01}] = din_d1;
if (bit_wen_d1[2])
idcv_ary[{wr_index_d1[6:2],2'b00,2'b10}] = din_d1;
if (bit_wen_d1[3])
idcv_ary[{wr_index_d1[6:2],2'b00,2'b11}] = din_d1;
`endif
// line 1 (5:4=01)
`ifdef FPGA_SYN_IDCT
if (bit_wen_d1[4]) idcv_ary_0100[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[5]) idcv_ary_0101[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[6]) idcv_ary_0110[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[7]) idcv_ary_0111[{wr_index_d1[6:2]}] = din_d1;
`else
if (bit_wen_d1[4])
idcv_ary[{wr_index_d1[6:2],2'b01,2'b00}] = din_d1;
if (bit_wen_d1[5])
idcv_ary[{wr_index_d1[6:2],2'b01,2'b01}] = din_d1;
if (bit_wen_d1[6])
idcv_ary[{wr_index_d1[6:2],2'b01,2'b10}] = din_d1;
if (bit_wen_d1[7])
idcv_ary[{wr_index_d1[6:2],2'b01,2'b11}] = din_d1;
`endif
// line 2 (5:4=10)
`ifdef FPGA_SYN_IDCT
if (bit_wen_d1[8]) idcv_ary_1000[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[9]) idcv_ary_1001[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[10]) idcv_ary_1010[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[11]) idcv_ary_1011[{wr_index_d1[6:2]}] = din_d1;
`else
if (bit_wen_d1[8])
idcv_ary[{wr_index_d1[6:2],2'b10,2'b00}] = din_d1;
if (bit_wen_d1[9])
idcv_ary[{wr_index_d1[6:2],2'b10,2'b01}] = din_d1;
if (bit_wen_d1[10])
idcv_ary[{wr_index_d1[6:2],2'b10,2'b10}] = din_d1;
if (bit_wen_d1[11])
idcv_ary[{wr_index_d1[6:2],2'b10,2'b11}] = din_d1;
`endif
// line 3 (5:4=11)
`ifdef FPGA_SYN_IDCT
if (bit_wen_d1[12]) idcv_ary_1100[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[13]) idcv_ary_1101[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[14]) idcv_ary_1110[{wr_index_d1[6:2]}] = din_d1;
if (bit_wen_d1[15]) idcv_ary_1111[{wr_index_d1[6:2]}] = din_d1;
`else
if (bit_wen_d1[12])
idcv_ary[{wr_index_d1[6:2],2'b11,2'b00}] = din_d1;
if (bit_wen_d1[13])
idcv_ary[{wr_index_d1[6:2],2'b11,2'b01}] = din_d1;
if (bit_wen_d1[14])
idcv_ary[{wr_index_d1[6:2],2'b11,2'b10}] = din_d1;
if (bit_wen_d1[15])
idcv_ary[{wr_index_d1[6:2],2'b11,2'b11}] = din_d1;
`endif
end
end // always @ (...
// synopsys translate_off
//----------------------------------------------------------------
// Monitors, shadow logic and other stuff not directly related to
// memory functionality
//----------------------------------------------------------------
`ifdef INNO_MUXEX
`else
// Address monitor
always @ (/*AUTOSENSE*/rd_index_d1 or rdreq_d1 or wr_index_d1
or wrreq_d1)
begin
if (rdreq_d1 && (rd_index_d1 == 7'bX))
begin
// 0in <fire -message "FATAL ERROR: bw_r_rf16x32 read address X"
`ifdef DEFINE_0IN
`else
//$error("RFRDADDR", "Error: bw_r_rf16x32 read address is %b\n", rd_index_d1);
`endif
end
else if (wrreq_d1 && (wr_index_d1 == 5'bX))
begin
// 0in <fire -message "FATAL ERROR: bw_r_rf16x32 write address X"
`ifdef DEFINE_0IN
`else
//$error("RFWRADDR", "Error: bw_r_rf16x32 write address is %b\n", wr_index_d1);
`endif
end
end // always @ (...
`endif // !`ifdef INNO_MUXEX
//reg [127:0] w0;
//reg [127:0] w1;
//reg [127:0] w2;
//reg [127:0] w3;
//integer i;
//
// always @(idcv_ary) begin
// for (i=0;i<128; i=i+1) begin
// w0[i] = idcv_ary[4*i];
// w1[i] = idcv_ary[4*i+1];
// w2[i] = idcv_ary[4*i+2];
// w3[i] = idcv_ary[4*i+3];
// end
// end
//
// reg [511:0] icv_ary;
//
// always @ (idcv_ary)
// icv_ary = idcv_ary;
// synopsys translate_on
endmodule // bw_r_rf16x32
|
/*
* Author : Tom Stanway-Mayers
* Description : CSR file and Priv. Arch. Implementation
* Version: :
* License : Apache License Version 2.0, January 2004
* License URL : http://www.apache.org/licenses/
*/
// TODO - implement the remaining CSRs
/* ==== CRS Field Specifications ====
* WIRI:
* WPRI:
* WLRL:
* Exceptions are not raised on illegal writes (optional)
* Will return last written value regardless of legality
* WARL:
*/
`include "riscv_defs.v"
module merlin_cs_regs
#(
parameter C_WORD_RESET_VECTOR = 30'h0
)
(
//
input wire clk_i,
input wire fclk_i,
input wire reset_i,
// access request / error reporting interface
input wire access_rd_i,
input wire access_wr_i,
input wire [11:0] access_addr_i,
output wire access_badcsr_o,
output wire access_badwrite_o,
output wire access_badpriv_o,
output reg [`RV_XLEN-1:0] access_rd_data_o,
// write-back interface
input wire wr_i, // already gated by the exceptions in the exception interface
input wire [1:0] wr_mode_i,
input wire [11:0] wr_addr_i,
input wire [`RV_XLEN-1:0] wr_data_i,
// exception, interrupt, and hart vectoring interface
input wire ex_valid_i,
input wire irqm_extern_i,
input wire irqm_softw_i,
input wire irqm_timer_i,
input wire irqs_extern_i,
input wire excp_ferr_i,
input wire excp_uerr_i,
input wire excp_maif_i,
input wire excp_mala_i,
input wire excp_masa_i,
input wire excp_ilgl_i,
input wire excp_ecall_i,
input wire [`RV_XLEN-1:0] excp_pc_i,
input wire [`RV_XLEN-1:0] excp_ins_i,
//
output wire interrupt_o,
//
output wire trap_call_o, // jump to trap
output wire [`RV_XLEN-1:0] trap_call_addr_o, // address to jump to
output wire [`RV_XLEN-1:0] trap_call_cause_o, // cause of trap
output reg [`RV_XLEN-1:0] trap_call_value_o, // trap call value ( [m|s|u]tval )
input wire trap_rtn_i, // return from trap
input wire [1:0] trap_rtn_mode_i, // mode of return ( [m|s|u]ret )
output reg [`RV_XLEN-1:0] trap_rtn_addr_o, // address to jump (return) to
// static i/o
output wire [1:0] mode_o // current processor mode
);
//--------------------------------------------------------------
// interface assignments
// access restriction logic
// csr read
reg access_badcsr;
// mstatus / sstatus / ustatus
wire [`RV_XLEN-1:0] mstatus;
wire [`RV_XLEN-1:0] sstatus;
wire [`RV_XLEN-1:0] ustatus;
//
reg [1:0] mode_d;
reg [1:0] mstatus_mpp_d;
reg mstatus_spp_d;
reg mstatus_mpie_d;
reg mstatus_spie_d;
reg mstatus_upie_d;
reg mstatus_mie_d;
reg mstatus_sie_d;
reg mstatus_uie_d;
//
reg [1:0] mode_q;
reg [1:0] mstatus_mpp_q;
reg mstatus_spp_q;
reg mstatus_mpie_q;
reg mstatus_spie_q;
reg mstatus_upie_q;
reg mstatus_mie_q;
reg mstatus_sie_q;
reg mstatus_uie_q;
// medeleg
wire [`RV_XLEN-1:0] medeleg;
//
reg medeleg_ecfs_d;
reg medeleg_ecfu_d;
reg medeleg_saf_d;
reg medeleg_sam_d;
reg medeleg_laf_d;
reg medeleg_lam_d;
reg medeleg_ii_d;
reg medeleg_iaf_d;
reg medeleg_iam_d;
//
reg medeleg_ecfs_q;
reg medeleg_ecfu_q;
reg medeleg_saf_q;
reg medeleg_sam_q;
reg medeleg_laf_q;
reg medeleg_lam_q;
reg medeleg_ii_q;
reg medeleg_iaf_q;
reg medeleg_iam_q;
// sedeleg
wire [`RV_XLEN-1:0] sedeleg;
//
reg sedeleg_ecfu_d;
reg sedeleg_saf_d;
reg sedeleg_sam_d;
reg sedeleg_laf_d;
reg sedeleg_lam_d;
reg sedeleg_ii_d;
reg sedeleg_iaf_d;
reg sedeleg_iam_d;
//
reg sedeleg_ecfu_q;
reg sedeleg_saf_q;
reg sedeleg_sam_q;
reg sedeleg_laf_q;
reg sedeleg_lam_q;
reg sedeleg_ii_q;
reg sedeleg_iaf_q;
reg sedeleg_iam_q;
// mideleg
wire [`RV_XLEN-1:0] mideleg;
//
reg mideleg_usi_d;
reg mideleg_ssi_d;
reg mideleg_uti_d;
reg mideleg_sti_d;
reg mideleg_uei_d;
reg mideleg_sei_d;
//
reg mideleg_usi_q;
reg mideleg_ssi_q;
reg mideleg_uti_q;
reg mideleg_sti_q;
reg mideleg_uei_q;
reg mideleg_sei_q;
// sideleg
wire [`RV_XLEN-1:0] sideleg;
//
reg sideleg_usi_d;
reg sideleg_uti_d;
reg sideleg_uei_d;
//
reg sideleg_usi_q;
reg sideleg_uti_q;
reg sideleg_uei_q;
// mtvec
wire [`RV_XLEN-1:0] mtvec;
//
reg [`RV_XLEN-3:0] mtvec_d;
reg [1:0] mtvec_mode_d;
//
reg [`RV_XLEN-3:0] mtvec_q;
reg [1:0] mtvec_mode_q;
// stvec
wire [`RV_XLEN-1:0] stvec;
//
reg [`RV_XLEN-3:0] stvec_d;
reg [1:0] stvec_mode_d;
//
reg [`RV_XLEN-3:0] stvec_q;
reg [1:0] stvec_mode_q;
// utvec
wire [`RV_XLEN-1:0] utvec;
//
reg [`RV_XLEN-3:0] utvec_d;
reg [1:0] utvec_mode_d;
//
reg [`RV_XLEN-3:0] utvec_q;
reg [1:0] utvec_mode_q;
// mie / sie / uie
wire [`RV_XLEN-1:0] mie;
wire [`RV_XLEN-1:0] sie;
wire [`RV_XLEN-1:0] uie;
//
reg mie_meie_d;
reg mie_seie_d;
reg mie_ueie_d;
reg mie_mtie_d;
reg mie_stie_d;
reg mie_utie_d;
reg mie_msie_d;
reg mie_ssie_d;
reg mie_usie_d;
//
reg mie_meie_q;
reg mie_seie_q;
reg mie_ueie_q;
reg mie_mtie_q;
reg mie_stie_q;
reg mie_utie_q;
reg mie_msie_q;
reg mie_ssie_q;
reg mie_usie_q;
// mip / sip / uip
wire [`RV_XLEN-1:0] mip;
wire [`RV_XLEN-1:0] sip;
wire [`RV_XLEN-1:0] uip;
//
wire mip_meip;
wire mip_mtip;
wire mip_msip;
wire mip_seip;
wire mip_stip;
wire mip_ssip;
wire mip_ueip;
wire mip_utip;
wire mip_usip;
//
reg mip_seip_d;
reg mip_ueip_d;
reg mip_stip_d;
reg mip_utip_d;
reg mip_ssip_d;
reg mip_usip_d;
//
reg mip_seip_q;
reg mip_ueip_q;
reg mip_stip_q;
reg mip_utip_q;
reg mip_ssip_q;
reg mip_usip_q;
// mscratch
wire [`RV_XLEN-1:0] mscratch;
//
reg [`RV_XLEN-1:0] mscratch_d;
//
reg [`RV_XLEN-1:0] mscratch_q;
// sscratch
wire [`RV_XLEN-1:0] sscratch;
//
reg [`RV_XLEN-1:0] sscratch_d;
//
reg [`RV_XLEN-1:0] sscratch_q;
// uscratch
wire [`RV_XLEN-1:0] uscratch;
//
reg [`RV_XLEN-1:0] uscratch_d;
//
reg [`RV_XLEN-1:0] uscratch_q;
// mepc
wire [`RV_XLEN-1:0] mepc;
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] mepc_d;
`else
reg [`RV_XLEN-3:0] mepc_d;
`endif
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] mepc_q;
`else
reg [`RV_XLEN-3:0] mepc_q;
`endif
// sepc
wire [`RV_XLEN-1:0] sepc;
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] sepc_d;
`else
reg [`RV_XLEN-3:0] sepc_d;
`endif
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] sepc_q;
`else
reg [`RV_XLEN-3:0] sepc_q;
`endif
// uepc
wire [`RV_XLEN-1:0] uepc;
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] uepc_d;
`else
reg [`RV_XLEN-3:0] uepc_d;
`endif
//
`ifdef RV_CONFIG_STDEXT_C
reg [`RV_XLEN-2:0] uepc_q;
`else
reg [`RV_XLEN-3:0] uepc_q;
`endif
// mcause
wire [`RV_XLEN-1:0] mcause;
//
reg mcause_int_d;
reg [3:0] mcause_code_d;
//
reg mcause_int_q;
reg [3:0] mcause_code_q;
// scause
wire [`RV_XLEN-1:0] scause;
//
reg scause_int_d;
reg [3:0] scause_code_d;
//
reg scause_int_q;
reg [3:0] scause_code_q;
// ucause
wire [`RV_XLEN-1:0] ucause;
//
reg ucause_int_d;
reg [3:0] ucause_code_d;
//
reg ucause_int_q;
reg [3:0] ucause_code_q;
// mtval
wire [`RV_XLEN-1:0] mtval;
//
reg [`RV_XLEN-1:0] mtval_d;
//
reg [`RV_XLEN-1:0] mtval_q;
// stval
wire [`RV_XLEN-1:0] stval;
//
reg [`RV_XLEN-1:0] stval_d;
//
reg [`RV_XLEN-1:0] stval_q;
// utval
wire [`RV_XLEN-1:0] utval;
//
reg [`RV_XLEN-1:0] utval_d;
//
reg [`RV_XLEN-1:0] utval_q;
// interrupt and exception logic
reg m_int_e_q;
reg m_int_t_q;
reg m_int_s_q;
reg s_int_e_q;
reg s_int_t_q;
reg s_int_s_q;
reg u_int_e_q;
reg u_int_t_q;
reg u_int_s_q;
//
reg interrupt;
reg [3:0] interrupt_cause;
reg [1:0] interrupt_mode;
//
reg exception;
reg [3:0] exception_cause;
reg [1:0] exception_mode;
// trap call logic
wire [3:0] trap_call_cause_code;
wire [1:0] trap_call_mode;
reg trap_call_vectored;
reg [`RV_XLEN-3:0] trap_call_base;
// trap return address mux
//--------------------------------------------------------------
//--------------------------------------------------------------
// read/modify/write functions
//--------------------------------------------------------------
function read_modify_write1;
input field_q;
input field_modifier;
begin
read_modify_write1 = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_write1 = field_q | field_modifier;
2'b11 : read_modify_write1 = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
//
function [1:0] read_modify_write2;
input [1:0] field_q;
input [1:0] field_modifier;
begin
read_modify_write2 = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_write2 = field_q | field_modifier;
2'b11 : read_modify_write2 = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
//
function [3:0] read_modify_write4;
input [3:0] field_q;
input [3:0] field_modifier;
begin
read_modify_write4 = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_write4 = field_q | field_modifier;
2'b11 : read_modify_write4 = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
//
`ifdef RV_CONFIG_STDEXT_C
function [`RV_XLEN-2:0] read_modify_writem1;
input [`RV_XLEN-2:0] field_q;
input [`RV_XLEN-2:0] field_modifier;
begin
read_modify_writem1 = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_writem1 = field_q | field_modifier;
2'b11 : read_modify_writem1 = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
`endif
//
function [`RV_XLEN-3:0] read_modify_writem2;
input [`RV_XLEN-3:0] field_q;
input [`RV_XLEN-3:0] field_modifier;
begin
read_modify_writem2 = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_writem2 = field_q | field_modifier;
2'b11 : read_modify_writem2 = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
//
function [`RV_XLEN-1:0] read_modify_write;
input [`RV_XLEN-1:0] field_q;
input [`RV_XLEN-1:0] field_modifier;
begin
read_modify_write = field_modifier;
case (wr_mode_i)
2'b10 : read_modify_write = field_q | field_modifier;
2'b11 : read_modify_write = field_q & ~field_modifier;
default : begin
end
endcase
end
endfunction
//--------------------------------------------------------------
// interface assignments
//--------------------------------------------------------------
assign interrupt_o = interrupt;
assign mode_o = mode_q;
//--------------------------------------------------------------
// access restriction logic
//--------------------------------------------------------------
assign access_badcsr_o = access_badcsr & (access_rd_i | access_wr_i);
assign access_badwrite_o = (access_addr_i[11:10] == 2'b11 ? access_wr_i
: 1'b0)
;
assign access_badpriv_o = (access_addr_i[9:8] > mode_d ? access_rd_i | access_wr_i
: 1'b0)
;
//--------------------------------------------------------------
// csr read
//--------------------------------------------------------------
always @ (*) begin
access_badcsr = 1'b0;
access_rd_data_o = { `RV_XLEN {1'bx} };
case (access_addr_i)
// user trap setup
12'h000 : access_rd_data_o = ustatus;
12'h004 : access_rd_data_o = uie;
12'h005 : access_rd_data_o = utvec;
// user trap handling
12'h040 : access_rd_data_o = uscratch;
12'h041 : access_rd_data_o = uepc;
12'h042 : access_rd_data_o = ucause;
12'h043 : access_rd_data_o = utval;
12'h044 : access_rd_data_o = uip;
// supervisor trap setup
12'h100 : access_rd_data_o = sstatus;
12'h102 : access_rd_data_o = sedeleg;
12'h103 : access_rd_data_o = sideleg;
12'h104 : access_rd_data_o = sie;
12'h105 : access_rd_data_o = stvec;
// 12'h106 : access_rd_data_o = ;
// supervisor trap handling
12'h140 : access_rd_data_o = sscratch;
12'h141 : access_rd_data_o = sepc;
12'h142 : access_rd_data_o = scause;
12'h143 : access_rd_data_o = stval;
12'h144 : access_rd_data_o = sip;
// machine information registers
// 12'hf00 : access_rd_data_o = ;
// 12'hf00 : access_rd_data_o = ;
// 12'hf00 : access_rd_data_o = ;
// 12'hf00 : access_rd_data_o = ;
// machine trap setup
12'h300 : access_rd_data_o = mstatus;
// 12'h301 : access_rd_data_o = ;
12'h302 : access_rd_data_o = medeleg;
12'h303 : access_rd_data_o = mideleg;
12'h304 : access_rd_data_o = mie;
12'h305 : access_rd_data_o = mtvec;
// 12'h306 : access_rd_data_o = ;
// machine trap handling
12'h340 : access_rd_data_o = mscratch;
12'h341 : access_rd_data_o = mepc;
12'h342 : access_rd_data_o = mcause;
12'h343 : access_rd_data_o = mtval;
12'h344 : access_rd_data_o = mip;
default : access_badcsr = 1'b1;
endcase
end
//--------------------------------------------------------------
// mstatus / sstatus / ustatus
//--------------------------------------------------------------
assign mstatus = {
`ifdef RV_CONFIG_STDEXT_64
1'b0, // SD - XS/FS signal dirty state
27'b0, // *WPRI*
2'b10, // SXL - supervisor XLEN (hardwired to 64-bit)
2'b10, // UXL - user XLEN (hardwired to 64-bit)
1'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
1'b0, // SD - XS/FS signal dirty state
`endif
8'b0, // *WPRI*
1'b0, // TSR - trap sret
1'b0, // TW - timeout wait
1'b0, // TVM - trap virtual memory
1'b0, // MXR - make executable readable
1'b0, // SUM - permit supervisor user mem access
1'b0, // MPRV - modify memory privilege
2'b0, // XS - user mode extension status
2'b0, // FS - fpu status
mstatus_mpp_d, // MPP - machine previous privilege
2'b0, // *WPRI*
mstatus_spp_d, // SPP - supervisor previous privilege
mstatus_mpie_d, // MPIE - machine previous interrupt enable
1'b0, // *WPRI*
mstatus_spie_d, // SPIE - supervisor previous interrupt enable
mstatus_upie_d, // UPIE - user previous interrupt enable
mstatus_mie_d, // MIE - machine interrupt enable
1'b0, // *WPRI*
mstatus_sie_d, // SIE - supervisor interrupt enable
mstatus_uie_d // UIE - user interrupt enable
};
assign sstatus = {
`ifdef RV_CONFIG_STDEXT_64
1'b0, // SD - XS/FS signal dirty state
27'b0, // *WPRI*
2'b00, // SXL - supervisor XLEN
2'b10, // UXL - user XLEN (hardwired to 64-bit)
1'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
1'b0, // SD - XS/FS signal dirty state
`endif
8'b0, // *WPRI*
1'b0, // TSR - trap sret
1'b0, // TW - timeout wait
1'b0, // TVM - trap virtual memory
1'b0, // MXR - make executable readable
1'b0, // SUM - permit supervisor user mem access
1'b0, // MPRV - modify memory privilege
2'b0, // XS - user mode extension status
2'b0, // FS - fpu status
2'b0, // MPP - machine previous privilege
2'b0, // *WPRI*
mstatus_spp_d, // SPP - supervisor previous privilege
1'b0, // MPIE - machine previous interrupt enable
1'b0, // *WPRI*
mstatus_spie_d, // SPIE - supervisor previous interrupt enable
mstatus_upie_d, // UPIE - user previous interrupt enable
1'b0, // MIE - machine interrupt enable
1'b0, // *WPRI*
mstatus_sie_d, // SIE - supervisor interrupt enable
mstatus_uie_d // UIE - user interrupt enable
};
assign ustatus = {
`ifdef RV_CONFIG_STDEXT_64
1'b0, // SD - XS/FS signal dirty state
27'b0, // *WPRI*
2'b00, // SXL - supervisor XLEN
2'b00, // UXL - user XLEN
1'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
1'b0, // SD - XS/FS signal dirty state
`endif
8'b0, // *WPRI*
1'b0, // TSR - trap sret
1'b0, // TW - timeout wait
1'b0, // TVM - trap virtual memory
1'b0, // MXR - make executable readable
1'b0, // SUM - permit supervisor user mem access
1'b0, // MPRV - modify memory privilege
2'b0, // XS - user mode extension status
2'b0, // FS - fpu status
2'b0, // MPP - machine previous privilege
2'b0, // *WPRI*
1'b0, // SPP - supervisor previous privilege
1'b0, // MPIE - machine previous interrupt enable
1'b0, // *WPRI*
1'b0, // SPIE - supervisor previous interrupt enable
mstatus_upie_d, // UPIE - user previous interrupt enable
1'b0, // MIE - machine interrupt enable
1'b0, // *WPRI*
1'b0, // SIE - supervisor interrupt enable
mstatus_uie_d // UIE - user interrupt enable
};
//
always @ (*) begin
mode_d = mode_q;
mstatus_mpp_d = mstatus_mpp_q;
mstatus_spp_d = mstatus_spp_q;
mstatus_mpie_d = mstatus_mpie_q;
mstatus_spie_d = mstatus_spie_q;
mstatus_upie_d = mstatus_upie_q;
mstatus_mie_d = mstatus_mie_q;
mstatus_sie_d = mstatus_sie_q;
mstatus_uie_d = mstatus_uie_q;
if (trap_call_o) begin
mode_d = trap_call_mode;
case (trap_call_mode)
`RV_CSR_MODE_MACHINE : begin
mstatus_mpp_d = mode_q;
mstatus_mpie_d = mstatus_mie_q;
mstatus_mie_d = 1'b0;
end
`RV_CSR_MODE_SUPERVISOR : begin
mstatus_spp_d = |mode_q; // 0 iff was user mode, 1 otherwise
mstatus_spie_d = mstatus_sie_q;
mstatus_sie_d = 1'b0;
end
`RV_CSR_MODE_USER : begin
mstatus_upie_d = mstatus_uie_q;
mstatus_uie_d = 1'b0;
end
default : begin
end
endcase
end else if (trap_rtn_i) begin
mstatus_mpp_d = `RV_CSR_MODE_USER;
mstatus_spp_d = 1'b0;
case (trap_rtn_mode_i)
`RV_CSR_MODE_MACHINE : begin
mode_d = mstatus_mpp_q;
mstatus_mie_d = mstatus_mpie_q;
mstatus_mpie_d = 1'b1;
end
`RV_CSR_MODE_SUPERVISOR : begin
if (mstatus_spp_q == 1'b0) begin
mode_d = `RV_CSR_MODE_USER;
end
mstatus_sie_d = mstatus_spie_q;
mstatus_spie_d = 1'b1;
end
`RV_CSR_MODE_USER : begin
mstatus_uie_d = mstatus_upie_q;
mstatus_upie_d = 1'b1;
end
default : begin
end
endcase
end else if (wr_i) begin
case (wr_addr_i)
12'h300 : begin // mstatus
mstatus_mpp_d = read_modify_write2(mstatus_mpp_q, wr_data_i[12:11]);
mstatus_spp_d = read_modify_write1(mstatus_spp_q, wr_data_i[8]);
mstatus_mpie_d = read_modify_write1(mstatus_mpie_q, wr_data_i[7]);
mstatus_spie_d = read_modify_write1(mstatus_spie_q, wr_data_i[5]);
mstatus_upie_d = read_modify_write1(mstatus_upie_q, wr_data_i[4]);
mstatus_mie_d = read_modify_write1(mstatus_mie_q, wr_data_i[3]);
mstatus_sie_d = read_modify_write1(mstatus_sie_q, wr_data_i[1]);
mstatus_uie_d = read_modify_write1(mstatus_uie_q, wr_data_i[0]);
end
12'h100 : begin // sstatus
mstatus_spp_d = read_modify_write1(mstatus_spp_q, wr_data_i[8]);
mstatus_spie_d = read_modify_write1(mstatus_spie_q, wr_data_i[5]);
mstatus_upie_d = read_modify_write1(mstatus_upie_q, wr_data_i[4]);
mstatus_sie_d = read_modify_write1(mstatus_sie_q, wr_data_i[1]);
mstatus_uie_d = read_modify_write1(mstatus_uie_q, wr_data_i[0]);
end
12'h000 : begin // ustatus
mstatus_upie_d = read_modify_write1(mstatus_upie_q, wr_data_i[4]);
mstatus_uie_d = read_modify_write1(mstatus_uie_q, wr_data_i[0]);
end
default : begin
end
endcase
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
mode_q <= `RV_CSR_MODE_MACHINE;
mstatus_mpp_q <= 2'b0;
mstatus_spp_q <= 1'b0;
mstatus_mpie_q <= 1'b0;
mstatus_spie_q <= 1'b0;
mstatus_upie_q <= 1'b0;
mstatus_mie_q <= 1'b0;
mstatus_sie_q <= 1'b0;
mstatus_uie_q <= 1'b0;
end else begin
mode_q <= mode_d;
mstatus_mpp_q <= mstatus_mpp_d;
mstatus_spp_q <= mstatus_spp_d;
mstatus_mpie_q <= mstatus_mpie_d;
mstatus_spie_q <= mstatus_spie_d;
mstatus_upie_q <= mstatus_upie_d;
mstatus_mie_q <= mstatus_mie_d;
mstatus_sie_q <= mstatus_sie_d;
mstatus_uie_q <= mstatus_uie_d;
end
end
//--------------------------------------------------------------
// medeleg
//--------------------------------------------------------------
assign medeleg = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WARL*
`else // 32-bit is the only supported alternative at the moment
`endif
16'b0, // *WARL*
1'b0, // store/amo page fault
1'b0, // *WARL*
1'b0, // load page fault
1'b0, // instruction page fault
1'b0, // environment call from m-mode (cannot be delegated!)
1'b0, // *WARL*
medeleg_ecfs_d, // environment call from s-mode
medeleg_ecfu_d, // environment call from u-mode
medeleg_saf_d, // store/amo access fault
medeleg_sam_d, // store/amo address misaligned
medeleg_laf_d, // load access fault
medeleg_lam_d, // load address misaligned
1'b0, // breakpoint
medeleg_ii_d, // illegal instruction
medeleg_iaf_d, // instruction access fault
medeleg_iam_d // instruction address misaligned
};
//
always @ (*) begin
medeleg_ecfs_d = medeleg_ecfs_q;
medeleg_ecfu_d = medeleg_ecfu_q;
medeleg_saf_d = medeleg_saf_q;
medeleg_sam_d = medeleg_sam_q;
medeleg_laf_d = medeleg_laf_q;
medeleg_lam_d = medeleg_lam_q;
medeleg_ii_d = medeleg_ii_q;
medeleg_iaf_d = medeleg_iaf_q;
medeleg_iam_d = medeleg_iam_q;
if (wr_i) begin
if (wr_addr_i == 12'h302) begin
medeleg_ecfs_d = read_modify_write1(medeleg_ecfs_q, wr_data_i[9]);
medeleg_ecfu_d = read_modify_write1(medeleg_ecfu_q, wr_data_i[8]);
medeleg_saf_d = read_modify_write1(medeleg_saf_q, wr_data_i[7]);
medeleg_sam_d = read_modify_write1(medeleg_sam_q, wr_data_i[6]);
medeleg_laf_d = read_modify_write1(medeleg_laf_q, wr_data_i[5]);
medeleg_lam_d = read_modify_write1(medeleg_lam_q, wr_data_i[4]);
medeleg_ii_d = read_modify_write1(medeleg_ii_q, wr_data_i[2]);
medeleg_iaf_d = read_modify_write1(medeleg_iaf_q, wr_data_i[1]);
medeleg_iam_d = read_modify_write1(medeleg_iam_q, wr_data_i[0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
medeleg_ecfs_q <= 1'b0;
medeleg_ecfu_q <= 1'b0;
medeleg_saf_q <= 1'b0;
medeleg_sam_q <= 1'b0;
medeleg_laf_q <= 1'b0;
medeleg_lam_q <= 1'b0;
medeleg_ii_q <= 1'b0;
medeleg_iaf_q <= 1'b0;
medeleg_iam_q <= 1'b0;
end else begin
medeleg_ecfs_q <= medeleg_ecfs_d;
medeleg_ecfu_q <= medeleg_ecfu_d;
medeleg_saf_q <= medeleg_saf_d;
medeleg_sam_q <= medeleg_sam_d;
medeleg_laf_q <= medeleg_laf_d;
medeleg_lam_q <= medeleg_lam_d;
medeleg_ii_q <= medeleg_ii_d;
medeleg_iaf_q <= medeleg_iaf_d;
medeleg_iam_q <= medeleg_iam_d;
end
end
//--------------------------------------------------------------
// sedeleg
//--------------------------------------------------------------
assign sedeleg = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WARL*
`else // 32-bit is the only supported alternative at the moment
`endif
16'b0, // *WARL*
1'b0, // store/amo page fault
1'b0, // *WARL*
1'b0, // load page fault
1'b0, // instruction page fault
1'b0, // environment call from m-mode (cannot be delegated!)
1'b0, // *WARL*
1'b0, // environment call from s-mode (cannot be delegated!)
sedeleg_ecfu_d, // environment call from u-mode
sedeleg_saf_d, // store/amo access fault
sedeleg_sam_d, // store/amo address misaligned
sedeleg_laf_d, // load access fault
sedeleg_lam_d, // load address misaligned
1'b0, // breakpoint
sedeleg_ii_d, // illegal instruction
sedeleg_iaf_d, // instruction access fault
sedeleg_iam_d // instruction address misaligned
};
//
always @ (*) begin
sedeleg_ecfu_d = sedeleg_ecfu_q;
sedeleg_saf_d = sedeleg_saf_q;
sedeleg_sam_d = sedeleg_sam_q;
sedeleg_laf_d = sedeleg_laf_q;
sedeleg_lam_d = sedeleg_lam_q;
sedeleg_ii_d = sedeleg_ii_q;
sedeleg_iaf_d = sedeleg_iaf_q;
sedeleg_iam_d = sedeleg_iam_q;
if (wr_i) begin
if (wr_addr_i == 12'h102) begin
sedeleg_ecfu_d = read_modify_write1(sedeleg_ecfu_q, wr_data_i[8]);
sedeleg_saf_d = read_modify_write1(sedeleg_saf_q, wr_data_i[7]);
sedeleg_sam_d = read_modify_write1(sedeleg_sam_q, wr_data_i[6]);
sedeleg_laf_d = read_modify_write1(sedeleg_laf_q, wr_data_i[5]);
sedeleg_lam_d = read_modify_write1(sedeleg_lam_q, wr_data_i[4]);
sedeleg_ii_d = read_modify_write1(sedeleg_ii_q, wr_data_i[2]);
sedeleg_iaf_d = read_modify_write1(sedeleg_iaf_q, wr_data_i[1]);
sedeleg_iam_d = read_modify_write1(sedeleg_iam_q, wr_data_i[0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
sedeleg_ecfu_q <= 1'b0;
sedeleg_saf_q <= 1'b0;
sedeleg_sam_q <= 1'b0;
sedeleg_laf_q <= 1'b0;
sedeleg_lam_q <= 1'b0;
sedeleg_ii_q <= 1'b0;
sedeleg_iaf_q <= 1'b0;
sedeleg_iam_q <= 1'b0;
end else begin
sedeleg_ecfu_q <= sedeleg_ecfu_d;
sedeleg_saf_q <= sedeleg_saf_d;
sedeleg_sam_q <= sedeleg_sam_d;
sedeleg_laf_q <= sedeleg_laf_d;
sedeleg_lam_q <= sedeleg_lam_d;
sedeleg_ii_q <= sedeleg_ii_d;
sedeleg_iaf_q <= sedeleg_iaf_d;
sedeleg_iam_q <= sedeleg_iam_d;
end
end
//--------------------------------------------------------------
// mideleg
//--------------------------------------------------------------
assign mideleg = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WARL*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WARL*
1'b0, // machine external interrupt
1'b0, // *WARL*
mideleg_sei_d, // supervisor external interrupt
mideleg_uei_d, // user external interrupt
1'b0, // machine timer interrupt
1'b0, // *WARL*
mideleg_sti_d, // supervisor timer interrupt
mideleg_uti_d, // user timer interrupt
1'b0, // machine software interrupt
1'b0, // *WARL*
mideleg_ssi_d, // supervisor software interrupt
mideleg_usi_d // user software interrupt
};
//
always @ (*) begin
mideleg_usi_d = mideleg_usi_q;
mideleg_ssi_d = mideleg_ssi_q;
mideleg_uti_d = mideleg_uti_q;
mideleg_sti_d = mideleg_sti_q;
mideleg_uei_d = mideleg_uei_q;
mideleg_sei_d = mideleg_sei_q;
if (wr_i) begin
if (wr_addr_i == 12'h303) begin
mideleg_usi_d = read_modify_write1(mideleg_usi_q, wr_data_i[0]);
mideleg_ssi_d = read_modify_write1(mideleg_ssi_q, wr_data_i[1]);
mideleg_uti_d = read_modify_write1(mideleg_uti_q, wr_data_i[4]);
mideleg_sti_d = read_modify_write1(mideleg_sti_q, wr_data_i[5]);
mideleg_uei_d = read_modify_write1(mideleg_uei_q, wr_data_i[8]);
mideleg_sei_d = read_modify_write1(mideleg_sei_q, wr_data_i[9]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
mideleg_usi_q <= 1'b0;
mideleg_ssi_q <= 1'b0;
mideleg_uti_q <= 1'b0;
mideleg_sti_q <= 1'b0;
mideleg_uei_q <= 1'b0;
mideleg_sei_q <= 1'b0;
end else begin
mideleg_usi_q <= mideleg_usi_d;
mideleg_ssi_q <= mideleg_ssi_d;
mideleg_uti_q <= mideleg_uti_d;
mideleg_sti_q <= mideleg_sti_d;
mideleg_uei_q <= mideleg_uei_d;
mideleg_sei_q <= mideleg_sei_d;
end
end
//--------------------------------------------------------------
// sideleg
//--------------------------------------------------------------
assign sideleg = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WARL*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WARL*
1'b0, // machine external interrupt
1'b0, // *WARL*
1'b0, // supervisor external interrupt
sideleg_uei_d, // user external interrupt
1'b0, // machine timer interrupt
1'b0, // *WARL*
1'b0, // supervisor timer interrupt
sideleg_uti_d, // user timer interrupt
1'b0, // machine software interrupt
1'b0, // *WARL*
1'b0, // supervisor software interrupt
sideleg_usi_d // user software interrupt
};
//
always @ (*) begin
sideleg_usi_d = sideleg_usi_q;
sideleg_uti_d = sideleg_uti_q;
sideleg_uei_d = sideleg_uei_q;
if (wr_i) begin
if (wr_addr_i == 12'h103) begin
sideleg_usi_d = read_modify_write1(sideleg_usi_q, wr_data_i[0]);
sideleg_uti_d = read_modify_write1(sideleg_uti_q, wr_data_i[4]);
sideleg_uei_d = read_modify_write1(sideleg_uei_q, wr_data_i[8]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
sideleg_usi_q <= 1'b0;
sideleg_uti_q <= 1'b0;
sideleg_uei_q <= 1'b0;
end else begin
sideleg_usi_q <= sideleg_usi_d;
sideleg_uti_q <= sideleg_uti_d;
sideleg_uei_q <= sideleg_uei_d;
end
end
//--------------------------------------------------------------
// mtvec
//--------------------------------------------------------------
/*
* NOTE: In vectored mode icause replaces the bottom 4 bits of base field.
* See "trap call logic"
*/
assign mtvec = {
mtvec_d, // 32-bit aligned trap vector base address
mtvec_mode_d // trap vector mode (0 => direct, 1 => vectored, others => reserved)
};
//
always @ (*) begin
mtvec_d = mtvec_q;
mtvec_mode_d = mtvec_mode_q;
if (wr_i) begin
if (wr_addr_i == 12'h305) begin
mtvec_d = read_modify_writem2(mtvec_q, wr_data_i[`RV_XLEN-1:2]);
mtvec_mode_d = read_modify_write2(mtvec_mode_q, wr_data_i[1:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
mtvec_q <= C_WORD_RESET_VECTOR;
mtvec_mode_q <= `RV_CSR_TVEC_MODE_DIRECT;
end else begin
mtvec_q <= mtvec_d;
mtvec_mode_q <= mtvec_mode_d;
end
end
//--------------------------------------------------------------
// stvec
//--------------------------------------------------------------
/*
* NOTE: In vectored mode icause replaces the bottom 4 bits of base field.
* See "trap call logic"
*/
assign stvec = {
stvec_d, // 32-bit aligned trap vector base address
stvec_mode_d // trap vector mode (0 => direct, 1 => vectored, others => reserved)
};
//
always @ (*) begin
stvec_d = stvec_q;
stvec_mode_d = stvec_mode_q;
if (wr_i) begin
if (wr_addr_i == 12'h105) begin
stvec_d = read_modify_writem2(stvec_q, wr_data_i[`RV_XLEN-1:2]);
stvec_mode_d = read_modify_write2(stvec_mode_q, wr_data_i[1:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
stvec_q <= stvec_d;
stvec_mode_q <= stvec_mode_d;
end
//--------------------------------------------------------------
// utvec
//--------------------------------------------------------------
/*
* NOTE: In vectored mode icause replaces the bottom 4 bits of base field.
* See "trap call logic"
*/
assign utvec = {
utvec_d, // 32-bit aligned trap vector base address
utvec_mode_d // trap vector mode (0 => direct, 1 => vectored, others => reserved)
};
//
always @ (*) begin
utvec_d = utvec_q;
utvec_mode_d = utvec_mode_q;
if (wr_i) begin
if (wr_addr_i == 12'h005) begin
utvec_d = read_modify_writem2(utvec_q, wr_data_i[`RV_XLEN-1:2]);
utvec_mode_d = read_modify_write2(utvec_mode_q, wr_data_i[1:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
utvec_q <= utvec_d;
utvec_mode_q <= utvec_mode_d;
end
//--------------------------------------------------------------
// mie / sie / uie
//--------------------------------------------------------------
assign mie = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
mie_meie_d, // machine external interrupt enable
1'b0, // *WPRI*
mie_seie_d, // supervisor external interrupt enable
mie_ueie_d, // user external interrupt enable
mie_mtie_d, // machine timer interrupt enable
1'b0, // *WPRI*
mie_stie_d, // supervisor timer interrupt enable
mie_utie_d, // user timer interrupt enable
mie_msie_d, // machine software interrupt enable
1'b0, // *WPRI*
mie_ssie_d, // supervisor software interrupt enable
mie_usie_d // user software interrupt enable
};
//
assign sie = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
1'b0, // machine external interrupt enable
1'b0, // *WPRI*
mie_seie_d, // supervisor external interrupt enable
mie_ueie_d, // user external interrupt enable
1'b0, // machine timer interrupt enable
1'b0, // *WPRI*
mie_stie_d, // supervisor timer interrupt enable
mie_utie_d, // user timer interrupt enable
1'b0, // machine software interrupt enable
1'b0, // *WPRI*
mie_ssie_d, // supervisor software interrupt enable
mie_usie_d // user software interrupt enable
};
//
assign uie = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
1'b0, // machine external interrupt enable
1'b0, // *WPRI*
1'b0, // supervisor external interrupt enable
mie_ueie_d, // user external interrupt enable
1'b0, // machine timer interrupt enable
1'b0, // *WPRI*
1'b0, // supervisor timer interrupt enable
mie_utie_d, // user timer interrupt enable
1'b0, // machine software interrupt enable
1'b0, // *WPRI*
1'b0, // supervisor software interrupt enable
mie_usie_d // user software interrupt enable
};
//
always @ (*) begin
mie_meie_d = mie_meie_q;
mie_seie_d = mie_seie_q;
mie_ueie_d = mie_ueie_q;
mie_mtie_d = mie_mtie_q;
mie_stie_d = mie_stie_q;
mie_utie_d = mie_utie_q;
mie_msie_d = mie_msie_q;
mie_ssie_d = mie_ssie_q;
mie_usie_d = mie_usie_q;
if (wr_i) begin
case (wr_addr_i)
12'h304 : begin // mie
mie_meie_d = read_modify_write1(mie_meie_q, wr_data_i[11]);
mie_seie_d = read_modify_write1(mie_seie_q, wr_data_i[9]);
mie_ueie_d = read_modify_write1(mie_ueie_q, wr_data_i[8]);
mie_mtie_d = read_modify_write1(mie_mtie_q, wr_data_i[7]);
mie_stie_d = read_modify_write1(mie_stie_q, wr_data_i[5]);
mie_utie_d = read_modify_write1(mie_utie_q, wr_data_i[4]);
mie_msie_d = read_modify_write1(mie_msie_q, wr_data_i[3]);
mie_ssie_d = read_modify_write1(mie_ssie_q, wr_data_i[1]);
mie_usie_d = read_modify_write1(mie_usie_q, wr_data_i[0]);
end
12'h104 : begin // sie
mie_seie_d = read_modify_write1(mie_seie_q, wr_data_i[9]);
mie_ueie_d = read_modify_write1(mie_ueie_q, wr_data_i[8]);
mie_stie_d = read_modify_write1(mie_stie_q, wr_data_i[5]);
mie_utie_d = read_modify_write1(mie_utie_q, wr_data_i[4]);
mie_ssie_d = read_modify_write1(mie_ssie_q, wr_data_i[1]);
mie_usie_d = read_modify_write1(mie_usie_q, wr_data_i[0]);
end
12'h004 : begin // uie
mie_ueie_d = read_modify_write1(mie_ueie_q, wr_data_i[8]);
mie_utie_d = read_modify_write1(mie_utie_q, wr_data_i[4]);
mie_usie_d = read_modify_write1(mie_usie_q, wr_data_i[0]);
end
default : begin
end
endcase
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
mie_meie_q <= 1'b0;
mie_seie_q <= 1'b0;
mie_ueie_q <= 1'b0;
mie_mtie_q <= 1'b0;
mie_stie_q <= 1'b0;
mie_utie_q <= 1'b0;
mie_msie_q <= 1'b0;
mie_ssie_q <= 1'b0;
mie_usie_q <= 1'b0;
end else begin
mie_meie_q <= mie_meie_d;
mie_seie_q <= mie_seie_d;
mie_ueie_q <= mie_ueie_d;
mie_mtie_q <= mie_mtie_d;
mie_stie_q <= mie_stie_d;
mie_utie_q <= mie_utie_d;
mie_msie_q <= mie_msie_d;
mie_ssie_q <= mie_ssie_d;
mie_usie_q <= mie_usie_d;
end
end
//--------------------------------------------------------------
// mip / sip / uip
//--------------------------------------------------------------
assign mip = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
mip_meip, // machine external interrupt pending
1'b0, // *WPRI*
mip_seip, // supervisor external interrupt pending
mip_ueip, // user external interrupt pending
mip_mtip, // machine timer interrupt pending
1'b0, // *WPRI*
mip_stip, // supervisor timer interrupt pending
mip_utip, // user timer interrupt pending
mip_msip, // machine software interrupt pending
1'b0, // *WPRI*
mip_ssip, // supervisor software interrupt pending
mip_usip // user software interrupt pending
};
//
assign sip = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
1'b0, // machine external interrupt pending
1'b0, // *WPRI*
mip_seip, // supervisor external interrupt pending
mip_ueip, // user external interrupt pending
1'b0, // machine timer interrupt pending
1'b0, // *WPRI*
mip_stip, // supervisor timer interrupt pending
mip_utip, // user timer interrupt pending
1'b0, // machine software interrupt pending
1'b0, // *WPRI*
mip_ssip, // supervisor software interrupt pending
mip_usip // user software interrupt pending
};
//
assign uip = {
`ifdef RV_CONFIG_STDEXT_64
32'b0, // *WPRI*
`else // 32-bit is the only supported alternative at the moment
`endif
20'b0, // *WPRI*
1'b0, // machine external interrupt pending
1'b0, // *WPRI*
1'b0, // supervisor external interrupt pending
mip_ueip, // user external interrupt pending
1'b0, // machine timer interrupt pending
1'b0, // *WPRI*
1'b0, // supervisor timer interrupt pending
mip_utip, // user timer interrupt pending
1'b0, // machine software interrupt pending
1'b0, // *WPRI*
1'b0, // supervisor software interrupt pending
mip_usip // user software interrupt pending
};
//
assign mip_meip = ( irqm_extern_i);
assign mip_mtip = ( irqm_timer_i );
assign mip_msip = ( irqm_softw_i );
assign mip_seip = (mip_seip_d | irqs_extern_i);
assign mip_stip = (mip_stip_d );
assign mip_ssip = (mip_ssip_d );
assign mip_ueip = (mip_ueip_d );
assign mip_utip = (mip_utip_d );
assign mip_usip = (mip_usip_d );
//
always @ (*) begin
mip_seip_d = mip_seip_q;
mip_ueip_d = mip_ueip_q;
mip_stip_d = mip_stip_q;
mip_utip_d = mip_utip_q;
mip_ssip_d = mip_ssip_q;
mip_usip_d = mip_usip_q;
if (wr_i) begin
case (wr_addr_i)
12'h344 : begin // mip
mip_seip_d = read_modify_write1(mip_seip_q, wr_data_i[9]);
mip_ueip_d = read_modify_write1(mip_ueip_q, wr_data_i[8]);
mip_stip_d = read_modify_write1(mip_stip_q, wr_data_i[5]);
mip_utip_d = read_modify_write1(mip_utip_q, wr_data_i[4]);
mip_ssip_d = read_modify_write1(mip_ssip_q, wr_data_i[1]);
mip_usip_d = read_modify_write1(mip_usip_q, wr_data_i[0]);
end
12'h144 : begin // sip
mip_ueip_d = read_modify_write1(mip_ueip_q, wr_data_i[8]);
mip_utip_d = read_modify_write1(mip_utip_q, wr_data_i[4]);
mip_ssip_d = read_modify_write1(mip_ssip_q, wr_data_i[1]);
mip_usip_d = read_modify_write1(mip_usip_q, wr_data_i[0]);
end
12'h044 : begin // uip
mip_usip_d = read_modify_write1(mip_usip_q, wr_data_i[0]);
end
default : begin
end
endcase
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK_RESET(clk_i, reset_i) begin
if (reset_i) begin
mip_seip_q <= 1'b0;
mip_ueip_q <= 1'b0;
mip_stip_q <= 1'b0;
mip_utip_q <= 1'b0;
mip_ssip_q <= 1'b0;
mip_usip_q <= 1'b0;
end else begin
mip_seip_q <= mip_seip_d;
mip_ueip_q <= mip_ueip_d;
mip_stip_q <= mip_stip_d;
mip_utip_q <= mip_utip_d;
mip_ssip_q <= mip_ssip_d;
mip_usip_q <= mip_usip_d;
end
end
//--------------------------------------------------------------
// mscratch
//--------------------------------------------------------------
assign mscratch = mscratch_d; // scratch register
//
always @ (*) begin
mscratch_d = mscratch_q;
if (wr_i) begin
if (wr_addr_i == 12'h340) begin
mscratch_d = read_modify_write(mscratch_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
mscratch_q <= mscratch_d;
end
//--------------------------------------------------------------
// sscratch
//--------------------------------------------------------------
assign sscratch = sscratch_d; // scratch register
//
always @ (*) begin
sscratch_d = sscratch_q;
if (wr_i) begin
if (wr_addr_i == 12'h140) begin
sscratch_d = read_modify_write(sscratch_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
sscratch_q <= sscratch_d;
end
//--------------------------------------------------------------
// uscratch
//--------------------------------------------------------------
assign uscratch = uscratch_d; // scratch register
//
always @ (*) begin
uscratch_d = uscratch_q;
if (wr_i) begin
if (wr_addr_i == 12'h040) begin
uscratch_d = read_modify_write(uscratch_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
uscratch_q <= uscratch_d;
end
//--------------------------------------------------------------
// mepc
//--------------------------------------------------------------
assign mepc = {
mepc_d, // exception program counter
`ifdef RV_CONFIG_STDEXT_C
`else
1'b0,
`endif
1'b0
};
//
always @ (*) begin
mepc_d = mepc_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_MACHINE) begin
`ifdef RV_CONFIG_STDEXT_C
mepc_d = excp_pc_i[`RV_XLEN-1:1];
`else
mepc_d = excp_pc_i[`RV_XLEN-1:2];
`endif
end else if (wr_i) begin
if (wr_addr_i == 12'h341) begin
`ifdef RV_CONFIG_STDEXT_C
mepc_d = read_modify_writem1(mepc_q, wr_data_i[`RV_XLEN-1:1]);
`else
mepc_d = read_modify_writem2(mepc_q, wr_data_i[`RV_XLEN-1:2]);
`endif
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
mepc_q <= mepc_d;
end
//--------------------------------------------------------------
// sepc
//--------------------------------------------------------------
assign sepc = {
sepc_d, // exception program counter
`ifdef RV_CONFIG_STDEXT_C
`else
1'b0,
`endif
1'b0
};
//
always @ (*) begin
sepc_d = sepc_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_SUPERVISOR) begin
`ifdef RV_CONFIG_STDEXT_C
sepc_d = excp_pc_i[`RV_XLEN-1:1];
`else
sepc_d = excp_pc_i[`RV_XLEN-1:2];
`endif
end else if (wr_i) begin
if (wr_addr_i == 12'h141) begin
`ifdef RV_CONFIG_STDEXT_C
sepc_d = read_modify_writem1(sepc_q, wr_data_i[`RV_XLEN-1:1]);
`else
sepc_d = read_modify_writem2(sepc_q, wr_data_i[`RV_XLEN-1:2]);
`endif
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
sepc_q <= sepc_d;
end
//--------------------------------------------------------------
// uepc
//--------------------------------------------------------------
assign uepc = {
uepc_d, // exception program counter
`ifdef RV_CONFIG_STDEXT_C
`else
1'b0,
`endif
1'b0
};
//
always @ (*) begin
uepc_d = uepc_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_USER) begin
`ifdef RV_CONFIG_STDEXT_C
uepc_d = excp_pc_i[`RV_XLEN-1:1];
`else
uepc_d = excp_pc_i[`RV_XLEN-1:2];
`endif
end else if (wr_i) begin
if (wr_addr_i == 12'h041) begin
`ifdef RV_CONFIG_STDEXT_C
uepc_d = read_modify_writem1(uepc_q, wr_data_i[`RV_XLEN-1:1]);
`else
uepc_d = read_modify_writem2(uepc_q, wr_data_i[`RV_XLEN-1:2]);
`endif
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
uepc_q <= uepc_d;
end
//--------------------------------------------------------------
// mcause
//--------------------------------------------------------------
assign mcause = {
mcause_int_d, // interrupt
{ `RV_XLEN-5 {1'b0} }, // *WLRL*
mcause_code_d // cause code
};
//
always @ (*) begin
mcause_int_d = mcause_int_q;
mcause_code_d = mcause_code_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_MACHINE) begin
mcause_int_d = interrupt;
mcause_code_d = trap_call_cause_code;
end else if (wr_i) begin
if (wr_addr_i == 12'h342) begin
mcause_int_d = read_modify_write1(mcause_int_q, wr_data_i[`RV_XLEN-1]);
mcause_code_d = read_modify_write4(mcause_code_q, wr_data_i[3:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
mcause_int_q <= mcause_int_d;
mcause_code_q <= mcause_code_d;
end
//--------------------------------------------------------------
// scause
//--------------------------------------------------------------
assign scause = {
scause_int_d, // interrupt
{ `RV_XLEN-5 {1'b0} }, // *WLRL*
scause_code_d // cause code
};
//
always @ (*) begin
scause_int_d = scause_int_q;
scause_code_d = scause_code_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_SUPERVISOR) begin
scause_int_d = interrupt;
scause_code_d = trap_call_cause_code;
end else if (wr_i) begin
if (wr_addr_i == 12'h142) begin
scause_int_d = read_modify_write1(scause_int_q, wr_data_i[`RV_XLEN-1]);
scause_code_d = read_modify_write4(scause_code_q, wr_data_i[3:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
scause_int_q <= scause_int_d;
scause_code_q <= scause_code_d;
end
//--------------------------------------------------------------
// ucause
//--------------------------------------------------------------
assign ucause = {
ucause_int_d, // interrupt
{ `RV_XLEN-5 {1'b0} }, // *WLRL*
ucause_code_d // cause code
};
//
always @ (*) begin
ucause_int_d = ucause_int_q;
ucause_code_d = ucause_code_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_USER) begin
ucause_int_d = interrupt;
ucause_code_d = trap_call_cause_code;
end else if (wr_i) begin
if (wr_addr_i == 12'h042) begin
ucause_int_d = read_modify_write1(ucause_int_q, wr_data_i[`RV_XLEN-1]);
ucause_code_d = read_modify_write4(ucause_code_q, wr_data_i[3:0]);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
ucause_int_q <= ucause_int_d;
ucause_code_q <= ucause_code_d;
end
//--------------------------------------------------------------
// mtval
//--------------------------------------------------------------
assign mtval = mtval_d; // trap value
//
always @ (*) begin
mtval_d = mtval_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_MACHINE) begin
mtval_d = trap_call_value_o;
end else if (wr_i) begin
if (wr_addr_i == 12'h343) begin
mtval_d = read_modify_write(mtval_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
mtval_q <= mtval_d;
end
//--------------------------------------------------------------
// stval
//--------------------------------------------------------------
assign stval = stval_d; // trap value
//
always @ (*) begin
stval_d = stval_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_SUPERVISOR) begin
stval_d = trap_call_value_o;
end else if (wr_i) begin
if (wr_addr_i == 12'h343) begin
stval_d = read_modify_write(stval_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
stval_q <= stval_d;
end
//--------------------------------------------------------------
// utval
//--------------------------------------------------------------
assign utval = utval_d; // trap value
//
always @ (*) begin
utval_d = utval_q;
if (trap_call_o && trap_call_mode == `RV_CSR_MODE_USER) begin
utval_d = trap_call_value_o;
end else if (wr_i) begin
if (wr_addr_i == 12'h343) begin
utval_d = read_modify_write(utval_q, wr_data_i);
end
end
end
//
always @ `RV_SYNC_LOGIC_CLOCK(clk_i) begin
utval_q <= utval_d;
end
//--------------------------------------------------------------
// interrupt and exception logic
//--------------------------------------------------------------
/*
* Traps should be taken with the following priority:
* 1) external interrupts
* 2) software interrupts
* 3) timer interrupts
* 4) synchronous traps
*/
always @ `RV_SYNC_LOGIC_CLOCK_RESET(fclk_i, reset_i) begin
if (reset_i) begin
m_int_e_q <= 1'b0;
m_int_t_q <= 1'b0;
m_int_s_q <= 1'b0;
s_int_e_q <= 1'b0;
s_int_t_q <= 1'b0;
s_int_s_q <= 1'b0;
u_int_e_q <= 1'b0;
u_int_t_q <= 1'b0;
u_int_s_q <= 1'b0;
end else begin
m_int_e_q <= mip_meip & mie_meie_q;
m_int_t_q <= mip_mtip & mie_mtie_q;
m_int_s_q <= mip_msip & mie_msie_q;
s_int_e_q <= mip_seip & mie_seie_q;
s_int_t_q <= mip_stip & mie_stie_q;
s_int_s_q <= mip_ssip & mie_ssie_q;
u_int_e_q <= mip_ueip & mie_ueie_q;
u_int_t_q <= mip_utip & mie_utie_q;
u_int_s_q <= mip_usip & mie_usie_q;
end
end
// interrupt logic
always @ (*) begin
interrupt = 1'b0;
interrupt_cause = 4'bx;
interrupt_mode = `RV_CSR_MODE_MACHINE;
case (mode_q)
`RV_CSR_MODE_MACHINE : begin
interrupt = (mstatus_mie_q & (m_int_e_q | m_int_t_q | m_int_s_q));
// interrupt cause encoder
if (m_int_e_q) begin // machine external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_ME;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (m_int_s_q) begin // machine software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MS;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else begin // machine timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MT;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end
end
`RV_CSR_MODE_SUPERVISOR : begin
interrupt = ( (m_int_e_q | m_int_t_q | m_int_s_q)) |
(mstatus_sie_q & (s_int_e_q | s_int_t_q | s_int_s_q)) ;
// interrupt cause and mode encoder
if (m_int_e_q) begin // machine external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_ME;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (m_int_s_q) begin // machine software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MS;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (m_int_t_q) begin // machine timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MT;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (s_int_e_q) begin // supervisor external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_SE;
interrupt_mode = (mideleg_sei_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (s_int_s_q) begin // supervisor software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_SS;
interrupt_mode = (mideleg_ssi_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else begin // supervisor timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_ST;
interrupt_mode = (mideleg_sti_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end
end
`RV_CSR_MODE_USER : begin
interrupt = ( (m_int_e_q | m_int_t_q | m_int_s_q)) |
( (s_int_e_q | s_int_t_q | s_int_s_q)) |
(mstatus_uie_q & (u_int_e_q | u_int_t_q | u_int_s_q)) ;
// interrupt cause and mode encoder
if (m_int_e_q) begin // machine external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_ME;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (m_int_s_q) begin // machine software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MS;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (m_int_t_q) begin // machine timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_MT;
interrupt_mode = `RV_CSR_MODE_MACHINE;
end else if (s_int_e_q) begin // supervisor external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_SE;
interrupt_mode = (mideleg_sei_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (s_int_s_q) begin // supervisor software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_SS;
interrupt_mode = (mideleg_ssi_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (s_int_t_q) begin // supervisor timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_ST;
interrupt_mode = (mideleg_sti_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (u_int_e_q) begin // user external interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_UE;
interrupt_mode = (mideleg_uei_q ? (sideleg_uei_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (u_int_s_q) begin // user software interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_US;
interrupt_mode = (mideleg_usi_q ? (sideleg_usi_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else begin // user timer interrupt
interrupt_cause = `RV_CSR_INTR_CAUSE_UT;
interrupt_mode = (mideleg_uti_q ? (sideleg_uti_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end
end
default : begin
end
endcase
end
// exception logic
always @ (*) begin
exception = 1'b0;
exception_cause = 4'bx;
exception_mode = `RV_CSR_MODE_MACHINE;
case (mode_q)
`RV_CSR_MODE_MACHINE : begin
// exception cause and mode encoder
if (excp_ferr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ACCESS_FAULT;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_uerr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_ilgl_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_maif_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ADDR_MISALIGNED;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_mala_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_LOAD_ADDR_MISALIGNED;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_masa_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_STORE_ADDR_MISALIGNED;
exception_mode = `RV_CSR_MODE_MACHINE;
end else if (excp_ecall_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ECALL_FROM_MMODE;
exception_mode = `RV_CSR_MODE_MACHINE;
end
end
`RV_CSR_MODE_SUPERVISOR : begin
// exception cause and mode encoder
if (excp_ferr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ACCESS_FAULT;
exception_mode = (medeleg_iaf_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_uerr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = (medeleg_ii_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_ilgl_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = (medeleg_ii_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_maif_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ADDR_MISALIGNED;
exception_mode = (medeleg_iam_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_mala_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_LOAD_ADDR_MISALIGNED;
exception_mode = (medeleg_lam_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_masa_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_STORE_ADDR_MISALIGNED;
exception_mode = (medeleg_sam_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_ecall_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ECALL_FROM_SMODE;
exception_mode = (medeleg_ecfs_q ? `RV_CSR_MODE_SUPERVISOR
: `RV_CSR_MODE_MACHINE)
;
end
end
`RV_CSR_MODE_USER : begin
// exception cause and mode encoder
if (excp_ferr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ACCESS_FAULT;
exception_mode = (medeleg_iaf_q ? (sedeleg_iaf_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_uerr_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = (medeleg_ii_q ? (sedeleg_ii_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_ilgl_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ILLEGAL_INS;
exception_mode = (medeleg_ii_q ? (sedeleg_ii_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_maif_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_INS_ADDR_MISALIGNED;
exception_mode = (medeleg_iam_q ? (sedeleg_iam_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_mala_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_LOAD_ADDR_MISALIGNED;
exception_mode = (medeleg_lam_q ? (sedeleg_lam_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_masa_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_STORE_ADDR_MISALIGNED;
exception_mode = (medeleg_sam_q ? (sedeleg_sam_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end else if (excp_ecall_i) begin
exception = 1'b1;
exception_cause = `RV_CSR_EXCP_CAUSE_ECALL_FROM_UMODE;
exception_mode = (medeleg_ecfu_q ? (sedeleg_ecfu_q ? `RV_CSR_MODE_USER
: `RV_CSR_MODE_SUPERVISOR)
: `RV_CSR_MODE_MACHINE)
;
end
end
default : begin
end
endcase
end
//--------------------------------------------------------------
// trap call logic
//--------------------------------------------------------------
/*
* Traps should be taken with the following priority:
* 1) external interrupts
* 2) software interrupts
* 3) timer interrupts
* 4) synchronous traps
*/
assign trap_call_o = ex_valid_i & (interrupt | exception);
assign trap_call_cause_o = { interrupt, { `RV_XLEN-5 {1'b0} }, trap_call_cause_code };
assign trap_call_addr_o = (trap_call_vectored ? { trap_call_base[`RV_XLEN-3:4], interrupt_cause, 2'b0 }
: { trap_call_base, 2'b0 })
;
assign trap_call_cause_code = (interrupt ? interrupt_cause
: exception_cause)
;
assign trap_call_mode = (interrupt ? interrupt_mode
: exception_mode)
;
// trap value encoder
always @ (*) begin
if (interrupt) begin // TODO hardware breakpoint | page fault
trap_call_value_o = { `RV_XLEN {1'b0} };
end else if (excp_maif_i | excp_mala_i | excp_masa_i) begin
trap_call_value_o = excp_pc_i;
end else if (excp_uerr_i | excp_ilgl_i) begin
trap_call_value_o = excp_ins_i;
end else begin
trap_call_value_o = { `RV_XLEN {1'b0} };
end
end
// trap call base address and offset mode decoder
always @ (*) begin
trap_call_vectored = 1'b0;
trap_call_base = { `RV_XLEN-2 {1'bx} };
case (trap_call_mode)
`RV_CSR_MODE_MACHINE : begin
trap_call_base = mtvec_q;
if (mtvec_mode_q == `RV_CSR_TVEC_MODE_VECTORED) begin
trap_call_vectored = interrupt;
end
end
`RV_CSR_MODE_SUPERVISOR : begin
trap_call_base = stvec_q;
if (stvec_mode_q == `RV_CSR_TVEC_MODE_VECTORED) begin
trap_call_vectored = interrupt;
end
end
`RV_CSR_MODE_USER : begin
trap_call_base = utvec_q;
if (utvec_mode_q == `RV_CSR_TVEC_MODE_VECTORED) begin
trap_call_vectored = interrupt;
end
end
default : begin
end
endcase
end
//--------------------------------------------------------------
// trap return address mux
//--------------------------------------------------------------
always @ (*) begin
trap_rtn_addr_o = { `RV_XLEN {1'bx} };
case (trap_rtn_mode_i)
`ifdef RV_CONFIG_STDEXT_C
`RV_CSR_MODE_MACHINE : trap_rtn_addr_o = { mepc_q, 1'b0 };
`RV_CSR_MODE_SUPERVISOR : trap_rtn_addr_o = { sepc_q, 1'b0 };
`RV_CSR_MODE_USER : trap_rtn_addr_o = { uepc_q, 1'b0 };
`else
`RV_CSR_MODE_MACHINE : trap_rtn_addr_o = { mepc_q, 2'b0 };
`RV_CSR_MODE_SUPERVISOR : trap_rtn_addr_o = { sepc_q, 2'b0 };
`RV_CSR_MODE_USER : trap_rtn_addr_o = { uepc_q, 2'b0 };
`endif
default : begin
end
endcase
end
endmodule
|
`timescale 1ns / 1ps
/*
-- Module Name: FIFO control
-- Description: Unidad de control para FIFO. Implementa los punteros de
escritura/lectura para las operaciones PUSH y POP.
-- Dependencies: -- system.vh
-- Parameters: -- CHANNEL_WIDTH: Ancho de palabra de los canales
de comunicacion entre routers.
-- BUFFER_DEPTH: Numero de direcciones en la
estructura de memoria.
-- ADDR_WIDTH: Numero de bits requerido para
representar el espacio de
direcciones del elemento de
memoria del FIFO.
-- Original Author: Héctor Cabrera
-- Current Author:
-- Notas:
-- History:
-- Creacion 07 de Junio 2015
*/
`include "system.vh"
module register_file
(
input wire clk,
// -- inputs ------------------------------------------------- >>>>>
input wire write_strobe_din,
input wire [ADDR_WIDTH-1:0] write_address_din,
input wire [`CHANNEL_WIDTH-1:0] write_data_din,
input wire [ADDR_WIDTH-1:0] read_address_din,
// -- outputs ------------------------------------------------ >>>>>
output wire [`CHANNEL_WIDTH-1:0] read_data_dout
);
// --- Definiciones Locales -------------------------------------- >>>>>
localparam ADDR_WIDTH = clog2(`BUFFER_DEPTH);
// -- Modelado de matriz de almacenamiento ----------------------- >>>>>
reg [`CHANNEL_WIDTH-1:0] REG_FILE [0:`BUFFER_DEPTH-1];
// -- Puerto de escritura sincrono ------------------------------- >>>>>
always @(posedge clk)
if (write_strobe_din)
REG_FILE[write_address_din] <= write_data_din;
// -- Puerto de lectura asincrono -------------------------------- >>>>>
assign read_data_dout = REG_FILE[read_address_din];
// -- Codigo no sintetizable ------------------------------------- >>>>>
// -- Funciones ---------------------------------------------- >>>>>
// -- Rutina de Inicializacion de Registro --------------- >>>>>
integer rf_index;
initial
for (rf_index = 0; rf_index < `BUFFER_DEPTH; rf_index = rf_index + 1)
REG_FILE[rf_index] = {`CHANNEL_WIDTH{1'b0}};
// -- Funcion de calculo: log2(x) ------------------------ >>>>>
function integer clog2;
input integer depth;
for (clog2=0; depth>0; clog2=clog2+1)
depth = depth >> 1;
endfunction
endmodule
/* -- Plantilla de Instancia ------------------------------------- >>>>>
wire [`CHANNEL_WIDTH-1:0] read_data;
register_file register_file
(
.clk (clk),
// -- inputs --------------------------------------------- >>>>>
.write_strobe_din (write_strobe_din),
.write_address_din (write_address_din),
.write_data_din (write_data_din),
.read_address_din (read_address_din),
// -- outputs -------------------------------------------- >>>>>
.read_data_dout (read_data)
);
*/ |
//////////////////////////////////////////////////////////////////////
//// ////
//// uart_regs.v ////
//// ////
//// ////
//// This file is part of the "UART 16550 compatible" project ////
//// http://www.opencores.org/cores/uart16550/ ////
//// ////
//// Documentation related to this project: ////
//// - http://www.opencores.org/cores/uart16550/ ////
//// ////
//// Projects compatibility: ////
//// - WISHBONE ////
//// RS232 Protocol ////
//// 16550D uart (mostly supported) ////
//// ////
//// Overview (main Features): ////
//// Registers of the uart 16550 core ////
//// ////
//// Known problems (limits): ////
//// Inserts 1 wait state in all WISHBONE transfers ////
//// ////
//// To Do: ////
//// Nothing or verification. ////
//// ////
//// Author(s): ////
//// - [email protected] ////
//// - Jacob Gorban ////
//// - Igor Mohor ([email protected]) ////
//// ////
//// Created: 2001/05/12 ////
//// Last Updated: (See log for the revision history ////
//// Modified for use in the ZAP project by Revanth Kamaraj ////
//// ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2000, 2001 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
//
// CVS Revision History
//
// $Log: not supported by cvs2svn $
// Revision 1.41 2004/05/21 11:44:41 tadejm
// Added synchronizer flops for RX input.
//
// Revision 1.40 2003/06/11 16:37:47 gorban
// This fixes errors in some cases when data is being read and put to the FIFO at the same time. Patch is submitted by Scott Furman. Update is very recommended.
//
// Revision 1.39 2002/07/29 21:16:18 gorban
// The uart_defines.v file is included again in sources.
//
// Revision 1.38 2002/07/22 23:02:23 gorban
// Bug Fixes:
// * Possible loss of sync and bad reception of stop bit on slow baud rates fixed.
// Problem reported by Kenny.Tung.
// * Bad (or lack of ) loopback handling fixed. Reported by Cherry Withers.
//
// Improvements:
// * Made FIFO's as general inferrable memory where possible.
// So on FPGA they should be inferred as RAM (Distributed RAM on Xilinx).
// This saves about 1/3 of the Slice count and reduces P&R and synthesis times.
//
// * Added optional baudrate output (baud_o).
// This is identical to BAUDOUT* signal on 16550 chip.
// It outputs 16xbit_clock_rate - the divided clock.
// It's disabled by default. Define UART_HAS_BAUDRATE_OUTPUT to use.
//
// Revision 1.37 2001/12/27 13:24:09 mohor
// lsr[7] was not showing overrun errors.
//
// Revision 1.36 2001/12/20 13:25:46 mohor
// rx push changed to be only one cycle wide.
//
// Revision 1.35 2001/12/19 08:03:34 mohor
// Warnings cleared.
//
// Revision 1.34 2001/12/19 07:33:54 mohor
// Synplicity was having troubles with the comment.
//
// Revision 1.33 2001/12/17 10:14:43 mohor
// Things related to msr register changed. After THRE IRQ occurs, and one
// character is written to the transmit fifo, the detection of the THRE bit in the
// LSR is delayed for one character time.
//
// Revision 1.32 2001/12/14 13:19:24 mohor
// MSR register fixed.
//
// Revision 1.31 2001/12/14 10:06:58 mohor
// After reset modem status register MSR should be reset.
//
// Revision 1.30 2001/12/13 10:09:13 mohor
// thre irq should be cleared only when being source of interrupt.
//
// Revision 1.29 2001/12/12 09:05:46 mohor
// LSR status bit 0 was not cleared correctly in case of reseting the FCR (rx fifo).
//
// Revision 1.28 2001/12/10 19:52:41 gorban
// Scratch register added
//
// Revision 1.27 2001/12/06 14:51:04 gorban
// Bug in LSR[0] is fixed.
// All WISHBONE signals are now sampled, so another wait-state is introduced on all transfers.
//
// Revision 1.26 2001/12/03 21:44:29 gorban
// Updated specification documentation.
// Added full 32-bit data bus interface, now as default.
// Address is 5-bit wide in 32-bit data bus mode.
// Added wb_sel_i input to the core. It's used in the 32-bit mode.
// Added debug interface with two 32-bit read-only registers in 32-bit mode.
// Bits 5 and 6 of LSR are now only cleared on TX FIFO write.
// My small test bench is modified to work with 32-bit mode.
//
// Revision 1.25 2001/11/28 19:36:39 gorban
// Fixed: timeout and break didn't pay attention to current data format when counting time
//
// Revision 1.24 2001/11/26 21:38:54 gorban
// Lots of fixes:
// Break condition wasn't handled correctly at all.
// LSR bits could lose their values.
// LSR value after reset was wrong.
// Timing of THRE interrupt signal corrected.
// LSR bit 0 timing corrected.
//
// Revision 1.23 2001/11/12 21:57:29 gorban
// fixed more typo bugs
//
// Revision 1.22 2001/11/12 15:02:28 mohor
// lsr1r error fixed.
//
// Revision 1.21 2001/11/12 14:57:27 mohor
// ti_int_pnd error fixed.
//
// Revision 1.20 2001/11/12 14:50:27 mohor
// ti_int_d error fixed.
//
// Revision 1.19 2001/11/10 12:43:21 gorban
// Logic Synthesis bugs fixed. Some other minor changes
//
// Revision 1.18 2001/11/08 14:54:23 mohor
// Comments in Slovene language deleted, few small fixes for better work of
// old tools. IRQs need to be fix.
//
// Revision 1.17 2001/11/07 17:51:52 gorban
// Heavily rewritten interrupt and LSR subsystems.
// Many bugs hopefully squashed.
//
// Revision 1.16 2001/11/02 09:55:16 mohor
// no message
//
// Revision 1.15 2001/10/31 15:19:22 gorban
// Fixes to break and timeout conditions
//
// Revision 1.14 2001/10/29 17:00:46 gorban
// fixed parity sending and tx_fifo resets over- and underrun
//
// Revision 1.13 2001/10/20 09:58:40 gorban
// Small synopsis fixes
//
// Revision 1.12 2001/10/19 16:21:40 gorban
// Changes data_out to be synchronous again as it should have been.
//
// Revision 1.11 2001/10/18 20:35:45 gorban
// small fix
//
// Revision 1.10 2001/08/24 21:01:12 mohor
// Things connected to parity changed.
// Clock devider changed.
//
// Revision 1.9 2001/08/23 16:05:05 mohor
// Stop bit bug fixed.
// Parity bug fixed.
// WISHBONE read cycle bug fixed,
// OE indicator (Overrun Error) bug fixed.
// PE indicator (Parity Error) bug fixed.
// Register read bug fixed.
//
// Revision 1.10 2001/06/23 11:21:48 gorban
// DL made 16-bit long. Fixed transmission/reception bugs.
//
// Revision 1.9 2001/05/31 20:08:01 gorban
// FIFO changes and other corrections.
//
// Revision 1.8 2001/05/29 20:05:04 gorban
// Fixed some bugs and synthesis problems.
//
// Revision 1.7 2001/05/27 17:37:49 gorban
// Fixed many bugs. Updated spec. Changed FIFO files structure. See CHANGES.txt file.
//
// Revision 1.6 2001/05/21 19:12:02 gorban
// Corrected some Linter messages.
//
// Revision 1.5 2001/05/17 18:34:18 gorban
// First 'stable' release. Should be sythesizable now. Also added new header.
//
// Revision 1.0 2001-05-17 21:27:11+02 jacob
// Initial revision
//
//
//// Modified for use in the ZAP project by Revanth Kamaraj ////
`include "uart_defines.v"
`define UART_DL1 7:0
`define UART_DL2 15:8
module uart_regs (clk,
wb_rst_i, wb_addr_i, wb_dat_i, wb_dat_o, wb_we_i, wb_re_i,
// additional signals
modem_inputs,
stx_pad_o, srx_pad_i,
`ifdef DATA_BUS_WIDTH_8
`else
// debug interface signals enabled
ier, iir, fcr, mcr, lcr, msr, lsr, rf_count, tf_count, tstate, rstate,
`endif
rts_pad_o, dtr_pad_o, int_o
`ifdef UART_HAS_BAUDRATE_OUTPUT
, baud_o
`endif
);
input clk;
input wb_rst_i;
input [`UART_ADDR_WIDTH-1:0] wb_addr_i;
input [7:0] wb_dat_i;
output [7:0] wb_dat_o;
input wb_we_i;
input wb_re_i;
output stx_pad_o;
input srx_pad_i;
input [3:0] modem_inputs;
output rts_pad_o;
output dtr_pad_o;
output int_o;
`ifdef UART_HAS_BAUDRATE_OUTPUT
output baud_o;
`endif
`ifdef DATA_BUS_WIDTH_8
`else
// if 32-bit databus and debug interface are enabled
output [3:0] ier;
output [3:0] iir;
output [1:0] fcr; /// bits 7 and 6 of fcr. Other bits are ignored
output [4:0] mcr;
output [7:0] lcr;
output [7:0] msr;
output [7:0] lsr;
output [`UART_FIFO_COUNTER_W-1:0] rf_count;
output [`UART_FIFO_COUNTER_W-1:0] tf_count;
output [2:0] tstate;
output [3:0] rstate;
`endif
wire [3:0] modem_inputs;
reg enable;
`ifdef UART_HAS_BAUDRATE_OUTPUT
assign baud_o = enable; // baud_o is actually the enable signal
`endif
wire stx_pad_o; // received from transmitter module
wire srx_pad_i;
wire srx_pad;
reg [7:0] wb_dat_o;
wire [`UART_ADDR_WIDTH-1:0] wb_addr_i;
wire [7:0] wb_dat_i;
reg [3:0] ier;
reg [3:0] iir;
reg [1:0] fcr; /// bits 7 and 6 of fcr. Other bits are ignored
reg [4:0] mcr;
reg [7:0] lcr;
reg [7:0] msr;
reg [15:0] dl; // 32-bit divisor latch
reg [7:0] scratch; // UART scratch register
reg start_dlc; // activate dlc on writing to UART_DL1
reg lsr_mask_d; // delay for lsr_mask condition
reg msi_reset; // reset MSR 4 lower bits indicator
//reg threi_clear; // THRE interrupt clear flag
reg [15:0] dlc; // 32-bit divisor latch counter
reg int_o;
reg [3:0] trigger_level; // trigger level of the receiver FIFO
reg rx_reset;
reg tx_reset;
wire dlab; // divisor latch access bit
wire cts_pad_i, dsr_pad_i, ri_pad_i, dcd_pad_i; // modem status bits
wire loopback; // loopback bit (MCR bit 4)
wire cts, dsr, ri, dcd; // effective signals
wire cts_c, dsr_c, ri_c, dcd_c; // Complement effective signals (considering loopback)
wire rts_pad_o, dtr_pad_o; // modem control outputs
// LSR bits wires and regs
wire [7:0] lsr;
wire lsr0, lsr1, lsr2, lsr3, lsr4, lsr5, lsr6, lsr7;
reg lsr0r, lsr1r, lsr2r, lsr3r, lsr4r, lsr5r, lsr6r, lsr7r;
wire lsr_mask; // lsr_mask
//
// ASSINGS
//
assign lsr[7:0] = { lsr7r, lsr6r, lsr5r, lsr4r, lsr3r, lsr2r, lsr1r, lsr0r };
assign {cts_pad_i, dsr_pad_i, ri_pad_i, dcd_pad_i} = modem_inputs;
assign {cts, dsr, ri, dcd} = ~{cts_pad_i,dsr_pad_i,ri_pad_i,dcd_pad_i};
assign {cts_c, dsr_c, ri_c, dcd_c} = loopback ? {mcr[`UART_MC_RTS],mcr[`UART_MC_DTR],mcr[`UART_MC_OUT1],mcr[`UART_MC_OUT2]}
: {cts_pad_i,dsr_pad_i,ri_pad_i,dcd_pad_i};
assign dlab = lcr[`UART_LC_DL];
assign loopback = mcr[4];
// assign modem outputs
assign rts_pad_o = mcr[`UART_MC_RTS];
assign dtr_pad_o = mcr[`UART_MC_DTR];
// Interrupt signals
wire rls_int; // receiver line status interrupt
wire rda_int; // receiver data available interrupt
wire ti_int; // timeout indicator interrupt
wire thre_int; // transmitter holding register empty interrupt
wire ms_int; // modem status interrupt
// FIFO signals
reg tf_push;
reg rf_pop;
wire [`UART_FIFO_REC_WIDTH-1:0] rf_data_out;
wire rf_error_bit; // an error (parity or framing) is inside the fifo
wire [`UART_FIFO_COUNTER_W-1:0] rf_count;
wire [`UART_FIFO_COUNTER_W-1:0] tf_count;
wire [2:0] tstate;
wire [3:0] rstate;
wire [9:0] counter_t;
wire thre_set_en; // THRE status is delayed one character time when a character is written to fifo.
reg [7:0] block_cnt; // While counter counts, THRE status is blocked (delayed one character cycle)
reg [7:0] block_value; // One character length minus stop bit
// Transmitter Instance
wire serial_out;
uart_transmitter transmitter(clk, wb_rst_i, lcr, tf_push, wb_dat_i, enable, serial_out, tstate, tf_count, tx_reset, lsr_mask);
// Synchronizing and sampling serial RX input
uart_sync_flops i_uart_sync_flops
(
.rst_i (wb_rst_i),
.clk_i (clk),
.stage1_rst_i (1'b0),
.stage1_clk_en_i (1'b1),
.async_dat_i (srx_pad_i),
.sync_dat_o (srx_pad)
);
defparam i_uart_sync_flops.width = 1;
defparam i_uart_sync_flops.init_value = 1'b1;
// handle loopback
wire serial_in = loopback ? serial_out : srx_pad;
assign stx_pad_o = loopback ? 1'b1 : serial_out;
// Receiver Instance
uart_receiver receiver(clk, wb_rst_i, lcr, rf_pop, serial_in, enable,
counter_t, rf_count, rf_data_out, rf_error_bit, rf_overrun, rx_reset, lsr_mask, rstate, rf_push_pulse);
// Asynchronous reading here because the outputs are sampled in uart_wb.v file
always @(dl or dlab or ier or iir or scratch
or lcr or lsr or msr or rf_data_out or wb_addr_i or wb_re_i) // asynchrounous reading
begin
case (wb_addr_i)
`UART_REG_RB : wb_dat_o = dlab ? dl[`UART_DL1] : rf_data_out[10:3];
`UART_REG_IE : wb_dat_o = dlab ? dl[`UART_DL2] : ier;
`UART_REG_II : wb_dat_o = {4'b1100,iir};
`UART_REG_LC : wb_dat_o = lcr;
`UART_REG_LS : wb_dat_o = lsr;
`UART_REG_MS : wb_dat_o = msr;
`UART_REG_SR : wb_dat_o = scratch;
default: wb_dat_o = 8'b0; // ??
endcase // case(wb_addr_i)
end // always @ (dl or dlab or ier or iir or scratch...
// rf_pop signal handling
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
rf_pop <= 0;
else
if (rf_pop) // restore the signal to 0 after one clock cycle
rf_pop <= 0;
else
if (wb_re_i && wb_addr_i == `UART_REG_RB && !dlab)
rf_pop <= 1; // advance read pointer
end
wire lsr_mask_condition;
wire iir_read;
wire msr_read;
wire fifo_read;
wire fifo_write;
assign lsr_mask_condition = (wb_re_i && wb_addr_i == `UART_REG_LS && !dlab);
assign iir_read = (wb_re_i && wb_addr_i == `UART_REG_II && !dlab);
assign msr_read = (wb_re_i && wb_addr_i == `UART_REG_MS && !dlab);
assign fifo_read = (wb_re_i && wb_addr_i == `UART_REG_RB && !dlab);
assign fifo_write = (wb_we_i && wb_addr_i == `UART_REG_TR && !dlab);
// lsr_mask_d delayed signal handling
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
lsr_mask_d <= 0;
else // reset bits in the Line Status Register
lsr_mask_d <= lsr_mask_condition;
end
// lsr_mask is rise detected
assign lsr_mask = lsr_mask_condition && ~lsr_mask_d;
// msi_reset signal handling
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
msi_reset <= 1;
else
if (msi_reset)
msi_reset <= 0;
else
if (msr_read)
msi_reset <= 1; // reset bits in Modem Status Register
end
//
// WRITES AND RESETS //
//
// Line Control Register
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i)
lcr <= 8'b00000011; // 8n1 setting
else
if (wb_we_i && wb_addr_i==`UART_REG_LC)
lcr <= wb_dat_i;
// Interrupt Enable Register or UART_DL2
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i)
begin
ier <= 4'b0000; // no interrupts after reset
dl[`UART_DL2] <= 8'b0;
end
else
if (wb_we_i && wb_addr_i==`UART_REG_IE)
if (dlab)
begin
dl[`UART_DL2] <= wb_dat_i;
end
else
ier <= wb_dat_i[3:0]; // ier uses only 4 lsb
// FIFO Control Register and rx_reset, tx_reset signals
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) begin
fcr <= 2'b11;
rx_reset <= 0;
tx_reset <= 0;
end else
if (wb_we_i && wb_addr_i==`UART_REG_FC) begin
fcr <= wb_dat_i[7:6];
rx_reset <= wb_dat_i[1];
tx_reset <= wb_dat_i[2];
end else begin
rx_reset <= 0;
tx_reset <= 0;
end
// Modem Control Register
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i)
mcr <= 5'b0;
else
if (wb_we_i && wb_addr_i==`UART_REG_MC)
mcr <= wb_dat_i[4:0];
// Scratch register
// Line Control Register
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i)
scratch <= 0; // 8n1 setting
else
if (wb_we_i && wb_addr_i==`UART_REG_SR)
scratch <= wb_dat_i;
// TX_FIFO or UART_DL1
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i)
begin
dl[`UART_DL1] <= 8'b0;
tf_push <= 1'b0;
start_dlc <= 1'b0;
end
else
if (wb_we_i && wb_addr_i==`UART_REG_TR)
if (dlab)
begin
dl[`UART_DL1] <= wb_dat_i;
start_dlc <= 1'b1; // enable DL counter
tf_push <= 1'b0;
end
else
begin
tf_push <= 1'b1;
start_dlc <= 1'b0;
end // else: !if(dlab)
else
begin
start_dlc <= 1'b0;
tf_push <= 1'b0;
end // else: !if(dlab)
// Receiver FIFO trigger level selection logic (asynchronous mux)
always @(fcr)
case (fcr[`UART_FC_TL])
2'b00 : trigger_level = 1;
2'b01 : trigger_level = 4;
2'b10 : trigger_level = 8;
2'b11 : trigger_level = 14;
endcase // case(fcr[`UART_FC_TL])
//
// STATUS REGISTERS //
//
// Modem Status Register
reg [3:0] delayed_modem_signals;
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
begin
msr <= 0;
delayed_modem_signals[3:0] <= 0;
end
else begin
msr[`UART_MS_DDCD:`UART_MS_DCTS] <= msi_reset ? 4'b0 :
msr[`UART_MS_DDCD:`UART_MS_DCTS] | ({dcd, ri, dsr, cts} ^ delayed_modem_signals[3:0]);
msr[`UART_MS_CDCD:`UART_MS_CCTS] <= {dcd_c, ri_c, dsr_c, cts_c};
delayed_modem_signals[3:0] <= {dcd, ri, dsr, cts};
end
end
// Line Status Register
// activation conditions
assign lsr0 = (rf_count==0 && rf_push_pulse); // data in receiver fifo available set condition
assign lsr1 = rf_overrun; // Receiver overrun error
assign lsr2 = rf_data_out[1]; // parity error bit
assign lsr3 = rf_data_out[0]; // framing error bit
assign lsr4 = rf_data_out[2]; // break error in the character
assign lsr5 = (tf_count==5'b0 && thre_set_en); // transmitter fifo is empty
assign lsr6 = (tf_count==5'b0 && thre_set_en && (tstate == /*`S_IDLE */ 0)); // transmitter empty
assign lsr7 = rf_error_bit | rf_overrun;
// lsr bit0 (receiver data available)
reg lsr0_d;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr0_d <= 0;
else lsr0_d <= lsr0;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr0r <= 0;
else lsr0r <= (rf_count==1 && rf_pop && !rf_push_pulse || rx_reset) ? 0 : // deassert condition
lsr0r || (lsr0 && ~lsr0_d); // set on rise of lsr0 and keep asserted until deasserted
// lsr bit 1 (receiver overrun)
reg lsr1_d; // delayed
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr1_d <= 0;
else lsr1_d <= lsr1;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr1r <= 0;
else lsr1r <= lsr_mask ? 0 : lsr1r || (lsr1 && ~lsr1_d); // set on rise
// lsr bit 2 (parity error)
reg lsr2_d; // delayed
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr2_d <= 0;
else lsr2_d <= lsr2;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr2r <= 0;
else lsr2r <= lsr_mask ? 0 : lsr2r || (lsr2 && ~lsr2_d); // set on rise
// lsr bit 3 (framing error)
reg lsr3_d; // delayed
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr3_d <= 0;
else lsr3_d <= lsr3;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr3r <= 0;
else lsr3r <= lsr_mask ? 0 : lsr3r || (lsr3 && ~lsr3_d); // set on rise
// lsr bit 4 (break indicator)
reg lsr4_d; // delayed
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr4_d <= 0;
else lsr4_d <= lsr4;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr4r <= 0;
else lsr4r <= lsr_mask ? 0 : lsr4r || (lsr4 && ~lsr4_d);
// lsr bit 5 (transmitter fifo is empty)
reg lsr5_d;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr5_d <= 1;
else lsr5_d <= lsr5;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr5r <= 1;
else lsr5r <= (fifo_write) ? 0 : lsr5r || (lsr5 && ~lsr5_d);
// lsr bit 6 (transmitter empty indicator)
reg lsr6_d;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr6_d <= 1;
else lsr6_d <= lsr6;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr6r <= 1;
else lsr6r <= (fifo_write) ? 0 : lsr6r || (lsr6 && ~lsr6_d);
// lsr bit 7 (error in fifo)
reg lsr7_d;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr7_d <= 0;
else lsr7_d <= lsr7;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) lsr7r <= 0;
else lsr7r <= lsr_mask ? 0 : lsr7r || (lsr7 && ~lsr7_d);
// Frequency divider
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
dlc <= 0;
else
if (start_dlc | ~ (|dlc))
dlc <= dl - 1; // preset counter
else
dlc <= dlc - 1; // decrement counter
end
// Enable signal generation logic
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
enable <= 1'b0;
else
if (|dl & ~(|dlc)) // dl>0 & dlc==0
enable <= 1'b1;
else
enable <= 1'b0;
end
// Delaying THRE status for one character cycle after a character is written to an empty fifo.
always @(lcr)
case (lcr[3:0])
4'b0000 : block_value = 95; // 6 bits
4'b0100 : block_value = 103; // 6.5 bits
4'b0001, 4'b1000 : block_value = 111; // 7 bits
4'b1100 : block_value = 119; // 7.5 bits
4'b0010, 4'b0101, 4'b1001 : block_value = 127; // 8 bits
4'b0011, 4'b0110, 4'b1010, 4'b1101 : block_value = 143; // 9 bits
4'b0111, 4'b1011, 4'b1110 : block_value = 159; // 10 bits
4'b1111 : block_value = 175; // 11 bits
endcase // case(lcr[3:0])
// Counting time of one character minus stop bit
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
block_cnt <= 8'd0;
else
if(lsr5r & fifo_write) // THRE bit set & write to fifo occured
block_cnt <= block_value;
else
if (enable & block_cnt != 8'b0) // only work on enable times
block_cnt <= block_cnt - 1; // decrement break counter
end // always of break condition detection
// Generating THRE status enable signal
assign thre_set_en = ~(|block_cnt);
//
// INTERRUPT LOGIC
//
assign rls_int = ier[`UART_IE_RLS] && (lsr[`UART_LS_OE] || lsr[`UART_LS_PE] || lsr[`UART_LS_FE] || lsr[`UART_LS_BI]);
assign rda_int = ier[`UART_IE_RDA] && (rf_count >= {1'b0,trigger_level});
assign thre_int = ier[`UART_IE_THRE] && lsr[`UART_LS_TFE];
assign ms_int = ier[`UART_IE_MS] && (| msr[3:0]);
assign ti_int = ier[`UART_IE_RDA] && (counter_t == 10'b0) && (|rf_count);
reg rls_int_d;
reg thre_int_d;
reg ms_int_d;
reg ti_int_d;
reg rda_int_d;
// delay lines
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) rls_int_d <= 0;
else rls_int_d <= rls_int;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) rda_int_d <= 0;
else rda_int_d <= rda_int;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) thre_int_d <= 0;
else thre_int_d <= thre_int;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) ms_int_d <= 0;
else ms_int_d <= ms_int;
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) ti_int_d <= 0;
else ti_int_d <= ti_int;
// rise detection signals
wire rls_int_rise;
wire thre_int_rise;
wire ms_int_rise;
wire ti_int_rise;
wire rda_int_rise;
assign rda_int_rise = rda_int & ~rda_int_d;
assign rls_int_rise = rls_int & ~rls_int_d;
assign thre_int_rise = thre_int & ~thre_int_d;
assign ms_int_rise = ms_int & ~ms_int_d;
assign ti_int_rise = ti_int & ~ti_int_d;
// interrupt pending flags
reg rls_int_pnd;
reg rda_int_pnd;
reg thre_int_pnd;
reg ms_int_pnd;
reg ti_int_pnd;
// interrupt pending flags assignments
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) rls_int_pnd <= 0;
else
rls_int_pnd <= lsr_mask ? 0 : // reset condition
rls_int_rise ? 1 : // latch condition
rls_int_pnd && ier[`UART_IE_RLS]; // default operation: remove if masked
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) rda_int_pnd <= 0;
else
rda_int_pnd <= ((rf_count == {1'b0,trigger_level}) && fifo_read) ? 0 : // reset condition
rda_int_rise ? 1 : // latch condition
rda_int_pnd && ier[`UART_IE_RDA]; // default operation: remove if masked
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) thre_int_pnd <= 0;
else
thre_int_pnd <= fifo_write || (iir_read & ~iir[`UART_II_IP] & iir[`UART_II_II] == `UART_II_THRE)? 0 :
thre_int_rise ? 1 :
thre_int_pnd && ier[`UART_IE_THRE];
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) ms_int_pnd <= 0;
else
ms_int_pnd <= msr_read ? 0 :
ms_int_rise ? 1 :
ms_int_pnd && ier[`UART_IE_MS];
always @(posedge clk or posedge wb_rst_i)
if (wb_rst_i) ti_int_pnd <= 0;
else
ti_int_pnd <= fifo_read ? 0 :
ti_int_rise ? 1 :
ti_int_pnd && ier[`UART_IE_RDA];
// end of pending flags
// INT_O logic
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
int_o <= 1'b0;
else
int_o <=
rls_int_pnd ? ~lsr_mask :
rda_int_pnd ? 1 :
ti_int_pnd ? ~fifo_read :
thre_int_pnd ? !(fifo_write & iir_read) :
ms_int_pnd ? ~msr_read :
0; // if no interrupt are pending
end
// Interrupt Identification register
always @(posedge clk or posedge wb_rst_i)
begin
if (wb_rst_i)
iir <= 1;
else
if (rls_int_pnd) // interrupt is pending
begin
iir[`UART_II_II] <= `UART_II_RLS; // set identification register to correct value
iir[`UART_II_IP] <= 1'b0; // and clear the IIR bit 0 (interrupt pending)
end else // the sequence of conditions determines priority of interrupt identification
if (rda_int)
begin
iir[`UART_II_II] <= `UART_II_RDA;
iir[`UART_II_IP] <= 1'b0;
end
else if (ti_int_pnd)
begin
iir[`UART_II_II] <= `UART_II_TI;
iir[`UART_II_IP] <= 1'b0;
end
else if (thre_int_pnd)
begin
iir[`UART_II_II] <= `UART_II_THRE;
iir[`UART_II_IP] <= 1'b0;
end
else if (ms_int_pnd)
begin
iir[`UART_II_II] <= `UART_II_MS;
iir[`UART_II_IP] <= 1'b0;
end else // no interrupt is pending
begin
iir[`UART_II_II] <= 0;
iir[`UART_II_IP] <= 1'b1;
end
end
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.