text
stringlengths 938
1.05M
|
---|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 07:00:53 AM
// Design Name:
// Module Name: Adder_Round
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Adder_Round
#(parameter SW=26) (
input wire clk,
input wire rst,
input wire load_i,//Reg load input
input wire [SW-1:0] Data_A_i,
input wire [SW-1:0] Data_B_i,
/////////////////////////////////////////////////////////////
output wire [SW-1:0] Data_Result_o,
output wire FSM_C_o
);
wire [SW:0] result_A_adder;
adder #(.W(SW)) A_operation (
.Data_A_i(Data_A_i),
.Data_B_i(Data_B_i),
.Data_S_o(result_A_adder)
);
RegisterAdd #(.W(SW)) Add_Subt_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW-1:0]),
.Q (Data_Result_o)
);
RegisterAdd #(.W(1)) Add_overflow_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW]),
.Q (FSM_C_o)
);
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 07:00:53 AM
// Design Name:
// Module Name: Adder_Round
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Adder_Round
#(parameter SW=26) (
input wire clk,
input wire rst,
input wire load_i,//Reg load input
input wire [SW-1:0] Data_A_i,
input wire [SW-1:0] Data_B_i,
/////////////////////////////////////////////////////////////
output wire [SW-1:0] Data_Result_o,
output wire FSM_C_o
);
wire [SW:0] result_A_adder;
adder #(.W(SW)) A_operation (
.Data_A_i(Data_A_i),
.Data_B_i(Data_B_i),
.Data_S_o(result_A_adder)
);
RegisterAdd #(.W(SW)) Add_Subt_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW-1:0]),
.Q (Data_Result_o)
);
RegisterAdd #(.W(1)) Add_overflow_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW]),
.Q (FSM_C_o)
);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc; initial cyc=0;
reg [63:0] crc;
wire [65:0] outData; // From fifo of fifo.v
wire [15:0] inData = crc[15:0];
wire [1:0] inWordPtr = crc[17:16];
wire wrEn = crc[20];
wire [1:0] wrPtr = crc[33:32];
wire [1:0] rdPtr = crc[34:33];
fifo fifo (
// Outputs
.outData (outData[65:0]),
// Inputs
.clk (clk),
.inWordPtr (inWordPtr[1:0]),
.inData (inData[15:0]),
.rdPtr (rdPtr),
.wrPtr (wrPtr),
.wrEn (wrEn));
always @ (posedge clk) begin
//$write("[%0t] cyc==%0d crc=%b q=%x\n",$time, cyc, crc, outData);
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
end
else if (cyc==90) begin
if (outData[63:0] != 64'hd9bcbc276f0984ea) $stop;
end
else if (cyc==91) begin
if (outData[63:0] != 64'hef77cd9b13a866f0) $stop;
end
else if (cyc==92) begin
if (outData[63:0] != 64'h2750cd9b13a866f0) $stop;
end
else if (cyc==93) begin
if (outData[63:0] != 64'h4ea0bc276f0984ea) $stop;
end
else if (cyc==94) begin
if (outData[63:0] != 64'h9d41bc276f0984ea) $stop;
end
else if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module fifo (/*AUTOARG*/
// Outputs
outData,
// Inputs
clk, inWordPtr, inData, wrPtr, rdPtr, wrEn
);
parameter fifoDepthLog2 = 1;
parameter fifoDepth = 1<<fifoDepthLog2;
`define PTRBITS (fifoDepthLog2+1)
`define PTRBITSM1 fifoDepthLog2
`define PTRBITSM2 (fifoDepthLog2-1)
input clk;
input [1:0] inWordPtr;
input [15:0] inData;
input [`PTRBITSM1:0] wrPtr;
input [`PTRBITSM1:0] rdPtr;
output [65:0] outData;
input wrEn;
reg [65:0] outData;
// verilator lint_off VARHIDDEN
// verilator lint_off LITENDIAN
reg [65:0] fifo[0:fifoDepth-1];
// verilator lint_on LITENDIAN
// verilator lint_on VARHIDDEN
//reg [65:0] temp;
always @(posedge clk) begin
//$write ("we=%x PT=%x ID=%x D=%x\n", wrEn, wrPtr[`PTRBITSM2:0], {1'b0,~inWordPtr,4'b0}, inData[15:0]);
if (wrEn) begin
fifo[ wrPtr[`PTRBITSM2:0] ][{1'b0,~inWordPtr,4'b0}+:16] <= inData[15:0];
// Equivelent to:
//temp = fifo[ wrPtr[`PTRBITSM2:0] ];
//temp [{1'b0,~inWordPtr,4'b0}+:16] = inData[15:0];
//fifo[ wrPtr[`PTRBITSM2:0] ] <= temp;
end
outData <= fifo[rdPtr[`PTRBITSM2:0]];
end
endmodule
|
// DESCRIPTION: Verilator: Simple test of unoptflat
//
// Demonstration of an UNOPTFLAT combinatorial loop using 3 bits and looping
// through 2 sub-modules.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [2:0] x;
initial begin
x = 3'b000;
end
test1 test1i ( .clk (clk),
.xvecin (x[1:0]),
.xvecout (x[2:1]));
test2 test2i ( .clk (clk),
.xvecin (x[2:1]),
.xvecout (x[1:0]));
always @(posedge clk or negedge clk) begin
`ifdef TEST_VERBOSE
$write("x = %x\n", x);
`endif
if (x[1] != 0) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule // t
module test1
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {xvecin[0], clk};
endmodule // test
module test2
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {clk, xvecin[1]};
endmodule // test
|
// DESCRIPTION: Verilator: Simple test of unoptflat
//
// Demonstration of an UNOPTFLAT combinatorial loop using 3 bits and looping
// through 2 sub-modules.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [2:0] x;
initial begin
x = 3'b000;
end
test1 test1i ( .clk (clk),
.xvecin (x[1:0]),
.xvecout (x[2:1]));
test2 test2i ( .clk (clk),
.xvecin (x[2:1]),
.xvecout (x[1:0]));
always @(posedge clk or negedge clk) begin
`ifdef TEST_VERBOSE
$write("x = %x\n", x);
`endif
if (x[1] != 0) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule // t
module test1
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {xvecin[0], clk};
endmodule // test
module test2
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {clk, xvecin[1]};
endmodule // test
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug511
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [7:0] au;
wire [7:0] as;
Test1 test1 (.au);
Test2 test2 (.as);
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] result=%x %x\n",$time, au, as);
`endif
if (au != 'h12) $stop;
if (as != 'h02) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module Test1 (output [7:0] au);
wire [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign au=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
module Test2 (output [7:0] as);
wire signed [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign as=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug511
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [7:0] au;
wire [7:0] as;
Test1 test1 (.au);
Test2 test2 (.as);
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] result=%x %x\n",$time, au, as);
`endif
if (au != 'h12) $stop;
if (as != 'h02) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module Test1 (output [7:0] au);
wire [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign au=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
module Test2 (output [7:0] as);
wire signed [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign as=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// input clk is 24Mhz
`include "min_max_tracker.v"
module lf_edge_detect(input clk, input [7:0] adc_d, input [7:0] lf_ed_threshold,
output [7:0] max, output [7:0] min,
output [7:0] high_threshold, output [7:0] highz_threshold,
output [7:0] lowz_threshold, output [7:0] low_threshold,
output edge_state, output edge_toggle);
min_max_tracker tracker(clk, adc_d, lf_ed_threshold, min, max);
// auto-tune
assign high_threshold = (max + min) / 2 + (max - min) / 4;
assign highz_threshold = (max + min) / 2 + (max - min) / 8;
assign lowz_threshold = (max + min) / 2 - (max - min) / 8;
assign low_threshold = (max + min) / 2 - (max - min) / 4;
// heuristic to see if it makes sense to try to detect an edge
wire enabled =
(high_threshold > highz_threshold)
& (highz_threshold > lowz_threshold)
& (lowz_threshold > low_threshold)
& ((high_threshold - highz_threshold) > 8)
& ((highz_threshold - lowz_threshold) > 16)
& ((lowz_threshold - low_threshold) > 8);
// Toggle the output with hysteresis
// Set to high if the ADC value is above the threshold
// Set to low if the ADC value is below the threshold
reg is_high = 0;
reg is_low = 0;
reg is_zero = 0;
reg trigger_enabled = 1;
reg output_edge = 0;
reg output_state;
always @(posedge clk)
begin
is_high <= (adc_d >= high_threshold);
is_low <= (adc_d <= low_threshold);
is_zero <= ((adc_d > lowz_threshold) & (adc_d < highz_threshold));
end
// all edges detection
always @(posedge clk)
if (enabled) begin
// To enable detecting two consecutive peaks at the same level
// (low or high) we check whether or not we went back near 0 in-between.
// This extra check is necessary to prevent from noise artifacts
// around the threshold values.
if (trigger_enabled & (is_high | is_low)) begin
output_edge <= ~output_edge;
trigger_enabled <= 0;
end else
trigger_enabled <= trigger_enabled | is_zero;
end
// edge states
always @(posedge clk)
if (enabled) begin
if (is_high)
output_state <= 1'd1;
else if (is_low)
output_state <= 1'd0;
end
assign edge_state = output_state;
assign edge_toggle = output_edge;
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// input clk is 24Mhz
`include "min_max_tracker.v"
module lf_edge_detect(input clk, input [7:0] adc_d, input [7:0] lf_ed_threshold,
output [7:0] max, output [7:0] min,
output [7:0] high_threshold, output [7:0] highz_threshold,
output [7:0] lowz_threshold, output [7:0] low_threshold,
output edge_state, output edge_toggle);
min_max_tracker tracker(clk, adc_d, lf_ed_threshold, min, max);
// auto-tune
assign high_threshold = (max + min) / 2 + (max - min) / 4;
assign highz_threshold = (max + min) / 2 + (max - min) / 8;
assign lowz_threshold = (max + min) / 2 - (max - min) / 8;
assign low_threshold = (max + min) / 2 - (max - min) / 4;
// heuristic to see if it makes sense to try to detect an edge
wire enabled =
(high_threshold > highz_threshold)
& (highz_threshold > lowz_threshold)
& (lowz_threshold > low_threshold)
& ((high_threshold - highz_threshold) > 8)
& ((highz_threshold - lowz_threshold) > 16)
& ((lowz_threshold - low_threshold) > 8);
// Toggle the output with hysteresis
// Set to high if the ADC value is above the threshold
// Set to low if the ADC value is below the threshold
reg is_high = 0;
reg is_low = 0;
reg is_zero = 0;
reg trigger_enabled = 1;
reg output_edge = 0;
reg output_state;
always @(posedge clk)
begin
is_high <= (adc_d >= high_threshold);
is_low <= (adc_d <= low_threshold);
is_zero <= ((adc_d > lowz_threshold) & (adc_d < highz_threshold));
end
// all edges detection
always @(posedge clk)
if (enabled) begin
// To enable detecting two consecutive peaks at the same level
// (low or high) we check whether or not we went back near 0 in-between.
// This extra check is necessary to prevent from noise artifacts
// around the threshold values.
if (trigger_enabled & (is_high | is_low)) begin
output_edge <= ~output_edge;
trigger_enabled <= 0;
end else
trigger_enabled <= trigger_enabled | is_zero;
end
// edge states
always @(posedge clk)
if (enabled) begin
if (is_high)
output_state <= 1'd1;
else if (is_low)
output_state <= 1'd0;
end
assign edge_state = output_state;
assign edge_toggle = output_edge;
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
//
// Test consists of the follow logic tree, which has many obvious
// places for dedupe:
/*
output
+
--------------/ \--------------
/ \
+ +
----/ \----- ----/ \----
/ + / +
+ / \ + / \
-/ \- a b -/ \- a b
/ \ / \
+ + + +
/ \ / \ / \ / \
a b c d a b c d
*/
module t(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left,right;
add add(sum,left,right,clk);
l l(left,a,b,c,d,clk);
r r(right,a,b,c,d,clk);
endmodule
module l(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
ll ll(left,a,b,c,d,clk);
lr lr(right,a,b,c,d,clk);
endmodule
module ll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
lll lll(left,a,b,c,d,clk);
llr llr(right,a,b,c,d,clk);
endmodule
module lll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module llr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,c,d,clk);
endmodule
module lr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module r(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rl rl(left,a,b,c,d,clk);
rr rr(right,a,b,c,d,clk);
endmodule
module rr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module rl(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rll rll(left,a,b,c,d,clk);
rlr rlr(right,a,b,c,d,clk);
endmodule
module rll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,a,b,clk);
endmodule
module rlr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,c,d,clk);
endmodule
module add(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
module add2(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
//
// Test consists of the follow logic tree, which has many obvious
// places for dedupe:
/*
output
+
--------------/ \--------------
/ \
+ +
----/ \----- ----/ \----
/ + / +
+ / \ + / \
-/ \- a b -/ \- a b
/ \ / \
+ + + +
/ \ / \ / \ / \
a b c d a b c d
*/
module t(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left,right;
add add(sum,left,right,clk);
l l(left,a,b,c,d,clk);
r r(right,a,b,c,d,clk);
endmodule
module l(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
ll ll(left,a,b,c,d,clk);
lr lr(right,a,b,c,d,clk);
endmodule
module ll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
lll lll(left,a,b,c,d,clk);
llr llr(right,a,b,c,d,clk);
endmodule
module lll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module llr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,c,d,clk);
endmodule
module lr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module r(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rl rl(left,a,b,c,d,clk);
rr rr(right,a,b,c,d,clk);
endmodule
module rr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module rl(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rll rll(left,a,b,c,d,clk);
rlr rlr(right,a,b,c,d,clk);
endmodule
module rll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,a,b,clk);
endmodule
module rlr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,c,d,clk);
endmodule
module add(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
module add2(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug598
module t (/*AUTOARG*/
// Outputs
val,
// Inputs
clk
);
input clk;
output integer val;
integer dbg_addr = 0;
function func1;
input en;
input [31:0] a;
func1 = en && (a == 1);
endfunction
function func2;
input en;
input [31:0] a;
func2 = en && (a == 2);
endfunction
always @(posedge clk) begin
case( 1'b1 )
// This line is OK:
func1(1'b1, dbg_addr) : val = 1;
// This fails:
// %Error: Internal Error: test.v:23: ../V3Task.cpp:993: Function not underneath a statement
// %Error: Internal Error: See the manual and http://www.veripool.org/verilator for more assistance.
func2(1'b1, dbg_addr) : val = 2;
default : val = 0;
endcase
//
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug598
module t (/*AUTOARG*/
// Outputs
val,
// Inputs
clk
);
input clk;
output integer val;
integer dbg_addr = 0;
function func1;
input en;
input [31:0] a;
func1 = en && (a == 1);
endfunction
function func2;
input en;
input [31:0] a;
func2 = en && (a == 2);
endfunction
always @(posedge clk) begin
case( 1'b1 )
// This line is OK:
func1(1'b1, dbg_addr) : val = 1;
// This fails:
// %Error: Internal Error: test.v:23: ../V3Task.cpp:993: Function not underneath a statement
// %Error: Internal Error: See the manual and http://www.veripool.org/verilator for more assistance.
func2(1'b1, dbg_addr) : val = 2;
default : val = 0;
endcase
//
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2005 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// verilator lint_off LITENDIAN
// verilator lint_off BLKANDNBLK
// 3 3 4
reg [71:0] memw [2:0][1:3][5:2];
reg [7:0] memn [2:0][1:3][5:2];
// verilator lint_on BLKANDNBLK
integer cyc; initial cyc=0;
reg [63:0] crc;
reg [71:0] wide;
reg [7:0] narrow;
reg [1:0] index0;
reg [1:0] index1;
reg [2:0] index2;
integer i0,i1,i2;
integer imem[2:0][1:3];
reg [2:0] cstyle[2];
// verilator lint_on LITENDIAN
initial begin
for (i0=0; i0<3; i0=i0+1) begin
for (i1=1; i1<4; i1=i1+1) begin
imem[i0[1:0]] [i1[1:0]] = i1;
for (i2=2; i2<6; i2=i2+1) begin
memw[i0[1:0]] [i1[1:0]] [i2[2:0]] = {56'hfe_fee0_fee0_fee0_,4'b0,i0[3:0],i1[3:0],i2[3:0]};
memn[i0[1:0]] [i1[1:0]] [i2[2:0]] = 8'b1000_0001;
end
end
end
end
reg [71:0] wread;
reg wreadb;
always @ (posedge clk) begin
//$write("cyc==%0d crc=%x i[%d][%d][%d] nar=%x wide=%x\n",cyc, crc, index0,index1,index2, narrow, wide);
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
narrow <= 8'h0;
wide <= 72'h0;
index0 <= 2'b0;
index1 <= 2'b0;
index2 <= 3'b0;
end
else if (cyc<90) begin
index0 <= crc[1:0];
index1 <= crc[3:2];
index2 <= crc[6:4];
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
// We never read past bounds, or get unspecific results
// We also never read lowest indexes, as writing outside of range may corrupt them
if (index0>=0+1 && index0<=2 && index1>=1+1 /*&& index1<=3 CMPCONST*/ && index2>=2+1 && index2<=5) begin
narrow <= ({narrow[6:0], narrow[7]^narrow[0]}
^ {memn[index0][index1][index2]});
wread = memw[index0][index1][index2];
wreadb = memw[index0][index1][index2][2];
wide <= ({wide[70:0], wide[71]^wide[2]^wide[0]} ^ wread);
//$write("Get memw[%d][%d][%d] -> %x\n",index0,index1,index2, wread);
end
// We may write past bounds of memory
memn[index0][index1][index2] [crc[10:8]+:3] <= crc[2:0];
memn[index0][index1][index2] <= {~crc[6:0],crc[7]};
memw[index0][index1][index2] <= {~crc[7:0],crc};
//$write("Set memw[%d][%d][%d] <= %x\n",index0,index1,index2, {~crc[7:0],crc});
cstyle[cyc[0]] <= cyc[2:0];
if (cyc>20) if (cstyle[~cyc[0]] != (cyc[2:0]-3'b1)) $stop;
end
else if (cyc==90) begin
memn[0][1][3] <= memn[0][1][3] ^ 8'ha8;
end
else if (cyc==91) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x nar=%x wide=%x\n",$time, cyc, crc, narrow, wide);
if (crc != 64'h65e3bddcd9bc2750) $stop;
if (narrow != 8'hca) $stop;
if (wide != 72'h4edafed31ba6873f73) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2005 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// verilator lint_off LITENDIAN
// verilator lint_off BLKANDNBLK
// 3 3 4
reg [71:0] memw [2:0][1:3][5:2];
reg [7:0] memn [2:0][1:3][5:2];
// verilator lint_on BLKANDNBLK
integer cyc; initial cyc=0;
reg [63:0] crc;
reg [71:0] wide;
reg [7:0] narrow;
reg [1:0] index0;
reg [1:0] index1;
reg [2:0] index2;
integer i0,i1,i2;
integer imem[2:0][1:3];
reg [2:0] cstyle[2];
// verilator lint_on LITENDIAN
initial begin
for (i0=0; i0<3; i0=i0+1) begin
for (i1=1; i1<4; i1=i1+1) begin
imem[i0[1:0]] [i1[1:0]] = i1;
for (i2=2; i2<6; i2=i2+1) begin
memw[i0[1:0]] [i1[1:0]] [i2[2:0]] = {56'hfe_fee0_fee0_fee0_,4'b0,i0[3:0],i1[3:0],i2[3:0]};
memn[i0[1:0]] [i1[1:0]] [i2[2:0]] = 8'b1000_0001;
end
end
end
end
reg [71:0] wread;
reg wreadb;
always @ (posedge clk) begin
//$write("cyc==%0d crc=%x i[%d][%d][%d] nar=%x wide=%x\n",cyc, crc, index0,index1,index2, narrow, wide);
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
narrow <= 8'h0;
wide <= 72'h0;
index0 <= 2'b0;
index1 <= 2'b0;
index2 <= 3'b0;
end
else if (cyc<90) begin
index0 <= crc[1:0];
index1 <= crc[3:2];
index2 <= crc[6:4];
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
// We never read past bounds, or get unspecific results
// We also never read lowest indexes, as writing outside of range may corrupt them
if (index0>=0+1 && index0<=2 && index1>=1+1 /*&& index1<=3 CMPCONST*/ && index2>=2+1 && index2<=5) begin
narrow <= ({narrow[6:0], narrow[7]^narrow[0]}
^ {memn[index0][index1][index2]});
wread = memw[index0][index1][index2];
wreadb = memw[index0][index1][index2][2];
wide <= ({wide[70:0], wide[71]^wide[2]^wide[0]} ^ wread);
//$write("Get memw[%d][%d][%d] -> %x\n",index0,index1,index2, wread);
end
// We may write past bounds of memory
memn[index0][index1][index2] [crc[10:8]+:3] <= crc[2:0];
memn[index0][index1][index2] <= {~crc[6:0],crc[7]};
memw[index0][index1][index2] <= {~crc[7:0],crc};
//$write("Set memw[%d][%d][%d] <= %x\n",index0,index1,index2, {~crc[7:0],crc});
cstyle[cyc[0]] <= cyc[2:0];
if (cyc>20) if (cstyle[~cyc[0]] != (cyc[2:0]-3'b1)) $stop;
end
else if (cyc==90) begin
memn[0][1][3] <= memn[0][1][3] ^ 8'ha8;
end
else if (cyc==91) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x nar=%x wide=%x\n",$time, cyc, crc, narrow, wide);
if (crc != 64'h65e3bddcd9bc2750) $stop;
if (narrow != 8'hca) $stop;
if (wide != 72'h4edafed31ba6873f73) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
wire [31:0] out; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.out (out[31:0]),
// Inputs
.clk (clk),
.in (in[31:0]));
// Aggregate outputs into a single result vector
wire [63:0] result = {32'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h458c2de282e30f8b
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test (/*AUTOARG*/
// Outputs
out,
// Inputs
clk, in
);
input clk;
input [31:0] in;
output wire [31:0] out;
reg [31:0] stage [3:0];
genvar g;
generate
for (g=0; g<4; g++) begin
always_comb begin
if (g==0) stage[g] = in;
else stage[g] = {stage[g-1][30:0],1'b1};
end
end
endgenerate
assign out = stage[3];
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
/****************************
* --------------------------
* Atomic Instruction Handler
* --------------------------
*
* Design Goal#1:
* --------------
* This module is instantiated at the end of global or local memory arbitration.
* It monitors every memory request issued to the memory, as well as readdata
* that is returned back. In case an incoming atomic request is detected, it
* activates necessary mechanisms so that memory state and readdata are consistent.
*
* Design Goal#2:
* --------------
* Because local memory interconnect and routers do not expect local
* memory to stall, this module does not stall incoming requests as long as
* (1) there is enough hardware to store all the state, (2) there is no incoming
* read/write/atomic request at the same cycle an earlier atomic request is writing
* to memory. The former requirement is handled by selecting approriate value
* for NUM_TXS parameter. The latter requirement is handled in the local memory
* interconnect, but not in global memory interconnect.
*
* Atomic Request Operands:
* ------------------------
* The operands for atomic operations are stored in writedata signal which is
* normally not used for read requests. This is the layout for writedata signal:
* Bit 0: high is this is atomic request.
* Bits 1-32: operand0 of atomic operation (valid atomic_add, atomic_min, etc.)
* Bits 33-64: operand1 of atomic operation (valid for atomic_cmpxchg)
* Bits 65-67: atomic operation types (e.g. add, min, cmpxchg, etc.)
* Bits 67-71: segment offset of the 32-bit atomic operation at the given address.
*
* Anatomy of an Atomic Request:
* -----------------------------
* We refer each memory request "a transaction" which
* go through the following states:
*
* ST_READ(R): a read from memory request is issued a response is expected.
* ST_ALU(A): readdata from memory is received and returned back to the arbitration
* in the previous cycle. In this cycle, the atomic operation (add, min, xor, etc.)
* is performed. At the end of this cycle, the result of atomic operation is stored
* in a register.
* ST_WRITEBACK(W): The result of atomic operation is written to memory.
*
* Hence, atomic requests can be represented with the following pipeline diagram
* (the number of ST_READ cycles depends on whether global or local memory is used).
*
* #1: atomic_inst: R1 R2 R3 R4 A W
*
* For ease of implementation, non-atomic read requests also go through the same
* pipeline stages. Non-atomic writes take one cycle, hence, do not go through
* pipeline stages.
*
* Conflicts:
* ----------
* We say two transactions are "conflicting", if they access the same
* address. Conflicts can potentially cause inconsistent memory state and
* incorrect readdata returns.
*
* Data Forwarding:
* ----------------
* "No-stall" atomics are realized via data forwarding between
* subsequent conflicting atomic transactions.
*
* ST_ALU-to-ST_ALU forwarding:
*
* #1: atomic_inc(A): R1 R2 R3 R4 A W
* #2: atomic_inc(A): R1 R2 R3 R4 A W
*
* We forward from ALU output of #1 to ALU input of #2.
*
* ST_ALU-to-ST_READ forwarding:
*
* #1: atomic_inc(A): R1 R2 R3 R4 A W
* #2: atomic_inc(A): R1 R2 R3 R4 A W
*
* We forward from ALU output of #1 to R3 of #2. Hence, each atomic transaction
* records data it receives via forwarding during its ST_READ stages.
*
* Selecting the readdata: Due to forwarding logic, an atomic transaction needs to
* choose which readdata to take as input to its ALU.
*
* There are 3 sources: (1) readdata received from memory,
* (2) ST_ALU-to-ST_READ forwarded data,
* (3) ST_ALU-to-ST_ALU forwarded data.
*
* This is in the order of most recent to least recent data in memory. Hence,
* priorities are 3-2-1.
*
* FMAX WARNING: This selection of inputs is the critical path for Fmax.
*
* Sequential Consistency:
* -----------------------
* For performance reasons, the atomic module does not provide sequential
* consistency for non-atomic read requests. That is, if a read request is received
* while there are conflicting atomic transactions, data forwarding will not be
* performed from atomic transactions to non-atomic read transactions, hence, the
* read request will return "old" data. It is trivial to perform data forwarding
* for non-atomic reads as long as they operate on 32-bit data. It is very complex
* to forward data when the non-atomic read request operates on wide data
* (burstcount > 1, or reads larger than 32-bit).
*
* Sequential consistency is provided for non-atomic writes. When an incoming
* non-atomic write conflicts with atomic transactions in flight, the atomic
* transactions take notice and dont write their results to memory in order not to
* overwrite the data of the non-atomic write.
*
* Optimizations:
* --------------
* (1) Selective ALU: instantiate ALU operations only for operations used in kernel,
* e.g. dont instantiate min operation if atomic_min is not used in kernel.
* (2) Free Transactions: dont keep state for non-atomic reads, if there are
* no atomics in flight.
*
*****************************/
module acl_atomics_nostall
(
clock, resetn,
// arbitration port
mem_arb_read,
mem_arb_write,
mem_arb_burstcount,
mem_arb_address,
mem_arb_writedata,
mem_arb_byteenable,
mem_arb_waitrequest,
mem_arb_readdata,
mem_arb_readdatavalid,
mem_arb_writeack,
// Avalon port
mem_avm_read,
mem_avm_write,
mem_avm_burstcount,
mem_avm_address,
mem_avm_writedata,
mem_avm_byteenable,
mem_avm_waitrequest,
mem_avm_readdata,
mem_avm_readdatavalid,
mem_avm_writeack
);
/*************
* Parameters *
*************/
// WARNING: this MUST match numAtomicOperations in ACLIntrinsics.h
parameter ATOMIC_OP_WIDTH=3; // this many atomic operations
// WARNING: this MUST match the alignment of atomic instructions (for now, it is
// always 4).
parameter SEGMENT_WIDTH_BYTES=4;
parameter USED_ATOMIC_OPERATIONS=8'b11111111; // atomics operations used in kernel
parameter ADDR_WIDTH=27; // width of addresses to memory
parameter DATA_WIDTH=96; // size of data chunks from/to memory
parameter BURST_WIDTH=6; // size of burst
parameter BYTEEN_WIDTH=32; // this many bytes in each data chunk
parameter OPERATION_WIDTH=32; // atomic operations are ALL 32-bit
parameter NUM_TXS=4; // support this many txs in flight
parameter COUNTER_WIDTH=32; // keep track of this many request between a memory request and its response
parameter LOCAL_MEM=0;
/******************
* Local Variables *
******************/
localparam OPERATION_WIDTH_BITS=$clog2(OPERATION_WIDTH);
localparam DATA_WIDTH_BITS=$clog2(DATA_WIDTH);
localparam DATA_WIDTH_BYTES=(DATA_WIDTH >> 3);
localparam DATA_WIDTH_BYTES_BITS=$clog2(DATA_WIDTH_BYTES);
localparam SEGMENT_WIDTH_BITS=$clog2(SEGMENT_WIDTH_BYTES);
// tx states
localparam tx_ST_IDLE=0;
localparam tx_ST_READ=1;
localparam tx_ST_ALU=2;
localparam tx_ST_WRITEBACK=3;
localparam NUM_STATES = 4; // must be power-of-2
// memory request types
localparam op_NONE=0;
localparam op_READ=1;
localparam op_WRITE=2;
localparam op_ATOMIC=3;
localparam NUM_OPS = 4; // must be power-of-2
localparam NO_TX=NUM_TXS;
localparam NUM_TXS_BITS = $clog2(NUM_TXS);
localparam NUM_STATES_BITS = $clog2(NUM_STATES);
localparam NUM_OPS_BITS = $clog2(NUM_OPS);
/********
* Ports *
********/
// Standard global signals
input logic clock;
input logic resetn;
// Arbitration port
input logic mem_arb_read;
input logic mem_arb_write;
input logic [BURST_WIDTH-1:0] mem_arb_burstcount;
input logic [ADDR_WIDTH-1:0] mem_arb_address;
input logic [DATA_WIDTH-1:0] mem_arb_writedata;
input logic [BYTEEN_WIDTH-1:0] mem_arb_byteenable;
output logic mem_arb_waitrequest;
output logic [DATA_WIDTH-1:0] mem_arb_readdata;
output logic mem_arb_readdatavalid;
output logic mem_arb_writeack;
// Avalon port
output mem_avm_read;
output mem_avm_write;
output [BURST_WIDTH-1:0] mem_avm_burstcount;
output [ADDR_WIDTH-1:0] mem_avm_address;
output [DATA_WIDTH-1:0] mem_avm_writedata;
output [BYTEEN_WIDTH-1:0] mem_avm_byteenable;
input mem_avm_waitrequest;
input [DATA_WIDTH-1:0] mem_avm_readdata;
input mem_avm_readdatavalid;
input mem_avm_writeack;
/***********************
* Transaction Metadata *
***********************/
reg [NUM_OPS_BITS-1:0] tx_op [0:NUM_TXS]; // read, write, atomic
reg [NUM_STATES_BITS-1:0] tx_state [0:NUM_TXS]; // read, alu, writeback
reg [ATOMIC_OP_WIDTH-1:0] tx_atomic_op [0:NUM_TXS]; // add, min, max, xor, and, etc.
reg [ADDR_WIDTH-1:0] tx_address [0:NUM_TXS];
reg [BYTEEN_WIDTH-1:0] tx_byteenable [0:NUM_TXS];
reg [BURST_WIDTH-1:0] tx_burstcount [0:NUM_TXS];
reg [DATA_WIDTH_BITS-1:0] tx_segment_address [0:NUM_TXS];
reg [OPERATION_WIDTH-1:0] tx_operand0 [0:NUM_TXS]; // operand0 of atomic operation
reg [OPERATION_WIDTH-1:0] tx_operand1 [0:NUM_TXS]; // operand1 of atomic operation
reg [OPERATION_WIDTH-1:0] tx_atomic_forwarded_readdata [0:NUM_TXS]; // forwarded data from earlier txs
reg tx_atomic_forwarded [0:NUM_TXS]; // data is forwarded from another atomic tx
reg [BYTEEN_WIDTH-1:0] tx_bytedisable [0:NUM_TXS]; // dont write to this address
reg [NUM_TXS-1:0] tx_conflict_list[0:NUM_TXS]; // active txs that this tx is conflicting with
reg [BURST_WIDTH-1:0] tx_num_outstanding_responses [0:NUM_TXS]; // responses this tx will receive, it is initialized to burstcount, tx remains in READ state until it is zero
reg [OPERATION_WIDTH-1:0] tx_writedata [0:NUM_TXS]; // what will be commited to memory
// these registers are used by a single tx at a time, so they are pipelined, and
// not replicated.
reg [OPERATION_WIDTH-1:0] tx_readdata; // what was read from memory, or forwarded, input for alu
wire [OPERATION_WIDTH-1:0] tx_alu_out; // the result of the atomic operation
reg [COUNTER_WIDTH-1:0] count_requests; // number of read requests that are sent to memory
reg [COUNTER_WIDTH-1:0] count_responses; // number of responses received from memory
/******************
* Various Signals *
******************/
reg [NUM_TXS_BITS:0] num_active_atomic_txs; // number of atomic txs in flight
reg [NUM_TXS_BITS:0] free_slot; // unoccupied slot next tx will be inserted in
wire slots_full; // high if all slots are full
// conflict detection
logic atomic_active[0:NUM_TXS];
logic conflicting_ops[0:NUM_TXS];
logic address_conflict[0:NUM_TXS];
logic byteen_conflict[0:NUM_TXS];
logic conflict[0:NUM_TXS];
logic [NUM_TXS:0] conflicts;
wire [NUM_TXS:0] conflicting_txs;
// decode the new transaction
wire [NUM_OPS_BITS-1:0] new_op_type;
wire [OPERATION_WIDTH-1:0] new_operand0;
wire [OPERATION_WIDTH-1:0] new_operand1;
wire [DATA_WIDTH_BITS-1:0] new_segment_address;
wire [ATOMIC_OP_WIDTH-1:0] new_atomic_op;
// find transactions in various stages
wire is_readdata_received;
logic [NUM_TXS_BITS:0] tx_readdata_received;
wire [DATA_WIDTH_BITS-1:0] segment_address_in_read_received;
wire atomic_forwarded_in_read_received;
wire [OPERATION_WIDTH-1:0] atomic_forwarded_readdata_in_read_received;
// oldest tx in READ state
reg [NUM_TXS_BITS:0] tx_next_readdata_received;
reg [NUM_TXS_BITS:0] tx_in_alu;
reg [NUM_OPS_BITS-1:0] op_in_alu;
reg [ATOMIC_OP_WIDTH-1:0] atomic_op_in_alu;
reg [OPERATION_WIDTH-1:0] operand0_in_alu;
reg [OPERATION_WIDTH-1:0] operand1_in_alu;
reg [DATA_WIDTH_BITS-1:0] segment_address_in_alu;
reg [DATA_WIDTH-1:0] tx_alu_out_last; // what was alu out last cycle?
reg [NUM_TXS_BITS:0] tx_in_alu_last; // which tx was in alu last cycle?
reg [NUM_TXS_BITS:0] num_txs_in_writeback; // number of txs waiting to commit to memory
reg [NUM_TXS_BITS:0] tx_in_writeback;
reg [NUM_OPS_BITS-1:0] op_in_writeback;
reg [DATA_WIDTH-1:0] writedata_in_writeback;
reg [ADDR_WIDTH-1:0] address_in_writeback;
reg [BYTEEN_WIDTH-1:0] byteenable_in_writeback;
reg [BURST_WIDTH-1:0] burstcount_in_writeback;
// keep track of oldest/youngest transaction
wire oldest_tx_is_committing;
wire youngest_tx_is_committing;
reg [NUM_TXS_BITS:0] oldest_tx;
reg [NUM_TXS_BITS:0] youngest_tx;
// control signals
wire can_send_read;
wire can_send_non_atomic_write;
wire can_send_atomic_write;
wire can_return_readdata;
wire [DATA_WIDTH-1:0] rrp_readdata;
wire send_read;
wire send_non_atomic_write;
wire send_atomic_write;
wire tx_commits;
wire new_read_request;
wire atomic_tx_starts;
wire atomic_tx_commits;
// support for "free" txs
// (i.e. txs that are not inserted in slots because they are no atomics in flight)
wire free_tx; // no atomic read tx and no atomics in slots.
wire free_tx_starts; // no atomic read tx and no atomics in slots.
wire free_readdata_expected; // next readdata response belongs to a free tx
wire free_readdata_received; // received readdata response belongs to a free tx
reg [COUNTER_WIDTH-1:0] free_requests;
reg [COUNTER_WIDTH-1:0] free_responses;
integer t;
/***************
* Local Memory *
***************/
wire [BURST_WIDTH-1:0] input_burstcount;
// connect unconnected signals in local memory
generate
if( LOCAL_MEM == 0 ) assign input_burstcount = mem_arb_burstcount;
else assign input_burstcount = 1;
endgenerate
/*********************************
* Arbitration/Avalon connections *
*********************************/
assign mem_avm_read = ( send_read || free_tx );
assign mem_avm_write = ( send_non_atomic_write || send_atomic_write );
assign mem_avm_burstcount = ( send_read || free_tx || send_non_atomic_write ) ? input_burstcount : burstcount_in_writeback;
assign mem_avm_address = ( send_read || free_tx || send_non_atomic_write ) ? mem_arb_address : address_in_writeback;
assign mem_avm_writedata = send_non_atomic_write ? mem_arb_writedata : writedata_in_writeback;
assign mem_avm_byteenable = ( send_read || free_tx || send_non_atomic_write ) ? mem_arb_byteenable : byteenable_in_writeback;
assign mem_arb_waitrequest = ( mem_avm_waitrequest || ( mem_arb_read && !can_send_read && !free_tx ) );
assign mem_arb_readdatavalid = ( can_return_readdata | free_readdata_received );
assign mem_arb_writeack = mem_avm_writeack;
assign mem_arb_readdata = free_readdata_received ? mem_avm_readdata : rrp_readdata;
/******************
* Control Signals *
******************/
// a read request (atomic or non-atomic) is stalled if all slots are full or
// there is an atomic tx writing to memory.
// free txs are never stalled.
assign can_send_read = ~free_tx && // no need to occupy slot
~slots_full &&
~send_atomic_write;
// non atomic write has priority, it is never stalled
assign can_send_non_atomic_write = 1'b1;
// atomic writes are stalled only if there is a free tx request
assign can_send_atomic_write = ~( free_tx || ( mem_arb_write && can_send_non_atomic_write) );
// what goes through the atomic module (for arbitration/avalon connections)
assign send_read = mem_arb_read && can_send_read;
assign send_non_atomic_write = mem_arb_write && can_send_non_atomic_write;
assign send_atomic_write = can_send_atomic_write && tx_in_writeback != NO_TX && op_in_writeback == op_ATOMIC;
// what actually happens (take into account waitrequest)
assign tx_can_commit = ( ~mem_avm_waitrequest && can_send_atomic_write );
assign tx_commits = ( ~mem_avm_waitrequest && can_send_atomic_write && tx_in_writeback != NO_TX );
assign new_read_request = ( ~mem_avm_waitrequest && can_send_read && mem_arb_read );
assign atomic_tx_starts = ( ~mem_avm_waitrequest && can_send_read && new_op_type == op_ATOMIC );
assign atomic_tx_commits = ( ~mem_avm_waitrequest && can_send_atomic_write && tx_in_writeback != NO_TX && op_in_writeback == op_ATOMIC );
/*************************
* Decode the new request *
**************************/
assign new_op_type = ( mem_arb_read & mem_arb_writedata[0:0] ) ? op_ATOMIC : mem_arb_read ? op_READ : mem_arb_write ? op_WRITE : op_NONE;
assign new_operand0 = mem_arb_writedata[1 +: OPERATION_WIDTH]; // mem_arb_writedata[32:1]
assign new_operand1 = mem_arb_writedata[OPERATION_WIDTH+1 +: OPERATION_WIDTH]; //mem_arb_writedata[64:33]
assign new_atomic_op = mem_arb_writedata[2*OPERATION_WIDTH+1 +: ATOMIC_OP_WIDTH]; // mem_arb_writedata[70:65]
assign new_segment_address = ( mem_arb_writedata[2*OPERATION_WIDTH+ATOMIC_OP_WIDTH+1 +: DATA_WIDTH_BYTES_BITS ] << (OPERATION_WIDTH_BITS - SEGMENT_WIDTH_BITS) ); // mem_arb_writedata[75:71]
/********************
* Free Transactions *
********************/
assign free_tx = ( new_op_type == op_READ && num_active_atomic_txs == 0 );
assign free_tx_starts = ( free_tx && ~mem_avm_waitrequest );
// the next readdata will belong to a free tx if the number of free requests dont
// match the number of responses received for free txs
assign free_readdata_expected = ( free_requests != free_responses );
assign free_readdata_received = ( ( mem_avm_readdatavalid == 1'b1 ) && ( free_requests != free_responses ) );
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
free_requests <= { COUNTER_WIDTH{1'b0} };
free_responses <= { COUNTER_WIDTH{1'b0} };
end
else begin
if( free_tx_starts ) begin
free_requests <= free_requests + input_burstcount;
end
if( free_readdata_received ) begin
free_responses <= free_responses + 1;
end
end
end
/*****************
* Find Free Slot *
*****************/
assign slots_full = (free_slot == NO_TX);
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
free_slot <= 0;
end
else begin
// initial condition, no tx in flight and there is no new request
if( youngest_tx == NO_TX && !new_read_request ) begin
free_slot <= 0;
end
// no tx in flight, and there is a new request
else if( youngest_tx == NO_TX && new_read_request ) begin
free_slot <= 1;
end
// there are txs in flight, and there is a new request
else if( new_read_request ) begin
free_slot <= ( tx_state[(free_slot+1)%NUM_TXS] == tx_ST_IDLE ) ? ( (free_slot+1)%NUM_TXS ) :
( oldest_tx_is_committing ) ? oldest_tx : NO_TX;
end
// there is no new request and youngest tx (and only tx) is committing
else if( youngest_tx_is_committing ) begin
free_slot <= 0;
end
// there is no new request, all slots are full but oldest tx is committing
else if( oldest_tx_is_committing && free_slot == NO_TX ) begin
free_slot <= oldest_tx;
end
end
end
/***************************
* Find Active Transactions *
****************************/
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
num_active_atomic_txs <= {NUM_TXS_BITS{1'b0}};
end
else begin
// new atomic transaction starting
if( atomic_tx_starts && !atomic_tx_commits ) begin
num_active_atomic_txs <= num_active_atomic_txs + 1;
end
// atomic transaction is committing
if( !atomic_tx_starts && atomic_tx_commits ) begin
num_active_atomic_txs <= num_active_atomic_txs - 1;
end
end
end
/*********************
* Conflict Detection *
*********************/
always @(*)
begin
conflicts = {NUM_TXS{1'b0}};
for (t=0; t<=NUM_TXS; t=t+1)
begin
// tx is active and not committing in this cycle
atomic_active[t] = ( ( tx_state[t] != tx_ST_IDLE ) && !( tx_can_commit && t == tx_in_writeback ) );
// keep track of conflicts only with atomics, non-atomic conflicts do not
// matter because we dont support sequential consistency
conflicting_ops[t] = ( ( new_op_type == op_ATOMIC || new_op_type == op_WRITE ) && ( tx_op[t] == op_ATOMIC ) );
address_conflict[t] = ( tx_address[t] == mem_arb_address );
byteen_conflict[t] = ( ( ( tx_byteenable[t] & ~tx_bytedisable[t] ) & mem_arb_byteenable ) != {BYTEEN_WIDTH{1'b0}} );
conflict[t] = atomic_active[t] & conflicting_ops[t] & address_conflict[t] & byteen_conflict[t];
if( conflict[t] ) begin
conflicts = conflicts | ( 1 << t );
end
end
end
assign conflicting_txs = conflicts;
/******************************
* Youngest/Oldest transaction *
******************************/
assign youngest_tx_is_committing = ( tx_can_commit && tx_in_writeback == youngest_tx );
assign oldest_tx_is_committing = ( tx_can_commit && tx_in_writeback == oldest_tx );
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
youngest_tx <= NO_TX;
end
else begin
// new transaction in free_slot
if( new_read_request ) begin
youngest_tx <= free_slot;
end
else if( youngest_tx_is_committing ) begin
youngest_tx <= NO_TX;
end
end
end
// find the first active transaction that comes after oldest_tx
wire [NUM_TXS_BITS:0] next_oldest_tx;
wire [NUM_TXS_BITS:0] next_oldest_tx_index;
assign next_oldest_tx_index = ( (oldest_tx+1) % NUM_TXS );
assign next_oldest_tx = ( tx_state[ next_oldest_tx_index ] != tx_ST_IDLE ) ? next_oldest_tx_index : NO_TX;
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
oldest_tx <= NO_TX;
end
else begin
// oldest tx is committing, there is no other tx, and there is a new request inserted in free_slot
if( oldest_tx_is_committing && next_oldest_tx == NO_TX && new_read_request ) begin
oldest_tx <= free_slot;
end
// oldest tx is committing, but there are other txs or there is no new request
else if ( oldest_tx_is_committing ) begin
oldest_tx <= next_oldest_tx;
end
// there are no txs in flight, and new request inserted in free_slot
else if ( new_read_request && ( oldest_tx == NO_TX ) ) begin
oldest_tx <= free_slot;
end
end
end
/********************
* State Transitions *
********************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_state[t] <= tx_ST_IDLE;
tx_op[t] <= op_NONE;
tx_atomic_op[t] <= {ATOMIC_OP_WIDTH{1'b0}};
tx_address[t] <= {ADDR_WIDTH{1'b0}};
tx_byteenable[t] <= {BYTEEN_WIDTH{1'b0}};
tx_segment_address[t] <= {DATA_WIDTH_BITS{1'b0}};
tx_operand0[t] <= {OPERATION_WIDTH{1'b0}};
tx_operand1[t] <= {OPERATION_WIDTH{1'b0}};
tx_conflict_list[t] <= {NUM_TXS{1'b0}};
end
else begin
case (tx_state[t])
tx_ST_IDLE:
begin
// new request inserted in free_slot
if ( new_read_request && ( t == free_slot ) ) begin
tx_state[t] <= tx_ST_READ;
tx_op[t] <= new_op_type;
tx_atomic_op[t] <= new_atomic_op;
tx_address[t] <= mem_arb_address;
tx_byteenable[t] <= mem_arb_byteenable;
tx_burstcount[t] <= input_burstcount;
tx_segment_address[t] <= new_segment_address;
tx_operand0[t] <= new_operand0;
tx_operand1[t] <= new_operand1;
tx_conflict_list[t] <= conflicting_txs;
end
end
tx_ST_READ:
begin
// readdata received from memory, sending readdatavalid to arb
// all the conflicts must already be resolved, also guaranteed
// to return data in order
// dont switch state unless ALL responses have arrived if burstcount >1
if( tx_readdata_received == t && (tx_num_outstanding_responses[t] == 1) ) begin
tx_state[t] <= tx_ST_ALU;
end
end
// ALU takes a single cycle
tx_ST_ALU:
begin
tx_state[t] <= tx_ST_WRITEBACK;
end
// write atomic result to memory if not stalled
tx_ST_WRITEBACK:
begin
tx_state[t] <= ( tx_can_commit && tx_in_writeback == t ) ? tx_ST_IDLE : tx_ST_WRITEBACK;
end
endcase
end
end
end
/**************************************
* Find Transaction that Receives Data *
**************************************/
// find the first active transaction that comes after tx_next_readdata_received
wire [NUM_TXS_BITS:0] next_tx_next_readdata_received;
wire [NUM_TXS_BITS:0] next_tx_next_readdata_received_index;
// the next-next tx that will receive readdata comes after the current tx expecting readddata
assign next_tx_next_readdata_received_index = ( (tx_next_readdata_received+1) % NUM_TXS );
// the next tx has already issued a read request, or it is issueing it in this cycle
assign next_tx_next_readdata_received = ( tx_state[ next_tx_next_readdata_received_index ] == tx_ST_READ ||
( new_read_request && free_slot == next_tx_next_readdata_received_index ) ) ? next_tx_next_readdata_received_index : NO_TX;
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
tx_next_readdata_received <= NO_TX;
end
else begin
// currently no tx is expecting readdata and there is a new tx at free_slot
if( tx_next_readdata_received == NO_TX && new_read_request ) begin
tx_next_readdata_received <= free_slot;
end
// the tx that expects readdata received it in this cycle,
// so it is not expecting readdata anymore, move to the next
else if ( tx_next_readdata_received != NO_TX &&
mem_avm_readdatavalid &&
~free_readdata_expected &&
// all readdata responses have been received in case burstcount > 1
( tx_num_outstanding_responses[tx_next_readdata_received] == 1 ) ) begin
tx_next_readdata_received <= next_tx_next_readdata_received;
end
end
end
// certain parameters that belong to tx that receives the readdata in this cycle
// if no readdata is received (i.e. tx_readdata_received == NO_TX ),
// these values would be wrong, but neither alu input nor return readdata does not matter anyways
assign segment_address_in_read_received = tx_segment_address[tx_next_readdata_received];
assign atomic_forwarded_in_read_received = tx_atomic_forwarded[tx_next_readdata_received];
assign atomic_forwarded_readdata_in_read_received = tx_atomic_forwarded_readdata[tx_next_readdata_received];
assign is_readdata_received = ( mem_avm_readdatavalid && ~free_readdata_expected );
assign tx_readdata_received = is_readdata_received ? tx_next_readdata_received : NO_TX;
/**************************
* Find Transaction in ALU *
**************************/
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_in_alu <= NO_TX;
op_in_alu <= op_NONE;
atomic_op_in_alu <= op_NONE;
operand0_in_alu <= {OPERATION_WIDTH{1'b0}};
operand1_in_alu <= {OPERATION_WIDTH{1'b0}};
segment_address_in_alu <= {DATA_WIDTH_BITS{1'b0}};
end
// do not transition to alu state if tx that received readdata has burstcount > 1
// and still serving outstanding requests
else if(tx_num_outstanding_responses[tx_readdata_received] != 1) begin
tx_in_alu <= NO_TX;
end
else begin
tx_in_alu <= tx_readdata_received;
op_in_alu <= tx_op[tx_next_readdata_received];
atomic_op_in_alu <= tx_atomic_op[tx_next_readdata_received];
operand0_in_alu <= tx_operand0[tx_next_readdata_received];
operand1_in_alu <= tx_operand1[tx_next_readdata_received];
segment_address_in_alu <= tx_segment_address[tx_next_readdata_received];
end
end
// find tx that was in alu in the last cycle
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
tx_alu_out_last <= { DATA_WIDTH{1'bx} };
tx_in_alu_last <= NO_TX;
end
else begin
tx_alu_out_last <= tx_alu_out;
tx_in_alu_last <= tx_in_alu;
end
end
/***************************************
* Find Transactions in Writeback State *
***************************************/
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
num_txs_in_writeback <= {NUM_TXS_BITS{1'b0}};
end
else
begin
if( tx_commits && tx_in_alu == NO_TX ) begin
num_txs_in_writeback <= num_txs_in_writeback - 1;
end
else if( !tx_commits && tx_in_alu != NO_TX ) begin
num_txs_in_writeback <= num_txs_in_writeback + 1;
end
end
end
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_in_writeback <= NO_TX;
op_in_writeback <= op_NONE;
writedata_in_writeback <= {DATA_WIDTH{1'b0}};
address_in_writeback <= {ADDR_WIDTH{1'b0}};
byteenable_in_writeback <= {BYTEEN_WIDTH{1'b0}};
burstcount_in_writeback <= {BURST_WIDTH{1'b0}};
end
else
// oldest tx (i.e. tx_in_writeback) is committing
// and next_oldest is also in atomic_writeback
if( tx_can_commit && num_txs_in_writeback > 1 )
//if(oldest_tx_is_committing && tx_state[next_oldest_tx_index] == tx_ST_WRITEBACK )
begin
tx_in_writeback <= next_oldest_tx;
op_in_writeback <= tx_op[next_oldest_tx_index];
writedata_in_writeback <= ( tx_writedata[next_oldest_tx_index] << tx_segment_address[next_oldest_tx_index] );
address_in_writeback <= tx_address[next_oldest_tx_index];
byteenable_in_writeback <= ( tx_byteenable[next_oldest_tx_index] & ~tx_bytedisable[next_oldest_tx_index] );
burstcount_in_writeback <= tx_burstcount[next_oldest_tx_index];
end
else
// oldest tx (i.e. tx_in_writeback) is committing
// or there is no tx in atomic writeback stage
if( tx_can_commit || ( num_txs_in_writeback == 0 ) )
begin
tx_in_writeback <= tx_in_alu;
op_in_writeback <= tx_op[tx_in_alu];
writedata_in_writeback <= ( tx_alu_out << segment_address_in_alu );
address_in_writeback <= tx_address[tx_in_alu];
byteenable_in_writeback <= ( tx_byteenable[tx_in_alu] & ~tx_bytedisable[tx_in_alu] );
burstcount_in_writeback <= tx_burstcount[tx_in_alu];
end
end
/********************************
* Count read requests/responses *
********************************/
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
count_requests <= { COUNTER_WIDTH{1'b0} };
count_responses <= { COUNTER_WIDTH{1'b0} };
end
else begin
// new read request
if( mem_avm_read & ~mem_avm_waitrequest ) begin
count_requests <= count_requests + input_burstcount;
end
// new read response
if( mem_avm_readdatavalid ) begin
count_responses <= count_responses + 1;
end
end
end
/****************************************
* Compute outstanding requests for a tx *
****************************************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_num_outstanding_responses[t] <= {BURST_WIDTH{1'b0}};
end
else if( new_read_request && t == free_slot ) begin
tx_num_outstanding_responses[t] <= input_burstcount;
end
else if( t == tx_readdata_received ) begin //&& tx_state[t] == tx_ST_READ ) begin
tx_num_outstanding_responses[t] <= tx_num_outstanding_responses[t] - 1;
end
end
end
/**********************************
* Non-atomic Write to Bytedisable *
**********************************/
// WARNING: Arbitration should make sure that a non-atomic write and atomic writeback
// do not happen in the same cycle. Thus, atomic does not miss the bytedisable
// signal when it writebacks
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_bytedisable[t] <= {BYTEEN_WIDTH{1'b0}};
end
else if ( tx_state[t] == tx_ST_IDLE ) begin
tx_bytedisable[t] <= {BYTEEN_WIDTH{1'b0}};
end
else
// conflicting write with this tx
if( mem_arb_write && ( conflicts & (1 << t) ) ) begin
tx_bytedisable[t] <= ( tx_bytedisable[t] | mem_arb_byteenable );
end
end
end
/****************************
* Find conflict with ALU tx *
****************************/
// detect the dependence early, so next cycle we know the conflict
reg readdata_received_conflicts_with_alu;
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
readdata_received_conflicts_with_alu <= 1'b0;
end
// readdata is received by a tx and this tx conflicts with tx that comes after it
// i.e. when this tx reaches ALU in the next cycle, it will conflict with the
// tx that receives readdata
else if ( ( is_readdata_received ) &&
( ( tx_conflict_list[next_tx_next_readdata_received_index] & (1 << tx_next_readdata_received) ) != 0 ) ) begin
readdata_received_conflicts_with_alu <= 1'b1;
end
else begin
readdata_received_conflicts_with_alu <= 1'b0;
end
end
/**************************
* Compute Return Readdata *
**************************/
logic [DATA_WIDTH-1:0] merge_readdata;
integer p;
always@(*)
begin
merge_readdata = mem_avm_readdata;
// merge with alu out
if( readdata_received_conflicts_with_alu ) begin
merge_readdata[segment_address_in_read_received +: OPERATION_WIDTH] = tx_alu_out;
end
// merge with forwarded data
else if( atomic_forwarded_in_read_received == 1'b1 ) begin
merge_readdata[segment_address_in_read_received +: OPERATION_WIDTH] = atomic_forwarded_readdata_in_read_received;
end
end
// readdata path is guaranteed to be in program order because
// a single tx will send read signal in each cycle
assign can_return_readdata = is_readdata_received;
assign rrp_readdata = merge_readdata;
/*******************
* Select ALU Input *
*******************/
wire [OPERATION_WIDTH-1:0] selected_readdata;
assign selected_readdata = readdata_received_conflicts_with_alu ? tx_alu_out :
( atomic_forwarded_in_read_received == 1'b1 ) ? atomic_forwarded_readdata_in_read_received :
mem_avm_readdata[segment_address_in_read_received +: OPERATION_WIDTH];
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_readdata <= {OPERATION_WIDTH{1'b0}};
end
else begin
tx_readdata <= selected_readdata;
end
end
/*********************
* Compute Atomic Out *
*********************/
atomic_alu # (.USED_ATOMIC_OPERATIONS(USED_ATOMIC_OPERATIONS), .ATOMIC_OP_WIDTH(ATOMIC_OP_WIDTH), .OPERATION_WIDTH(OPERATION_WIDTH)) tx_alu
(
.readdata( tx_readdata ),
.atomic_op( atomic_op_in_alu ),
.operand0( operand0_in_alu ),
.operand1( operand1_in_alu ),
.atomic_out( tx_alu_out )
);
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_writedata[t] <= {DATA_WIDTH{1'b0}};
end
else if( tx_state[t] == tx_ST_ALU ) begin
tx_writedata[t] <= tx_alu_out;
end
end
end
/******************
* Data Forwarding *
******************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_atomic_forwarded_readdata[t] <= {OPERATION_WIDTH{1'b0}};
tx_atomic_forwarded[t] <= 1'b0;
end
// this tx is a new tx
else if( mem_arb_read == 1'b1 && t == free_slot ) begin
tx_atomic_forwarded_readdata[t] <= {OPERATION_WIDTH{1'b0}};
tx_atomic_forwarded[t] <= 1'b0;
end
// this tx has a conflict with the tx in ALU
else if( (tx_conflict_list[t] & (1 << tx_in_alu)) != 0 ) begin
tx_atomic_forwarded_readdata[t] <= tx_alu_out;
tx_atomic_forwarded[t] <= 1'b1;
end
// this tx had a conflict with the tx in ALU last cycle (matters when this is a new tx)
else if( ( tx_conflict_list[t] & (1 << tx_in_alu_last) ) != 0 ) begin
tx_atomic_forwarded_readdata[t] <= tx_alu_out_last;
tx_atomic_forwarded[t] <= 1'b1;
end
end
end
endmodule
/****************************
* ALU for atomic operations *
****************************/
module atomic_alu
(
readdata,
atomic_op,
operand0,
operand1,
atomic_out
);
parameter ATOMIC_OP_WIDTH=3; // this many atomic operations
parameter OPERATION_WIDTH=32; // atomic operations are ALL 32-bit
parameter USED_ATOMIC_OPERATIONS=8'b00000001;
// WARNING: these MUST match ACLIntrinsics::ID enum in ACLIntrinsics.h
localparam a_ADD=0;
localparam a_XCHG=1;
localparam a_CMPXCHG=2;
localparam a_MIN=3;
localparam a_MAX=4;
localparam a_AND=5;
localparam a_OR=6;
localparam a_XOR=7;
// Standard global signals
input logic [OPERATION_WIDTH-1:0] readdata;
input logic [ATOMIC_OP_WIDTH-1:0] atomic_op;
input logic [OPERATION_WIDTH-1:0] operand0;
input logic [OPERATION_WIDTH-1:0] operand1;
output logic [OPERATION_WIDTH-1:0] atomic_out;
wire [31:0] atomic_out_add /* synthesis keep */;
wire [31:0] atomic_out_cmp /* synthesis keep */;
wire [31:0] atomic_out_cmpxchg /* synthesis keep */;
wire [31:0] atomic_out_min /* synthesis keep */;
wire [31:0] atomic_out_max /* synthesis keep */;
wire [31:0] atomic_out_and /* synthesis keep */;
wire [31:0] atomic_out_or /* synthesis keep */;
wire [31:0] atomic_out_xor /* synthesis keep */;
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_ADD) ) != 0 ) assign atomic_out_add = readdata + operand0;
else assign atomic_out_add = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_XCHG) ) != 0 ) assign atomic_out_cmp = operand0;
else assign atomic_out_cmp = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_CMPXCHG) ) != 0 ) assign atomic_out_cmpxchg = ( readdata == operand0 ) ? operand1 : readdata;
else assign atomic_out_cmpxchg = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_MIN) ) != 0 ) assign atomic_out_min = ( readdata < operand0 ) ? readdata : operand0;
else assign atomic_out_min = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_MAX) ) != 0 ) assign atomic_out_max = (readdata > operand0) ? readdata : operand0;
else assign atomic_out_max = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_AND) ) != 0 ) assign atomic_out_and = ( readdata & operand0 );
else assign atomic_out_and = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_OR) ) != 0 ) assign atomic_out_or = ( readdata | operand0 );
else assign atomic_out_or = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_XOR) ) != 0 ) assign atomic_out_xor = ( readdata ^ operand0 );
else assign atomic_out_xor = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
always @(*)
begin
case ( atomic_op )
a_ADD:
begin
atomic_out = atomic_out_add;
end
a_XCHG:
begin
atomic_out = atomic_out_cmp;
end
a_CMPXCHG:
begin
atomic_out = atomic_out_cmpxchg;
end
a_MIN:
begin
atomic_out = atomic_out_min;
end
a_MAX:
begin
atomic_out = atomic_out_max;
end
a_AND:
begin
atomic_out = atomic_out_and;
end
a_OR:
begin
atomic_out = atomic_out_or;
end
default:
begin
atomic_out = atomic_out_xor;
end
endcase
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
module timer #
(
parameter WIDTH = 64,
parameter USE_2XCLK = 0,
parameter S_WIDTH_A = 2
)
(
input clk,
input clk2x,
input resetn,
// Slave port
input [S_WIDTH_A-1:0] slave_address, // Word address
input [WIDTH-1:0] slave_writedata,
input slave_read,
input slave_write,
input [WIDTH/8-1:0] slave_byteenable,
output slave_waitrequest,
output [WIDTH-1:0] slave_readdata,
output slave_readdatavalid
);
reg [WIDTH-1:0] counter;
reg [WIDTH-1:0] counter2x;
reg clock_sel;
always@(posedge clk or negedge resetn)
if (!resetn)
clock_sel <= 1'b0;
else if (slave_write)
if (|slave_writedata)
clock_sel <= 1'b1;
else
clock_sel <= 1'b0;
always@(posedge clk or negedge resetn)
if (!resetn)
counter <= {WIDTH{1'b0}};
else if (slave_write)
counter <= {WIDTH{1'b0}};
else
counter <= counter + 2'b01;
always@(posedge clk2x or negedge resetn)
if (!resetn)
counter2x <= {WIDTH{1'b0}};
else if (slave_write)
counter2x <= {WIDTH{1'b0}};
else
counter2x <= counter2x + 2'b01;
assign slave_waitrequest = 1'b0;
assign slave_readdata = (USE_2XCLK && clock_sel) ? counter2x : counter;
assign slave_readdatavalid = slave_read;
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// 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 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.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// 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 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.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// 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 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.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
(** * Extraction: Extracting ML from Coq *)
(** * Basic Extraction *)
(** In its simplest form, program extraction from Coq is completely straightforward. *)
(** First we say what language we want to extract into. Options are OCaml (the
most mature), Haskell (which mostly works), and Scheme (a bit out
of date). *)
Extraction Language Ocaml.
(** Now we load up the Coq environment with some definitions, either
directly or by importing them from other modules. *)
Require Import SfLib.
Require Import ImpCEvalFun.
(** Finally, we tell Coq the name of a definition to extract and the
name of a file to put the extracted code into. *)
Extraction "imp1.ml" ceval_step.
(** When Coq processes this command, it generates a file [imp1.ml]
containing an extracted version of [ceval_step], together with
everything that it recursively depends on. Have a look at this
file now. *)
(* ############################################################## *)
(** * Controlling Extraction of Specific Types *)
(** We can tell Coq to extract certain [Inductive] definitions to
specific OCaml types. For each one, we must say
- how the Coq type itself should be represented in OCaml, and
- how each constructor should be translated. *)
Extract Inductive bool => "bool" [ "true" "false" ].
(** Also, for non-enumeration types (where the constructors take
arguments), we give an OCaml expression that can be used as a
"recursor" over elements of the type. (Think Church numerals.) *)
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n ->
if n=0 then zero () else succ (n-1))".
(** We can also extract defined constants to specific OCaml terms or
operators. *)
Extract Constant plus => "( + )".
Extract Constant mult => "( * )".
Extract Constant beq_nat => "( = )".
(** Important: It is entirely _your responsibility_ to make sure that
the translations you're proving make sense. For example, it might
be tempting to include this one
Extract Constant minus => "( - )".
but doing so could lead to serious confusion! (Why?)
*)
Extraction "imp2.ml" ceval_step.
(** Have a look at the file [imp2.ml]. Notice how the fundamental
definitions have changed from [imp1.ml]. *)
(* ############################################################## *)
(** * A Complete Example *)
(** To use our extracted evaluator to run Imp programs, all we need to
add is a tiny driver program that calls the evaluator and somehow
prints out the result.
For simplicity, we'll print results by dumping out the first four
memory locations in the final state.
Also, to make it easier to type in examples, let's extract a
parser from the [ImpParser] Coq module. To do this, we need a few
more declarations to set up the right correspondence between Coq
strings and lists of OCaml characters. *)
Require Import Ascii String.
Extract Inductive ascii => char
[
"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))"
]
"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))".
Extract Constant zero => "'\000'".
Extract Constant one => "'\001'".
Extract Constant shift =>
"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)".
Extract Inlined Constant ascii_dec => "(=)".
(** We also need one more variant of booleans. *)
Extract Inductive sumbool => "bool" ["true" "false"].
(** The extraction is the same as always. *)
Require Import Imp.
Require Import ImpParser.
Extraction "imp.ml" empty_state ceval_step parse.
(** Now let's run our generated Imp evaluator. First, have a look at
[impdriver.ml]. (This was written by hand, not extracted.)
Next, compile the driver together with the extracted code and
execute it, as follows.
<<
ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml
./impdriver
>>
(The [-w] flags to [ocamlc] are just there to suppress a few
spurious warnings.) *)
(* ############################################################## *)
(** * Discussion *)
(** Since we've proved that the [ceval_step] function behaves the same
as the [ceval] relation in an appropriate sense, the extracted
program can be viewed as a _certified_ Imp interpreter. (Of
course, the parser is not certified in any interesting sense,
since we didn't prove anything about it.) *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Extraction: Extracting ML from Coq *)
(** * Basic Extraction *)
(** In its simplest form, program extraction from Coq is completely straightforward. *)
(** First we say what language we want to extract into. Options are OCaml (the
most mature), Haskell (which mostly works), and Scheme (a bit out
of date). *)
Extraction Language Ocaml.
(** Now we load up the Coq environment with some definitions, either
directly or by importing them from other modules. *)
Require Import SfLib.
Require Import ImpCEvalFun.
(** Finally, we tell Coq the name of a definition to extract and the
name of a file to put the extracted code into. *)
Extraction "imp1.ml" ceval_step.
(** When Coq processes this command, it generates a file [imp1.ml]
containing an extracted version of [ceval_step], together with
everything that it recursively depends on. Have a look at this
file now. *)
(* ############################################################## *)
(** * Controlling Extraction of Specific Types *)
(** We can tell Coq to extract certain [Inductive] definitions to
specific OCaml types. For each one, we must say
- how the Coq type itself should be represented in OCaml, and
- how each constructor should be translated. *)
Extract Inductive bool => "bool" [ "true" "false" ].
(** Also, for non-enumeration types (where the constructors take
arguments), we give an OCaml expression that can be used as a
"recursor" over elements of the type. (Think Church numerals.) *)
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n ->
if n=0 then zero () else succ (n-1))".
(** We can also extract defined constants to specific OCaml terms or
operators. *)
Extract Constant plus => "( + )".
Extract Constant mult => "( * )".
Extract Constant beq_nat => "( = )".
(** Important: It is entirely _your responsibility_ to make sure that
the translations you're proving make sense. For example, it might
be tempting to include this one
Extract Constant minus => "( - )".
but doing so could lead to serious confusion! (Why?)
*)
Extraction "imp2.ml" ceval_step.
(** Have a look at the file [imp2.ml]. Notice how the fundamental
definitions have changed from [imp1.ml]. *)
(* ############################################################## *)
(** * A Complete Example *)
(** To use our extracted evaluator to run Imp programs, all we need to
add is a tiny driver program that calls the evaluator and somehow
prints out the result.
For simplicity, we'll print results by dumping out the first four
memory locations in the final state.
Also, to make it easier to type in examples, let's extract a
parser from the [ImpParser] Coq module. To do this, we need a few
more declarations to set up the right correspondence between Coq
strings and lists of OCaml characters. *)
Require Import Ascii String.
Extract Inductive ascii => char
[
"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))"
]
"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))".
Extract Constant zero => "'\000'".
Extract Constant one => "'\001'".
Extract Constant shift =>
"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)".
Extract Inlined Constant ascii_dec => "(=)".
(** We also need one more variant of booleans. *)
Extract Inductive sumbool => "bool" ["true" "false"].
(** The extraction is the same as always. *)
Require Import Imp.
Require Import ImpParser.
Extraction "imp.ml" empty_state ceval_step parse.
(** Now let's run our generated Imp evaluator. First, have a look at
[impdriver.ml]. (This was written by hand, not extracted.)
Next, compile the driver together with the extracted code and
execute it, as follows.
<<
ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml
./impdriver
>>
(The [-w] flags to [ocamlc] are just there to suppress a few
spurious warnings.) *)
(* ############################################################## *)
(** * Discussion *)
(** Since we've proved that the [ceval_step] function behaves the same
as the [ceval] relation in an appropriate sense, the extracted
program can be viewed as a _certified_ Imp interpreter. (Of
course, the parser is not certified in any interesting sense,
since we didn't prove anything about it.) *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_address_to_bankaddress #(
parameter integer ADDRESS_W = 32, // > 0
parameter integer NUM_BANKS = 2, // > 1
parameter integer BANK_SEL_BIT = ADDRESS_W-$clog2(NUM_BANKS)
)
(
input logic [ADDRESS_W-1:0] address,
output logic [NUM_BANKS-1:0] bank_sel, // one-hot
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] bank_address
);
integer i;
// To support NUM_BANKS=1 we need a wider address
logic [ADDRESS_W:0] wider_address;
assign wider_address = {1'b0,address};
always@*
begin
for (i=0; i<NUM_BANKS; i=i+1)
bank_sel[i] = (wider_address[BANK_SEL_BIT+$clog2(NUM_BANKS)-1 : BANK_SEL_BIT] == i);
end
assign bank_address = ((address>>(BANK_SEL_BIT+$clog2(NUM_BANKS)))<<(BANK_SEL_BIT)) |
// Take address[BANKS_SEL_BIT-1:0] in a manner that allows BANK_SEL_BIT=0
((~({ADDRESS_W{1'b1}}<<BANK_SEL_BIT)) & address);
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_address_to_bankaddress #(
parameter integer ADDRESS_W = 32, // > 0
parameter integer NUM_BANKS = 2, // > 1
parameter integer BANK_SEL_BIT = ADDRESS_W-$clog2(NUM_BANKS)
)
(
input logic [ADDRESS_W-1:0] address,
output logic [NUM_BANKS-1:0] bank_sel, // one-hot
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] bank_address
);
integer i;
// To support NUM_BANKS=1 we need a wider address
logic [ADDRESS_W:0] wider_address;
assign wider_address = {1'b0,address};
always@*
begin
for (i=0; i<NUM_BANKS; i=i+1)
bank_sel[i] = (wider_address[BANK_SEL_BIT+$clog2(NUM_BANKS)-1 : BANK_SEL_BIT] == i);
end
assign bank_address = ((address>>(BANK_SEL_BIT+$clog2(NUM_BANKS)))<<(BANK_SEL_BIT)) |
// Take address[BANKS_SEL_BIT-1:0] in a manner that allows BANK_SEL_BIT=0
((~({ADDRESS_W{1'b1}}<<BANK_SEL_BIT)) & address);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2011 by Wilson Snyder.
// bug420
typedef logic [7-1:0] wb_ind_t;
typedef logic [7-1:0] id_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
wire [6:0] out = line_wb_ind( in[6:0] );
// Aggregate outputs into a single result vector
wire [63:0] result = {57'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'hc918fa0aa882a206
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
function wb_ind_t line_wb_ind( id_t id );
if( id[$bits(id_t)-1] == 0 )
return {2'b00, id[$bits(wb_ind_t)-3:0]};
else
return {2'b01, id[$bits(wb_ind_t)-3:0]};
endfunction // line_wb_ind
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2011 by Wilson Snyder.
// bug420
typedef logic [7-1:0] wb_ind_t;
typedef logic [7-1:0] id_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
wire [6:0] out = line_wb_ind( in[6:0] );
// Aggregate outputs into a single result vector
wire [63:0] result = {57'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'hc918fa0aa882a206
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
function wb_ind_t line_wb_ind( id_t id );
if( id[$bits(id_t)-1] == 0 )
return {2'b00, id[$bits(wb_ind_t)-3:0]};
else
return {2'b01, id[$bits(wb_ind_t)-3:0]};
endfunction // line_wb_ind
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
(** * 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 (with some of the basic extensions from [MoreStlc]).
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.
[] *)
(** *** 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]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** 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.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** 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
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** 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.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- 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].
- 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].
[] *)
(** **** 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
]]
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** 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
]]
[] *)
(** **** 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
]]
[] *)
(** **** 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.)
[] *)
(** **** 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.
[] *)
(* ###################################################### *)
(** * 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
.
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" |
].
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
.
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"
].
(* ################################### *)
(** *** 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
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
.
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)
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"
].
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)
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"
].
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 :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
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
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" ].
(* 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) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** 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 *)
(* FILL IN HERE *)
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** **** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** 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.
(* ########################################## *)
(** ** 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.
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.
(** 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.
(* ########################################## *)
(** ** 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)
.
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...
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)...
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...
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 *)
(** **** 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
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * 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-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * 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 (with some of the basic extensions from [MoreStlc]).
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.
[] *)
(** *** 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]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** 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.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** 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
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** 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.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- 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].
- 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].
[] *)
(** **** 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
]]
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** 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
]]
[] *)
(** **** 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
]]
[] *)
(** **** 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.)
[] *)
(** **** 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.
[] *)
(* ###################################################### *)
(** * 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
.
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" |
].
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
.
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"
].
(* ################################### *)
(** *** 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
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
.
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)
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"
].
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)
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"
].
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 :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
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
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" ].
(* 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) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** 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 *)
(* FILL IN HERE *)
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** **** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** 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.
(* ########################################## *)
(** ** 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.
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.
(** 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.
(* ########################################## *)
(** ** 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)
.
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...
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)...
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...
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 *)
(** **** 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
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * 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-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * 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 (with some of the basic extensions from [MoreStlc]).
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.
[] *)
(** *** 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]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** 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.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** 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
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** 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.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- 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].
- 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].
[] *)
(** **** 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
]]
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** 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
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** 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
]]
[] *)
(** **** 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
]]
[] *)
(** **** 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.)
[] *)
(** **** 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.
[] *)
(* ###################################################### *)
(** * 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
.
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" |
].
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
.
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"
].
(* ################################### *)
(** *** 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
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
.
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)
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"
].
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)
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"
].
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 :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
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
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" ].
(* 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) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** 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 *)
(* FILL IN HERE *)
(** [] *)
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.
(* FILL IN HERE *) Admitted.
(** **** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** 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.
(* FILL IN HERE *) Admitted.
(** [] *)
(** 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.
(* ########################################## *)
(** ** 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.
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.
(** 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.
(* ########################################## *)
(** ** 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)
.
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...
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)...
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...
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 *)
(** **** 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
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * 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-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * RecordSub: Subtyping with Records *)
Require Export MoreStlc.
(* ###################################################### *)
(** * Core Definitions *)
(* ################################### *)
(** *** Syntax *)
Inductive ty : Type :=
(* proper types *)
| TTop : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
(* record types *)
| TRNil : ty
| TRCons : id -> ty -> ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TRNil" | Case_aux c "TRCons" ].
Inductive tm : Type :=
(* proper terms *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tproj : tm -> id -> tm
(* record terms *)
| trnil : tm
| trcons : id -> tm -> 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 "tproj" | Case_aux c "trnil" | Case_aux c "trcons" ].
(* ################################### *)
(** *** Well-Formedness *)
Inductive record_ty : ty -> Prop :=
| RTnil :
record_ty TRNil
| RTcons : forall i T1 T2,
record_ty (TRCons i T1 T2).
Inductive record_tm : tm -> Prop :=
| rtnil :
record_tm trnil
| rtcons : forall i t1 t2,
record_tm (trcons i t1 t2).
Inductive well_formed_ty : ty -> Prop :=
| wfTTop :
well_formed_ty TTop
| wfTBase : forall i,
well_formed_ty (TBase i)
| wfTArrow : forall T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
well_formed_ty (TArrow T1 T2)
| wfTRNil :
well_formed_ty TRNil
| wfTRCons : forall i T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
record_ty T2 ->
well_formed_ty (TRCons i T1 T2).
Hint Constructors record_ty record_tm well_formed_ty.
(* ################################### *)
(** *** Substitution *)
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)
| tproj t1 i => tproj (subst x s t1) i
| trnil => trnil
| trcons i t1 tr2 => trcons i (subst x s t1) (subst x s tr2)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_rnil : value trnil
| v_rcons : forall i v vr,
value v ->
value vr ->
value (trcons i v vr).
Hint Constructors value.
Fixpoint Tlookup (i:id) (Tr:ty) : option ty :=
match Tr with
| TRCons i' T Tr' => if eq_id_dec i i' then Some T else Tlookup i Tr'
| _ => None
end.
Fixpoint tlookup (i:id) (tr:tm) : option tm :=
match tr with
| trcons i' t tr' => if eq_id_dec i i' then Some t else tlookup i tr'
| _ => None
end.
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_Proj1 : forall tr tr' i,
tr ==> tr' ->
(tproj tr i) ==> (tproj tr' i)
| ST_ProjRcd : forall tr i vi,
value tr ->
tlookup i tr = Some vi ->
(tproj tr i) ==> vi
| ST_Rcd_Head : forall i t1 t1' tr2,
t1 ==> t1' ->
(trcons i t1 tr2) ==> (trcons i t1' tr2)
| ST_Rcd_Tail : forall i v1 tr2 tr2',
value v1 ->
tr2 ==> tr2' ->
(trcons i v1 tr2) ==> (trcons i v1 tr2')
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_Proj1" | Case_aux c "ST_ProjRcd" | Case_aux c "ST_Rcd"
| Case_aux c "ST_Rcd_Head" | Case_aux c "ST_Rcd_Tail" ].
Hint Constructors step.
(* ###################################################################### *)
(** * Subtyping *)
(** Now we come to the interesting part. We begin by defining
the subtyping relation and developing some of its important
technical properties. *)
(* ################################### *)
(** ** Definition *)
(** The definition of subtyping is essentially just what we
sketched in the motivating discussion, but we need to add
well-formedness side conditions to some of the rules. *)
Inductive subtype : ty -> ty -> Prop :=
(* Subtyping between proper types *)
| S_Refl : forall T,
well_formed_ty T ->
subtype T T
| S_Trans : forall S U T,
subtype S U ->
subtype U T ->
subtype S T
| S_Top : forall S,
well_formed_ty S ->
subtype S TTop
| S_Arrow : forall S1 S2 T1 T2,
subtype T1 S1 ->
subtype S2 T2 ->
subtype (TArrow S1 S2) (TArrow T1 T2)
(* Subtyping between record types *)
| S_RcdWidth : forall i T1 T2,
well_formed_ty (TRCons i T1 T2) ->
subtype (TRCons i T1 T2) TRNil
| S_RcdDepth : forall i S1 T1 Sr2 Tr2,
subtype S1 T1 ->
subtype Sr2 Tr2 ->
record_ty Sr2 ->
record_ty Tr2 ->
subtype (TRCons i S1 Sr2) (TRCons i T1 Tr2)
| S_RcdPerm : forall i1 i2 T1 T2 Tr3,
well_formed_ty (TRCons i1 T1 (TRCons i2 T2 Tr3)) ->
i1 <> i2 ->
subtype (TRCons i1 T1 (TRCons i2 T2 Tr3))
(TRCons i2 T2 (TRCons i1 T1 Tr3)).
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_RcdWidth"
| Case_aux c "S_RcdDepth" | Case_aux c "S_RcdPerm" ].
(* ############################################### *)
(** ** Subtyping Examples and Exercises *)
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation j := (Id 3).
Notation k := (Id 4).
Notation i := (Id 5).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Definition TRcd_j :=
(TRCons j (TArrow B B) TRNil). (* {j:B->B} *)
Definition TRcd_kj :=
TRCons k (TArrow A A) TRcd_j. (* {k:C->C,j:B->B} *)
Example subtyping_example_0 :
subtype (TArrow C TRcd_kj)
(TArrow C TRNil).
(* C->{k:A->A,j:B->B} <: C->{} *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
unfold TRcd_kj, TRcd_j. apply S_RcdWidth; 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: 2 stars *)
Example subtyping_example_1 :
subtype TRcd_kj TRcd_j.
(* {k:A->A,j:B->B} <: {j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_2 :
subtype (TArrow TTop TRcd_kj)
(TArrow (TArrow C C) TRcd_j).
(* Top->{k:A->A,j:B->B} <: (C->C)->{j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_3 :
subtype (TArrow TRNil (TRCons j A TRNil))
(TArrow (TRCons k B TRNil) TRNil).
(* {}->{j:A} <: {k:B}->{} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example subtyping_example_4 :
subtype (TRCons x A (TRCons y B (TRCons z C TRNil)))
(TRCons z C (TRCons y B (TRCons x A TRNil))).
(* {x:A,y:B,z:C} <: {z:C,y:B,x:A} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Definition trcd_kj :=
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil)).
End Examples.
(* ###################################################################### *)
(** ** Properties of Subtyping *)
(** *** Well-Formedness *)
Lemma subtype__wf : forall S T,
subtype S T ->
well_formed_ty T /\ well_formed_ty S.
Proof with eauto.
intros S T Hsub.
subtype_cases (induction Hsub) Case;
intros; try (destruct IHHsub1; destruct IHHsub2)...
Case "S_RcdPerm".
split... inversion H. subst. inversion H5... Qed.
Lemma wf_rcd_lookup : forall i T Ti,
well_formed_ty T ->
Tlookup i T = Some Ti ->
well_formed_ty Ti.
Proof with eauto.
intros i T.
T_cases (induction T) Case; intros; try solve by inversion.
Case "TRCons".
inversion H. subst. unfold Tlookup in H0.
destruct (eq_id_dec i i0)... inversion H0; subst... Qed.
(** *** Field Lookup *)
(** Our record matching lemmas get a little more complicated in
the presence of subtyping for two reasons: First, record
types no longer necessarily describe the exact structure of
corresponding terms. Second, reasoning by induction on
[has_type] derivations becomes harder in general, because
[has_type] is no longer syntax directed. *)
Lemma rcd_types_match : forall S T i Ti,
subtype S T ->
Tlookup i T = Some Ti ->
exists Si, Tlookup i S = Some Si /\ subtype Si Ti.
Proof with (eauto using wf_rcd_lookup).
intros S T i Ti Hsub Hget. generalize dependent Ti.
subtype_cases (induction Hsub) Case; intros Ti Hget;
try solve by inversion.
Case "S_Refl".
exists Ti...
Case "S_Trans".
destruct (IHHsub2 Ti) as [Ui Hui]... destruct Hui.
destruct (IHHsub1 Ui) as [Si Hsi]... destruct Hsi.
exists Si...
Case "S_RcdDepth".
rename i0 into k.
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i k)...
SCase "i = k -- we're looking up the first field".
inversion Hget. subst. exists S1...
Case "S_RcdPerm".
exists Ti. split.
SCase "lookup".
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i i1)...
SSCase "i = i1 -- we're looking up the first field".
destruct (eq_id_dec i i2)...
SSSCase "i = i2 - -contradictory".
destruct H0.
subst...
SCase "subtype".
inversion H. subst. inversion H5. subst... Qed.
(** **** Exercise: 3 stars (rcd_types_match_informal) *)
(** Write a careful informal proof of the [rcd_types_match]
lemma. *)
(* FILL IN HERE *)
(** [] *)
(** *** Inversion Lemmas *)
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
subtype U (TArrow V1 V2) ->
exists U1, exists U2,
(U=(TArrow U1 U2)) /\ (subtype V1 U1) /\ (subtype U2 V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Typing *)
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 :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
well_formed_ty T ->
has_type Gamma (tvar x) T
| T_Abs : forall Gamma x T11 T12 t12,
well_formed_ty T11 ->
has_type (extend Gamma x T11) t12 T12 ->
has_type Gamma (tabs x T11 t12) (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
has_type Gamma t1 (TArrow T1 T2) ->
has_type Gamma t2 T1 ->
has_type Gamma (tapp t1 t2) T2
| T_Proj : forall Gamma i t T Ti,
has_type Gamma t T ->
Tlookup i T = Some Ti ->
has_type Gamma (tproj t i) Ti
(* Subsumption *)
| T_Sub : forall Gamma t S T,
has_type Gamma t S ->
subtype S T ->
has_type Gamma t T
(* Rules for record terms *)
| T_RNil : forall Gamma,
has_type Gamma trnil TRNil
| T_RCons : forall Gamma i t T tr Tr,
has_type Gamma t T ->
has_type Gamma tr Tr ->
record_ty Tr ->
record_tm tr ->
has_type Gamma (trcons i t tr) (TRCons i T Tr)
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_Proj" | Case_aux c "T_Sub"
| Case_aux c "T_RNil" | Case_aux c "T_RCons" ].
(* ############################################### *)
(** ** Typing Examples *)
Module Examples2.
Import Examples.
(** **** Exercise: 1 star *)
Example typing_example_0 :
has_type empty
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil))
TRcd_kj.
(* empty |- {k=(\z:A.z), j=(\z:B.z)} : {k:A->A,j:B->B} *)
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example typing_example_1 :
has_type empty
(tapp (tabs x TRcd_j (tproj (tvar x) j))
(trcd_kj))
(TArrow B B).
(* empty |- (\x:{k:A->A,j:B->B}. x.j) {k=(\z:A.z), j=(\z:B.z)} : B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Example typing_example_2 :
has_type empty
(tapp (tabs z (TArrow (TArrow C C) TRcd_j)
(tproj (tapp (tvar z)
(tabs x C (tvar x)))
j))
(tabs z (TArrow C C) trcd_kj))
(TArrow B B).
(* empty |- (\z:(C->C)->{j:B->B}. (z (\x:C.x)).j)
(\z:C->C. {k=(\z:A.z), j=(\z:B.z)})
: B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples2.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** *** Well-Formedness *)
Lemma has_type__wf : forall Gamma t T,
has_type Gamma t T -> well_formed_ty T.
Proof with eauto.
intros Gamma t T Htyp.
has_type_cases (induction Htyp) Case...
Case "T_App".
inversion IHHtyp1...
Case "T_Proj".
eapply wf_rcd_lookup...
Case "T_Sub".
apply subtype__wf in H.
destruct H...
Qed.
Lemma step_preserves_record_tm : forall tr tr',
record_tm tr ->
tr ==> tr' ->
record_tm tr'.
Proof.
intros tr tr' Hrt Hstp.
inversion Hrt; subst; inversion Hstp; subst; eauto.
Qed.
(** *** Field Lookup *)
Lemma lookup_field_in_value : forall v T i Ti,
value v ->
has_type empty v T ->
Tlookup i T = Some Ti ->
exists vi, tlookup i v = Some vi /\ has_type empty vi Ti.
Proof with eauto.
remember empty as Gamma.
intros t T i Ti Hval Htyp. revert Ti HeqGamma Hval.
has_type_cases (induction Htyp) Case; intros; subst; try solve by inversion.
Case "T_Sub".
apply (rcd_types_match S) in H0... destruct H0 as [Si [HgetSi Hsub]].
destruct (IHHtyp Si) as [vi [Hget Htyvi]]...
Case "T_RCons".
simpl in H0. simpl. simpl in H1.
destruct (eq_id_dec i i0).
SCase "i is first".
inversion H1. subst. exists t...
SCase "i in tail".
destruct (IHHtyp2 Ti) as [vi [get Htyvi]]...
inversion Hval... Qed.
(* ########################################## *)
(** *** Progress *)
(** **** Exercise: 3 stars (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
has_type Gamma s (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Theorem progress : forall t T,
has_type empty t 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".
destruct H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
destruct H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Proj".
right. destruct IHHt...
SCase "rcd is value".
destruct (lookup_field_in_value t T i Ti) as [t' [Hget Ht']]...
SCase "rcd_steps".
destruct H0 as [t' Hstp]. exists (tproj t' i)...
Case "T_RCons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. destruct H2 as [tr' Hstp].
exists (trcons i t tr')...
SCase "head steps".
right. destruct H1 as [t' Hstp].
exists (trcons i t' tr)... Qed.
(** Informal proof of progress:
Theorem : 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 such that [empty |- t : T]. We go
by induction on the typing derivation. Cases [T_Abs] and
[T_RNil] are immediate because abstractions and [{}] are always
values. Case [T_Var] is vacuous because variables cannot be
typed in the empty context.
- If the last step in the typing derivation is by [T_App], then
there are terms [t1] [t2] and types [T1] [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2] and
[empty |- t2 : T1].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [t2] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[t1 t2 ==> t1' t2] by [ST_App1].
- Otherwise [t1] is a value.
- Suppose [t2 ==> t2'] for some term [t2']. Then
[t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a value.
- Otherwise, [t2] is a value. By lemma
[canonical_forms_for_arrow_types], [t1 = \x:S1.s2] for some
[x], [S1], and [s2]. And [(\x:S1.s2) t2 ==> [x:=t2]s2] by
[ST_AppAbs], since [t2] is a value.
- If the last step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing subderivation gives us that either [tr]
is a value or it steps. If [tr ==> tr'] for some term [tr'],
then [tr.i ==> tr'.i] by rule [ST_Proj1].
Otherwise, [tr] is a value. In this case, lemma
[lookup_field_in_value] yields that there is a term [ti] such
that [tlookup i tr = Some ti]. It follows that [tr.i ==> ti]
by rule [ST_ProjRcd].
- 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.
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [tr] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[{i=t1, tr} ==> {i=t1', tr}] by rule [ST_Rcd_Head].
- Otherwise [t1] is a value.
- Suppose [tr ==> tr'] for some term [tr']. Then
[{i=t1, tr} ==> {i=t1, tr'}] by rule [ST_Rcd_Tail],
since [t1] is a value.
- Otherwise, [tr] is also a value. So, [{i=t1, tr}] is a
value by [v_rcons]. *)
(* ########################################## *)
(** *** Inversion Lemmas *)
Lemma typing_inversion_var : forall Gamma x T,
has_type Gamma (tvar x) T ->
exists S,
Gamma x = Some S /\ subtype 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,
has_type Gamma (tapp t1 t2) T2 ->
exists T1,
has_type Gamma t1 (TArrow T1 T2) /\
has_type Gamma t2 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]]...
assert (Hwf := has_type__wf _ _ _ Hty2).
exists U1... Qed.
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
has_type Gamma (tabs x S1 t2) T ->
(exists S2, subtype (TArrow S1 S2) T
/\ has_type (extend Gamma x S1) t2 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".
assert (Hwf := has_type__wf _ _ _ H0).
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
Lemma typing_inversion_proj : forall Gamma i t1 Ti,
has_type Gamma (tproj t1 i) Ti ->
exists T, exists Si,
Tlookup i T = Some Si /\ subtype Si Ti /\ has_type Gamma t1 T.
Proof with eauto.
intros Gamma i t1 Ti H.
remember (tproj t1 i) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Proj".
assert (well_formed_ty Ti) as Hwf.
SCase "pf of assertion".
apply (wf_rcd_lookup i T Ti)...
apply has_type__wf in H...
exists T. exists Ti...
Case "T_Sub".
destruct IHhas_type as [U [Ui [Hget [Hsub Hty]]]]...
exists U. exists Ui... Qed.
Lemma typing_inversion_rcons : forall Gamma i ti tr T,
has_type Gamma (trcons i ti tr) T ->
exists Si, exists Sr,
subtype (TRCons i Si Sr) T /\ has_type Gamma ti Si /\
record_tm tr /\ has_type Gamma tr Sr.
Proof with eauto.
intros Gamma i ti tr T Hty.
remember (trcons i ti tr) as t.
has_type_cases (induction Hty) Case;
inversion Heqt; subst...
Case "T_Sub".
apply IHHty in H0.
destruct H0 as [Ri [Rr [HsubRS [HtypRi HtypRr]]]].
exists Ri. exists Rr...
Case "T_RCons".
assert (well_formed_ty (TRCons i T Tr)) as Hwf.
SCase "pf of assertion".
apply has_type__wf in Hty1.
apply has_type__wf in Hty2...
exists T. exists Tr... Qed.
Lemma abs_arrow : forall x S1 s2 T1 T2,
has_type empty (tabs x S1 s2) (TArrow T1 T2) ->
subtype T1 S1
/\ has_type (extend empty x S1) s2 T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
destruct Hty as [S2 [Hsub Hty]].
apply sub_inversion_arrow in Hsub.
destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** *** Context Invariance *)
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_proj : forall x t i,
appears_free_in x t ->
appears_free_in x (tproj t i)
| afi_rhead : forall x i t tr,
appears_free_in x t ->
appears_free_in x (trcons i t tr)
| afi_rtail : forall x i t tr,
appears_free_in x tr ->
appears_free_in x (trcons i t tr).
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
has_type Gamma t S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
has_type Gamma' t 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_App".
apply T_App with T1...
Case "T_RCons".
apply T_RCons... Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
has_type Gamma t 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 H5) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** *** Preservation *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
has_type (extend Gamma x U) t S ->
has_type empty v U ->
has_type Gamma ([x:=v]t) 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'.
SCase "x<>y".
destruct (subtype__wf _ _ Hsub)...
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]].
destruct (subtype__wf _ _ Hsub) as [Hwf1 Hwf2].
inversion Hwf2. subst.
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 "tproj".
destruct (typing_inversion_proj _ _ _ _ Htypt)
as [T [Ti [Hget [Hsub Htypt1]]]]...
Case "trnil".
eapply context_invariance...
intros y Hcontra. inversion Hcontra.
Case "trcons".
destruct (typing_inversion_rcons _ _ _ _ _ Htypt) as
[Ti [Tr [Hsub [HtypTi [Hrcdt2 HtypTr]]]]].
apply T_Sub with (TRCons i Ti Tr)...
apply T_RCons...
SCase "record_ty Tr".
apply subtype__wf in Hsub. destruct Hsub. inversion H0...
SCase "record_tm ([x:=v]t2)".
inversion Hrcdt2; subst; simpl... Qed.
Theorem preservation : forall t t' T,
has_type empty t T ->
t ==> t' ->
has_type empty t' 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_Proj".
destruct (lookup_field_in_value _ _ _ _ H2 HT H)
as [vi [Hget Hty]].
rewrite H4 in Hget. inversion Hget. subst...
Case "T_RCons".
eauto using step_preserves_record_tm. Qed.
(** Informal proof of [preservation]:
Theorem: 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 go
by induction on the structure of this typing derivation, leaving
[t'] general. Cases [T_Abs] and [T_RNil] are vacuous because
abstractions and {} 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] [t2] and types [T1] [T2] such that [t = t1 t2],
[T = T2], [empty |- t1 : T1 -> T2] and [empty |- t2 : T1].
By inspection of 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 lemma [substitution_preserves_typing] that
[empty |- [x:=t2] t12 : T2] as desired.
- If the final step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing derivation gives us that, for any term
[tr'], if [tr ==> tr'] then [empty |- tr' Tr]. Inspection of
the definition of the step relation reveals that there are two
ways a projection can step. Case [ST_Proj1] follows
immediately by the IH.
Instead suppose [tr.i] steps by [ST_ProjRcd]. Then [tr] is a
value and there is some term [vi] such that
[tlookup i tr = Some vi] and [t' = vi]. But by lemma
[lookup_field_in_value], [empty |- vi : Ti] as desired.
- 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].
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
By the definition of the step relation, [t] must have stepped
by [ST_Rcd_Head] or [ST_Rcd_Tail]. In the first case, the
result follows by the IH for [t1]'s typing derivation and
[T_RCons]. In the second case, the result follows by the IH
for [tr]'s typing derivation, [T_RCons], and a use of the
[step_preserves_record_tm] lemma. *)
(* ###################################################### *)
(** ** Exercises on Typing *)
(** **** Exercise: 2 stars, optional (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with records 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
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
{} ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
{} <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: {}
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
- Suppose we add the same evaluation rule *and* a new typing rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
---------------------- (T_Funny6)
empty |- {} : Top->Top
- Suppose we *change* the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
(** [] *)
*)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// 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 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.
`timescale 1ps/1ps
module altera_pll_reconfig_mif_reader
#(
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter MIF_ADDR_WIDTH = 6,
parameter ROM_ADDR_WIDTH = 9, // 512 words x
parameter ROM_DATA_WIDTH = 32, // 32 bits per word = 20kB
parameter ROM_NUM_WORDS = 512, // Default 512 32-bit words = 1 M20K
parameter DEVICE_FAMILY = "Stratix V",
parameter ENABLE_MIF = 0,
parameter MIF_FILE_NAME = ""
) (
// Inputs
input wire mif_clk,
input wire mif_rst,
// Reconfig Module interface for internal register mapping
input wire reconfig_busy, // waitrequest
input wire [RECONFIG_DATA_WIDTH-1:0] reconfig_read_data,
output reg [RECONFIG_DATA_WIDTH-1:0] reconfig_write_data,
output reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_addr,
output reg reconfig_write,
output reg reconfig_read,
// MIF Controller Interface
input wire [ROM_ADDR_WIDTH-1:0] mif_base_addr,
input wire mif_start,
output wire mif_busy
);
// NOTE: Assumes settings opcodes/registers are continguous and OP_MODE is 0
// ROM Interface ctlr states
localparam NUM_STATES = 5;
localparam STATE_REG_WIDTH = 32;
localparam MIF_IDLE = 32'd0;
localparam SET_INSTR_ADDR = 32'd1;
localparam FETCH_INSTR = 32'd2;
localparam WAIT_FOR_ROM_INSTR = 32'd3;
localparam STORE_INSTR = 32'd4;
localparam DECODE_ROM_INSTR = 32'd5;
localparam SET_DATA_ADDR = 32'd6;
localparam SET_DATA_ADDR_DLY = 32'd34;
localparam FETCH_DATA = 32'd7;
localparam WAIT_FOR_ROM_DATA = 32'd8;
localparam STORE_DATA = 32'd9;
localparam SET_INDEX = 32'd35;
localparam CHANGE_SETTINGS_REG = 32'd10;
localparam SET_MODE_REG_INFO = 32'd11;
localparam WAIT_MODE_REG = 32'd12;
localparam SAVE_MODE_REG = 32'd13;
localparam SET_WR_MODE = 32'd14;
localparam WAIT_WRITE_MODE = 32'd15;
localparam INIT_RECONFIG_PARAMS = 32'd16;
localparam CHECK_RECONFIG_SETTING = 32'd17;
localparam WRITE_RECONFIG_SETTING = 32'd18;
localparam DECREMENT_SETTING_NUM = 32'd19;
localparam CHECK_C_SETTINGS = 32'd20;
localparam WRITE_C_SETTINGS = 32'd21;
localparam DECREMENT_C_NUM = 32'd22;
localparam CHECK_DPS_SETTINGS = 32'd23;
localparam WRITE_DPS_SETTINGS = 32'd24;
localparam DECREMENT_DPS_NUM = 32'd25;
localparam START_RECONFIG_CHANGE = 32'd26;
localparam START_RECONFIG_DELAY = 32'd27;
localparam START_RECONFIG_DELAY2 = 32'd28;
localparam WAIT_DONE_SIGNAL = 32'd29;
localparam SET_MODE_REG = 32'd30;
localparam WRITE_FINAL_MODE = 32'd31;
localparam WAIT_FINAL_MODE = 32'd32;
localparam MIF_STREAMING_DONE = 32'd33;
// MIF Opcodes
// Addresses for settings from PLL Reconfig module
localparam OP_MODE = 6'b000000;
localparam OP_STATUS = 6'b000001; // Read only
localparam OP_START = 6'b000010;
localparam OP_N = 6'b000011;
localparam OP_M = 6'b000100;
localparam OP_C_COUNTERS = 6'b000101;
localparam OP_DPS = 6'b000110;
localparam OP_DSM = 6'b000111;
localparam OP_BWCTRL = 6'b001000;
localparam OP_CP_CURRENT = 6'b001001;
localparam OP_SOM = 6'b111110;
localparam OP_EOM = 6'b111111;
localparam INVAL_SETTING = 6'b111100;
localparam MODE_WR = 1'b0;
localparam MODE_POLL = 1'b1;
// Total MIF changeable settings = 8
// + Total non-MIF changeable settings = 2 (status, start)
// + StartOfMif, EndOfMif, Invalid = 3
// = 13 total settings
localparam NUM_SETTINGS = 6'd13;
localparam NUM_MIF_SETTINGS = 6'd10; // Mode = 0.. CP_Current=9
localparam LOG2NUM_SETTINGS = 6; // Consistent with Reconfig addr width
localparam NUM_C_COUNTERS = 5'd18;
localparam LOG2NUM_C_COUNTERS = 3'd5;
localparam NUM_DPS_COUNTERS = 6'd32;
localparam LOG2NUM_DPS_COUNTERS = 3'd6;
// Reconfig Module parameters
localparam WAITREQUEST_MODE = 1'b1;
// Control flow registers
reg [STATE_REG_WIDTH-1:0] mif_curstate;
reg [STATE_REG_WIDTH-1:0] mif_nextstate;
wire is_done;
// Internal data registers
reg [ROM_ADDR_WIDTH-1:0] reg_mif_base_addr;
reg [LOG2NUM_SETTINGS-1:0] reg_instr;
reg [RECONFIG_DATA_WIDTH-1:0] reg_data;
reg [RECONFIG_DATA_WIDTH-1:0] settings_reg [NUM_MIF_SETTINGS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] c_settings_reg [NUM_C_COUNTERS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] dps_settings_reg [NUM_DPS_COUNTERS-1:0];
reg [4:0] c_cntr_index; // C cntr is data[22:18];
reg [4:0] dps_index; // DPS is data[20:16];
reg [NUM_SETTINGS-1:0] is_setting_changed; // 1 bit per setting
reg [NUM_C_COUNTERS-1:0] is_c_cntr_changed;
reg [NUM_DPS_COUNTERS-1:0] is_dps_changed;
reg user_mode_setting; // 0 for waitrequest mode, 1 for polling
reg mif_started;
reg saved_mode;
reg mode_reg;
reg [RECONFIG_ADDR_WIDTH-1:0] setting_number;
reg [LOG2NUM_C_COUNTERS-1:0] c_cntr_number;
reg [LOG2NUM_DPS_COUNTERS-1:0] dps_number;
reg c_done;
reg dps_done;
reg is_mode_changed;
// ROM Interface
wire [ROM_DATA_WIDTH-1:0] rom_q;
reg [ROM_ADDR_WIDTH-1:0] rom_addr;
assign mif_busy = (is_done) ? 1'b0 : 1'b1;
// mif_started register
always @(posedge mif_clk)
begin
if (mif_curstate == MIF_IDLE)
mif_started <= 0;
else if (reg_instr == OP_SOM && mif_curstate == DECODE_ROM_INSTR)
mif_started <= 1;
else
mif_started <= mif_started;
end
// is_done logic
assign is_done = (mif_curstate == MIF_IDLE && mif_nextstate == MIF_IDLE) ? 1'b1 : 1'b0;
// State register
always @(posedge mif_clk)
begin
if (mif_rst)
mif_curstate <= MIF_IDLE;
else
mif_curstate <= mif_nextstate;
end
// Next state logic
always @(*)
begin
case (mif_curstate)
MIF_IDLE:
begin
if (mif_start)
mif_nextstate = SET_INSTR_ADDR;
else
mif_nextstate = MIF_IDLE;
end
// Set address for instruction to be fetched from ROM
SET_INSTR_ADDR: // SET_ROM_INFO
begin
mif_nextstate = FETCH_INSTR;
end
FETCH_INSTR:
begin
mif_nextstate = WAIT_FOR_ROM_INSTR;
end
WAIT_FOR_ROM_INSTR:
begin
mif_nextstate = STORE_INSTR;
end
STORE_INSTR:
begin
mif_nextstate = DECODE_ROM_INSTR;
end
DECODE_ROM_INSTR:
begin
if (reg_instr == OP_SOM)
mif_nextstate = SET_INSTR_ADDR;
else if (reg_instr == OP_EOM)
mif_nextstate = SET_MODE_REG_INFO; // Done reading MIF, send it to reconfig module
else
mif_nextstate = SET_DATA_ADDR;
end
SET_DATA_ADDR:
begin
mif_nextstate = SET_DATA_ADDR_DLY;
end
SET_DATA_ADDR_DLY:
begin
mif_nextstate = FETCH_DATA;
end
FETCH_DATA:
begin
mif_nextstate = WAIT_FOR_ROM_DATA;
end
WAIT_FOR_ROM_DATA:
begin
mif_nextstate = STORE_DATA;
end
STORE_DATA:
begin
mif_nextstate = SET_INDEX;
end
SET_INDEX:
begin
mif_nextstate = CHANGE_SETTINGS_REG;
end
CHANGE_SETTINGS_REG:
begin
mif_nextstate = SET_INSTR_ADDR; // Loop back to read rest of MIF file
end
// --- CHANGE RECONFIG REGISTERS --- //
// GENERAL STEPS FOR MANAGING WITH RECONFIG MODULE:
// 1) Save user's configured mode register,
// 2) Change mode to waitrequest mode,
// 3) Send all settings that have changed to
// 4) Start reconfig
// 5) Wait till PLL has locked again.
// 6) Restore user's mode register
SET_MODE_REG_INFO:
begin
mif_nextstate = WAIT_MODE_REG;
end
WAIT_MODE_REG:
begin
mif_nextstate = SAVE_MODE_REG;
end
SAVE_MODE_REG:
begin
mif_nextstate = SET_WR_MODE;
end
SET_WR_MODE:
begin
mif_nextstate = WAIT_WRITE_MODE;
end
WAIT_WRITE_MODE:
begin
mif_nextstate = INIT_RECONFIG_PARAMS;
end
INIT_RECONFIG_PARAMS:
begin
mif_nextstate = CHECK_RECONFIG_SETTING;
end
// PARENT LOOP (writing to reconfig)
CHECK_RECONFIG_SETTING: // Loop over changed settings until setting_num = 0 = MODE
begin
// Don't write the user's mode reg just yet
// Stay in WR mode till we're done with reconfig IP
// then restore the user's old mode/the new mode
// they wrote in the MIF
if (setting_number == 6'b0)
mif_nextstate = START_RECONFIG_CHANGE;
else
begin
if(is_setting_changed[setting_number])
// C and DPS settings are different,
// since multiple can be reconfigured in
// one MIF. If they are changed, check them all.
// In their respective loops
if (setting_number == OP_C_COUNTERS)
begin
mif_nextstate = DECREMENT_C_NUM;
end
else if (setting_number == OP_DPS)
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
else
begin
mif_nextstate = WRITE_RECONFIG_SETTING;
end
else
mif_nextstate = DECREMENT_SETTING_NUM;
end
end
// C LOOP
// We need to check the 0th setting always (unlike the parent loop) so decrement first.
DECREMENT_C_NUM:
begin
if (c_done)
begin
// Done checking and writing C counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_C_SETTINGS;
end
CHECK_C_SETTINGS:
begin
if (is_c_cntr_changed[c_cntr_number])
mif_nextstate = WRITE_C_SETTINGS;
else
mif_nextstate = DECREMENT_C_NUM;
end
WRITE_C_SETTINGS:
begin
mif_nextstate = DECREMENT_C_NUM;
end
//End C Loop
// DPS LOOP
// Same as C loop, decrement first.
DECREMENT_DPS_NUM:
begin
if (dps_done)
begin
// Done checking and writing DPS counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_DPS_SETTINGS; // Check next DPS setting
end
CHECK_DPS_SETTINGS:
begin
if(is_dps_changed[dps_number])
mif_nextstate = WRITE_DPS_SETTINGS;
else
mif_nextstate = DECREMENT_DPS_NUM;
end
WRITE_DPS_SETTINGS:
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
mif_nextstate = DECREMENT_SETTING_NUM;
end
DECREMENT_SETTING_NUM:
begin
mif_nextstate = CHECK_RECONFIG_SETTING; // Loop back
end
// --- DONE CHANGING SETTINGS, START RECONFIG --- //
START_RECONFIG_CHANGE:
begin
mif_nextstate = START_RECONFIG_DELAY;
end
START_RECONFIG_DELAY:
begin
mif_nextstate = START_RECONFIG_DELAY2;
end
START_RECONFIG_DELAY2: // register at top level before we mux into reconfig
begin
mif_nextstate = WAIT_DONE_SIGNAL;
end
WAIT_DONE_SIGNAL:
begin
if (reconfig_busy)
mif_nextstate = WAIT_DONE_SIGNAL;
else
mif_nextstate = SET_MODE_REG;
end
SET_MODE_REG:
begin
mif_nextstate = WRITE_FINAL_MODE;
end
WRITE_FINAL_MODE:
begin
mif_nextstate = WAIT_FINAL_MODE;
end
WAIT_FINAL_MODE:
begin
mif_nextstate = MIF_STREAMING_DONE;
end
MIF_STREAMING_DONE:
begin
mif_nextstate = MIF_IDLE;
end
default:
begin
mif_nextstate = MIF_IDLE;
end
endcase
end
// Data flow
reg [LOG2NUM_SETTINGS-1:0] i;
reg [LOG2NUM_C_COUNTERS-1:0] j;
reg [LOG2NUM_DPS_COUNTERS-1:0] k;
always @(posedge mif_clk)
begin
if (mif_rst)
begin
reg_mif_base_addr <= 0;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
else
begin
case (mif_curstate)
MIF_IDLE:
begin
reg_mif_base_addr <= mif_base_addr;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
// ----- ROM FLOW ----- //
SET_INSTR_ADDR: rom_addr <= (mif_started) ? rom_addr + 9'd1 : reg_mif_base_addr; // ROM_ADDR_WIDTH = 9
FETCH_INSTR: ;
WAIT_FOR_ROM_INSTR: ;
STORE_INSTR: reg_instr <= rom_q [LOG2NUM_SETTINGS-1:0]; // Only the last 6 bits are instr bits, rest is reserved
DECODE_ROM_INSTR: ;
SET_DATA_ADDR: rom_addr <= rom_addr + 9'd1; // ROM_ADDR_WIDTH = 9
SET_DATA_ADDR_DLY: ;
FETCH_DATA: ;
WAIT_FOR_ROM_DATA: ;
STORE_DATA: reg_data <= rom_q; // Data is 32 bits
SET_INDEX:
begin
c_cntr_index <= reg_data[22:18];
dps_index <= reg_data[20:16];
end
CHANGE_SETTINGS_REG:
begin
if (reg_instr == OP_C_COUNTERS)
begin
c_settings_reg [c_cntr_index] <= reg_data; //22:18 is c cnt number
is_c_cntr_changed [c_cntr_index] <= 1'b1;
end
else if (reg_instr == OP_DPS)
begin
dps_settings_reg [dps_index] <= reg_data; //20:16 is DPS number
is_dps_changed [dps_index] <= 1'b1;
end
else
begin
c_settings_reg [c_cntr_index] <= c_settings_reg [c_cntr_index];
is_c_cntr_changed [c_cntr_index] <= is_c_cntr_changed[c_cntr_index];
dps_settings_reg [dps_index] <= dps_settings_reg [dps_index];
is_dps_changed [dps_index] <= is_dps_changed [dps_index];
end
settings_reg [reg_instr] <= reg_data;
is_setting_changed [reg_instr] <= 1'b1;
end
// ---------- RECONFIG FLOW ---------- //
// Reading/writing mode takes only one cycle
// (we don't know what mode its in initally)
SET_MODE_REG_INFO:
begin
reconfig_addr <= OP_MODE;
reconfig_read <= 1'b1;
reconfig_write <= 1'b0;
reconfig_write_data <= 0;
end
WAIT_MODE_REG: reconfig_read <= 1'b0;
SAVE_MODE_REG: saved_mode <= reconfig_read_data[0];
SET_WR_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write <= 1'b1;
reconfig_write_data[0] <= MODE_WR; // Want WaitRequest Mode while MIF reader changes Reconfig regs
end
WAIT_WRITE_MODE: reconfig_write <= 1'b0;
// Done saving the mode reg, start writing the reconfig regs
// Start with the highest setting and work our way down
INIT_RECONFIG_PARAMS:
begin
setting_number <= NUM_MIF_SETTINGS - 6'd1;
c_cntr_number <= NUM_C_COUNTERS;
dps_number <= NUM_DPS_COUNTERS;
end
CHECK_RECONFIG_SETTING: ;
// C LOOP
DECREMENT_C_NUM:
begin
c_cntr_number <= c_cntr_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_C_SETTINGS:
begin
if (c_cntr_number == 5'b0)
c_done <= 1'b1;
else
c_done <= c_done;
end
WRITE_C_SETTINGS:
begin
reconfig_addr <= OP_C_COUNTERS;
reconfig_write_data <= c_settings_reg[c_cntr_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End C Loop
// DPS LOOP
DECREMENT_DPS_NUM:
begin
dps_number <= dps_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_DPS_SETTINGS:
begin
if (dps_number == 5'b0)
dps_done <= 1'b1;
else
dps_done <= dps_done;
end
WRITE_DPS_SETTINGS:
begin
reconfig_addr <= OP_DPS;
reconfig_write_data <= dps_settings_reg[dps_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
reconfig_addr <= setting_number; // setting_number = OP_CODE
reconfig_write_data <= settings_reg[setting_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
DECREMENT_SETTING_NUM:
begin
reconfig_write <= 1'b0;
setting_number <= setting_number - 6'd1; // Decrement for looping back
end
// --- Wrote all the changed settings to the Reconfig IP except MODE
// --- Start the Reconfig process (write to start reg) and wait for
// --- waitrequest signal to deassert
START_RECONFIG_CHANGE:
begin
reconfig_addr <= OP_START;
reconfig_write_data <= 1;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
START_RECONFIG_DELAY:
begin
reconfig_write <= 1'b0;
end
WAIT_DONE_SIGNAL: ;
// --- Restore saved MODE reg ONLY if mode hasn't been changed by MIF
SET_MODE_REG:
mode_reg <= (is_setting_changed[OP_MODE]) ? settings_reg [OP_MODE][0] : saved_mode;
WRITE_FINAL_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write_data[0] <= mode_reg;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
WAIT_FINAL_MODE:
begin
reconfig_write <= 1'b0;
end
MIF_STREAMING_DONE: ;
default : ;
endcase
end
end
// RAM block
altsyncram altsyncram_component (
.address_a (rom_addr),
.clock0 (mif_clk),
.q_a (rom_q),
.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 ({32{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 = MIF_FILE_NAME,
altsyncram_component.intended_device_family = "Stratix V",
altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = ROM_NUM_WORDS,
altsyncram_component.operation_mode = "ROM",
altsyncram_component.outdata_aclr_a = "NONE",
altsyncram_component.outdata_reg_a = "CLOCK0",
altsyncram_component.widthad_a = ROM_ADDR_WIDTH,
altsyncram_component.width_a = ROM_DATA_WIDTH,
altsyncram_component.width_byteena_a = 1;
endmodule // mif_reader
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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 acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
// verilator lint_off MULTIDRIVEN
wire [31:0] outb0c0;
wire [31:0] outb0c1;
wire [31:0] outb1c0;
wire [31:0] outb1c1;
reg [7:0] lclmem [7:0];
ma ma0 (.outb0c0(outb0c0), .outb0c1(outb0c1),
.outb1c0(outb1c0), .outb1c1(outb1c1)
);
global_mod #(32'hf00d) global_cell ();
global_mod #(32'hf22d) global_cell2 ();
input clk;
integer cyc=1;
always @ (posedge clk) begin
cyc <= cyc + 1;
`ifdef TEST_VERBOSE
$write("[%0t] cyc%0d: %0x %0x %0x %0x\n", $time, cyc, outb0c0, outb0c1, outb1c0, outb1c1);
`endif
if (cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf22d) $stop;
if (outb0c0 != 32'h00) $stop;
if (outb0c1 != 32'h01) $stop;
if (outb1c0 != 32'h10) $stop;
if (outb1c1 != 32'h11) $stop;
end
if (cyc==3) begin
// Can we scope down and read and write vars?
ma0.mb0.mc0.out <= ma0.mb0.mc0.out + 32'h100;
ma0.mb0.mc1.out <= ma0.mb0.mc1.out + 32'h100;
ma0.mb1.mc0.out <= ma0.mb1.mc0.out + 32'h100;
ma0.mb1.mc1.out <= ma0.mb1.mc1.out + 32'h100;
end
if (cyc==4) begin
// Can we do dotted's inside array sels?
ma0.rmtmem[ma0.mb0.mc0.out[2:0]] = 8'h12;
lclmem[ma0.mb0.mc0.out[2:0]] = 8'h24;
if (outb0c0 != 32'h100) $stop;
if (outb0c1 != 32'h101) $stop;
if (outb1c0 != 32'h110) $stop;
if (outb1c1 != 32'h111) $stop;
end
if (cyc==5) begin
if (ma0.rmtmem[ma0.mb0.mc0.out[2:0]] != 8'h12) $stop;
if (lclmem[ma0.mb0.mc0.out[2:0]] != 8'h24) $stop;
if (outb0c0 != 32'h1100) $stop;
if (outb0c1 != 32'h2101) $stop;
if (outb1c0 != 32'h2110) $stop;
if (outb1c1 != 32'h3111) $stop;
end
if (cyc==6) begin
if (outb0c0 != 32'h31100) $stop;
if (outb0c1 != 32'h02101) $stop;
if (outb1c0 != 32'h42110) $stop;
if (outb1c1 != 32'h03111) $stop;
end
if (cyc==9) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifdef USE_INLINE_MID
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator no_inline_module*/
`else
`ifdef USE_INLINE
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator inline_module*/
`else
`define INLINE_MODULE /*verilator public_module*/
`define INLINE_MID_MODULE /*verilator public_module*/
`endif
`endif
module global_mod;
`INLINE_MODULE
parameter INITVAL = 0;
integer globali;
initial globali = INITVAL;
endmodule
module ma (
output wire [31:0] outb0c0,
output wire [31:0] outb0c1,
output wire [31:0] outb1c0,
output wire [31:0] outb1c1
);
`INLINE_MODULE
reg [7:0] rmtmem [7:0];
mb #(0) mb0 (.outc0(outb0c0), .outc1(outb0c1));
mb #(1) mb1 (.outc0(outb1c0), .outc1(outb1c1));
endmodule
module mb (
output wire [31:0] outc0,
output wire [31:0] outc1
);
`INLINE_MID_MODULE
parameter P2 = 0;
mc #(P2,0) mc0 (.out(outc0));
mc #(P2,1) mc1 (.out(outc1));
global_mod #(32'hf33d) global_cell2 ();
wire reach_up_clk = t.clk;
always @(reach_up_clk) begin
if (P2==0) begin // Only for mb0
if (outc0 !== t.ma0.mb0.mc0.out) $stop; // Top module name and lower instances
if (outc0 !== ma0.mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== ma .mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== mb.mc0.out) $stop; // This module name and lower instances
if (outc0 !== mb0.mc0.out) $stop; // Upper instance name and lower instances
if (outc0 !== mc0.out) $stop; // Lower instances
if (outc1 !== t.ma0.mb0.mc1.out) $stop; // Top module name and lower instances
if (outc1 !== ma0.mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== ma .mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== mb.mc1.out) $stop; // This module name and lower instances
if (outc1 !== mb0.mc1.out) $stop; // Upper instance name and lower instances
if (outc1 !== mc1.out) $stop; // Lower instances
end
end
endmodule
module mc (output reg [31:0] out);
`INLINE_MODULE
parameter P2 = 0;
parameter P3 = 0;
initial begin
out = {24'h0,P2[3:0],P3[3:0]};
//$write("%m P2=%0x p3=%0x out=%x\n",P2, P3, out);
end
// Can we look from the top module name down?
wire [31:0] reach_up_cyc = t.cyc;
always @ (posedge t.clk) begin
//$write("[%0t] %m: Got reachup, cyc=%0d\n", $time, reach_up_cyc);
if (reach_up_cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf33d) $stop;
end
if (reach_up_cyc==4) begin
out[15:12] <= {P2[3:0]+P3[3:0]+4'd1};
end
if (reach_up_cyc==5) begin
// Can we set another instance?
if (P3==1) begin // Without this, there are two possible correct answers...
mc0.out[19:16] <= {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2};
$display("%m Set %x->%x %x %x %x %x",mc0.out, {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2}, mc0.out[19:16],P2[3:0],P3[3:0],4'd2);
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
// verilator lint_off MULTIDRIVEN
wire [31:0] outb0c0;
wire [31:0] outb0c1;
wire [31:0] outb1c0;
wire [31:0] outb1c1;
reg [7:0] lclmem [7:0];
ma ma0 (.outb0c0(outb0c0), .outb0c1(outb0c1),
.outb1c0(outb1c0), .outb1c1(outb1c1)
);
global_mod #(32'hf00d) global_cell ();
global_mod #(32'hf22d) global_cell2 ();
input clk;
integer cyc=1;
always @ (posedge clk) begin
cyc <= cyc + 1;
`ifdef TEST_VERBOSE
$write("[%0t] cyc%0d: %0x %0x %0x %0x\n", $time, cyc, outb0c0, outb0c1, outb1c0, outb1c1);
`endif
if (cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf22d) $stop;
if (outb0c0 != 32'h00) $stop;
if (outb0c1 != 32'h01) $stop;
if (outb1c0 != 32'h10) $stop;
if (outb1c1 != 32'h11) $stop;
end
if (cyc==3) begin
// Can we scope down and read and write vars?
ma0.mb0.mc0.out <= ma0.mb0.mc0.out + 32'h100;
ma0.mb0.mc1.out <= ma0.mb0.mc1.out + 32'h100;
ma0.mb1.mc0.out <= ma0.mb1.mc0.out + 32'h100;
ma0.mb1.mc1.out <= ma0.mb1.mc1.out + 32'h100;
end
if (cyc==4) begin
// Can we do dotted's inside array sels?
ma0.rmtmem[ma0.mb0.mc0.out[2:0]] = 8'h12;
lclmem[ma0.mb0.mc0.out[2:0]] = 8'h24;
if (outb0c0 != 32'h100) $stop;
if (outb0c1 != 32'h101) $stop;
if (outb1c0 != 32'h110) $stop;
if (outb1c1 != 32'h111) $stop;
end
if (cyc==5) begin
if (ma0.rmtmem[ma0.mb0.mc0.out[2:0]] != 8'h12) $stop;
if (lclmem[ma0.mb0.mc0.out[2:0]] != 8'h24) $stop;
if (outb0c0 != 32'h1100) $stop;
if (outb0c1 != 32'h2101) $stop;
if (outb1c0 != 32'h2110) $stop;
if (outb1c1 != 32'h3111) $stop;
end
if (cyc==6) begin
if (outb0c0 != 32'h31100) $stop;
if (outb0c1 != 32'h02101) $stop;
if (outb1c0 != 32'h42110) $stop;
if (outb1c1 != 32'h03111) $stop;
end
if (cyc==9) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifdef USE_INLINE_MID
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator no_inline_module*/
`else
`ifdef USE_INLINE
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator inline_module*/
`else
`define INLINE_MODULE /*verilator public_module*/
`define INLINE_MID_MODULE /*verilator public_module*/
`endif
`endif
module global_mod;
`INLINE_MODULE
parameter INITVAL = 0;
integer globali;
initial globali = INITVAL;
endmodule
module ma (
output wire [31:0] outb0c0,
output wire [31:0] outb0c1,
output wire [31:0] outb1c0,
output wire [31:0] outb1c1
);
`INLINE_MODULE
reg [7:0] rmtmem [7:0];
mb #(0) mb0 (.outc0(outb0c0), .outc1(outb0c1));
mb #(1) mb1 (.outc0(outb1c0), .outc1(outb1c1));
endmodule
module mb (
output wire [31:0] outc0,
output wire [31:0] outc1
);
`INLINE_MID_MODULE
parameter P2 = 0;
mc #(P2,0) mc0 (.out(outc0));
mc #(P2,1) mc1 (.out(outc1));
global_mod #(32'hf33d) global_cell2 ();
wire reach_up_clk = t.clk;
always @(reach_up_clk) begin
if (P2==0) begin // Only for mb0
if (outc0 !== t.ma0.mb0.mc0.out) $stop; // Top module name and lower instances
if (outc0 !== ma0.mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== ma .mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== mb.mc0.out) $stop; // This module name and lower instances
if (outc0 !== mb0.mc0.out) $stop; // Upper instance name and lower instances
if (outc0 !== mc0.out) $stop; // Lower instances
if (outc1 !== t.ma0.mb0.mc1.out) $stop; // Top module name and lower instances
if (outc1 !== ma0.mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== ma .mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== mb.mc1.out) $stop; // This module name and lower instances
if (outc1 !== mb0.mc1.out) $stop; // Upper instance name and lower instances
if (outc1 !== mc1.out) $stop; // Lower instances
end
end
endmodule
module mc (output reg [31:0] out);
`INLINE_MODULE
parameter P2 = 0;
parameter P3 = 0;
initial begin
out = {24'h0,P2[3:0],P3[3:0]};
//$write("%m P2=%0x p3=%0x out=%x\n",P2, P3, out);
end
// Can we look from the top module name down?
wire [31:0] reach_up_cyc = t.cyc;
always @ (posedge t.clk) begin
//$write("[%0t] %m: Got reachup, cyc=%0d\n", $time, reach_up_cyc);
if (reach_up_cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf33d) $stop;
end
if (reach_up_cyc==4) begin
out[15:12] <= {P2[3:0]+P3[3:0]+4'd1};
end
if (reach_up_cyc==5) begin
// Can we set another instance?
if (P3==1) begin // Without this, there are two possible correct answers...
mc0.out[19:16] <= {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2};
$display("%m Set %x->%x %x %x %x %x",mc0.out, {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2}, mc0.out[19:16],P2[3:0],P3[3:0],4'd2);
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
// verilator lint_off MULTIDRIVEN
wire [31:0] outb0c0;
wire [31:0] outb0c1;
wire [31:0] outb1c0;
wire [31:0] outb1c1;
reg [7:0] lclmem [7:0];
ma ma0 (.outb0c0(outb0c0), .outb0c1(outb0c1),
.outb1c0(outb1c0), .outb1c1(outb1c1)
);
global_mod #(32'hf00d) global_cell ();
global_mod #(32'hf22d) global_cell2 ();
input clk;
integer cyc=1;
always @ (posedge clk) begin
cyc <= cyc + 1;
`ifdef TEST_VERBOSE
$write("[%0t] cyc%0d: %0x %0x %0x %0x\n", $time, cyc, outb0c0, outb0c1, outb1c0, outb1c1);
`endif
if (cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf22d) $stop;
if (outb0c0 != 32'h00) $stop;
if (outb0c1 != 32'h01) $stop;
if (outb1c0 != 32'h10) $stop;
if (outb1c1 != 32'h11) $stop;
end
if (cyc==3) begin
// Can we scope down and read and write vars?
ma0.mb0.mc0.out <= ma0.mb0.mc0.out + 32'h100;
ma0.mb0.mc1.out <= ma0.mb0.mc1.out + 32'h100;
ma0.mb1.mc0.out <= ma0.mb1.mc0.out + 32'h100;
ma0.mb1.mc1.out <= ma0.mb1.mc1.out + 32'h100;
end
if (cyc==4) begin
// Can we do dotted's inside array sels?
ma0.rmtmem[ma0.mb0.mc0.out[2:0]] = 8'h12;
lclmem[ma0.mb0.mc0.out[2:0]] = 8'h24;
if (outb0c0 != 32'h100) $stop;
if (outb0c1 != 32'h101) $stop;
if (outb1c0 != 32'h110) $stop;
if (outb1c1 != 32'h111) $stop;
end
if (cyc==5) begin
if (ma0.rmtmem[ma0.mb0.mc0.out[2:0]] != 8'h12) $stop;
if (lclmem[ma0.mb0.mc0.out[2:0]] != 8'h24) $stop;
if (outb0c0 != 32'h1100) $stop;
if (outb0c1 != 32'h2101) $stop;
if (outb1c0 != 32'h2110) $stop;
if (outb1c1 != 32'h3111) $stop;
end
if (cyc==6) begin
if (outb0c0 != 32'h31100) $stop;
if (outb0c1 != 32'h02101) $stop;
if (outb1c0 != 32'h42110) $stop;
if (outb1c1 != 32'h03111) $stop;
end
if (cyc==9) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifdef USE_INLINE_MID
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator no_inline_module*/
`else
`ifdef USE_INLINE
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator inline_module*/
`else
`define INLINE_MODULE /*verilator public_module*/
`define INLINE_MID_MODULE /*verilator public_module*/
`endif
`endif
module global_mod;
`INLINE_MODULE
parameter INITVAL = 0;
integer globali;
initial globali = INITVAL;
endmodule
module ma (
output wire [31:0] outb0c0,
output wire [31:0] outb0c1,
output wire [31:0] outb1c0,
output wire [31:0] outb1c1
);
`INLINE_MODULE
reg [7:0] rmtmem [7:0];
mb #(0) mb0 (.outc0(outb0c0), .outc1(outb0c1));
mb #(1) mb1 (.outc0(outb1c0), .outc1(outb1c1));
endmodule
module mb (
output wire [31:0] outc0,
output wire [31:0] outc1
);
`INLINE_MID_MODULE
parameter P2 = 0;
mc #(P2,0) mc0 (.out(outc0));
mc #(P2,1) mc1 (.out(outc1));
global_mod #(32'hf33d) global_cell2 ();
wire reach_up_clk = t.clk;
always @(reach_up_clk) begin
if (P2==0) begin // Only for mb0
if (outc0 !== t.ma0.mb0.mc0.out) $stop; // Top module name and lower instances
if (outc0 !== ma0.mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== ma .mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== mb.mc0.out) $stop; // This module name and lower instances
if (outc0 !== mb0.mc0.out) $stop; // Upper instance name and lower instances
if (outc0 !== mc0.out) $stop; // Lower instances
if (outc1 !== t.ma0.mb0.mc1.out) $stop; // Top module name and lower instances
if (outc1 !== ma0.mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== ma .mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== mb.mc1.out) $stop; // This module name and lower instances
if (outc1 !== mb0.mc1.out) $stop; // Upper instance name and lower instances
if (outc1 !== mc1.out) $stop; // Lower instances
end
end
endmodule
module mc (output reg [31:0] out);
`INLINE_MODULE
parameter P2 = 0;
parameter P3 = 0;
initial begin
out = {24'h0,P2[3:0],P3[3:0]};
//$write("%m P2=%0x p3=%0x out=%x\n",P2, P3, out);
end
// Can we look from the top module name down?
wire [31:0] reach_up_cyc = t.cyc;
always @ (posedge t.clk) begin
//$write("[%0t] %m: Got reachup, cyc=%0d\n", $time, reach_up_cyc);
if (reach_up_cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf33d) $stop;
end
if (reach_up_cyc==4) begin
out[15:12] <= {P2[3:0]+P3[3:0]+4'd1};
end
if (reach_up_cyc==5) begin
// Can we set another instance?
if (P3==1) begin // Without this, there are two possible correct answers...
mc0.out[19:16] <= {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2};
$display("%m Set %x->%x %x %x %x %x",mc0.out, {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2}, mc0.out[19:16],P2[3:0],P3[3:0],4'd2);
end
end
end
endmodule
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Low-latency RAM-based FIFO. Uses a low-latency register-based FIFO to
// mask the latency of the RAM-based FIFO.
//
// This FIFO uses additional area beyond the FIFO capacity and
// counters in order to compensate for the latency in a normal RAM FIFO.
//
//===----------------------------------------------------------------------===//
module acl_ll_ram_fifo
#(
parameter integer DATA_WIDTH = 32, // >0
parameter integer DEPTH = 32 // >3
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
output logic empty,
output logic full
);
localparam SEL_RAM = 0;
localparam SEL_LL = 1;
// Three FIFOs:
// 1. data - RAM FIFO (normal latency)
// 2. data - LL REG FIFO
// 3. selector - LL REG FIFO
//
// Selector determines which of the two data FIFOs to select the current
// output from.
//
// TODO Implementation note:
// It's probably possible to use a more compact storage mechanism than
// a FIFO for the selector because the sequence of selector values
// should be highly compressible (e.g. long sequences of SEL_RAM). The
// selector FIFO can probably be replaced with a small number of counters.
// A future enhancement.
logic [DATA_WIDTH-1:0] ram_data_in, ram_data_out;
logic ram_valid_in, ram_valid_out, ram_stall_in, ram_stall_out;
logic [DATA_WIDTH-1:0] ll_data_in, ll_data_out;
logic ll_valid_in, ll_valid_out, ll_stall_in, ll_stall_out;
logic sel_data_in, sel_data_out;
logic sel_valid_in, sel_valid_out, sel_stall_in, sel_stall_out;
// Top-level outputs.
assign data_out = sel_data_out == SEL_LL ? ll_data_out : ram_data_out;
assign valid_out = sel_valid_out; // the required ll_valid_out/ram_valid_out must also be asserted
assign stall_out = sel_stall_out;
// RAM FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH - 3),
.IMPL("ram")
)
ram_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ram_data_in),
.data_out(ram_data_out),
.valid_in(ram_valid_in),
.valid_out(ram_valid_out),
.stall_in(ram_stall_in),
.stall_out(ram_stall_out)
);
assign ram_data_in = data_in;
assign ram_valid_in = valid_in & ll_stall_out; // only write to RAM FIFO if LL FIFO is stalled
assign ram_stall_in = (sel_data_out != SEL_RAM) | stall_in;
// Low-latency FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(3),
.IMPL("ll_reg")
)
ll_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ll_data_in),
.data_out(ll_data_out),
.valid_in(ll_valid_in),
.valid_out(ll_valid_out),
.stall_in(ll_stall_in),
.stall_out(ll_stall_out)
);
assign ll_data_in = data_in;
assign ll_valid_in = valid_in & ~ll_stall_out; // write to LL FIFO if it is not stalled
assign ll_stall_in = (sel_data_out != SEL_LL) | stall_in;
// Selector FIFO.
acl_data_fifo #(
.DATA_WIDTH(1),
.DEPTH(DEPTH),
.IMPL("ll_reg")
)
sel_fifo (
.clock(clock),
.resetn(resetn),
.data_in(sel_data_in),
.data_out(sel_data_out),
.valid_in(sel_valid_in),
.valid_out(sel_valid_out),
.stall_in(sel_stall_in),
.stall_out(sel_stall_out),
.empty(empty),
.full(full)
);
assign sel_data_in = ll_valid_in ? SEL_LL : SEL_RAM;
assign sel_valid_in = valid_in;
assign sel_stall_in = stall_in;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Low-latency RAM-based FIFO. Uses a low-latency register-based FIFO to
// mask the latency of the RAM-based FIFO.
//
// This FIFO uses additional area beyond the FIFO capacity and
// counters in order to compensate for the latency in a normal RAM FIFO.
//
//===----------------------------------------------------------------------===//
module acl_ll_ram_fifo
#(
parameter integer DATA_WIDTH = 32, // >0
parameter integer DEPTH = 32 // >3
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
output logic empty,
output logic full
);
localparam SEL_RAM = 0;
localparam SEL_LL = 1;
// Three FIFOs:
// 1. data - RAM FIFO (normal latency)
// 2. data - LL REG FIFO
// 3. selector - LL REG FIFO
//
// Selector determines which of the two data FIFOs to select the current
// output from.
//
// TODO Implementation note:
// It's probably possible to use a more compact storage mechanism than
// a FIFO for the selector because the sequence of selector values
// should be highly compressible (e.g. long sequences of SEL_RAM). The
// selector FIFO can probably be replaced with a small number of counters.
// A future enhancement.
logic [DATA_WIDTH-1:0] ram_data_in, ram_data_out;
logic ram_valid_in, ram_valid_out, ram_stall_in, ram_stall_out;
logic [DATA_WIDTH-1:0] ll_data_in, ll_data_out;
logic ll_valid_in, ll_valid_out, ll_stall_in, ll_stall_out;
logic sel_data_in, sel_data_out;
logic sel_valid_in, sel_valid_out, sel_stall_in, sel_stall_out;
// Top-level outputs.
assign data_out = sel_data_out == SEL_LL ? ll_data_out : ram_data_out;
assign valid_out = sel_valid_out; // the required ll_valid_out/ram_valid_out must also be asserted
assign stall_out = sel_stall_out;
// RAM FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH - 3),
.IMPL("ram")
)
ram_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ram_data_in),
.data_out(ram_data_out),
.valid_in(ram_valid_in),
.valid_out(ram_valid_out),
.stall_in(ram_stall_in),
.stall_out(ram_stall_out)
);
assign ram_data_in = data_in;
assign ram_valid_in = valid_in & ll_stall_out; // only write to RAM FIFO if LL FIFO is stalled
assign ram_stall_in = (sel_data_out != SEL_RAM) | stall_in;
// Low-latency FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(3),
.IMPL("ll_reg")
)
ll_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ll_data_in),
.data_out(ll_data_out),
.valid_in(ll_valid_in),
.valid_out(ll_valid_out),
.stall_in(ll_stall_in),
.stall_out(ll_stall_out)
);
assign ll_data_in = data_in;
assign ll_valid_in = valid_in & ~ll_stall_out; // write to LL FIFO if it is not stalled
assign ll_stall_in = (sel_data_out != SEL_LL) | stall_in;
// Selector FIFO.
acl_data_fifo #(
.DATA_WIDTH(1),
.DEPTH(DEPTH),
.IMPL("ll_reg")
)
sel_fifo (
.clock(clock),
.resetn(resetn),
.data_in(sel_data_in),
.data_out(sel_data_out),
.valid_in(sel_valid_in),
.valid_out(sel_valid_out),
.stall_in(sel_stall_in),
.stall_out(sel_stall_out),
.empty(empty),
.full(full)
);
assign sel_data_in = ll_valid_in ? SEL_LL : SEL_RAM;
assign sel_valid_in = valid_in;
assign sel_stall_in = stall_in;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Low-latency RAM-based FIFO. Uses a low-latency register-based FIFO to
// mask the latency of the RAM-based FIFO.
//
// This FIFO uses additional area beyond the FIFO capacity and
// counters in order to compensate for the latency in a normal RAM FIFO.
//
//===----------------------------------------------------------------------===//
module acl_ll_ram_fifo
#(
parameter integer DATA_WIDTH = 32, // >0
parameter integer DEPTH = 32 // >3
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
output logic empty,
output logic full
);
localparam SEL_RAM = 0;
localparam SEL_LL = 1;
// Three FIFOs:
// 1. data - RAM FIFO (normal latency)
// 2. data - LL REG FIFO
// 3. selector - LL REG FIFO
//
// Selector determines which of the two data FIFOs to select the current
// output from.
//
// TODO Implementation note:
// It's probably possible to use a more compact storage mechanism than
// a FIFO for the selector because the sequence of selector values
// should be highly compressible (e.g. long sequences of SEL_RAM). The
// selector FIFO can probably be replaced with a small number of counters.
// A future enhancement.
logic [DATA_WIDTH-1:0] ram_data_in, ram_data_out;
logic ram_valid_in, ram_valid_out, ram_stall_in, ram_stall_out;
logic [DATA_WIDTH-1:0] ll_data_in, ll_data_out;
logic ll_valid_in, ll_valid_out, ll_stall_in, ll_stall_out;
logic sel_data_in, sel_data_out;
logic sel_valid_in, sel_valid_out, sel_stall_in, sel_stall_out;
// Top-level outputs.
assign data_out = sel_data_out == SEL_LL ? ll_data_out : ram_data_out;
assign valid_out = sel_valid_out; // the required ll_valid_out/ram_valid_out must also be asserted
assign stall_out = sel_stall_out;
// RAM FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH - 3),
.IMPL("ram")
)
ram_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ram_data_in),
.data_out(ram_data_out),
.valid_in(ram_valid_in),
.valid_out(ram_valid_out),
.stall_in(ram_stall_in),
.stall_out(ram_stall_out)
);
assign ram_data_in = data_in;
assign ram_valid_in = valid_in & ll_stall_out; // only write to RAM FIFO if LL FIFO is stalled
assign ram_stall_in = (sel_data_out != SEL_RAM) | stall_in;
// Low-latency FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(3),
.IMPL("ll_reg")
)
ll_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ll_data_in),
.data_out(ll_data_out),
.valid_in(ll_valid_in),
.valid_out(ll_valid_out),
.stall_in(ll_stall_in),
.stall_out(ll_stall_out)
);
assign ll_data_in = data_in;
assign ll_valid_in = valid_in & ~ll_stall_out; // write to LL FIFO if it is not stalled
assign ll_stall_in = (sel_data_out != SEL_LL) | stall_in;
// Selector FIFO.
acl_data_fifo #(
.DATA_WIDTH(1),
.DEPTH(DEPTH),
.IMPL("ll_reg")
)
sel_fifo (
.clock(clock),
.resetn(resetn),
.data_in(sel_data_in),
.data_out(sel_data_out),
.valid_in(sel_valid_in),
.valid_out(sel_valid_out),
.stall_in(sel_stall_in),
.stall_out(sel_stall_out),
.empty(empty),
.full(full)
);
assign sel_data_in = ll_valid_in ? SEL_LL : SEL_RAM;
assign sel_valid_in = valid_in;
assign sel_stall_in = stall_in;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
//
// The given generate loops should only access valid bits of mask, since that
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 4
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, but for good measure we do one clock
// cycle.
integer count;
initial begin
count = 0;
end
always @(posedge clk) begin
if (count == 1) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
count = count + 1;
end
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that rely on short-circuiting of the logic to avoid errors.
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) || ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g < SIZE) -> ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical infer generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g < SIZE ? MASK[g] : 1'b0) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
// The other way round
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g >= SIZE ? 1'b0 : MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t;
localparam P4 = f_add(P3,1);
localparam P8 = f_add2(P3,P3,f_add(1,1));
localparam P5 = f_while(7);
localparam P16 = f_for(P4);
localparam P18 = f_case(P4);
localparam P6 = f_return(P4);
localparam P3 = 3;
initial begin
`ifdef TEST_VERBOSE
$display("P5=%0d P8=%0d P16=%0d P18=%0d",P5,P8,P16,P18);
`endif
if (P3 !== 3) $stop;
if (P4 !== 4) $stop;
if (P5 !== 5) $stop;
if (P6 !== 6) $stop;
if (P8 !== 8) $stop;
if (P16 !== 16) $stop;
if (P18 !== 18) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
function integer f_add(input [31:0] a, input [31:0] b);
f_add = a+b;
endfunction
// Speced ok: function called from function
function integer f_add2(input [31:0] a, input [31:0] b, input [31:0] c);
f_add2 = f_add(a,b)+c;
endfunction
// Speced ok: local variables
function integer f_for(input [31:0] a);
integer i;
integer times;
begin
times = 1;
for (i=0; i<a; i=i+1) times = times*2;
f_for = times;
end
endfunction
function integer f_while(input [31:0] a);
integer i;
begin
i=0;
begin : named
f_while = 1;
end : named
while (i<=a) begin
if (i[0]) f_while = f_while + 1;
i = i + 1;
end
end
endfunction
// Speced ok: local variables
function integer f_case(input [31:0] a);
case(a)
32'd1: f_case = 1;
32'd0, 32'd4: f_case = 18;
32'd1234: begin $display("never get here"); $stop; end
default: f_case = 99;
endcase
endfunction
function integer f_return(input [31:0] a);
integer out = 2;
while (1) begin
out = out+1;
if (a>1) break;
end
while (1) begin
out = out+1;
if (a>1) return 2+out;
end
f_return = 0;
endfunction
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t;
localparam P4 = f_add(P3,1);
localparam P8 = f_add2(P3,P3,f_add(1,1));
localparam P5 = f_while(7);
localparam P16 = f_for(P4);
localparam P18 = f_case(P4);
localparam P6 = f_return(P4);
localparam P3 = 3;
initial begin
`ifdef TEST_VERBOSE
$display("P5=%0d P8=%0d P16=%0d P18=%0d",P5,P8,P16,P18);
`endif
if (P3 !== 3) $stop;
if (P4 !== 4) $stop;
if (P5 !== 5) $stop;
if (P6 !== 6) $stop;
if (P8 !== 8) $stop;
if (P16 !== 16) $stop;
if (P18 !== 18) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
function integer f_add(input [31:0] a, input [31:0] b);
f_add = a+b;
endfunction
// Speced ok: function called from function
function integer f_add2(input [31:0] a, input [31:0] b, input [31:0] c);
f_add2 = f_add(a,b)+c;
endfunction
// Speced ok: local variables
function integer f_for(input [31:0] a);
integer i;
integer times;
begin
times = 1;
for (i=0; i<a; i=i+1) times = times*2;
f_for = times;
end
endfunction
function integer f_while(input [31:0] a);
integer i;
begin
i=0;
begin : named
f_while = 1;
end : named
while (i<=a) begin
if (i[0]) f_while = f_while + 1;
i = i + 1;
end
end
endfunction
// Speced ok: local variables
function integer f_case(input [31:0] a);
case(a)
32'd1: f_case = 1;
32'd0, 32'd4: f_case = 18;
32'd1234: begin $display("never get here"); $stop; end
default: f_case = 99;
endcase
endfunction
function integer f_return(input [31:0] a);
integer out = 2;
while (1) begin
out = out+1;
if (a>1) break;
end
while (1) begin
out = out+1;
if (a>1) return 2+out;
end
f_return = 0;
endfunction
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t;
localparam P4 = f_add(P3,1);
localparam P8 = f_add2(P3,P3,f_add(1,1));
localparam P5 = f_while(7);
localparam P16 = f_for(P4);
localparam P18 = f_case(P4);
localparam P6 = f_return(P4);
localparam P3 = 3;
initial begin
`ifdef TEST_VERBOSE
$display("P5=%0d P8=%0d P16=%0d P18=%0d",P5,P8,P16,P18);
`endif
if (P3 !== 3) $stop;
if (P4 !== 4) $stop;
if (P5 !== 5) $stop;
if (P6 !== 6) $stop;
if (P8 !== 8) $stop;
if (P16 !== 16) $stop;
if (P18 !== 18) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
function integer f_add(input [31:0] a, input [31:0] b);
f_add = a+b;
endfunction
// Speced ok: function called from function
function integer f_add2(input [31:0] a, input [31:0] b, input [31:0] c);
f_add2 = f_add(a,b)+c;
endfunction
// Speced ok: local variables
function integer f_for(input [31:0] a);
integer i;
integer times;
begin
times = 1;
for (i=0; i<a; i=i+1) times = times*2;
f_for = times;
end
endfunction
function integer f_while(input [31:0] a);
integer i;
begin
i=0;
begin : named
f_while = 1;
end : named
while (i<=a) begin
if (i[0]) f_while = f_while + 1;
i = i + 1;
end
end
endfunction
// Speced ok: local variables
function integer f_case(input [31:0] a);
case(a)
32'd1: f_case = 1;
32'd0, 32'd4: f_case = 18;
32'd1234: begin $display("never get here"); $stop; end
default: f_case = 99;
endcase
endfunction
function integer f_return(input [31:0] a);
integer out = 2;
while (1) begin
out = out+1;
if (a>1) break;
end
while (1) begin
out = out+1;
if (a>1) return 2+out;
end
f_return = 0;
endfunction
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: INSTITUTO TECNOLOGICO DE COSTA RICA
// Engineer: MAURICIO CARVAJAL DELGADO
//
// Create Date: 11:24:36 03/17/2013
// Design Name:
// Module Name: Coun_Baud
// Project Name:
// Target Devices:
// Tool versions:
// Description: Contador de Bauds, lo que genera es un tick
//////////////////////////////////////////////////////////////////////////////////
module Coun_Baud // este modo es para generar los pulsos necesarios para el modo receptor y transmisor
#(
parameter N=10, // number of bits incounter = log2(M)
M=656 // mod-M Para una frecuencia de relog 100 MHZ --->9600bauds
) // M se obtiene de 100MHZ/(2X8X9600)
(
input wire clk, reset,
output wire max_tick
);
// Declaracion de Se;ales
reg [N-1:0] r_reg=0;
wire [N-1:0] r_next;
// Registro de estado
always @ (posedge clk , posedge reset)
if (reset)
r_reg <= 0 ;
else
r_reg <= r_next;
// Logica de estado siguiente
assign r_next = (r_reg==(M-1)) ? 0 : r_reg + 1;
//Logica de salida
assign max_tick = (r_reg==(M-1)) ? 1'b1 : 1'b0;
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: INSTITUTO TECNOLOGICO DE COSTA RICA
// Engineer: MAURICIO CARVAJAL DELGADO
//
// Create Date: 11:24:36 03/17/2013
// Design Name:
// Module Name: Coun_Baud
// Project Name:
// Target Devices:
// Tool versions:
// Description: Contador de Bauds, lo que genera es un tick
//////////////////////////////////////////////////////////////////////////////////
module Coun_Baud // este modo es para generar los pulsos necesarios para el modo receptor y transmisor
#(
parameter N=10, // number of bits incounter = log2(M)
M=656 // mod-M Para una frecuencia de relog 100 MHZ --->9600bauds
) // M se obtiene de 100MHZ/(2X8X9600)
(
input wire clk, reset,
output wire max_tick
);
// Declaracion de Se;ales
reg [N-1:0] r_reg=0;
wire [N-1:0] r_next;
// Registro de estado
always @ (posedge clk , posedge reset)
if (reset)
r_reg <= 0 ;
else
r_reg <= r_next;
// Logica de estado siguiente
assign r_next = (r_reg==(M-1)) ? 0 : r_reg + 1;
//Logica de salida
assign max_tick = (r_reg==(M-1)) ? 1'b1 : 1'b0;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This is almost an exact copy of the lsu_burst_master, but has special support
// for placing items into a a block ram rather than a fifo. I'd rather leave them
// as separate files rather than complicating the already existing lsu's which are
// are known to work.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_prefetch_block (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
cache_line_to_write_to,
control_done,
control_early_done,
// user logic inputs and outputs
cache_line_to_read_from,
user_buffer_address,
user_buffer_data,
user_data_available,
read_reg_enable,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MWIDTH = DATAWIDTH;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter N=8;
parameter LOG2N=3;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
input [LOG2N-1:0] cache_line_to_write_to;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input [LOG2N-1:0] cache_line_to_read_from;
input [FIFODEPTH_LOG2-1:0] user_buffer_address;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
input read_reg_enable;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
reg [FIFODEPTH_LOG2:0] w_user_buffer_address;
// Pipelining
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata /* synthesis dont_merge */;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// user buffer address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
if(control_go == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
w_user_buffer_address <= w_user_buffer_address + r_avm_readdatavalid;
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = 1'b0;
assign control_early_done = 1'b0;
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = 0;
/* --- Pipeline Return Path --- */
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= master_readdata;
r_avm_readdatavalid <= master_readdatavalid;
end
end
assign user_data_available = w_user_buffer_address[FIFODEPTH_LOG2];
altsyncram altsyncram_component (
.clock0 (clk),
.address_a ({cache_line_to_write_to,w_user_buffer_address[FIFODEPTH_LOG2-1:0]}),
.wren_a (r_avm_readdatavalid),
.data_a (r_avm_readdata),
.address_b ({cache_line_to_read_from,user_buffer_address}),
.q_b (user_buffer_data),
.aclr0 (1'b0),
.aclr1 (1'b0),
.addressstall_a (1'b0),
.addressstall_b (~read_reg_enable),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_b ({DATAWIDTH{1'b1}}),
.eccstatus (),
.q_a (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_b = "NONE",
altsyncram_component.address_reg_b = "CLOCK0",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_input_b = "BYPASS",
altsyncram_component.clock_enable_output_b = "BYPASS",
altsyncram_component.intended_device_family = "Stratix IV",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = N*FIFODEPTH,
altsyncram_component.numwords_b = N*FIFODEPTH,
altsyncram_component.operation_mode = "DUAL_PORT",
altsyncram_component.outdata_aclr_b = "NONE",
altsyncram_component.outdata_reg_b = "UNREGISTERED",
altsyncram_component.power_up_uninitialized = "FALSE",
altsyncram_component.read_during_write_mode_mixed_ports = "DONT_CARE",
altsyncram_component.widthad_a = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.widthad_b = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.width_a = DATAWIDTH,
altsyncram_component.width_b = DATAWIDTH,
altsyncram_component.width_byteena_a = 1;
assign o_active = |length;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This is almost an exact copy of the lsu_burst_master, but has special support
// for placing items into a a block ram rather than a fifo. I'd rather leave them
// as separate files rather than complicating the already existing lsu's which are
// are known to work.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_prefetch_block (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
cache_line_to_write_to,
control_done,
control_early_done,
// user logic inputs and outputs
cache_line_to_read_from,
user_buffer_address,
user_buffer_data,
user_data_available,
read_reg_enable,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MWIDTH = DATAWIDTH;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter N=8;
parameter LOG2N=3;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
input [LOG2N-1:0] cache_line_to_write_to;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input [LOG2N-1:0] cache_line_to_read_from;
input [FIFODEPTH_LOG2-1:0] user_buffer_address;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
input read_reg_enable;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
reg [FIFODEPTH_LOG2:0] w_user_buffer_address;
// Pipelining
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata /* synthesis dont_merge */;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// user buffer address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
if(control_go == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
w_user_buffer_address <= w_user_buffer_address + r_avm_readdatavalid;
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = 1'b0;
assign control_early_done = 1'b0;
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = 0;
/* --- Pipeline Return Path --- */
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= master_readdata;
r_avm_readdatavalid <= master_readdatavalid;
end
end
assign user_data_available = w_user_buffer_address[FIFODEPTH_LOG2];
altsyncram altsyncram_component (
.clock0 (clk),
.address_a ({cache_line_to_write_to,w_user_buffer_address[FIFODEPTH_LOG2-1:0]}),
.wren_a (r_avm_readdatavalid),
.data_a (r_avm_readdata),
.address_b ({cache_line_to_read_from,user_buffer_address}),
.q_b (user_buffer_data),
.aclr0 (1'b0),
.aclr1 (1'b0),
.addressstall_a (1'b0),
.addressstall_b (~read_reg_enable),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_b ({DATAWIDTH{1'b1}}),
.eccstatus (),
.q_a (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_b = "NONE",
altsyncram_component.address_reg_b = "CLOCK0",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_input_b = "BYPASS",
altsyncram_component.clock_enable_output_b = "BYPASS",
altsyncram_component.intended_device_family = "Stratix IV",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = N*FIFODEPTH,
altsyncram_component.numwords_b = N*FIFODEPTH,
altsyncram_component.operation_mode = "DUAL_PORT",
altsyncram_component.outdata_aclr_b = "NONE",
altsyncram_component.outdata_reg_b = "UNREGISTERED",
altsyncram_component.power_up_uninitialized = "FALSE",
altsyncram_component.read_during_write_mode_mixed_ports = "DONT_CARE",
altsyncram_component.widthad_a = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.widthad_b = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.width_a = DATAWIDTH,
altsyncram_component.width_b = DATAWIDTH,
altsyncram_component.width_byteena_a = 1;
assign o_active = |length;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This is almost an exact copy of the lsu_burst_master, but has special support
// for placing items into a a block ram rather than a fifo. I'd rather leave them
// as separate files rather than complicating the already existing lsu's which are
// are known to work.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_prefetch_block (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
cache_line_to_write_to,
control_done,
control_early_done,
// user logic inputs and outputs
cache_line_to_read_from,
user_buffer_address,
user_buffer_data,
user_data_available,
read_reg_enable,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MWIDTH = DATAWIDTH;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter N=8;
parameter LOG2N=3;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
input [LOG2N-1:0] cache_line_to_write_to;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input [LOG2N-1:0] cache_line_to_read_from;
input [FIFODEPTH_LOG2-1:0] user_buffer_address;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
input read_reg_enable;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
reg [FIFODEPTH_LOG2:0] w_user_buffer_address;
// Pipelining
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata /* synthesis dont_merge */;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// user buffer address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
if(control_go == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
w_user_buffer_address <= w_user_buffer_address + r_avm_readdatavalid;
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = 1'b0;
assign control_early_done = 1'b0;
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = 0;
/* --- Pipeline Return Path --- */
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= master_readdata;
r_avm_readdatavalid <= master_readdatavalid;
end
end
assign user_data_available = w_user_buffer_address[FIFODEPTH_LOG2];
altsyncram altsyncram_component (
.clock0 (clk),
.address_a ({cache_line_to_write_to,w_user_buffer_address[FIFODEPTH_LOG2-1:0]}),
.wren_a (r_avm_readdatavalid),
.data_a (r_avm_readdata),
.address_b ({cache_line_to_read_from,user_buffer_address}),
.q_b (user_buffer_data),
.aclr0 (1'b0),
.aclr1 (1'b0),
.addressstall_a (1'b0),
.addressstall_b (~read_reg_enable),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_b ({DATAWIDTH{1'b1}}),
.eccstatus (),
.q_a (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_b = "NONE",
altsyncram_component.address_reg_b = "CLOCK0",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_input_b = "BYPASS",
altsyncram_component.clock_enable_output_b = "BYPASS",
altsyncram_component.intended_device_family = "Stratix IV",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = N*FIFODEPTH,
altsyncram_component.numwords_b = N*FIFODEPTH,
altsyncram_component.operation_mode = "DUAL_PORT",
altsyncram_component.outdata_aclr_b = "NONE",
altsyncram_component.outdata_reg_b = "UNREGISTERED",
altsyncram_component.power_up_uninitialized = "FALSE",
altsyncram_component.read_during_write_mode_mixed_ports = "DONT_CARE",
altsyncram_component.widthad_a = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.widthad_b = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.width_a = DATAWIDTH,
altsyncram_component.width_b = DATAWIDTH,
altsyncram_component.width_byteena_a = 1;
assign o_active = |length;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
/********
* This module captures the relative frequency with which each bit in 'value'
* toggles. This can be useful for detecting address patterns for example.
*
* Eg. (in hex)
* Linear: 1ff ff 80 40 20 10 08 04 02 1 0 0 0 ...
* Linear predicated: 1ff ff 80 40 00 00 00 20 10 8 4 2 1 0 0 0 ...
* Strided: 00 00 ff 80 40 20 10 08 04 02 1 0 0 0 ...
* Random: ff ff ff ff ff ff ff ff ff ...
*
* The counters that track the toggle rates automatically get divided by 2 once
* any of their values comes close to overflowing. Hence the toggle rates are
* relative, and comparable only within a single module instance.
*
* The last counter (count[WIDTH]) is a saturating counter storing the number of
* times a scaledown was performed. If you assume the relative rates don't
* change between scaledowns, this can be used to approximate absolute toggle
* rates (which can be compared against rates from another instance).
*****************/
module acl_toggle_detect
#(
parameter WIDTH=13, // Width of input signal in bits
parameter COUNTERWIDTH=10 // in bits, MUST be greater than 3
)
(
input logic clk,
input logic resetn,
input logic valid,
input logic [WIDTH-1:0] value,
output logic [COUNTERWIDTH-1:0] count[WIDTH+1]
);
/******************
* LOCAL PARAMETERS
*******************/
/******************
* SIGNALS
*******************/
logic [WIDTH-1:0] last_value;
logic [WIDTH-1:0] bits_toggled;
logic scaledown;
/******************
* ARCHITECTURE
*******************/
always@(posedge clk or negedge resetn)
if (!resetn)
last_value<={WIDTH{1'b0}};
else if (valid)
last_value<=value;
// Compute which bits toggled via XOR
always@(posedge clk or negedge resetn)
if (!resetn)
bits_toggled<={WIDTH{1'b0}};
else if (valid)
bits_toggled<=value^last_value;
else
bits_toggled<={WIDTH{1'b0}};
// Create one counter for each bit in value. Increment the respective
// counter if that bit toggled.
genvar i;
generate
for (i = 0; i < WIDTH; i = i + 1)
begin:counters
always@(posedge clk or negedge resetn)
if (!resetn)
count[i] <= {COUNTERWIDTH{1'b0}};
else if (bits_toggled[i] && scaledown)
count[i] <= (count[i] + 2'b1) >> 1;
else if (bits_toggled[i])
count[i] <= count[i] + 2'b1;
else if (scaledown)
count[i] <= count[i] >> 1;
end
endgenerate
// Count total number of times scaled down - saturating counter
// This can be used to approximate absolute toggle rates
always@(posedge clk or negedge resetn)
if (!resetn)
count[WIDTH] <= 1'b0;
else if (scaledown && count[WIDTH]!={COUNTERWIDTH{1'b1}})
count[WIDTH] <= count[WIDTH] + 2'b1;
// If any counter value's top 3 bits are 1s, scale down all counter values
integer j;
always@(posedge clk or negedge resetn)
if (!resetn)
scaledown <= 1'b0;
else if (scaledown)
scaledown <= 1'b0;
else
for (j = 0; j < WIDTH; j = j + 1)
if (&count[j][COUNTERWIDTH-1:COUNTERWIDTH-3])
scaledown <= 1'b1;
endmodule
|
// Testbench for ltcminer_icarus.v
`timescale 1ns/1ps
`ifdef SIM // Avoids wrong top selected if included in ISE/PlanAhead sources
module test_ltcminer ();
reg clk = 1'b0;
reg [31:0] cycle = 32'd0;
initial begin
clk = 0;
while(1)
begin
#5 clk = 1; #5 clk = 0;
end
end
always @ (posedge clk)
begin
cycle <= cycle + 32'd1;
end
// Running with default zero's for the data1..3 regs.
// tx_hash=553a4b69b43913a61b42013ce210f713eaa7332e48cda1bdf3b93b10161d0876 at 187,990 nS and
// final_hash (if SIM is defined) at 188,000 nS with golden_nonce_match flag NOT set since it is
// not a diff=32 share. To test golden_nonce, just tweak the target eg 31'hffffffff will match everything
// With serial input(at comm_clk_frequency=1_000_000), we get rx_done at t=70,220nS, however there is already a
// PBKDF2_SHA256_80_128 loaded in Xbuf (for nonce=00000001). The first final_hash at 188,000 nS is corrupted as
// the input data has changed from all 0's. The Xbuf starts salsa rom at t=188,000 but the nonce is incorrectly
// taken from the newly loaded data so once salsa in complete it also generates a corrupt final_hash at ~362,000 nS.
// Nonce is incremented then the newly loaded data starts PBKDF2_SHA256_80_128, so we must supply a nonce 1 less
// than the expected golden_nonce. The correct PBKDF2_SHA256_80_128 is ready at ~ 197,000 nS. We get final_hash for
// the corrupted work at ~362,000 nS then our required golden_nonce is at 536,180 nS.
// This is only really a problem for simulation. With live hashing we just lose 2 nonces every time getwork is
// loaded, which isn't a big deal.
wire RxD;
wire TxD;
wire extminer_rxd = 0;
wire extminer_txd;
wire [3:0] dip = 0;
wire [3:0] led;
wire TMP_SCL=1, TMP_SDA=1, TMP_ALERT=1;
parameter comm_clk_frequency = 1_000_000; // Speeds up serial loading enormously rx_done is at t=70,220nS
parameter baud_rate = 115_200;
ltcminer_icarus #(.comm_clk_frequency(comm_clk_frequency)) uut
(clk, RxD, TxD, led, extminer_rxd, extminer_txd, dip, TMP_SCL, TMP_SDA, TMP_ALERT);
// Send serial data - 84 bytes, matches on nonce 318f (included in data)
// NB starting nonce is 381e NOT 381f (see note above)
// NORMAL...
// reg [671:0] data = 672'h000007ff0000318e7e71441b141fe951b2b0c7dfc791d4646240fc2a2d1b80900020a24dc501ef1599fc48ed6cbac920af75575618e7b1e8eaf0b62a90d1942ea64d250357e9a09c063a47827c57b44e01000000;
// DYNPLL...
reg [671:0] data = 672'h55aa07ff0000318e7e71441b141fe951b2b0c7dfc791d4646240fc2a2d1b80900020a24dc501ef1599fc48ed6cbac920af75575618e7b1e8eaf0b62a90d1942ea64d250357e9a09c063a47827c57b44e01000000;
reg serial_send = 0;
wire serial_busy;
reg [31:0] data_32 = 0;
reg [31:0] start_cycle = 0;
serial_transmit #(.comm_clk_frequency(comm_clk_frequency), .baud_rate(baud_rate)) sertx (.clk(clk), .TxD(RxD), .send(serial_send), .busy(serial_busy), .word(data_32));
// TUNE this according to comm_clk_frequency so we send a single getwork (else it gets overwritten with 0's)
// parameter stop_cycle = 7020; // For comm_clk_frequency=1_000_000
parameter stop_cycle = 0; // Use this to DISABLE sending data
always @ (posedge clk)
begin
serial_send <= 0; // Default
// Send data every time tx goes idle (NB the !serial_send is to prevent serial_send
// going high for two cycles since serial_busy arrives one cycle after serial_send)
if (cycle > 5 && cycle < stop_cycle && !serial_busy && !serial_send)
begin
serial_send <= 1;
data_32 <= data[671:640];
data <= { data[639:0], 32'd0 };
start_cycle <= cycle; // Remember each start cycle (makes debugging easier)
end
end
endmodule
`endif
|
// Testbench for ltcminer_icarus.v
`timescale 1ns/1ps
`ifdef SIM // Avoids wrong top selected if included in ISE/PlanAhead sources
module test_ltcminer ();
reg clk = 1'b0;
reg [31:0] cycle = 32'd0;
initial begin
clk = 0;
while(1)
begin
#5 clk = 1; #5 clk = 0;
end
end
always @ (posedge clk)
begin
cycle <= cycle + 32'd1;
end
// Running with default zero's for the data1..3 regs.
// tx_hash=553a4b69b43913a61b42013ce210f713eaa7332e48cda1bdf3b93b10161d0876 at 187,990 nS and
// final_hash (if SIM is defined) at 188,000 nS with golden_nonce_match flag NOT set since it is
// not a diff=32 share. To test golden_nonce, just tweak the target eg 31'hffffffff will match everything
// With serial input(at comm_clk_frequency=1_000_000), we get rx_done at t=70,220nS, however there is already a
// PBKDF2_SHA256_80_128 loaded in Xbuf (for nonce=00000001). The first final_hash at 188,000 nS is corrupted as
// the input data has changed from all 0's. The Xbuf starts salsa rom at t=188,000 but the nonce is incorrectly
// taken from the newly loaded data so once salsa in complete it also generates a corrupt final_hash at ~362,000 nS.
// Nonce is incremented then the newly loaded data starts PBKDF2_SHA256_80_128, so we must supply a nonce 1 less
// than the expected golden_nonce. The correct PBKDF2_SHA256_80_128 is ready at ~ 197,000 nS. We get final_hash for
// the corrupted work at ~362,000 nS then our required golden_nonce is at 536,180 nS.
// This is only really a problem for simulation. With live hashing we just lose 2 nonces every time getwork is
// loaded, which isn't a big deal.
wire RxD;
wire TxD;
wire extminer_rxd = 0;
wire extminer_txd;
wire [3:0] dip = 0;
wire [3:0] led;
wire TMP_SCL=1, TMP_SDA=1, TMP_ALERT=1;
parameter comm_clk_frequency = 1_000_000; // Speeds up serial loading enormously rx_done is at t=70,220nS
parameter baud_rate = 115_200;
ltcminer_icarus #(.comm_clk_frequency(comm_clk_frequency)) uut
(clk, RxD, TxD, led, extminer_rxd, extminer_txd, dip, TMP_SCL, TMP_SDA, TMP_ALERT);
// Send serial data - 84 bytes, matches on nonce 318f (included in data)
// NB starting nonce is 381e NOT 381f (see note above)
// NORMAL...
// reg [671:0] data = 672'h000007ff0000318e7e71441b141fe951b2b0c7dfc791d4646240fc2a2d1b80900020a24dc501ef1599fc48ed6cbac920af75575618e7b1e8eaf0b62a90d1942ea64d250357e9a09c063a47827c57b44e01000000;
// DYNPLL...
reg [671:0] data = 672'h55aa07ff0000318e7e71441b141fe951b2b0c7dfc791d4646240fc2a2d1b80900020a24dc501ef1599fc48ed6cbac920af75575618e7b1e8eaf0b62a90d1942ea64d250357e9a09c063a47827c57b44e01000000;
reg serial_send = 0;
wire serial_busy;
reg [31:0] data_32 = 0;
reg [31:0] start_cycle = 0;
serial_transmit #(.comm_clk_frequency(comm_clk_frequency), .baud_rate(baud_rate)) sertx (.clk(clk), .TxD(RxD), .send(serial_send), .busy(serial_busy), .word(data_32));
// TUNE this according to comm_clk_frequency so we send a single getwork (else it gets overwritten with 0's)
// parameter stop_cycle = 7020; // For comm_clk_frequency=1_000_000
parameter stop_cycle = 0; // Use this to DISABLE sending data
always @ (posedge clk)
begin
serial_send <= 0; // Default
// Send data every time tx goes idle (NB the !serial_send is to prevent serial_send
// going high for two cycles since serial_busy arrives one cycle after serial_send)
if (cycle > 5 && cycle < stop_cycle && !serial_busy && !serial_send)
begin
serial_send <= 1;
data_32 <= data[671:640];
data <= { data[639:0], 32'd0 };
start_cycle <= cycle; // Remember each start cycle (makes debugging easier)
end
end
endmodule
`endif
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// One-to-many fanout adaptor. Ensures that fanouts
// see the right number of valid_outs under all stall conditions.
module acl_multi_fanout_adaptor #(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer NUM_FANOUTS = 2 // >0
)
(
input logic clock,
input logic resetn,
// Upstream interface
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
input logic valid_in,
output logic stall_out,
// Downstream interface
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
output logic [NUM_FANOUTS-1:0] valid_out,
input logic [NUM_FANOUTS-1:0] stall_in
);
genvar i;
logic [NUM_FANOUTS-1:0] consumed, true_stall_in;
// A downstream interface is truly stalled only if it has not already consumed
// the valid data.
assign true_stall_in = stall_in & ~consumed;
// Stall upstream if any downstream is stalling.
assign stall_out = |true_stall_in;
generate
if( DATA_WIDTH > 0 )
// Data out is just data in. Only valid if valid_out[i] is asserted.
assign data_out = data_in;
endgenerate
// Downstream output is valid if input is valid and the data has not
// already been consumed.
assign valid_out = {NUM_FANOUTS{valid_in}} & ~consumed;
// Consumed: a downstream interface has consumed its data if at least one
// downstream interface is stalling but not itself. The consumed state is
// only reset once all downstream interfaces have consumed their data.
//
// In the case where no downstream is stalling, the consumed bits are not
// used.
generate
for( i = 0; i < NUM_FANOUTS; i = i + 1 )
begin:c
always @( posedge clock or negedge resetn )
if( !resetn )
consumed[i] <= 1'b0;
else if( valid_in & (|true_stall_in) )
begin
// Valid data and there's at least one downstream interface
// stalling. Check if this interface is stalled...
if( ~stall_in[i] )
consumed[i] <= 1'b1;
end
else
consumed[i] <= 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// One-to-many fanout adaptor. Ensures that fanouts
// see the right number of valid_outs under all stall conditions.
module acl_multi_fanout_adaptor #(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer NUM_FANOUTS = 2 // >0
)
(
input logic clock,
input logic resetn,
// Upstream interface
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
input logic valid_in,
output logic stall_out,
// Downstream interface
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
output logic [NUM_FANOUTS-1:0] valid_out,
input logic [NUM_FANOUTS-1:0] stall_in
);
genvar i;
logic [NUM_FANOUTS-1:0] consumed, true_stall_in;
// A downstream interface is truly stalled only if it has not already consumed
// the valid data.
assign true_stall_in = stall_in & ~consumed;
// Stall upstream if any downstream is stalling.
assign stall_out = |true_stall_in;
generate
if( DATA_WIDTH > 0 )
// Data out is just data in. Only valid if valid_out[i] is asserted.
assign data_out = data_in;
endgenerate
// Downstream output is valid if input is valid and the data has not
// already been consumed.
assign valid_out = {NUM_FANOUTS{valid_in}} & ~consumed;
// Consumed: a downstream interface has consumed its data if at least one
// downstream interface is stalling but not itself. The consumed state is
// only reset once all downstream interfaces have consumed their data.
//
// In the case where no downstream is stalling, the consumed bits are not
// used.
generate
for( i = 0; i < NUM_FANOUTS; i = i + 1 )
begin:c
always @( posedge clock or negedge resetn )
if( !resetn )
consumed[i] <= 1'b0;
else if( valid_in & (|true_stall_in) )
begin
// Valid data and there's at least one downstream interface
// stalling. Check if this interface is stalled...
if( ~stall_in[i] )
consumed[i] <= 1'b1;
end
else
consumed[i] <= 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module defines an iterator over work item space.
// Semantics:
//
// - Items for the same workgroup are issued contiguously.
// That is, items from different workgroups are never interleaved.
//
// - Subject to the previous constraint, we make the lower
// order ids (e.g. local_id[0]) iterate faster than
// higher order (e.g. local_id[2])
//
// - Id values start at zero and only increase.
//
// - Behaviour is unspecified if "issue" is asserted more than
// global_id[0] * global_id[1] * global_id[2] times between times
// that "start" is asserted.
module acl_work_item_iterator #(parameter WIDTH=32) (
input clock,
input resetn,
input start, // Assert to restart the iterators
input issue, // Assert to issue another item, i.e. advance the counters
// We assume these values are steady while "start" is not asserted.
input [WIDTH-1:0] local_size[2:0],
input [WIDTH-1:0] global_size[2:0],
// inputs from id_iterator
input [WIDTH-1:0] global_id_base[2:0],
// The counter values we export.
output reg [WIDTH-1:0] local_id[2:0],
output reg [WIDTH-1:0] global_id[2:0],
// output to id_iterator
output last_in_group
);
// This is the invariant relationship between the various ids.
// Keep these around for debugging.
wire [WIDTH-1:0] global_total = global_id[0] + global_size[0] * ( global_id[1] + global_size[1] * global_id[2] );
wire [WIDTH-1:0] local_total = local_id[0] + local_size[0] * ( local_id[1] + local_size[1] * local_id[2] );
function [WIDTH-1:0] incr_lid ( input [WIDTH-1:0] old_lid, input to_incr, input last );
if ( to_incr )
if ( last )
incr_lid = {WIDTH{1'b0}};
else
incr_lid = old_lid + 2'b01;
else
incr_lid = old_lid;
endfunction
//////////////////////////////////
// Handle local ids.
reg [WIDTH-1:0] max_local_id[2:0];
wire last_local_id[2:0];
assign last_local_id[0] = (local_id[0] == max_local_id[0] );
assign last_local_id[1] = (local_id[1] == max_local_id[1] );
assign last_local_id[2] = (local_id[2] == max_local_id[2] );
assign last_in_group = last_local_id[0] & last_local_id[1] & last_local_id[2];
wire bump_local_id[2:0];
assign bump_local_id[0] = (max_local_id[0] != 0);
assign bump_local_id[1] = (max_local_id[1] != 0) && last_local_id[0];
assign bump_local_id[2] = (max_local_id[2] != 0) && last_local_id[0] && last_local_id[1];
// Local id register updates.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= {WIDTH{1'b0}};
max_local_id[1] <= {WIDTH{1'b0}};
max_local_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= local_size[0] - 2'b01;
max_local_id[1] <= local_size[1] - 2'b01;
max_local_id[2] <= local_size[2] - 2'b01;
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
local_id[0] <= incr_lid (local_id[0], bump_local_id[0], last_local_id[0]);
local_id[1] <= incr_lid (local_id[1], bump_local_id[1], last_local_id[1]);
local_id[2] <= incr_lid (local_id[2], bump_local_id[2], last_local_id[2]);
end
end
end
// goes high one cycle after last_in_group. stays high until
// next cycle where 'issue' is high.
reg just_seen_last_in_group;
always @(posedge clock or negedge resetn) begin
if ( ~resetn )
just_seen_last_in_group <= 1'b1;
else if ( start )
just_seen_last_in_group <= 1'b1;
else if (last_in_group & issue)
just_seen_last_in_group <= 1'b1;
else if (issue)
just_seen_last_in_group <= 1'b0;
else
just_seen_last_in_group <= just_seen_last_in_group;
end
//////////////////////////////////
// Handle global ids.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
if ( !last_in_group ) begin
if ( just_seen_last_in_group ) begin
// get new global_id starting point from dispatcher.
// global_id_base will be one cycle late, so get it on the next cycle
// after encountering last element in previous group.
// id iterator will know to ignore the global id value on that cycle.
global_id[0] <= global_id_base[0] + bump_local_id[0];
global_id[1] <= global_id_base[1] + bump_local_id[1];
global_id[2] <= global_id_base[2] + bump_local_id[2];
end else begin
if ( bump_local_id[0] ) global_id[0] <= (last_local_id[0] ? (global_id[0] - max_local_id[0]) : (global_id[0] + 2'b01));
if ( bump_local_id[1] ) global_id[1] <= (last_local_id[1] ? (global_id[1] - max_local_id[1]) : (global_id[1] + 2'b01));
if ( bump_local_id[2] ) global_id[2] <= (last_local_id[2] ? (global_id[2] - max_local_id[2]) : (global_id[2] + 2'b01));
end
end
end
end
end
endmodule
// vim:set filetype=verilog:
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module defines an iterator over work item space.
// Semantics:
//
// - Items for the same workgroup are issued contiguously.
// That is, items from different workgroups are never interleaved.
//
// - Subject to the previous constraint, we make the lower
// order ids (e.g. local_id[0]) iterate faster than
// higher order (e.g. local_id[2])
//
// - Id values start at zero and only increase.
//
// - Behaviour is unspecified if "issue" is asserted more than
// global_id[0] * global_id[1] * global_id[2] times between times
// that "start" is asserted.
module acl_work_item_iterator #(parameter WIDTH=32) (
input clock,
input resetn,
input start, // Assert to restart the iterators
input issue, // Assert to issue another item, i.e. advance the counters
// We assume these values are steady while "start" is not asserted.
input [WIDTH-1:0] local_size[2:0],
input [WIDTH-1:0] global_size[2:0],
// inputs from id_iterator
input [WIDTH-1:0] global_id_base[2:0],
// The counter values we export.
output reg [WIDTH-1:0] local_id[2:0],
output reg [WIDTH-1:0] global_id[2:0],
// output to id_iterator
output last_in_group
);
// This is the invariant relationship between the various ids.
// Keep these around for debugging.
wire [WIDTH-1:0] global_total = global_id[0] + global_size[0] * ( global_id[1] + global_size[1] * global_id[2] );
wire [WIDTH-1:0] local_total = local_id[0] + local_size[0] * ( local_id[1] + local_size[1] * local_id[2] );
function [WIDTH-1:0] incr_lid ( input [WIDTH-1:0] old_lid, input to_incr, input last );
if ( to_incr )
if ( last )
incr_lid = {WIDTH{1'b0}};
else
incr_lid = old_lid + 2'b01;
else
incr_lid = old_lid;
endfunction
//////////////////////////////////
// Handle local ids.
reg [WIDTH-1:0] max_local_id[2:0];
wire last_local_id[2:0];
assign last_local_id[0] = (local_id[0] == max_local_id[0] );
assign last_local_id[1] = (local_id[1] == max_local_id[1] );
assign last_local_id[2] = (local_id[2] == max_local_id[2] );
assign last_in_group = last_local_id[0] & last_local_id[1] & last_local_id[2];
wire bump_local_id[2:0];
assign bump_local_id[0] = (max_local_id[0] != 0);
assign bump_local_id[1] = (max_local_id[1] != 0) && last_local_id[0];
assign bump_local_id[2] = (max_local_id[2] != 0) && last_local_id[0] && last_local_id[1];
// Local id register updates.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= {WIDTH{1'b0}};
max_local_id[1] <= {WIDTH{1'b0}};
max_local_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= local_size[0] - 2'b01;
max_local_id[1] <= local_size[1] - 2'b01;
max_local_id[2] <= local_size[2] - 2'b01;
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
local_id[0] <= incr_lid (local_id[0], bump_local_id[0], last_local_id[0]);
local_id[1] <= incr_lid (local_id[1], bump_local_id[1], last_local_id[1]);
local_id[2] <= incr_lid (local_id[2], bump_local_id[2], last_local_id[2]);
end
end
end
// goes high one cycle after last_in_group. stays high until
// next cycle where 'issue' is high.
reg just_seen_last_in_group;
always @(posedge clock or negedge resetn) begin
if ( ~resetn )
just_seen_last_in_group <= 1'b1;
else if ( start )
just_seen_last_in_group <= 1'b1;
else if (last_in_group & issue)
just_seen_last_in_group <= 1'b1;
else if (issue)
just_seen_last_in_group <= 1'b0;
else
just_seen_last_in_group <= just_seen_last_in_group;
end
//////////////////////////////////
// Handle global ids.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
if ( !last_in_group ) begin
if ( just_seen_last_in_group ) begin
// get new global_id starting point from dispatcher.
// global_id_base will be one cycle late, so get it on the next cycle
// after encountering last element in previous group.
// id iterator will know to ignore the global id value on that cycle.
global_id[0] <= global_id_base[0] + bump_local_id[0];
global_id[1] <= global_id_base[1] + bump_local_id[1];
global_id[2] <= global_id_base[2] + bump_local_id[2];
end else begin
if ( bump_local_id[0] ) global_id[0] <= (last_local_id[0] ? (global_id[0] - max_local_id[0]) : (global_id[0] + 2'b01));
if ( bump_local_id[1] ) global_id[1] <= (last_local_id[1] ? (global_id[1] - max_local_id[1]) : (global_id[1] + 2'b01));
if ( bump_local_id[2] ) global_id[2] <= (last_local_id[2] ? (global_id[2] - max_local_id[2]) : (global_id[2] + 2'b01));
end
end
end
end
end
endmodule
// vim:set filetype=verilog:
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module defines an iterator over work item space.
// Semantics:
//
// - Items for the same workgroup are issued contiguously.
// That is, items from different workgroups are never interleaved.
//
// - Subject to the previous constraint, we make the lower
// order ids (e.g. local_id[0]) iterate faster than
// higher order (e.g. local_id[2])
//
// - Id values start at zero and only increase.
//
// - Behaviour is unspecified if "issue" is asserted more than
// global_id[0] * global_id[1] * global_id[2] times between times
// that "start" is asserted.
module acl_work_item_iterator #(parameter WIDTH=32) (
input clock,
input resetn,
input start, // Assert to restart the iterators
input issue, // Assert to issue another item, i.e. advance the counters
// We assume these values are steady while "start" is not asserted.
input [WIDTH-1:0] local_size[2:0],
input [WIDTH-1:0] global_size[2:0],
// inputs from id_iterator
input [WIDTH-1:0] global_id_base[2:0],
// The counter values we export.
output reg [WIDTH-1:0] local_id[2:0],
output reg [WIDTH-1:0] global_id[2:0],
// output to id_iterator
output last_in_group
);
// This is the invariant relationship between the various ids.
// Keep these around for debugging.
wire [WIDTH-1:0] global_total = global_id[0] + global_size[0] * ( global_id[1] + global_size[1] * global_id[2] );
wire [WIDTH-1:0] local_total = local_id[0] + local_size[0] * ( local_id[1] + local_size[1] * local_id[2] );
function [WIDTH-1:0] incr_lid ( input [WIDTH-1:0] old_lid, input to_incr, input last );
if ( to_incr )
if ( last )
incr_lid = {WIDTH{1'b0}};
else
incr_lid = old_lid + 2'b01;
else
incr_lid = old_lid;
endfunction
//////////////////////////////////
// Handle local ids.
reg [WIDTH-1:0] max_local_id[2:0];
wire last_local_id[2:0];
assign last_local_id[0] = (local_id[0] == max_local_id[0] );
assign last_local_id[1] = (local_id[1] == max_local_id[1] );
assign last_local_id[2] = (local_id[2] == max_local_id[2] );
assign last_in_group = last_local_id[0] & last_local_id[1] & last_local_id[2];
wire bump_local_id[2:0];
assign bump_local_id[0] = (max_local_id[0] != 0);
assign bump_local_id[1] = (max_local_id[1] != 0) && last_local_id[0];
assign bump_local_id[2] = (max_local_id[2] != 0) && last_local_id[0] && last_local_id[1];
// Local id register updates.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= {WIDTH{1'b0}};
max_local_id[1] <= {WIDTH{1'b0}};
max_local_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= local_size[0] - 2'b01;
max_local_id[1] <= local_size[1] - 2'b01;
max_local_id[2] <= local_size[2] - 2'b01;
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
local_id[0] <= incr_lid (local_id[0], bump_local_id[0], last_local_id[0]);
local_id[1] <= incr_lid (local_id[1], bump_local_id[1], last_local_id[1]);
local_id[2] <= incr_lid (local_id[2], bump_local_id[2], last_local_id[2]);
end
end
end
// goes high one cycle after last_in_group. stays high until
// next cycle where 'issue' is high.
reg just_seen_last_in_group;
always @(posedge clock or negedge resetn) begin
if ( ~resetn )
just_seen_last_in_group <= 1'b1;
else if ( start )
just_seen_last_in_group <= 1'b1;
else if (last_in_group & issue)
just_seen_last_in_group <= 1'b1;
else if (issue)
just_seen_last_in_group <= 1'b0;
else
just_seen_last_in_group <= just_seen_last_in_group;
end
//////////////////////////////////
// Handle global ids.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
if ( !last_in_group ) begin
if ( just_seen_last_in_group ) begin
// get new global_id starting point from dispatcher.
// global_id_base will be one cycle late, so get it on the next cycle
// after encountering last element in previous group.
// id iterator will know to ignore the global id value on that cycle.
global_id[0] <= global_id_base[0] + bump_local_id[0];
global_id[1] <= global_id_base[1] + bump_local_id[1];
global_id[2] <= global_id_base[2] + bump_local_id[2];
end else begin
if ( bump_local_id[0] ) global_id[0] <= (last_local_id[0] ? (global_id[0] - max_local_id[0]) : (global_id[0] + 2'b01));
if ( bump_local_id[1] ) global_id[1] <= (last_local_id[1] ? (global_id[1] - max_local_id[1]) : (global_id[1] + 2'b01));
if ( bump_local_id[2] ) global_id[2] <= (last_local_id[2] ? (global_id[2] - max_local_id[2]) : (global_id[2] + 2'b01));
end
end
end
end
end
endmodule
// vim:set filetype=verilog:
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module defines an iterator over work item space.
// Semantics:
//
// - Items for the same workgroup are issued contiguously.
// That is, items from different workgroups are never interleaved.
//
// - Subject to the previous constraint, we make the lower
// order ids (e.g. local_id[0]) iterate faster than
// higher order (e.g. local_id[2])
//
// - Id values start at zero and only increase.
//
// - Behaviour is unspecified if "issue" is asserted more than
// global_id[0] * global_id[1] * global_id[2] times between times
// that "start" is asserted.
module acl_work_item_iterator #(parameter WIDTH=32) (
input clock,
input resetn,
input start, // Assert to restart the iterators
input issue, // Assert to issue another item, i.e. advance the counters
// We assume these values are steady while "start" is not asserted.
input [WIDTH-1:0] local_size[2:0],
input [WIDTH-1:0] global_size[2:0],
// inputs from id_iterator
input [WIDTH-1:0] global_id_base[2:0],
// The counter values we export.
output reg [WIDTH-1:0] local_id[2:0],
output reg [WIDTH-1:0] global_id[2:0],
// output to id_iterator
output last_in_group
);
// This is the invariant relationship between the various ids.
// Keep these around for debugging.
wire [WIDTH-1:0] global_total = global_id[0] + global_size[0] * ( global_id[1] + global_size[1] * global_id[2] );
wire [WIDTH-1:0] local_total = local_id[0] + local_size[0] * ( local_id[1] + local_size[1] * local_id[2] );
function [WIDTH-1:0] incr_lid ( input [WIDTH-1:0] old_lid, input to_incr, input last );
if ( to_incr )
if ( last )
incr_lid = {WIDTH{1'b0}};
else
incr_lid = old_lid + 2'b01;
else
incr_lid = old_lid;
endfunction
//////////////////////////////////
// Handle local ids.
reg [WIDTH-1:0] max_local_id[2:0];
wire last_local_id[2:0];
assign last_local_id[0] = (local_id[0] == max_local_id[0] );
assign last_local_id[1] = (local_id[1] == max_local_id[1] );
assign last_local_id[2] = (local_id[2] == max_local_id[2] );
assign last_in_group = last_local_id[0] & last_local_id[1] & last_local_id[2];
wire bump_local_id[2:0];
assign bump_local_id[0] = (max_local_id[0] != 0);
assign bump_local_id[1] = (max_local_id[1] != 0) && last_local_id[0];
assign bump_local_id[2] = (max_local_id[2] != 0) && last_local_id[0] && last_local_id[1];
// Local id register updates.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= {WIDTH{1'b0}};
max_local_id[1] <= {WIDTH{1'b0}};
max_local_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= local_size[0] - 2'b01;
max_local_id[1] <= local_size[1] - 2'b01;
max_local_id[2] <= local_size[2] - 2'b01;
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
local_id[0] <= incr_lid (local_id[0], bump_local_id[0], last_local_id[0]);
local_id[1] <= incr_lid (local_id[1], bump_local_id[1], last_local_id[1]);
local_id[2] <= incr_lid (local_id[2], bump_local_id[2], last_local_id[2]);
end
end
end
// goes high one cycle after last_in_group. stays high until
// next cycle where 'issue' is high.
reg just_seen_last_in_group;
always @(posedge clock or negedge resetn) begin
if ( ~resetn )
just_seen_last_in_group <= 1'b1;
else if ( start )
just_seen_last_in_group <= 1'b1;
else if (last_in_group & issue)
just_seen_last_in_group <= 1'b1;
else if (issue)
just_seen_last_in_group <= 1'b0;
else
just_seen_last_in_group <= just_seen_last_in_group;
end
//////////////////////////////////
// Handle global ids.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
if ( !last_in_group ) begin
if ( just_seen_last_in_group ) begin
// get new global_id starting point from dispatcher.
// global_id_base will be one cycle late, so get it on the next cycle
// after encountering last element in previous group.
// id iterator will know to ignore the global id value on that cycle.
global_id[0] <= global_id_base[0] + bump_local_id[0];
global_id[1] <= global_id_base[1] + bump_local_id[1];
global_id[2] <= global_id_base[2] + bump_local_id[2];
end else begin
if ( bump_local_id[0] ) global_id[0] <= (last_local_id[0] ? (global_id[0] - max_local_id[0]) : (global_id[0] + 2'b01));
if ( bump_local_id[1] ) global_id[1] <= (last_local_id[1] ? (global_id[1] - max_local_id[1]) : (global_id[1] + 2'b01));
if ( bump_local_id[2] ) global_id[2] <= (last_local_id[2] ? (global_id[2] - max_local_id[2]) : (global_id[2] + 2'b01));
end
end
end
end
end
endmodule
// vim:set filetype=verilog:
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cnt = 0;
integer mod = 0;
// event counter
always @ (posedge clk)
if (cnt==20) begin
cnt <= 0;
mod <= mod + 1;
end else begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (mod==3) begin
$write("*-* All Finished *-*\n");
$finish;
end
// anonymous type variable declaration
enum logic [2:0] {red=1, orange, yellow, green, blue, indigo, violet} rainbow7;
// named type
typedef enum logic {OFF, ON} t_switch;
t_switch switch;
// numbering examples
enum integer {father, mother, son[2], daughter, gerbil, dog[3]=10, cat[3:5]=20, car[3:1]=30} family;
// test of raibow7 type
always @ (posedge clk)
if (mod==0) begin
// write value to array
if (cnt== 0) begin
rainbow7 <= rainbow7.first();
// check number
if (rainbow7.num() !== 7 ) begin $display("%d", rainbow7.num() ); $stop(); end
if (rainbow7 !== 3'bxxx ) begin $display("%b", rainbow7 ); $stop(); end
end
else if (cnt== 1) begin
if (rainbow7 !== 3'd1 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== red ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 2) begin
if (rainbow7 !== 3'd2 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== orange ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 3) begin
if (rainbow7 !== 3'd3 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== yellow ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 4) begin
if (rainbow7 !== 3'd4 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== green ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 5) begin
if (rainbow7 !== 3'd5 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== blue ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 6) begin
if (rainbow7 !== 3'd6 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== indigo ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 7) begin
if (rainbow7 !== 3'd7 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== violet ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
else if (cnt== 8) begin
if (rainbow7 !== 3'd1 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== red ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.next();
end
end else if (mod==1) begin
// write value to array
if (cnt== 0) begin
rainbow7 <= rainbow7.last();
// check number
if (rainbow7.num() !== 7 ) begin $display("%d", rainbow7.num() ); $stop(); end
end
else if (cnt== 1) begin
if (rainbow7 !== 3'd7 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== violet ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 2) begin
if (rainbow7 !== 3'd6 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== indigo ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 3) begin
if (rainbow7 !== 3'd5 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== blue ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 4) begin
if (rainbow7 !== 3'd4 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== green ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 5) begin
if (rainbow7 !== 3'd3 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== yellow ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 6) begin
if (rainbow7 !== 3'd2 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== orange ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 7) begin
if (rainbow7 !== 3'd1 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== red ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
else if (cnt== 8) begin
if (rainbow7 !== 3'd7 ) begin $display("%b", rainbow7 ); $stop(); end
if (rainbow7 !== violet ) begin $display("%b", rainbow7 ); $stop(); end
rainbow7 <= rainbow7.prev();
end
end
// test of t_switch type
always @ (posedge clk)
if (mod==0) begin
// write value to array
if (cnt== 0) begin
switch <= switch.first();
// check number
if (switch.num() !== 2 ) begin $display("%d", switch.num() ); $stop(); end
if (switch !== 1'bx) begin $display("%b", switch ); $stop(); end
end
else if (cnt== 1) begin
if (switch !== 1'b0) begin $display("%b", switch ); $stop(); end
if (switch !== OFF ) begin $display("%b", switch ); $stop(); end
switch <= switch.next();
end
else if (cnt== 2) begin
if (switch !== 1'b1) begin $display("%b", switch ); $stop(); end
if (switch !== ON ) begin $display("%b", switch ); $stop(); end
switch <= switch.next();
end
else if (cnt== 3) begin
if (switch !== 1'b0) begin $display("%b", switch ); $stop(); end
if (switch !== OFF ) begin $display("%b", switch ); $stop(); end
switch <= switch.next();
end
end else if (mod==1) begin
// write value to array
if (cnt== 0) begin
rainbow7 <= rainbow7.last();
// check number
if (switch.num() !== 2 ) begin $display("%d", switch.num() ); $stop(); end
end
else if (cnt== 1) begin
if (switch !== 1'b1) begin $display("%b", switch ); $stop(); end
if (switch !== ON ) begin $display("%b", switch ); $stop(); end
switch <= switch.prev();
end
else if (cnt== 2) begin
if (switch !== 1'b0) begin $display("%b", switch ); $stop(); end
if (switch !== OFF ) begin $display("%b", switch ); $stop(); end
switch <= switch.prev();
end
else if (cnt== 3) begin
if (switch !== 1'b1) begin $display("%b", switch ); $stop(); end
if (switch !== ON ) begin $display("%b", switch ); $stop(); end
switch <= switch.prev();
end
end
// test of raibow7 type
always @ (posedge clk)
if (mod==0) begin
// write value to array
if (cnt== 0) begin
family <= family.first();
// check number
if (family.num() !== 15 ) begin $display("%d", family.num() ); $stop(); end
if (family !== 32'dx ) begin $display("%b", family ); $stop(); end
end
else if (cnt== 1) begin
if (family !== 0 ) begin $display("%b", family ); $stop(); end
if (family !== father ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 2) begin
if (family !== 1 ) begin $display("%b", family ); $stop(); end
if (family !== mother ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 3) begin
if (family !== 2 ) begin $display("%b", family ); $stop(); end
if (family !== son0 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 4) begin
if (family !== 3 ) begin $display("%b", family ); $stop(); end
if (family !== son1 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 5) begin
if (family !== 4 ) begin $display("%b", family ); $stop(); end
if (family !== daughter ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 6) begin
if (family !== 5 ) begin $display("%b", family ); $stop(); end
if (family !== gerbil ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 7) begin
if (family !== 10 ) begin $display("%b", family ); $stop(); end
if (family !== dog0 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 8) begin
if (family !== 11 ) begin $display("%b", family ); $stop(); end
if (family !== dog1 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 9) begin
if (family !== 12 ) begin $display("%b", family ); $stop(); end
if (family !== dog2 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 10) begin
if (family !== 20 ) begin $display("%b", family ); $stop(); end
if (family !== cat3 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 11) begin
if (family !== 21 ) begin $display("%b", family ); $stop(); end
if (family !== cat4 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 12) begin
if (family !== 22 ) begin $display("%b", family ); $stop(); end
if (family !== cat5 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 13) begin
if (family !== 30 ) begin $display("%b", family ); $stop(); end
if (family !== car3 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 14) begin
if (family !== 31 ) begin $display("%b", family ); $stop(); end
if (family !== car2 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
else if (cnt== 15) begin
if (family !== 32 ) begin $display("%b", family ); $stop(); end
if (family !== car1 ) begin $display("%b", family ); $stop(); end
family <= family.next();
end
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// one-way bidirectional connection:
// altera message_off 10665
module acl_ic_master_endpoint
#(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer TOTAL_NUM_MASTERS = 1, // > 0
parameter integer ID = 0 // [0..2^ID_W-1]
)
(
input logic clock,
input logic resetn,
acl_ic_master_intf m_intf,
acl_arb_intf arb_intf,
acl_ic_wrp_intf wrp_intf,
acl_ic_rrp_intf rrp_intf
);
// Pass-through arbitration data.
assign arb_intf.req = m_intf.arb.req;
assign m_intf.arb.stall = arb_intf.stall;
generate
if( TOTAL_NUM_MASTERS > 1 )
begin
// There shouldn't be any truncation, but be explicit about the id width.
logic [ID_W-1:0] id = ID;
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack & (wrp_intf.id == id);
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid & (rrp_intf.id == id);
assign m_intf.rrp.data = rrp_intf.data;
end
else // TOTAL_NUM_MASTERS == 1
begin
// Only one master driving the entire interconnect, so there's no need
// to check the id.
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack;
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid;
assign m_intf.rrp.data = rrp_intf.data;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level load/store unit
//
// Attributes of load/store units
// Coalesced: Accesses to neighbouring memory locations are grouped together
// to improve efficiency and efficiently utilize memory bandwidth.
// Hazard-Safe:The LSU is not susceptable to data hazards.
// Ordered: The LSU requires accesses to be in-order to properly coalesce.
// Pipeline: The LSU can handle multiple requests at a time without
// stalling. Improves throughput.
//
// Supports the following memory access patterns:
// Simple - STYLE="SIMPLE"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined, No
// Simple un-pipelined memory access. Low throughput.
// Pipelined - STYLE="PIPELINED"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Coalesced - STYLE="BASIC-COALESCED"
// "basic" Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Coalesced - STYLE="BURST-COALESCED"
// "burst" Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// Requests are buffered until the biggest possible burst can
// be made.
// Streaming - STYLE="STREAMING"
// Coalesced: Yes, Ordered: Yes, Hazard-Safe: No, Pipelined: ?
// A FIFO is instantiated which burst reads large blocks from
// memory to keep the FIFO full of valid data. This block can
// only be used if accesses are in-order, and addresses can be
// simply calculated from (base_address + n * word_width). The
// block has no built-in hazard protection.
// Atomic - STYLE="ATOMIC-PIPELINED"
//"pipelined"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// Atomic: Yes
// Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Response is returned as soon as read is complete,
// write is issued subsequently by the atomic module at the end
// of arbitration.
module lsu_top
(
clock, clock2x, resetn, stream_base_addr, stream_size, stream_reset, i_atomic_op, o_stall,
i_valid, i_address, i_writedata, i_cmpdata, i_predicate, i_bitwiseor, i_stall, o_valid, o_readdata, avm_address,
avm_read, avm_readdata, avm_write, avm_writeack, avm_writedata, avm_byteenable,
avm_waitrequest, avm_readdatavalid, avm_burstcount,
o_active,
o_input_fifo_depth,
o_writeack,
i_byteenable,
flush,
// profile signals
profile_bw, profile_bw_incr,
profile_total_ivalid,
profile_total_req,
profile_i_stall_count,
profile_o_stall_count,
profile_avm_readwrite_count,
profile_avm_burstcount_total, profile_avm_burstcount_total_incr,
profile_req_cache_hit_count,
profile_extra_unaligned_reqs,
profile_avm_stall
);
/*************
* Parameters *
*************/
parameter STYLE="PIPELINED"; // The LSU style to use (see style list above)
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter ATOMIC_WIDTH=6; // Width of operation operation indices
parameter WIDTH_BYTES=4; // Width of the request (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter WRITEDATAWIDTH_BYTES=32; // Width of the readdata/writedata signals,
// may be larger than MWIDTH_BYTES for atomics
parameter ALIGNMENT_BYTES=2; // Request address alignment (bytes)
parameter READ=1; // Read or write?
parameter ATOMIC=0; // Atomic?
parameter BURSTCOUNT_WIDTH=6;// Determines max burst size
// Why two latencies? E.g. A streaming unit prefetches data, its latency to
// the kernel is very low because data is for the most part ready and waiting.
// But the lsu needs to know how much data to buffer to hide the latency to
// memory, hence the memory side latency.
parameter KERNEL_SIDE_MEM_LATENCY=1; // Effective Latency in cycles as seen by the kernel pipeline
parameter MEMORY_SIDE_MEM_LATENCY=1; // Latency in cycles between LSU and memory
parameter USE_WRITE_ACK=0; // Enable the write-acknowledge signal
parameter USECACHING=0;
parameter USE_BYTE_EN=0;
parameter CACHESIZE=1024;
parameter PROFILE_ADDR_TOGGLE=0;
parameter USEINPUTFIFO=1; // FIXME specific to lsu_pipelined
parameter USEOUTPUTFIFO=1; // FIXME specific to lsu_pipelined
parameter FORCE_NOP_SUPPORT=0; // Stall free pipeline doesn't want the NOP fifo
parameter HIGH_FMAX=1; // Enable optimizations for high Fmax
// Profiling
parameter ACL_PROFILE=0; // Set to 1 to enable stall/valid profiling
parameter ACL_PROFILE_INCREMENT_WIDTH=32;
// Verilog readability and parsing only - no functional purpose
parameter ADDRSPACE=0;
// Local memory parameters
parameter ENABLE_BANKED_MEMORY=0;// Flag enables address permutation for banked local memory config
parameter ABITS_PER_LMEM_BANK=0; // Used when permuting lmem address bits to stride across banks
parameter NUMBER_BANKS=1; // Number of memory banks - used in address permutation (1-disable)
parameter LMEM_ADDR_PERMUTATION_STYLE=0; // Type of address permutation (currently unused)
// The following localparams have if conditions, and the second is named
// "HACKED..." because address bit permutations are controlled by the
// ENABLE_BANKED_MEMORY parameter. The issue is that this forms the select
// input of a MUX (if statement), and synthesis evaluates both inputs.
// When not using banked memory, the bit select ranges don't make sense on
// the input that isn't used, so we need to hack them in the non-banked case
// to get through ModelSim and Quartus.
localparam BANK_SELECT_BITS = (ENABLE_BANKED_MEMORY==1) ? $clog2(NUMBER_BANKS) : 1; // Bank select bits in address permutation
localparam HACKED_ABITS_PER_LMEM_BANK = (ENABLE_BANKED_MEMORY==1) ? ABITS_PER_LMEM_BANK : $clog2(MWIDTH_BYTES)+1;
// Parameter limitations:
// AWIDTH: Only tested with 32-bit addresses
// WIDTH_BYTES: Must be a power of two
// MWIDTH_BYTES: Must be a power of 2 >= WIDTH_BYTES
// ALIGNMENT_BYTES: Must be a power of 2 satisfying,
// WIDTH_BYTES <= ALIGNMENT_BYTES <= MWIDTH_BYTES
//
// The width and alignment restrictions ensure we never try to read a word
// that strides across two "pages" (MWIDTH sized words)
// TODO: Convert these back into localparams when the back-end supports it
parameter WIDTH=8*WIDTH_BYTES; // Width in bits
parameter MWIDTH=8*MWIDTH_BYTES; // Width in bits
parameter WRITEDATAWIDTH=8*WRITEDATAWIDTH_BYTES; // Width in bits
localparam ALIGNMENT_ABITS=$clog2(ALIGNMENT_BYTES); // Address bits to ignore
localparam LSU_CAPACITY=256; // Maximum number of 'in-flight' load/store operations
localparam WIDE_LSU = (WIDTH > MWIDTH);
// Performance monitor signals
parameter INPUTFIFO_USEDW_MAXBITS=8;
// LSU unit properties
localparam ATOMIC_PIPELINED_LSU=(STYLE=="ATOMIC-PIPELINED");
localparam PIPELINED_LSU=( (STYLE=="PIPELINED") || (STYLE=="BASIC-COALESCED") || (STYLE=="BURST-COALESCED") || (STYLE=="BURST-NON-ALIGNED") );
localparam SUPPORTS_NOP= (STYLE=="STREAMING") || (STYLE=="SEMI-STREAMING") || (STYLE=="BURST-NON-ALIGNED") || (STYLE=="BURST-COALESCED") || (FORCE_NOP_SUPPORT==1);
localparam SUPPORTS_BURSTS=( (STYLE=="STREAMING") || (STYLE=="BURST-COALESCED") || (STYLE=="SEMI-STREAMING") || (STYLE=="BURST-NON-ALIGNED") );
/********
* Ports *
********/
// Standard global signals
input clock;
input clock2x;
input resetn;
input flush;
// Streaming interface signals
input [AWIDTH-1:0] stream_base_addr;
input [31:0] stream_size;
input stream_reset;
// Atomic interface
input [WIDTH-1:0] i_cmpdata; // only used by atomic_cmpxchg
input [ATOMIC_WIDTH-1:0] i_atomic_op;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input i_predicate;
input [AWIDTH-1:0] i_bitwiseor;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [WRITEDATAWIDTH-1:0] avm_readdata;
output avm_write;
input avm_writeack;
output o_writeack;
output [WRITEDATAWIDTH-1:0] avm_writedata;
output [WRITEDATAWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output reg o_active;
// For profiling/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
// Profiler Signals
output logic profile_bw;
output logic [ACL_PROFILE_INCREMENT_WIDTH-1:0] profile_bw_incr;
output logic profile_total_ivalid;
output logic profile_total_req;
output logic profile_i_stall_count;
output logic profile_o_stall_count;
output logic profile_avm_readwrite_count;
output logic profile_avm_burstcount_total;
output logic [ACL_PROFILE_INCREMENT_WIDTH-1:0] profile_avm_burstcount_total_incr;
output logic profile_req_cache_hit_count;
output logic profile_extra_unaligned_reqs;
output logic profile_avm_stall;
// help timing; reduce the high fanout of global reset from iface
reg [1:0] sync_rstn_MS /* synthesis syn_preserve = 1 */ ;
wire sync_rstn;
assign sync_rstn = sync_rstn_MS[1];
always @(posedge clock or negedge resetn) begin
if(!resetn) sync_rstn_MS <= 2'b00;
else sync_rstn_MS <= {sync_rstn_MS[0], 1'b1};
end
generate
if(WIDE_LSU) begin
//break transaction into multiple cycles
lsu_wide_wrapper lsu_wide (
.clock(clock),
.clock2x(clock2x),
.resetn(sync_rstn),
.flush(flush),
.stream_base_addr(stream_base_addr),
.stream_size(stream_size),
.stream_reset(stream_reset),
.o_stall(o_stall),
.i_valid(i_valid),
.i_address(i_address),
.i_writedata(i_writedata),
.i_cmpdata(i_cmpdata),
.i_predicate(i_predicate),
.i_bitwiseor(i_bitwiseor),
.i_byteenable(i_byteenable),
.i_stall(i_stall),
.o_valid(o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_writeack(o_writeack),
.i_atomic_op(i_atomic_op),
.o_active(o_active),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_write(avm_write),
.avm_writeack(avm_writeack),
.avm_burstcount(avm_burstcount),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest),
.avm_readdatavalid(avm_readdatavalid),
.profile_req_cache_hit_count(profile_req_cache_hit_count),
.profile_extra_unaligned_reqs(profile_extra_unaligned_reqs)
);
defparam lsu_wide.STYLE = STYLE;
defparam lsu_wide.AWIDTH = AWIDTH;
defparam lsu_wide.ATOMIC_WIDTH = ATOMIC_WIDTH;
defparam lsu_wide.WIDTH_BYTES = WIDTH_BYTES;
defparam lsu_wide.MWIDTH_BYTES = MWIDTH_BYTES;
defparam lsu_wide.WRITEDATAWIDTH_BYTES = WRITEDATAWIDTH_BYTES;
defparam lsu_wide.ALIGNMENT_BYTES = ALIGNMENT_BYTES;
defparam lsu_wide.READ = READ;
defparam lsu_wide.ATOMIC = ATOMIC;
defparam lsu_wide.BURSTCOUNT_WIDTH = BURSTCOUNT_WIDTH;
defparam lsu_wide.KERNEL_SIDE_MEM_LATENCY = KERNEL_SIDE_MEM_LATENCY;
defparam lsu_wide.MEMORY_SIDE_MEM_LATENCY = MEMORY_SIDE_MEM_LATENCY;
defparam lsu_wide.USE_WRITE_ACK = USE_WRITE_ACK;
defparam lsu_wide.USECACHING = USECACHING;
defparam lsu_wide.USE_BYTE_EN = USE_BYTE_EN;
defparam lsu_wide.CACHESIZE = CACHESIZE;
defparam lsu_wide.PROFILE_ADDR_TOGGLE = PROFILE_ADDR_TOGGLE;
defparam lsu_wide.USEINPUTFIFO = USEINPUTFIFO;
defparam lsu_wide.USEOUTPUTFIFO = USEOUTPUTFIFO;
defparam lsu_wide.FORCE_NOP_SUPPORT = FORCE_NOP_SUPPORT;
defparam lsu_wide.HIGH_FMAX = HIGH_FMAX;
defparam lsu_wide.ACL_PROFILE = ACL_PROFILE;
defparam lsu_wide.ACL_PROFILE_INCREMENT_WIDTH = ACL_PROFILE_INCREMENT_WIDTH;
defparam lsu_wide.ENABLE_BANKED_MEMORY = ENABLE_BANKED_MEMORY;
defparam lsu_wide.ABITS_PER_LMEM_BANK = ABITS_PER_LMEM_BANK;
defparam lsu_wide.NUMBER_BANKS = NUMBER_BANKS;
defparam lsu_wide.WIDTH = WIDTH;
defparam lsu_wide.MWIDTH = MWIDTH;
defparam lsu_wide.WRITEDATAWIDTH = WRITEDATAWIDTH;
defparam lsu_wide.INPUTFIFO_USEDW_MAXBITS = INPUTFIFO_USEDW_MAXBITS;
defparam lsu_wide.LMEM_ADDR_PERMUTATION_STYLE = LMEM_ADDR_PERMUTATION_STYLE;
defparam lsu_wide.ADDRSPACE = ADDRSPACE;
//the wrapped LSU doesnt interface directly with the avalon master, so profiling here is more accurate for avm signals
//two signals generated directly by the LSU need to be passed in
if(ACL_PROFILE==1)
begin
// keep track of write bursts
reg [BURSTCOUNT_WIDTH-1:0] profile_remaining_writeburst_count;
wire active_write_burst;
assign active_write_burst = (profile_remaining_writeburst_count != {BURSTCOUNT_WIDTH{1'b0}});
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
profile_remaining_writeburst_count <= {BURSTCOUNT_WIDTH{1'b0}};
else if(avm_write & ~avm_waitrequest & ~active_write_burst)
// start of a new write burst
profile_remaining_writeburst_count <= avm_burstcount - 1;
else if(~avm_waitrequest & active_write_burst)
// count down one burst
profile_remaining_writeburst_count <= profile_remaining_writeburst_count - 1;
assign profile_bw = (READ==1) ? avm_readdatavalid : (avm_write & ~avm_waitrequest);
assign profile_bw_incr = MWIDTH_BYTES;
assign profile_total_ivalid = (i_valid & ~o_stall);
assign profile_total_req = (i_valid & ~i_predicate & ~o_stall);
assign profile_i_stall_count = (i_stall & o_valid);
assign profile_o_stall_count = (o_stall & i_valid);
assign profile_avm_readwrite_count = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total_incr = avm_burstcount;
assign profile_avm_stall = ((avm_read | avm_write) & avm_waitrequest);
end
else begin
assign profile_bw = 1'b0;
assign profile_bw_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_total_ivalid = 1'b0;
assign profile_total_req = 1'b0;
assign profile_i_stall_count = 1'b0;
assign profile_o_stall_count = 1'b0;
assign profile_avm_readwrite_count = 1'b0;
assign profile_avm_burstcount_total = 1'b0;
assign profile_avm_burstcount_total_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_avm_stall = 1'b0;
end
end
else begin
wire lsu_active;
// For handling dependents of this lsu
assign o_writeack = avm_writeack;
// If this is a banked local memory LSU, then permute address bits so that
// consective words in memory are in different banks. Do this by
// taking the k lowest bits of the word-address and shifting them to the top
// of the aggregate local memory address width. The number of bits k
// corresponds to the number of banks parameter.
localparam MWIDTH_BYTES_CLIP = (MWIDTH_BYTES==1) ? 2 : MWIDTH_BYTES; //to get around modelsim looking at addr[-1:0] if MWIDTH_BYTES==1
function [AWIDTH-1:0] permute_addr ( input [AWIDTH-1:0] addr);
if (ENABLE_BANKED_MEMORY==1)
begin
if (MWIDTH_BYTES==1) begin
permute_addr= {
addr[(AWIDTH-1) : (HACKED_ABITS_PER_LMEM_BANK+BANK_SELECT_BITS)], // High order bits unchanged
addr[($clog2(MWIDTH_BYTES)+BANK_SELECT_BITS-1) : $clog2(MWIDTH_BYTES)], // Bank select from lsbits
addr[(HACKED_ABITS_PER_LMEM_BANK + BANK_SELECT_BITS-1) : ($clog2(MWIDTH_BYTES) + BANK_SELECT_BITS)]
};
end
else begin
permute_addr= {
addr[(AWIDTH-1) : (HACKED_ABITS_PER_LMEM_BANK+BANK_SELECT_BITS)], // High order bits unchanged
addr[($clog2(MWIDTH_BYTES)+BANK_SELECT_BITS-1) : $clog2(MWIDTH_BYTES)], // Bank select from lsbits
addr[(HACKED_ABITS_PER_LMEM_BANK + BANK_SELECT_BITS-1) : ($clog2(MWIDTH_BYTES) + BANK_SELECT_BITS)],
addr[($clog2(MWIDTH_BYTES_CLIP)-1) : 0] // Byte address within a word
};
end
end
else
begin
permute_addr= addr;
end
endfunction
wire [AWIDTH-1:0] avm_address_raw;
assign avm_address=permute_addr(avm_address_raw);
/***************
* Architecture *
***************/
// Tie off the unused read/write signals
// atomics dont have unused signals
if(ATOMIC==0) begin
if(READ==1)
begin
assign avm_write = 1'b0;
//assign avm_writedata = {MWIDTH{1'bx}};
assign avm_writedata = {MWIDTH{1'b0}}; // make writedata 0 because it is used by atomics
end
else // WRITE
begin
assign avm_read = 1'b0;
end
end
else begin //ATOMIC
assign avm_write = 1'b0;
end
// Write acknowledge support: If WRITEACK is not to be supported, than assume
// that a write is fully completed as soon as it is accepted by the fabric.
// Otherwise, wait for the writeack signal to return.
wire lsu_writeack;
if(USE_WRITE_ACK==1)
begin
assign lsu_writeack = avm_writeack;
end
else
begin
assign lsu_writeack = avm_write && !avm_waitrequest;
end
// NOP support: The least-significant address bit indicates if this is a NOP
// instruction (i.e. we do not wish a read/write to be performed).
// Appropriately adjust the valid and stall inputs to the core LSU block to
// ensure NOP instructions are not executed and preserve their ordering with
// other threads.
wire lsu_i_valid;
wire lsu_o_valid;
wire lsu_i_stall;
wire lsu_o_stall;
wire [AWIDTH-1:0] address;
wire nop;
if(SUPPORTS_NOP)
begin
// Module intrinsicly supports NOP operations, just pass them on through
assign lsu_i_valid = i_valid;
assign lsu_i_stall = i_stall;
assign o_valid = lsu_o_valid;
assign o_stall = lsu_o_stall;
assign address = i_address | i_bitwiseor;
end
else if(PIPELINED_LSU || ATOMIC_PIPELINED_LSU)
begin
// No built-in NOP support. Pipelined LSUs without NOP support need us to
// build a fifo along side the core LSU to track NOP instructions
wire nop_fifo_empty;
wire nop_fifo_full;
wire nop_next;
assign nop = i_predicate;
assign address = i_address | i_bitwiseor;
// Store the NOP status flags along side the core LSU
// Assume (TODO eliminate this assumption?) that KERNEL_SIDE_MEM_LATENCY is the max
// number of simultaneous requests in flight for the LSU. The NOP FIFO will
// will be sized to KERNEL_SIDE_MEM_LATENCY+1 to prevent stalls when the LSU is
// full.
//
// For smaller latency values, use registers to implement the FIFO.
if(KERNEL_SIDE_MEM_LATENCY <= 64)
begin
acl_ll_fifo #(
.WIDTH(1),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) nop_fifo (
.clk(clock),
.reset(~sync_rstn),
.data_in(nop),
.write(i_valid && !o_stall),
.data_out(nop_next),
.read(o_valid && !i_stall),
.full(nop_fifo_full),
.empty(nop_fifo_empty)
);
end
else
begin
scfifo #(
.add_ram_output_register( "OFF" ),
.intended_device_family( "Stratix IV" ),
.lpm_numwords( KERNEL_SIDE_MEM_LATENCY+1 ),
.lpm_showahead( "ON" ),
.lpm_type( "scfifo" ),
.lpm_width( 1 ),
.lpm_widthu( $clog2(KERNEL_SIDE_MEM_LATENCY+1) ),
.overflow_checking( "OFF" ),
.underflow_checking( "OFF" )
) nop_fifo (
.clock(clock),
.data(nop),
.rdreq(o_valid && !i_stall),
.wrreq(i_valid && !o_stall),
.empty(nop_fifo_empty),
.full(nop_fifo_full),
.q(nop_next),
.aclr(!sync_rstn),
.almost_full(),
.almost_empty(),
.usedw(),
.sclr()
);
end
// Logic to prevent NOP instructions from entering the core
assign lsu_i_valid = !nop && i_valid && !nop_fifo_full;
assign lsu_i_stall = nop_fifo_empty || nop_next || i_stall;
// Logic to generate the valid bit for NOP instructions that have bypassed
// the LSU. The instructions must be kept in order so they are consistant
// with data propagating through pipelines outside of the LSU.
assign o_valid = (lsu_o_valid || nop_next) && !nop_fifo_empty;
assign o_stall = nop_fifo_full || lsu_o_stall;
end
else
begin
// An unpipelined LSU will only have one active request at a time. We just
// need to track whether there is a pending request in the LSU core and
// appropriately bypass the core with NOP requests while preserving the
// thread ordering. (A NOP passes straight through to the downstream
// block, unless there is a pending request in the block, in which case
// we stall until the request is complete).
reg pending;
always@(posedge clock or negedge sync_rstn)
begin
if(sync_rstn == 1'b0)
pending <= 1'b0;
else
pending <= pending ? ((lsu_i_valid && !lsu_o_stall) || !(lsu_o_valid && !lsu_i_stall)) :
((lsu_i_valid && !lsu_o_stall) && !(lsu_o_valid && !lsu_i_stall));
end
assign nop = i_predicate;
assign address = i_address | i_bitwiseor;
assign lsu_i_valid = i_valid && !nop;
assign lsu_i_stall = i_stall;
assign o_valid = lsu_o_valid || (!pending && i_valid && nop);
assign o_stall = lsu_o_stall || (pending && nop);
end
// Styles with no burst support require burstcount=1
if(!SUPPORTS_BURSTS)
begin
assign avm_burstcount = 1;
end
// Profiling signals.
wire req_cache_hit_count;
wire extra_unaligned_reqs;
// initialize
if(READ==0 || STYLE!="BURST-NON-ALIGNED")
assign extra_unaligned_reqs = 1'b0;
if(READ==0 || (STYLE!="BURST-COALESCED" && STYLE!="BURST-NON-ALIGNED" && STYLE!="SEMI-STREAMING"))
assign req_cache_hit_count = 1'b0;
// Generate different architectures based on the STYLE parameter
////////////////
// Simple LSU //
////////////////
if(STYLE=="SIMPLE")
begin
if(READ == 1)
begin
lsu_simple_read #(
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.HIGH_FMAX(HIGH_FMAX)
) simple_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.o_readdata(o_readdata),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_simple_write #(
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) simple_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.i_byteenable(i_byteenable),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
///////////////
// Pipelined //
///////////////
else if(STYLE=="PIPELINED")
begin
wire sub_o_stall;
if(USEINPUTFIFO == 0) begin : GEN_0
assign lsu_o_stall = sub_o_stall & !i_predicate;
end
else begin : GEN_1
assign lsu_o_stall = sub_o_stall;
end
if(READ == 1)
begin
lsu_pipelined_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO),
.USEOUTPUTFIFO(USEOUTPUTFIFO)
) pipelined_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(sub_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_pipelined_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO)
) pipelined_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(sub_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_byteenable(i_byteenable),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
//////////////////////
// Atomic Pipelined //
//////////////////////
else if(STYLE=="ATOMIC-PIPELINED")
begin
lsu_atomic_pipelined #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.WRITEDATAWIDTH_BYTES(WRITEDATAWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO),
.USEOUTPUTFIFO(USEOUTPUTFIFO),
.ATOMIC_WIDTH(ATOMIC_WIDTH)
) atomic_pipelined (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.i_atomic_op(i_atomic_op),
.i_writedata(i_writedata),
.i_cmpdata(i_cmpdata),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata)
);
end
/////////////////////
// Basic Coalesced //
/////////////////////
else if(STYLE=="BASIC-COALESCED")
begin
if(READ == 1)
begin
lsu_basic_coalesced_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) basic_coalesced_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_basic_coalesced_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) basic_coalesced_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_writedata(i_writedata),
.i_byteenable(i_byteenable),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
/////////////////////
// Burst Coalesced //
/////////////////////
else if(STYLE=="BURST-COALESCED")
begin
if(READ == 1)
begin
lsu_bursting_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USECACHING(USECACHING),
.HIGH_FMAX(HIGH_FMAX),
.ACL_PROFILE(ACL_PROFILE),
.CACHE_SIZE_N(CACHESIZE)
) bursting_read (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.flush(flush),
.i_nop(i_predicate),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_readdatavalid(avm_readdatavalid),
.req_cache_hit_count(req_cache_hit_count)
);
end
else
begin
// Non-writeack stores are similar to streaming, where the pipeline
// needs only few threads which just drop off data, and internally the
// LSU must account for arbitration contention and other delays.
lsu_bursting_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_write (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_nop(i_predicate),
.i_address(address),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest)
);
end
end
/////////////////////////////////
// Burst Coalesced Non Aligned //
/////////////////////////////////
else if(STYLE=="BURST-NON-ALIGNED")
begin
if(READ == 1)
begin
lsu_bursting_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USECACHING(USECACHING),
.CACHE_SIZE_N(CACHESIZE),
.HIGH_FMAX(HIGH_FMAX),
.ACL_PROFILE(ACL_PROFILE),
.UNALIGNED(1)
) bursting_non_aligned_read (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.flush(flush),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_nop(i_predicate),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_readdatavalid(avm_readdatavalid),
.extra_unaligned_reqs(extra_unaligned_reqs),
.req_cache_hit_count(req_cache_hit_count)
);
end
else
begin
lsu_non_aligned_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_non_aligned_write (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_nop(i_predicate),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest)
);
end
end
///////////////
// Streaming //
///////////////
else if(STYLE=="STREAMING")
begin
if(READ==1)
begin
lsu_streaming_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH)
) streaming_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.i_nop(i_predicate),
.base_address(stream_base_addr),
.size(stream_size),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_streaming_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_BYTE_EN(USE_BYTE_EN)
) streaming_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.i_writedata(i_writedata),
.i_nop(i_predicate),
.base_address(stream_base_addr),
.size(stream_size),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
////////////////////
// SEMI-Streaming //
////////////////////
else if(STYLE=="SEMI-STREAMING")
begin
if(READ==1)
begin
lsu_read_cache #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.ACL_PROFILE(ACL_PROFILE),
.REQUESTED_SIZE(CACHESIZE)
) read_cache (
.clk(clock),
.reset(!sync_rstn),
.flush(flush),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.i_nop(i_predicate),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.req_cache_hit_count(req_cache_hit_count)
);
end
end
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
o_active <= 1'b0;
else
o_active <= lsu_active;
// Profile the valids and stalls of the LSU
if(ACL_PROFILE==1)
begin
// keep track of write bursts
reg [BURSTCOUNT_WIDTH-1:0] profile_remaining_writeburst_count;
wire active_write_burst;
assign active_write_burst = (profile_remaining_writeburst_count != {BURSTCOUNT_WIDTH{1'b0}});
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
profile_remaining_writeburst_count <= {BURSTCOUNT_WIDTH{1'b0}};
else if(avm_write & ~avm_waitrequest & ~active_write_burst)
// start of a new write burst
profile_remaining_writeburst_count <= avm_burstcount - 1;
else if(~avm_waitrequest & active_write_burst)
// count down one burst
profile_remaining_writeburst_count <= profile_remaining_writeburst_count - 1;
assign profile_bw = (READ==1) ? avm_readdatavalid : (avm_write & ~avm_waitrequest);
assign profile_bw_incr = MWIDTH_BYTES;
assign profile_total_ivalid = (i_valid & ~o_stall);
assign profile_total_req = (i_valid & ~i_predicate & ~o_stall);
assign profile_i_stall_count = (i_stall & o_valid);
assign profile_o_stall_count = (o_stall & i_valid);
assign profile_avm_readwrite_count = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total_incr = avm_burstcount;
assign profile_req_cache_hit_count = req_cache_hit_count;
assign profile_extra_unaligned_reqs = extra_unaligned_reqs;
assign profile_avm_stall = ((avm_read | avm_write) & avm_waitrequest);
end
else begin
assign profile_bw = 1'b0;
assign profile_bw_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_total_ivalid = 1'b0;
assign profile_total_req = 1'b0;
assign profile_i_stall_count = 1'b0;
assign profile_o_stall_count = 1'b0;
assign profile_avm_readwrite_count = 1'b0;
assign profile_avm_burstcount_total = 1'b0;
assign profile_avm_burstcount_total_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_req_cache_hit_count = 1'b0;
assign profile_extra_unaligned_reqs = 1'b0;
assign profile_avm_stall = 1'b0;
end
// synthesis translate_off
// Profiling data - for simulation only
reg [31:0] bw_kernel;
reg [31:0] bw_avalon;
// Measure Bandwidth on Avalon signals
always@(posedge clock or negedge sync_rstn)
begin
if (!sync_rstn)
bw_avalon <= 0;
else
if (READ==1 && avm_readdatavalid)
bw_avalon <= bw_avalon + MWIDTH_BYTES;
else if (READ==0 && avm_write && ~avm_waitrequest)
bw_avalon <= bw_avalon + MWIDTH_BYTES;
end
// Measure Bandwidth on kernel signals
always@(posedge clock or negedge sync_rstn)
begin
if (!sync_rstn)
bw_kernel <= 0;
else if (i_valid && !o_stall && ~nop)
bw_kernel <= bw_kernel + WIDTH_BYTES;
end
// synthesis translate_on
if(PROFILE_ADDR_TOGGLE==1 && STYLE!="SIMPLE")
begin
localparam COUNTERWIDTH=12;
// We currently assume AWIDTH is always 32, but we really need to set this to
// a tight lower bound to avoid wasting area here.
logic [COUNTERWIDTH-1:0] togglerate[AWIDTH-ALIGNMENT_ABITS+1];
acl_toggle_detect
#(.WIDTH(AWIDTH-ALIGNMENT_ABITS), .COUNTERWIDTH(COUNTERWIDTH)) atd (
.clk(clock),
.resetn(sync_rstn),
.valid(i_valid && ~o_stall && ~nop),
.value({i_address >> ALIGNMENT_ABITS,{ALIGNMENT_ABITS{1'b0}}}),
.count(togglerate));
acl_debug_mem #(.WIDTH(COUNTERWIDTH), .SIZE(AWIDTH-ALIGNMENT_ABITS+1)) dbg_mem (
.clk(clock),
.resetn(sync_rstn),
.write(i_valid && ~o_stall && ~nop),
.data(togglerate));
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level load/store unit
//
// Attributes of load/store units
// Coalesced: Accesses to neighbouring memory locations are grouped together
// to improve efficiency and efficiently utilize memory bandwidth.
// Hazard-Safe:The LSU is not susceptable to data hazards.
// Ordered: The LSU requires accesses to be in-order to properly coalesce.
// Pipeline: The LSU can handle multiple requests at a time without
// stalling. Improves throughput.
//
// Supports the following memory access patterns:
// Simple - STYLE="SIMPLE"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined, No
// Simple un-pipelined memory access. Low throughput.
// Pipelined - STYLE="PIPELINED"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Coalesced - STYLE="BASIC-COALESCED"
// "basic" Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Coalesced - STYLE="BURST-COALESCED"
// "burst" Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// Requests are buffered until the biggest possible burst can
// be made.
// Streaming - STYLE="STREAMING"
// Coalesced: Yes, Ordered: Yes, Hazard-Safe: No, Pipelined: ?
// A FIFO is instantiated which burst reads large blocks from
// memory to keep the FIFO full of valid data. This block can
// only be used if accesses are in-order, and addresses can be
// simply calculated from (base_address + n * word_width). The
// block has no built-in hazard protection.
// Atomic - STYLE="ATOMIC-PIPELINED"
//"pipelined"
// Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// Atomic: Yes
// Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Response is returned as soon as read is complete,
// write is issued subsequently by the atomic module at the end
// of arbitration.
module lsu_top
(
clock, clock2x, resetn, stream_base_addr, stream_size, stream_reset, i_atomic_op, o_stall,
i_valid, i_address, i_writedata, i_cmpdata, i_predicate, i_bitwiseor, i_stall, o_valid, o_readdata, avm_address,
avm_read, avm_readdata, avm_write, avm_writeack, avm_writedata, avm_byteenable,
avm_waitrequest, avm_readdatavalid, avm_burstcount,
o_active,
o_input_fifo_depth,
o_writeack,
i_byteenable,
flush,
// profile signals
profile_bw, profile_bw_incr,
profile_total_ivalid,
profile_total_req,
profile_i_stall_count,
profile_o_stall_count,
profile_avm_readwrite_count,
profile_avm_burstcount_total, profile_avm_burstcount_total_incr,
profile_req_cache_hit_count,
profile_extra_unaligned_reqs,
profile_avm_stall
);
/*************
* Parameters *
*************/
parameter STYLE="PIPELINED"; // The LSU style to use (see style list above)
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter ATOMIC_WIDTH=6; // Width of operation operation indices
parameter WIDTH_BYTES=4; // Width of the request (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter WRITEDATAWIDTH_BYTES=32; // Width of the readdata/writedata signals,
// may be larger than MWIDTH_BYTES for atomics
parameter ALIGNMENT_BYTES=2; // Request address alignment (bytes)
parameter READ=1; // Read or write?
parameter ATOMIC=0; // Atomic?
parameter BURSTCOUNT_WIDTH=6;// Determines max burst size
// Why two latencies? E.g. A streaming unit prefetches data, its latency to
// the kernel is very low because data is for the most part ready and waiting.
// But the lsu needs to know how much data to buffer to hide the latency to
// memory, hence the memory side latency.
parameter KERNEL_SIDE_MEM_LATENCY=1; // Effective Latency in cycles as seen by the kernel pipeline
parameter MEMORY_SIDE_MEM_LATENCY=1; // Latency in cycles between LSU and memory
parameter USE_WRITE_ACK=0; // Enable the write-acknowledge signal
parameter USECACHING=0;
parameter USE_BYTE_EN=0;
parameter CACHESIZE=1024;
parameter PROFILE_ADDR_TOGGLE=0;
parameter USEINPUTFIFO=1; // FIXME specific to lsu_pipelined
parameter USEOUTPUTFIFO=1; // FIXME specific to lsu_pipelined
parameter FORCE_NOP_SUPPORT=0; // Stall free pipeline doesn't want the NOP fifo
parameter HIGH_FMAX=1; // Enable optimizations for high Fmax
// Profiling
parameter ACL_PROFILE=0; // Set to 1 to enable stall/valid profiling
parameter ACL_PROFILE_INCREMENT_WIDTH=32;
// Verilog readability and parsing only - no functional purpose
parameter ADDRSPACE=0;
// Local memory parameters
parameter ENABLE_BANKED_MEMORY=0;// Flag enables address permutation for banked local memory config
parameter ABITS_PER_LMEM_BANK=0; // Used when permuting lmem address bits to stride across banks
parameter NUMBER_BANKS=1; // Number of memory banks - used in address permutation (1-disable)
parameter LMEM_ADDR_PERMUTATION_STYLE=0; // Type of address permutation (currently unused)
// The following localparams have if conditions, and the second is named
// "HACKED..." because address bit permutations are controlled by the
// ENABLE_BANKED_MEMORY parameter. The issue is that this forms the select
// input of a MUX (if statement), and synthesis evaluates both inputs.
// When not using banked memory, the bit select ranges don't make sense on
// the input that isn't used, so we need to hack them in the non-banked case
// to get through ModelSim and Quartus.
localparam BANK_SELECT_BITS = (ENABLE_BANKED_MEMORY==1) ? $clog2(NUMBER_BANKS) : 1; // Bank select bits in address permutation
localparam HACKED_ABITS_PER_LMEM_BANK = (ENABLE_BANKED_MEMORY==1) ? ABITS_PER_LMEM_BANK : $clog2(MWIDTH_BYTES)+1;
// Parameter limitations:
// AWIDTH: Only tested with 32-bit addresses
// WIDTH_BYTES: Must be a power of two
// MWIDTH_BYTES: Must be a power of 2 >= WIDTH_BYTES
// ALIGNMENT_BYTES: Must be a power of 2 satisfying,
// WIDTH_BYTES <= ALIGNMENT_BYTES <= MWIDTH_BYTES
//
// The width and alignment restrictions ensure we never try to read a word
// that strides across two "pages" (MWIDTH sized words)
// TODO: Convert these back into localparams when the back-end supports it
parameter WIDTH=8*WIDTH_BYTES; // Width in bits
parameter MWIDTH=8*MWIDTH_BYTES; // Width in bits
parameter WRITEDATAWIDTH=8*WRITEDATAWIDTH_BYTES; // Width in bits
localparam ALIGNMENT_ABITS=$clog2(ALIGNMENT_BYTES); // Address bits to ignore
localparam LSU_CAPACITY=256; // Maximum number of 'in-flight' load/store operations
localparam WIDE_LSU = (WIDTH > MWIDTH);
// Performance monitor signals
parameter INPUTFIFO_USEDW_MAXBITS=8;
// LSU unit properties
localparam ATOMIC_PIPELINED_LSU=(STYLE=="ATOMIC-PIPELINED");
localparam PIPELINED_LSU=( (STYLE=="PIPELINED") || (STYLE=="BASIC-COALESCED") || (STYLE=="BURST-COALESCED") || (STYLE=="BURST-NON-ALIGNED") );
localparam SUPPORTS_NOP= (STYLE=="STREAMING") || (STYLE=="SEMI-STREAMING") || (STYLE=="BURST-NON-ALIGNED") || (STYLE=="BURST-COALESCED") || (FORCE_NOP_SUPPORT==1);
localparam SUPPORTS_BURSTS=( (STYLE=="STREAMING") || (STYLE=="BURST-COALESCED") || (STYLE=="SEMI-STREAMING") || (STYLE=="BURST-NON-ALIGNED") );
/********
* Ports *
********/
// Standard global signals
input clock;
input clock2x;
input resetn;
input flush;
// Streaming interface signals
input [AWIDTH-1:0] stream_base_addr;
input [31:0] stream_size;
input stream_reset;
// Atomic interface
input [WIDTH-1:0] i_cmpdata; // only used by atomic_cmpxchg
input [ATOMIC_WIDTH-1:0] i_atomic_op;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input i_predicate;
input [AWIDTH-1:0] i_bitwiseor;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [WRITEDATAWIDTH-1:0] avm_readdata;
output avm_write;
input avm_writeack;
output o_writeack;
output [WRITEDATAWIDTH-1:0] avm_writedata;
output [WRITEDATAWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output reg o_active;
// For profiling/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
// Profiler Signals
output logic profile_bw;
output logic [ACL_PROFILE_INCREMENT_WIDTH-1:0] profile_bw_incr;
output logic profile_total_ivalid;
output logic profile_total_req;
output logic profile_i_stall_count;
output logic profile_o_stall_count;
output logic profile_avm_readwrite_count;
output logic profile_avm_burstcount_total;
output logic [ACL_PROFILE_INCREMENT_WIDTH-1:0] profile_avm_burstcount_total_incr;
output logic profile_req_cache_hit_count;
output logic profile_extra_unaligned_reqs;
output logic profile_avm_stall;
// help timing; reduce the high fanout of global reset from iface
reg [1:0] sync_rstn_MS /* synthesis syn_preserve = 1 */ ;
wire sync_rstn;
assign sync_rstn = sync_rstn_MS[1];
always @(posedge clock or negedge resetn) begin
if(!resetn) sync_rstn_MS <= 2'b00;
else sync_rstn_MS <= {sync_rstn_MS[0], 1'b1};
end
generate
if(WIDE_LSU) begin
//break transaction into multiple cycles
lsu_wide_wrapper lsu_wide (
.clock(clock),
.clock2x(clock2x),
.resetn(sync_rstn),
.flush(flush),
.stream_base_addr(stream_base_addr),
.stream_size(stream_size),
.stream_reset(stream_reset),
.o_stall(o_stall),
.i_valid(i_valid),
.i_address(i_address),
.i_writedata(i_writedata),
.i_cmpdata(i_cmpdata),
.i_predicate(i_predicate),
.i_bitwiseor(i_bitwiseor),
.i_byteenable(i_byteenable),
.i_stall(i_stall),
.o_valid(o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_writeack(o_writeack),
.i_atomic_op(i_atomic_op),
.o_active(o_active),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_write(avm_write),
.avm_writeack(avm_writeack),
.avm_burstcount(avm_burstcount),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest),
.avm_readdatavalid(avm_readdatavalid),
.profile_req_cache_hit_count(profile_req_cache_hit_count),
.profile_extra_unaligned_reqs(profile_extra_unaligned_reqs)
);
defparam lsu_wide.STYLE = STYLE;
defparam lsu_wide.AWIDTH = AWIDTH;
defparam lsu_wide.ATOMIC_WIDTH = ATOMIC_WIDTH;
defparam lsu_wide.WIDTH_BYTES = WIDTH_BYTES;
defparam lsu_wide.MWIDTH_BYTES = MWIDTH_BYTES;
defparam lsu_wide.WRITEDATAWIDTH_BYTES = WRITEDATAWIDTH_BYTES;
defparam lsu_wide.ALIGNMENT_BYTES = ALIGNMENT_BYTES;
defparam lsu_wide.READ = READ;
defparam lsu_wide.ATOMIC = ATOMIC;
defparam lsu_wide.BURSTCOUNT_WIDTH = BURSTCOUNT_WIDTH;
defparam lsu_wide.KERNEL_SIDE_MEM_LATENCY = KERNEL_SIDE_MEM_LATENCY;
defparam lsu_wide.MEMORY_SIDE_MEM_LATENCY = MEMORY_SIDE_MEM_LATENCY;
defparam lsu_wide.USE_WRITE_ACK = USE_WRITE_ACK;
defparam lsu_wide.USECACHING = USECACHING;
defparam lsu_wide.USE_BYTE_EN = USE_BYTE_EN;
defparam lsu_wide.CACHESIZE = CACHESIZE;
defparam lsu_wide.PROFILE_ADDR_TOGGLE = PROFILE_ADDR_TOGGLE;
defparam lsu_wide.USEINPUTFIFO = USEINPUTFIFO;
defparam lsu_wide.USEOUTPUTFIFO = USEOUTPUTFIFO;
defparam lsu_wide.FORCE_NOP_SUPPORT = FORCE_NOP_SUPPORT;
defparam lsu_wide.HIGH_FMAX = HIGH_FMAX;
defparam lsu_wide.ACL_PROFILE = ACL_PROFILE;
defparam lsu_wide.ACL_PROFILE_INCREMENT_WIDTH = ACL_PROFILE_INCREMENT_WIDTH;
defparam lsu_wide.ENABLE_BANKED_MEMORY = ENABLE_BANKED_MEMORY;
defparam lsu_wide.ABITS_PER_LMEM_BANK = ABITS_PER_LMEM_BANK;
defparam lsu_wide.NUMBER_BANKS = NUMBER_BANKS;
defparam lsu_wide.WIDTH = WIDTH;
defparam lsu_wide.MWIDTH = MWIDTH;
defparam lsu_wide.WRITEDATAWIDTH = WRITEDATAWIDTH;
defparam lsu_wide.INPUTFIFO_USEDW_MAXBITS = INPUTFIFO_USEDW_MAXBITS;
defparam lsu_wide.LMEM_ADDR_PERMUTATION_STYLE = LMEM_ADDR_PERMUTATION_STYLE;
defparam lsu_wide.ADDRSPACE = ADDRSPACE;
//the wrapped LSU doesnt interface directly with the avalon master, so profiling here is more accurate for avm signals
//two signals generated directly by the LSU need to be passed in
if(ACL_PROFILE==1)
begin
// keep track of write bursts
reg [BURSTCOUNT_WIDTH-1:0] profile_remaining_writeburst_count;
wire active_write_burst;
assign active_write_burst = (profile_remaining_writeburst_count != {BURSTCOUNT_WIDTH{1'b0}});
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
profile_remaining_writeburst_count <= {BURSTCOUNT_WIDTH{1'b0}};
else if(avm_write & ~avm_waitrequest & ~active_write_burst)
// start of a new write burst
profile_remaining_writeburst_count <= avm_burstcount - 1;
else if(~avm_waitrequest & active_write_burst)
// count down one burst
profile_remaining_writeburst_count <= profile_remaining_writeburst_count - 1;
assign profile_bw = (READ==1) ? avm_readdatavalid : (avm_write & ~avm_waitrequest);
assign profile_bw_incr = MWIDTH_BYTES;
assign profile_total_ivalid = (i_valid & ~o_stall);
assign profile_total_req = (i_valid & ~i_predicate & ~o_stall);
assign profile_i_stall_count = (i_stall & o_valid);
assign profile_o_stall_count = (o_stall & i_valid);
assign profile_avm_readwrite_count = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total_incr = avm_burstcount;
assign profile_avm_stall = ((avm_read | avm_write) & avm_waitrequest);
end
else begin
assign profile_bw = 1'b0;
assign profile_bw_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_total_ivalid = 1'b0;
assign profile_total_req = 1'b0;
assign profile_i_stall_count = 1'b0;
assign profile_o_stall_count = 1'b0;
assign profile_avm_readwrite_count = 1'b0;
assign profile_avm_burstcount_total = 1'b0;
assign profile_avm_burstcount_total_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_avm_stall = 1'b0;
end
end
else begin
wire lsu_active;
// For handling dependents of this lsu
assign o_writeack = avm_writeack;
// If this is a banked local memory LSU, then permute address bits so that
// consective words in memory are in different banks. Do this by
// taking the k lowest bits of the word-address and shifting them to the top
// of the aggregate local memory address width. The number of bits k
// corresponds to the number of banks parameter.
localparam MWIDTH_BYTES_CLIP = (MWIDTH_BYTES==1) ? 2 : MWIDTH_BYTES; //to get around modelsim looking at addr[-1:0] if MWIDTH_BYTES==1
function [AWIDTH-1:0] permute_addr ( input [AWIDTH-1:0] addr);
if (ENABLE_BANKED_MEMORY==1)
begin
if (MWIDTH_BYTES==1) begin
permute_addr= {
addr[(AWIDTH-1) : (HACKED_ABITS_PER_LMEM_BANK+BANK_SELECT_BITS)], // High order bits unchanged
addr[($clog2(MWIDTH_BYTES)+BANK_SELECT_BITS-1) : $clog2(MWIDTH_BYTES)], // Bank select from lsbits
addr[(HACKED_ABITS_PER_LMEM_BANK + BANK_SELECT_BITS-1) : ($clog2(MWIDTH_BYTES) + BANK_SELECT_BITS)]
};
end
else begin
permute_addr= {
addr[(AWIDTH-1) : (HACKED_ABITS_PER_LMEM_BANK+BANK_SELECT_BITS)], // High order bits unchanged
addr[($clog2(MWIDTH_BYTES)+BANK_SELECT_BITS-1) : $clog2(MWIDTH_BYTES)], // Bank select from lsbits
addr[(HACKED_ABITS_PER_LMEM_BANK + BANK_SELECT_BITS-1) : ($clog2(MWIDTH_BYTES) + BANK_SELECT_BITS)],
addr[($clog2(MWIDTH_BYTES_CLIP)-1) : 0] // Byte address within a word
};
end
end
else
begin
permute_addr= addr;
end
endfunction
wire [AWIDTH-1:0] avm_address_raw;
assign avm_address=permute_addr(avm_address_raw);
/***************
* Architecture *
***************/
// Tie off the unused read/write signals
// atomics dont have unused signals
if(ATOMIC==0) begin
if(READ==1)
begin
assign avm_write = 1'b0;
//assign avm_writedata = {MWIDTH{1'bx}};
assign avm_writedata = {MWIDTH{1'b0}}; // make writedata 0 because it is used by atomics
end
else // WRITE
begin
assign avm_read = 1'b0;
end
end
else begin //ATOMIC
assign avm_write = 1'b0;
end
// Write acknowledge support: If WRITEACK is not to be supported, than assume
// that a write is fully completed as soon as it is accepted by the fabric.
// Otherwise, wait for the writeack signal to return.
wire lsu_writeack;
if(USE_WRITE_ACK==1)
begin
assign lsu_writeack = avm_writeack;
end
else
begin
assign lsu_writeack = avm_write && !avm_waitrequest;
end
// NOP support: The least-significant address bit indicates if this is a NOP
// instruction (i.e. we do not wish a read/write to be performed).
// Appropriately adjust the valid and stall inputs to the core LSU block to
// ensure NOP instructions are not executed and preserve their ordering with
// other threads.
wire lsu_i_valid;
wire lsu_o_valid;
wire lsu_i_stall;
wire lsu_o_stall;
wire [AWIDTH-1:0] address;
wire nop;
if(SUPPORTS_NOP)
begin
// Module intrinsicly supports NOP operations, just pass them on through
assign lsu_i_valid = i_valid;
assign lsu_i_stall = i_stall;
assign o_valid = lsu_o_valid;
assign o_stall = lsu_o_stall;
assign address = i_address | i_bitwiseor;
end
else if(PIPELINED_LSU || ATOMIC_PIPELINED_LSU)
begin
// No built-in NOP support. Pipelined LSUs without NOP support need us to
// build a fifo along side the core LSU to track NOP instructions
wire nop_fifo_empty;
wire nop_fifo_full;
wire nop_next;
assign nop = i_predicate;
assign address = i_address | i_bitwiseor;
// Store the NOP status flags along side the core LSU
// Assume (TODO eliminate this assumption?) that KERNEL_SIDE_MEM_LATENCY is the max
// number of simultaneous requests in flight for the LSU. The NOP FIFO will
// will be sized to KERNEL_SIDE_MEM_LATENCY+1 to prevent stalls when the LSU is
// full.
//
// For smaller latency values, use registers to implement the FIFO.
if(KERNEL_SIDE_MEM_LATENCY <= 64)
begin
acl_ll_fifo #(
.WIDTH(1),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) nop_fifo (
.clk(clock),
.reset(~sync_rstn),
.data_in(nop),
.write(i_valid && !o_stall),
.data_out(nop_next),
.read(o_valid && !i_stall),
.full(nop_fifo_full),
.empty(nop_fifo_empty)
);
end
else
begin
scfifo #(
.add_ram_output_register( "OFF" ),
.intended_device_family( "Stratix IV" ),
.lpm_numwords( KERNEL_SIDE_MEM_LATENCY+1 ),
.lpm_showahead( "ON" ),
.lpm_type( "scfifo" ),
.lpm_width( 1 ),
.lpm_widthu( $clog2(KERNEL_SIDE_MEM_LATENCY+1) ),
.overflow_checking( "OFF" ),
.underflow_checking( "OFF" )
) nop_fifo (
.clock(clock),
.data(nop),
.rdreq(o_valid && !i_stall),
.wrreq(i_valid && !o_stall),
.empty(nop_fifo_empty),
.full(nop_fifo_full),
.q(nop_next),
.aclr(!sync_rstn),
.almost_full(),
.almost_empty(),
.usedw(),
.sclr()
);
end
// Logic to prevent NOP instructions from entering the core
assign lsu_i_valid = !nop && i_valid && !nop_fifo_full;
assign lsu_i_stall = nop_fifo_empty || nop_next || i_stall;
// Logic to generate the valid bit for NOP instructions that have bypassed
// the LSU. The instructions must be kept in order so they are consistant
// with data propagating through pipelines outside of the LSU.
assign o_valid = (lsu_o_valid || nop_next) && !nop_fifo_empty;
assign o_stall = nop_fifo_full || lsu_o_stall;
end
else
begin
// An unpipelined LSU will only have one active request at a time. We just
// need to track whether there is a pending request in the LSU core and
// appropriately bypass the core with NOP requests while preserving the
// thread ordering. (A NOP passes straight through to the downstream
// block, unless there is a pending request in the block, in which case
// we stall until the request is complete).
reg pending;
always@(posedge clock or negedge sync_rstn)
begin
if(sync_rstn == 1'b0)
pending <= 1'b0;
else
pending <= pending ? ((lsu_i_valid && !lsu_o_stall) || !(lsu_o_valid && !lsu_i_stall)) :
((lsu_i_valid && !lsu_o_stall) && !(lsu_o_valid && !lsu_i_stall));
end
assign nop = i_predicate;
assign address = i_address | i_bitwiseor;
assign lsu_i_valid = i_valid && !nop;
assign lsu_i_stall = i_stall;
assign o_valid = lsu_o_valid || (!pending && i_valid && nop);
assign o_stall = lsu_o_stall || (pending && nop);
end
// Styles with no burst support require burstcount=1
if(!SUPPORTS_BURSTS)
begin
assign avm_burstcount = 1;
end
// Profiling signals.
wire req_cache_hit_count;
wire extra_unaligned_reqs;
// initialize
if(READ==0 || STYLE!="BURST-NON-ALIGNED")
assign extra_unaligned_reqs = 1'b0;
if(READ==0 || (STYLE!="BURST-COALESCED" && STYLE!="BURST-NON-ALIGNED" && STYLE!="SEMI-STREAMING"))
assign req_cache_hit_count = 1'b0;
// Generate different architectures based on the STYLE parameter
////////////////
// Simple LSU //
////////////////
if(STYLE=="SIMPLE")
begin
if(READ == 1)
begin
lsu_simple_read #(
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.HIGH_FMAX(HIGH_FMAX)
) simple_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.o_readdata(o_readdata),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_simple_write #(
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) simple_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.i_byteenable(i_byteenable),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
///////////////
// Pipelined //
///////////////
else if(STYLE=="PIPELINED")
begin
wire sub_o_stall;
if(USEINPUTFIFO == 0) begin : GEN_0
assign lsu_o_stall = sub_o_stall & !i_predicate;
end
else begin : GEN_1
assign lsu_o_stall = sub_o_stall;
end
if(READ == 1)
begin
lsu_pipelined_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO),
.USEOUTPUTFIFO(USEOUTPUTFIFO)
) pipelined_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(sub_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_pipelined_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO)
) pipelined_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(sub_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_byteenable(i_byteenable),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
//////////////////////
// Atomic Pipelined //
//////////////////////
else if(STYLE=="ATOMIC-PIPELINED")
begin
lsu_atomic_pipelined #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.WRITEDATAWIDTH_BYTES(WRITEDATAWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USEINPUTFIFO(USEINPUTFIFO),
.USEOUTPUTFIFO(USEOUTPUTFIFO),
.ATOMIC_WIDTH(ATOMIC_WIDTH)
) atomic_pipelined (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_input_fifo_depth(o_input_fifo_depth),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.i_atomic_op(i_atomic_op),
.i_writedata(i_writedata),
.i_cmpdata(i_cmpdata),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata)
);
end
/////////////////////
// Basic Coalesced //
/////////////////////
else if(STYLE=="BASIC-COALESCED")
begin
if(READ == 1)
begin
lsu_basic_coalesced_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) basic_coalesced_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_basic_coalesced_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.USE_BYTE_EN(USE_BYTE_EN),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) basic_coalesced_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_writedata(i_writedata),
.i_byteenable(i_byteenable),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
/////////////////////
// Burst Coalesced //
/////////////////////
else if(STYLE=="BURST-COALESCED")
begin
if(READ == 1)
begin
lsu_bursting_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USECACHING(USECACHING),
.HIGH_FMAX(HIGH_FMAX),
.ACL_PROFILE(ACL_PROFILE),
.CACHE_SIZE_N(CACHESIZE)
) bursting_read (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.flush(flush),
.i_nop(i_predicate),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_readdatavalid(avm_readdatavalid),
.req_cache_hit_count(req_cache_hit_count)
);
end
else
begin
// Non-writeack stores are similar to streaming, where the pipeline
// needs only few threads which just drop off data, and internally the
// LSU must account for arbitration contention and other delays.
lsu_bursting_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_write (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_nop(i_predicate),
.i_address(address),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest)
);
end
end
/////////////////////////////////
// Burst Coalesced Non Aligned //
/////////////////////////////////
else if(STYLE=="BURST-NON-ALIGNED")
begin
if(READ == 1)
begin
lsu_bursting_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USECACHING(USECACHING),
.CACHE_SIZE_N(CACHESIZE),
.HIGH_FMAX(HIGH_FMAX),
.ACL_PROFILE(ACL_PROFILE),
.UNALIGNED(1)
) bursting_non_aligned_read (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.flush(flush),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_nop(i_predicate),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.avm_address(avm_address_raw),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_readdatavalid(avm_readdatavalid),
.extra_unaligned_reqs(extra_unaligned_reqs),
.req_cache_hit_count(req_cache_hit_count)
);
end
else
begin
lsu_non_aligned_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_non_aligned_write (
.clk(clock),
.clk2x(clock2x),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_nop(i_predicate),
.i_writedata(i_writedata),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.avm_address(avm_address_raw),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest)
);
end
end
///////////////
// Streaming //
///////////////
else if(STYLE=="STREAMING")
begin
if(READ==1)
begin
lsu_streaming_read #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH)
) streaming_read (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.i_nop(i_predicate),
.base_address(stream_base_addr),
.size(stream_size),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
end
else
begin
lsu_streaming_write #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.USE_BYTE_EN(USE_BYTE_EN)
) streaming_write (
.clk(clock),
.reset(!sync_rstn),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_active(lsu_active),
.i_byteenable(i_byteenable),
.i_writedata(i_writedata),
.i_nop(i_predicate),
.base_address(stream_base_addr),
.size(stream_size),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_write(avm_write),
.avm_writeack(lsu_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_waitrequest(avm_waitrequest)
);
end
end
////////////////////
// SEMI-Streaming //
////////////////////
else if(STYLE=="SEMI-STREAMING")
begin
if(READ==1)
begin
lsu_read_cache #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.ACL_PROFILE(ACL_PROFILE),
.REQUESTED_SIZE(CACHESIZE)
) read_cache (
.clk(clock),
.reset(!sync_rstn),
.flush(flush),
.o_stall(lsu_o_stall),
.i_valid(lsu_i_valid),
.i_address(address),
.i_stall(lsu_i_stall),
.o_valid(lsu_o_valid),
.o_readdata(o_readdata),
.o_active(lsu_active),
.i_nop(i_predicate),
.avm_address(avm_address_raw),
.avm_burstcount(avm_burstcount),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.req_cache_hit_count(req_cache_hit_count)
);
end
end
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
o_active <= 1'b0;
else
o_active <= lsu_active;
// Profile the valids and stalls of the LSU
if(ACL_PROFILE==1)
begin
// keep track of write bursts
reg [BURSTCOUNT_WIDTH-1:0] profile_remaining_writeburst_count;
wire active_write_burst;
assign active_write_burst = (profile_remaining_writeburst_count != {BURSTCOUNT_WIDTH{1'b0}});
always@(posedge clock or negedge sync_rstn)
if (!sync_rstn)
profile_remaining_writeburst_count <= {BURSTCOUNT_WIDTH{1'b0}};
else if(avm_write & ~avm_waitrequest & ~active_write_burst)
// start of a new write burst
profile_remaining_writeburst_count <= avm_burstcount - 1;
else if(~avm_waitrequest & active_write_burst)
// count down one burst
profile_remaining_writeburst_count <= profile_remaining_writeburst_count - 1;
assign profile_bw = (READ==1) ? avm_readdatavalid : (avm_write & ~avm_waitrequest);
assign profile_bw_incr = MWIDTH_BYTES;
assign profile_total_ivalid = (i_valid & ~o_stall);
assign profile_total_req = (i_valid & ~i_predicate & ~o_stall);
assign profile_i_stall_count = (i_stall & o_valid);
assign profile_o_stall_count = (o_stall & i_valid);
assign profile_avm_readwrite_count = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total = ((avm_read | avm_write) & ~avm_waitrequest & ~active_write_burst);
assign profile_avm_burstcount_total_incr = avm_burstcount;
assign profile_req_cache_hit_count = req_cache_hit_count;
assign profile_extra_unaligned_reqs = extra_unaligned_reqs;
assign profile_avm_stall = ((avm_read | avm_write) & avm_waitrequest);
end
else begin
assign profile_bw = 1'b0;
assign profile_bw_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_total_ivalid = 1'b0;
assign profile_total_req = 1'b0;
assign profile_i_stall_count = 1'b0;
assign profile_o_stall_count = 1'b0;
assign profile_avm_readwrite_count = 1'b0;
assign profile_avm_burstcount_total = 1'b0;
assign profile_avm_burstcount_total_incr = {ACL_PROFILE_INCREMENT_WIDTH{1'b0}};
assign profile_req_cache_hit_count = 1'b0;
assign profile_extra_unaligned_reqs = 1'b0;
assign profile_avm_stall = 1'b0;
end
// synthesis translate_off
// Profiling data - for simulation only
reg [31:0] bw_kernel;
reg [31:0] bw_avalon;
// Measure Bandwidth on Avalon signals
always@(posedge clock or negedge sync_rstn)
begin
if (!sync_rstn)
bw_avalon <= 0;
else
if (READ==1 && avm_readdatavalid)
bw_avalon <= bw_avalon + MWIDTH_BYTES;
else if (READ==0 && avm_write && ~avm_waitrequest)
bw_avalon <= bw_avalon + MWIDTH_BYTES;
end
// Measure Bandwidth on kernel signals
always@(posedge clock or negedge sync_rstn)
begin
if (!sync_rstn)
bw_kernel <= 0;
else if (i_valid && !o_stall && ~nop)
bw_kernel <= bw_kernel + WIDTH_BYTES;
end
// synthesis translate_on
if(PROFILE_ADDR_TOGGLE==1 && STYLE!="SIMPLE")
begin
localparam COUNTERWIDTH=12;
// We currently assume AWIDTH is always 32, but we really need to set this to
// a tight lower bound to avoid wasting area here.
logic [COUNTERWIDTH-1:0] togglerate[AWIDTH-ALIGNMENT_ABITS+1];
acl_toggle_detect
#(.WIDTH(AWIDTH-ALIGNMENT_ABITS), .COUNTERWIDTH(COUNTERWIDTH)) atd (
.clk(clock),
.resetn(sync_rstn),
.valid(i_valid && ~o_stall && ~nop),
.value({i_address >> ALIGNMENT_ABITS,{ALIGNMENT_ABITS{1'b0}}}),
.count(togglerate));
acl_debug_mem #(.WIDTH(COUNTERWIDTH), .SIZE(AWIDTH-ALIGNMENT_ABITS+1)) dbg_mem (
.clk(clock),
.resetn(sync_rstn),
.write(i_valid && ~o_stall && ~nop),
.data(togglerate));
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for pipelined memory access.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Pipelined read unit:
// Accept read requests on the upstream interface. When a request is
// received, store the requested byte address in the request fifo and
// pass the request through to the avalon interface. Response data
// is buffered in the response fifo and the appropriate word is muxed
// out of the response fifo based on the address in the request fifo.
// The response fifo has limited capacity, so a counter is used to track
// the number of pending responses to generate an upstream stall if
// we run out of room.
module lsu_pipelined_read
(
clk, reset, o_stall, i_valid, i_address, i_burstcount, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid,
o_input_fifo_depth,
avm_burstcount
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // The max number of live threads
parameter USEBURST=0;
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USEINPUTFIFO=1;
parameter USEOUTPUTFIFO=1;
parameter INPUTFIFOSIZE=32;
parameter PIPELINE_INPUT=0;
parameter SUPERPIPELINE=0; // Enable extremely aggressive pipelining of the LSU
parameter HIGH_FMAX=1;
localparam INPUTFIFO_USEDW_MAXBITS=$clog2(INPUTFIFOSIZE);
// Derived parameters
localparam MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
//
// We only o_stall if we have more than KERNEL_SIDE_MEM_LATENCY inflight requests
//
localparam RETURN_FIFO_SIZE=KERNEL_SIDE_MEM_LATENCY+(USEBURST ? 0 : 1);
localparam COUNTER_WIDTH=USEBURST ? $clog2(RETURN_FIFO_SIZE+1+MAX_BURST) : $clog2(RETURN_FIFO_SIZE+1);
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [BURSTCOUNT_WIDTH-1:0] i_burstcount;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// For profiler/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
/***************
* Architecture *
***************/
wire i_valid_from_fifo;
wire [AWIDTH-1:0] i_address_from_fifo;
wire o_stall_to_fifo;
wire [BURSTCOUNT_WIDTH-1:0] i_burstcount_from_fifo;
wire read_accepted;
wire read_used;
wire [BYTE_SELECT_BITS-1:0] byte_select;
wire ready;
wire out_fifo_wait;
localparam FIFO_DEPTH_BITS=USEINPUTFIFO ? $clog2(INPUTFIFOSIZE) : 0;
wire [FIFO_DEPTH_BITS-1:0] usedw_true_width;
generate
if (USEINPUTFIFO)
assign o_input_fifo_depth[FIFO_DEPTH_BITS-1:0] = usedw_true_width;
// Set unused bits to 0
genvar bit_index;
for(bit_index = FIFO_DEPTH_BITS; bit_index < INPUTFIFO_USEDW_MAXBITS; bit_index = bit_index + 1)
begin: read_fifo_depth_zero_assign
assign o_input_fifo_depth[bit_index] = 1'b0;
end
endgenerate
generate
if(USEINPUTFIFO && SUPERPIPELINE)
begin
wire int_stall;
wire int_valid;
wire [AWIDTH+BURSTCOUNT_WIDTH-1:0] int_data;
acl_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) input_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_burstcount} ),
.data_out( int_data ),
.valid_in( i_valid ),
.valid_out( int_valid ),
.stall_in( int_stall ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
// Add a pipeline and stall-breaking FIFO
// TODO: Consider making this parameterizeable
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_fifo_buffer (
.clock(clk),
.resetn(!reset),
.data_in( int_data ),
.valid_in( int_valid ),
.data_out( {i_address_from_fifo,i_burstcount_from_fifo} ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( int_stall )
);
end
else if(USEINPUTFIFO && !SUPERPIPELINE)
begin
acl_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) input_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_burstcount} ),
.data_out( {i_address_from_fifo,i_burstcount_from_fifo} ),
.valid_in( i_valid ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
end
else if(PIPELINE_INPUT)
begin
reg r_valid;
reg [AWIDTH-1:0] r_address;
reg [BURSTCOUNT_WIDTH-1:0] r_burstcount;
assign o_stall = r_valid && o_stall_to_fifo;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
r_valid <= 1'b0;
else
begin
if (!o_stall)
begin
r_valid <= i_valid;
r_address <= i_address;
r_burstcount <= i_burstcount;
end
end
end
assign i_valid_from_fifo = r_valid;
assign i_address_from_fifo = r_address;
assign i_burstcount_from_fifo = r_burstcount;
end
else
begin
assign i_valid_from_fifo = i_valid;
assign i_address_from_fifo = i_address;
assign o_stall = o_stall_to_fifo;
assign i_burstcount_from_fifo = i_burstcount;
end
endgenerate
// Track the number of transactions waiting in the pipeline here
reg [COUNTER_WIDTH-1:0] counter;
wire incr, decr;
assign incr = read_accepted;
assign decr = read_used;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
counter <= {COUNTER_WIDTH{1'b0}};
o_active <= 1'b0;
end
else
begin
o_active <= (counter != {COUNTER_WIDTH{1'b0}});
// incr - add one or i_burstcount_from_fifo; decr - subtr one;
if (USEBURST==1)
counter <= counter + (incr ? i_burstcount_from_fifo : 0) - decr;
else
counter <= counter + incr - decr;
end
end
generate
if(USEBURST)
// Use the burstcount to figure out if there is enough space
assign ready = ((counter+i_burstcount_from_fifo) <= RETURN_FIFO_SIZE);
//
// Can also use decr in this calaculation to make ready respond faster
// but this seems to hurt Fmax ( ie. not worth it )
//assign ready = ((counter+i_burstcount_from_fifo-decr) <= RETURN_FIFO_SIZE);
else
// Can we hold one more item
assign ready = (counter <= (RETURN_FIFO_SIZE-1));
endgenerate
assign o_stall_to_fifo = !ready || out_fifo_wait;
// Optional Pipeline register before return
//
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata;
generate
if(SUPERPIPELINE)
begin
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= avm_readdata;
r_avm_readdatavalid <= avm_readdatavalid;
end
end
end
else
begin
// Don't register the return
always@(*)
begin
r_avm_readdata = avm_readdata;
r_avm_readdatavalid = avm_readdatavalid;
end
end
endgenerate
wire [WIDTH-1:0] rdata;
// Byte-addresses enter a FIFO so we can demux the appropriate data back out.
generate
if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_address_out;
wire [SEGMENT_SELECT_BITS-1:0] segment_address_in;
assign segment_address_in = i_address_from_fifo[ALIGNMENT_ABITS +: BYTE_SELECT_BITS-ALIGNMENT_ABITS];
acl_ll_fifo #(
.WIDTH(SEGMENT_SELECT_BITS),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( segment_address_in ),
.data_out( segment_address_out ),
.write( read_accepted ),
.read( r_avm_readdatavalid ),
.empty(),
.full()
);
assign byte_select = (segment_address_out << ALIGNMENT_ABITS);
assign rdata = r_avm_readdata[8*byte_select +: WIDTH];
end
else
begin
assign byte_select = '0;
assign rdata = r_avm_readdata;
end
endgenerate
// Status bits
assign read_accepted = i_valid_from_fifo && ready && !out_fifo_wait;
assign read_used = o_valid && !i_stall;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Optional: Pipelining FIFO on the AVM interface
//
generate
if(SUPERPIPELINE)
begin
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in({((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS),i_burstcount_from_fifo}),
.valid_in( i_valid_from_fifo && ready ),
.data_out( {avm_address,avm_burstcount} ),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( out_fifo_wait )
);
end
else
begin
// No interface pipelining
assign out_fifo_wait = avm_waitrequest;
assign avm_address = ((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_read = i_valid_from_fifo && ready;
assign avm_burstcount = i_burstcount_from_fifo;
end
endgenerate
// ---------------------------------------------------------------------------------
// Output fifo - must be at least as deep as the maximum number of pending requests
// so that we can guarantee a place for the response data if the downstream blocks
// are stalling.
//
generate
if(USEOUTPUTFIFO)
begin
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(RETURN_FIFO_SIZE),
.IMPL((SUPERPIPELINE && HIGH_FMAX) ? "ram_plus_reg" : "ram")
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( rdata ),
.data_out( o_readdata ),
.valid_in( r_avm_readdatavalid ),
.valid_out( o_valid ),
.stall_in( i_stall ),
.stall_out()
);
end
else
begin
assign o_valid = r_avm_readdatavalid;
assign o_readdata = rdata;
end
endgenerate
endmodule
/******************************************************************************/
// Pipelined write unit:
// Accept write requests on the upstream interface. Mux the data into the
// appropriate word lines based on the segment select bits. Also toggle
// the appropriate byte-enable lines to preserve data we are not
// overwriting. A counter keeps track of how many requests have been
// send but not yet acknowledged by downstream blocks.
module lsu_pipelined_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, o_input_fifo_depth
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter COUNTER_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=32;
parameter USEINPUTFIFO=1;
parameter USE_BYTE_EN=0;
parameter INPUTFIFOSIZE=32;
parameter INPUTFIFO_USEDW_MAXBITS=$clog2(INPUTFIFOSIZE);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
// For profiler/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
/***************
* Architecture *
***************/
reg transaction_complete;
wire write_accepted;
wire ready;
wire sr_stall;
wire i_valid_from_fifo;
wire [AWIDTH-1:0] i_address_from_fifo;
wire [WIDTH-1:0] i_writedata_from_fifo;
wire [WIDTH_BYTES-1:0] i_byteenable_from_fifo;
wire o_stall_to_fifo;
localparam FIFO_DEPTH_BITS=USEINPUTFIFO ? $clog2(INPUTFIFOSIZE) : 0;
wire [FIFO_DEPTH_BITS-1:0] usedw_true_width;
generate
if (USEINPUTFIFO)
assign o_input_fifo_depth[FIFO_DEPTH_BITS-1:0] = usedw_true_width;
// Set unused bits to 0
genvar bit_index;
for(bit_index = FIFO_DEPTH_BITS; bit_index < INPUTFIFO_USEDW_MAXBITS; bit_index = bit_index + 1)
begin: write_fifo_depth_zero_assign
assign o_input_fifo_depth[bit_index] = 1'b0;
end
endgenerate
localparam DATA_WIDTH = AWIDTH+WIDTH+(USE_BYTE_EN ? WIDTH_BYTES : 0);
generate
if(USEINPUTFIFO)
begin
wire valid_int;
wire stall_int;
wire [DATA_WIDTH-1:0] data_int;
if(!USE_BYTE_EN)
begin
acl_fifo #(
.DATA_WIDTH(AWIDTH+WIDTH),
.DEPTH(INPUTFIFOSIZE)
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_writedata} ),
.data_out( data_int ),
.valid_in( i_valid ),
.valid_out( valid_int ),
.stall_in( stall_int ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_buf (
.clock(clk),
.resetn(!reset),
.data_in( data_int ),
.data_out( {i_address_from_fifo,i_writedata_from_fifo} ),
.valid_in( valid_int ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( stall_int )
);
assign i_byteenable_from_fifo = {WIDTH_BYTES{1'b1}};
end else begin
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_byteenable, i_address,i_writedata}),
.data_out( data_int ),
.valid_in( i_valid ),
.valid_out( valid_int ),
.stall_in( stall_int ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_buf (
.clock(clk),
.resetn(!reset),
.data_in( data_int ),
.data_out({i_byteenable_from_fifo,i_address_from_fifo,i_writedata_from_fifo}),
.valid_in( valid_int ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( stall_int )
);
end
end
else
begin
assign i_valid_from_fifo = i_valid;
assign i_address_from_fifo = i_address;
assign i_writedata_from_fifo = i_writedata;
assign o_stall = o_stall_to_fifo;
assign i_byteenable_from_fifo = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
endgenerate
// Avalon interface
assign avm_address = ((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid_from_fifo;
// Mux in the correct data
generate
if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address_from_fifo[ALIGNMENT_ABITS +: BYTE_SELECT_BITS-ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata_from_fifo;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = i_byteenable_from_fifo;
end
end
else
begin
always@(*)
begin
avm_writedata = i_writedata_from_fifo;
avm_byteenable = i_byteenable_from_fifo;
end
end
endgenerate
// Control logic
reg [COUNTER_WIDTH-1:0] occ_counter; // occupancy counter
wire occ_incr, occ_decr;
reg [COUNTER_WIDTH-1:0] ack_counter; // acknowledge writes counter
wire ack_incr, ack_decr;
// Track the number of transactions waiting in the pipeline here
assign occ_incr = write_accepted;
assign occ_decr = o_valid && !i_stall;
assign ack_incr = avm_writeack;
assign ack_decr = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
o_active <= 1'b0;
end
else
begin
// incr - add one; decr - subtr one; both - stay the same
occ_counter <= occ_counter + { {(COUNTER_WIDTH-1){!occ_incr && occ_decr}}, (occ_incr ^ occ_decr) };
ack_counter <= ack_counter + { {(COUNTER_WIDTH-1){!ack_incr && ack_decr}}, (ack_incr ^ ack_decr) };
o_active <= (occ_counter != {COUNTER_WIDTH{1'b0}});
end
end
assign ready = (occ_counter != {COUNTER_WIDTH{1'b1}});
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall_to_fifo = !ready || avm_waitrequest;
assign o_valid = (ack_counter != {COUNTER_WIDTH{1'b0}});
endmodule
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
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_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST 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_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the 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_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
Tactic Notation "afi_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "afi_var"
| Case_aux c "afi_app1" | Case_aux c "afi_app2" | Case_aux c "afi_abs"
| Case_aux c "afi_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma H;
inversion H; subst; simpl...
Case "tvar".
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
rewrite extend_eq in H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
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_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST 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_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the 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_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
Tactic Notation "afi_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "afi_var"
| Case_aux c "afi_app1" | Case_aux c "afi_app2" | Case_aux c "afi_abs"
| Case_aux c "afi_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma H;
inversion H; subst; simpl...
Case "tvar".
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
rewrite extend_eq in H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
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_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST 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_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the 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_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
Tactic Notation "afi_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "afi_var"
| Case_aux c "afi_app1" | Case_aux c "afi_app2" | Case_aux c "afi_abs"
| Case_aux c "afi_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma H;
inversion H; subst; simpl...
Case "tvar".
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
rewrite extend_eq in H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
module lsu_bursting_read
(
clk, clk2x, reset, flush, i_nop, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid,
avm_burstcount,
// Profiling
extra_unaligned_reqs,
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=8; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=64; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=$clog2(WIDTH_BYTES); // Request address alignment (address bits)
parameter DEVICE = "Stratix V"; // DEVICE
parameter BURSTCOUNT_WIDTH=5; // MAX BURST = 2**(BURSTCOUNT_WIDTH-1)
parameter KERNEL_SIDE_MEM_LATENCY=1; // Effective Latency in cycles as seen by the kernel pipeline
parameter MEMORY_SIDE_MEM_LATENCY = 1; // Latency in cycles between LSU and memory
parameter MAX_THREADS=64; // Maximum # of threads to group into a burst request
parameter TIME_OUT=8; // Time out counter max
parameter USECACHING = 0; // Enable internal cache
parameter CACHE_SIZE_N=1024; // Cache depth (width = WIDTH_BYTES)
parameter ACL_PROFILE = 0; // Profiler
parameter HIGH_FMAX = 1; // Add pipeline to io if set to 1
parameter UNALIGNED = 0; // Output word unaligned
/*****************
* Local Parameters *
*****************/
localparam MAX_BURST = 2**(BURSTCOUNT_WIDTH-1);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam A_BYTES = 2**ALIGNMENT_ABITS;
localparam WORD_BYTES = (WIDTH_BYTES >= A_BYTES & (UNALIGNED == 0))? WIDTH_BYTES : A_BYTES;
localparam NUM_WORD = MWIDTH_BYTES / WORD_BYTES;
localparam MB_W=$clog2(MWIDTH_BYTES);
localparam OB_W = $clog2(WIDTH_BYTES);
localparam PAGE_ADDR_WIDTH = AWIDTH - MB_W;
localparam OFFSET_WIDTH = $clog2(NUM_WORD);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam CACHE_BASE_ADDR_W = AWIDTH-MB_W-CACHE_ADDR_W;
localparam UNALIGNED_DIV_ALIGN = WIDTH_BYTES / A_BYTES;
localparam UNALIGNED_SELECTION_BITS=$clog2(UNALIGNED_DIV_ALIGN);
// Standard global signals
input clk;
input clk2x;
input reset;
input flush;
input i_nop;
// Upstream interface
output logic o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Profiling
output logic extra_unaligned_reqs;
output logic req_cache_hit_count;
// internal signals
logic stall_pre;
wire reg_valid;
wire reg_nop;
wire [AWIDTH-1:0] reg_address;
// registed to help P&R
logic R_valid, R_nop;
wire [AWIDTH-1:0] addr_next_wire;
logic [AWIDTH-1:0] R_addr, R_addr_next, R_addr_next_hold;
// cache status
reg [CACHE_BASE_ADDR_W:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "M20K" */;
wire [1:0] in_cache_pre;
logic [CACHE_BASE_ADDR_W-1:0] cached_tag [2];
wire [CACHE_BASE_ADDR_W-1:0] R_tag [2];
wire [CACHE_ADDR_W-1:0] rd_c_index [2];
wire [CACHE_ADDR_W-1:0] wr_c_index;
logic cached_tag_valid [2];
wire tag_match [2];
wire consecutive;
reg cache_ready;
logic [1:0] in_cache;
wire [MB_W-1:0] byte_offset;
reg include_2nd_part;
logic update_cache;
logic [CACHE_BASE_ADDR_W-1:0] new_tag;
logic issue_2nd_word;
reg issue_2nd_hold;
logic need_2_page;
wire stall_int;
wire need_2_cc;
wire [UNALIGNED_SELECTION_BITS-1:0] shift;
logic [AWIDTH-1:0] lsu_i_address;
reg p_valid;
reg [AWIDTH-1:0] p_addr;
reg [1:0] R_consecutive;
reg [63:0] non_align_hit_cache;
// coalesced addr
wire [BURSTCOUNT_WIDTH-1:0]c_burstcount;
wire [PAGE_ADDR_WIDTH-1:0] c_page_addr;
wire c_req_valid;
wire c_new_page;
logic [OFFSET_WIDTH-1 : 0] p_offset, c_word_offset;
logic p_offset_valid;
reg [CACHE_ADDR_W-1:0] R_cache_addr;
// fifo
reg fifo_din_en;
reg [1:0] fi_in_cache;
reg [CACHE_ADDR_W-1:0] fi_cached_addr;
reg [UNALIGNED_SELECTION_BITS-1:0] fi_shift;
reg fi_second, fi_2nd_valid;
reg [UNALIGNED_SELECTION_BITS-1:0] R_shift;
reg [MB_W-1:0] fi_byte_offset;
wire p_ae;
generate
if(HIGH_FMAX) begin: GEN_PIPE_INPUT
acl_io_pipeline #(
.WIDTH(1+AWIDTH)
) in_pipeline (
.clk(clk),
.reset(reset),
.i_stall(stall_pre),
.i_valid(i_valid),
.i_data({i_nop, i_address}),
.o_stall(o_stall),
.o_valid(reg_valid),
.o_data({reg_nop, reg_address})
);
end
else begin : GEN_FAST_INPUT
assign {reg_valid, reg_nop, reg_address} = {i_valid, i_nop, i_address};
end
if(USECACHING) begin : GEN_ENABLE_CACHE
reg R_flush;
reg [CACHE_ADDR_W:0] flush_cnt;
reg cache_status_ready;
assign rd_c_index[0] = R_addr[CACHE_ADDR_W-1+MB_W:MB_W];
assign rd_c_index[1] = R_addr_next[CACHE_ADDR_W-1+MB_W:MB_W];
assign {cached_tag_valid[0], cached_tag[0]} = cache[rd_c_index[0]];
assign {cached_tag_valid[1], cached_tag[1]} = cache[rd_c_index[1]];
assign wr_c_index = lsu_i_address[CACHE_ADDR_W-1+MB_W:MB_W];
assign R_tag[0] = R_addr[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign R_tag[1] = R_addr_next[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign tag_match[0] = cached_tag[0] == R_tag[0] & cached_tag_valid[0] === 1'b1;
assign tag_match[1] = cached_tag[1] == R_tag[1] & cached_tag_valid[1] === 1'b1;
assign in_cache_pre[0] = tag_match[0] & !issue_2nd_word & cache_ready;
assign in_cache_pre[1] = tag_match[1] & !issue_2nd_word & cache_ready;
assign new_tag = lsu_i_address[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign update_cache = R_valid & !R_nop | issue_2nd_word;
always @(posedge clk or posedge reset) begin
if(reset) cache_status_ready <= 1'b0;
else cache_status_ready <= flush_cnt[CACHE_ADDR_W];
end
always @ (posedge clk) begin
R_flush <= flush;
if(flush & !R_flush) flush_cnt <= '0;
else if(!flush_cnt[CACHE_ADDR_W]) flush_cnt <= flush_cnt + 1'b1;
cache_ready <= flush_cnt[CACHE_ADDR_W];
if(!flush_cnt[CACHE_ADDR_W]) cache[flush_cnt] <= '0;
else if(update_cache) cache[wr_c_index] <= {1'b1, new_tag};
in_cache[0] <= R_valid & (in_cache_pre[0] | R_nop) & !issue_2nd_word;
in_cache[1] <= UNALIGNED? R_valid & (in_cache_pre[1] | R_nop) & !issue_2nd_word & need_2_page : 1'b0;
include_2nd_part <= issue_2nd_word | in_cache_pre[1] & need_2_page;
p_valid <= issue_2nd_word | R_valid & !in_cache_pre[0] & !R_nop; // not include nop
p_offset_valid <= issue_2nd_word | R_valid;
p_addr <= lsu_i_address;
R_cache_addr <= lsu_i_address[MB_W+CACHE_ADDR_W-1:MB_W];
end
if(OFFSET_WIDTH > 0) begin
always @ (posedge clk) begin
p_offset <= R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end
if(ACL_PROFILE == 1) begin
assign req_cache_hit_count = ((|fi_in_cache) & fifo_din_en);
end
else
begin
assign req_cache_hit_count = 1'b0;
end
end // end GEN_ENABLE_CACHE
else begin : GEN_DISABLE_CACHE
assign req_cache_hit_count = 1'b0;
assign in_cache_pre = 2'b0;
assign in_cache = 2'b0;
assign include_2nd_part = issue_2nd_word;
assign p_valid = issue_2nd_word | R_valid & !R_nop; // not include nop
assign p_offset_valid = issue_2nd_word | R_valid;
assign p_addr = lsu_i_address;
if(OFFSET_WIDTH > 0) begin
assign p_offset = R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end // end GEN_DISABLE_CACHE
if (UNALIGNED) begin : GEN_UNALIGN
assign addr_next_wire[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] = reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH]+1'b1;
assign addr_next_wire[AWIDTH-PAGE_ADDR_WIDTH-1:0] = '0;
// Look at the higher bits to determine how much we need to shift the two aligned accesses
wire [UNALIGNED_SELECTION_BITS-1:0] temp = NUM_WORD - R_addr[AWIDTH-1:ALIGNMENT_ABITS];
assign shift = UNALIGNED_DIV_ALIGN - temp;
assign consecutive = reg_nop | reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] == R_addr_next[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH];
// When do we need to issue the 2nd word ?
// The previous address needed a 2nd page and
// [1] the current requested address isn't in the (previous+1)th page and
// [2] The second page is not in the cache
assign need_2_cc = need_2_page & !in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]); // need 2 clock cycles to combine segments from 2 pages
// simulation only
assign byte_offset = stall_pre? R_addr[MB_W-1:0] : reg_address[MB_W-1:0];
always @(posedge clk or posedge reset) begin
if(reset) begin
issue_2nd_word <= 1'b0;
R_consecutive <= 'x;
stall_pre <= 1'b0;
issue_2nd_hold <= 'x;
end
else begin
issue_2nd_word <= need_2_cc;
if(!stall_pre | issue_2nd_word) issue_2nd_hold <= need_2_cc;
R_consecutive[0] <= reg_valid & !stall_int & consecutive & need_2_cc;
R_consecutive[1] <= R_consecutive[0];
stall_pre <= (stall_int | need_2_cc & reg_valid & !consecutive);
end
end
always @(posedge clk) begin
if(reg_valid & !stall_pre) need_2_page <= !reg_nop & (reg_address[MB_W-1:0] + WIDTH_BYTES) > MWIDTH_BYTES;
if(reg_valid & !stall_pre & !reg_nop) begin
R_addr <= reg_address;
R_addr_next <= addr_next_wire;
end
R_addr_next_hold <= R_addr_next;
if(!issue_2nd_word | !stall_pre) begin
R_valid <= reg_valid & !stall_pre;
R_nop <= reg_nop;
end
end
if(ACL_PROFILE == 1) begin
assign extra_unaligned_reqs = need_2_cc & reg_valid & !consecutive;
always @(posedge clk or posedge reset) begin
if(reset) begin
non_align_hit_cache <= '0;
end
else begin
non_align_hit_cache <= non_align_hit_cache + (need_2_page & in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]) & reg_valid & !consecutive);
end
end
end // end ACL_PROFILE == 1
end // end GEN_UNALIGN
else begin : GEN_ALIGN
assign issue_2nd_word = 1'b0;
assign need_2_page = 1'b0;
assign R_addr = reg_address;
assign R_valid = reg_valid & !stall_int;
assign R_nop = reg_nop;
assign stall_pre = stall_int;
end // end GEN_ALIGN
endgenerate
assign lsu_i_address = issue_2nd_word ? R_addr_next_hold : R_addr;
always @(posedge clk) begin
c_word_offset <= p_offset;
R_shift <= need_2_page? shift : '0;
fifo_din_en <= (|in_cache) | p_offset_valid;
{fi_in_cache, fi_cached_addr, fi_second} <= {in_cache, R_cache_addr, include_2nd_part};
if(!include_2nd_part) fi_byte_offset <= p_addr[MB_W-1:0];
fi_shift <= USECACHING? R_shift : (need_2_page? shift : '0);
fi_2nd_valid <= USECACHING? R_consecutive[1] : R_consecutive[0];
end
acl_stall_free_coalescer #(
.AW(AWIDTH),
.PAGE_AW(PAGE_ADDR_WIDTH),
.MAX_BURST(MAX_BURST),
.TIME_OUT(TIME_OUT),
.CACHE_LAST(USECACHING),
.MAX_THREAD(MAX_THREADS),
.DISABLE_COALESCE(0)
) coalescer(
.clk(clk),
.reset(reset),
.i_valid(p_valid),
.i_addr(p_addr),
.i_empty(p_ae),
.o_page_addr(c_page_addr),
.o_page_addr_valid(c_req_valid),
.o_num_burst(c_burstcount),
.o_new_page(c_new_page)
);
lsu_bursting_pipelined_read #(
.INPUT_AW(PAGE_ADDR_WIDTH),
.AWIDTH(AWIDTH),
.WIDTH(WIDTH),
.MWIDTH(MWIDTH),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.DEVICE(DEVICE),
.CACHE_SIZE_N(CACHE_SIZE_N),
.USECACHING(USECACHING),
.UNALIGNED(UNALIGNED),
.UNALIGNED_SHIFT_WIDTH(UNALIGNED_SELECTION_BITS),
.MAX_BURST(MAX_BURST),
.INCLUDE_BYTE_OFFSET(0), // sim-only
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) pipelined_read(
.clk (clk),
.reset (reset),
.i_address (c_page_addr),
.i_addr_valid (c_req_valid),
.i_burst_count (c_burstcount),
.i_new_page (c_new_page),
.i_word_offset (c_word_offset),
.i_byte_offset (fi_byte_offset),
.i_in_cache (fi_in_cache),
.i_cache_addr (fi_cached_addr),
.i_shift (fi_shift),
.i_second (fi_second),
.i_2nd_valid (fi_2nd_valid), // has two segments' info in one cc
.i_word_offset_valid(fifo_din_en),
.i_stall (i_stall),
.o_ae (p_ae),
.o_empty (p_empty),
.o_readdata (o_readdata),
.o_valid (o_valid),
.o_stall (stall_int),
.avm_address (avm_address),
.avm_read (avm_read),
.avm_readdata (avm_readdata),
.avm_waitrequest (avm_waitrequest),
.avm_byteenable (avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.avm_burstcount (avm_burstcount)
);
endmodule
module acl_io_pipeline #(
parameter WIDTH = 1
)(
input clk,
input reset,
input i_stall,
input i_valid,
input [WIDTH-1:0] i_data,
output o_stall,
output reg o_valid,
output reg [WIDTH-1:0] o_data
);
reg R_valid;
assign o_stall = i_stall & R_valid;
always@(posedge clk) begin
if(!o_stall) {o_valid, o_data} <= {i_valid, i_data};
end
always@(posedge clk or posedge reset)begin
if(reset) R_valid <= 1'b0;
else if(!o_stall) R_valid <= i_valid;
end
endmodule
module lsu_bursting_pipelined_read
(
clk, reset,
i_in_cache,
i_cache_addr,
i_addr_valid,
i_address,
i_burst_count,
i_word_offset,
i_byte_offset,
i_shift,
i_second,
i_2nd_valid,
i_word_offset_valid,
i_new_page,
o_readdata,
o_valid,
i_stall,
o_stall,
o_empty,
o_ae,
avm_address,
avm_read,
avm_readdata,
avm_waitrequest,
avm_byteenable,
avm_burstcount,
avm_readdatavalid
);
parameter INPUT_AW = 32;
parameter AWIDTH=32;
parameter WIDTH=32;
parameter MWIDTH=512;
parameter MAX_BURST = 16;
parameter ALIGNMENT_ABITS=2;
parameter DEVICE = "Stratix V";
parameter MEMORY_SIDE_MEM_LATENCY=160;
parameter USECACHING = 0;
parameter CACHE_SIZE_N = 1024;
parameter UNALIGNED = 0;
parameter UNALIGNED_SHIFT_WIDTH = 0;
parameter INCLUDE_BYTE_OFFSET = 0; // testing purpose
localparam ALIGNMENT_WIDTH = 2**ALIGNMENT_ABITS * 8;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH/8);
localparam WORD_WIDTH = (WIDTH >= ALIGNMENT_WIDTH & (UNALIGNED == 0))? WIDTH : ALIGNMENT_WIDTH;
localparam NUM_WORD = MWIDTH / WORD_WIDTH;
localparam OFFSET_WIDTH = (NUM_WORD==1)? 1 : $clog2(NUM_WORD);
localparam WIDE_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY < 256)? 256 : MEMORY_SIDE_MEM_LATENCY;
localparam OFFSET_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY <= 246)? 256 : MEMORY_SIDE_MEM_LATENCY + 10;
localparam REQUEST_FIFO_DEPTH = OFFSET_FIFO_DEPTH;
localparam WIDE_FIFO_DEPTH_THRESH = MEMORY_SIDE_MEM_LATENCY;
localparam WIDE_FIFO_AW = $clog2(WIDE_FIFO_DEPTH);
localparam BURST_CNT_WIDTH = (MAX_BURST == 1)? 1 : $clog2(MAX_BURST + 1);
localparam REQUEST_FIFO_AW = $clog2(REQUEST_FIFO_DEPTH);
localparam OFFSET_FIFO_AW = $clog2(OFFSET_FIFO_DEPTH);
localparam REQUEST_FIFO_WIDTH = INPUT_AW + BURST_CNT_WIDTH;
localparam CACHE_SIZE_LOG2N=$clog2(CACHE_SIZE_N);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam OFFSET_FIFO_WIDTH = 1 + ((NUM_WORD > 1)? OFFSET_WIDTH : 0) + (USECACHING? 1 + CACHE_ADDR_W : 0) + (UNALIGNED? UNALIGNED_SHIFT_WIDTH + 3 : 0) + (INCLUDE_BYTE_OFFSET? BYTE_SELECT_BITS : 0);
// I/O
input clk, reset;
input [UNALIGNED:0] i_in_cache;
input [CACHE_ADDR_W-1:0] i_cache_addr;
input [INPUT_AW-1:0] i_address;
input [BURST_CNT_WIDTH-1:0] i_burst_count;
input [OFFSET_WIDTH-1:0] i_word_offset;
input [BYTE_SELECT_BITS-1:0] i_byte_offset; // simulation
input [UNALIGNED_SHIFT_WIDTH-1:0] i_shift; // used only when UNALIGNED = 1
input i_second; // used only when UNALIGNED = 1
input i_2nd_valid; // used only when UNALIGNED = 1
input i_word_offset_valid;
input i_new_page;
input i_addr_valid;
input i_stall;
output logic [WIDTH-1:0] o_readdata;
output logic o_valid;
output reg o_stall;
output reg o_empty;
output o_ae;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output reg avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH/8-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURST_CNT_WIDTH-1:0] avm_burstcount;
// offset fifo
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_din;
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_dout;
// req FIFO
wire rd_req_en;
wire req_fifo_ae, req_fifo_af, req_overflow, offset_overflow, rd_req_empty; // FIFO status
// end req FIFO
// output FIFO
wire rd_data_fifo;
reg R_rd_data;
wire rd_data_empty;
wire rd_offset;
wire offset_fifo_empty;
wire offset_af;
wire [UNALIGNED:0] d_in_cache;
wire rd_next_page;
wire [CACHE_ADDR_W-1:0] d_cache_addr;
wire [BYTE_SELECT_BITS-1:0] d_byte_offset; // for simulation
reg R_in_cache;
wire d_second, d_2nd_valid;
wire unalign_stall_offset, unalign_stall_data;
wire [UNALIGNED_SHIFT_WIDTH-1:0] d_shift;
wire [OFFSET_WIDTH-1 : 0] d_offset;
reg [OFFSET_WIDTH-1 : 0] R_offset;
reg [MWIDTH-1:0] R_avm_rd_data;
wire [MWIDTH-1:0] rd_data;
// end output FIFO
assign avm_address[AWIDTH - INPUT_AW - 1 : 0] = 0;
assign avm_byteenable = {(MWIDTH/8){1'b1}};
assign o_ae = req_fifo_ae;
assign rd_req_en = !avm_read | !avm_waitrequest;
always @(posedge clk or posedge reset) begin
if(reset) begin
o_empty = 1'b0;
avm_read <= 1'b0;
o_stall <= 1'b0;
end
else begin
o_empty <= rd_req_empty;
o_stall <= offset_af;
if(rd_req_en) avm_read <= !rd_req_empty;
end
end
generate
if(NUM_WORD > 1) begin : GEN_WORD_OFFSET_FIFO
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
else begin : GEN_SINGLE_WORD_RD_NEXT
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "OFF"), // not instantiate block ram
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
endgenerate
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (REQUEST_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (REQUEST_FIFO_WIDTH),
.lpm_widthu (REQUEST_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(20),
.almost_empty_value(3)
) rd_request_fifo (
.clock (clk),
.data ({i_address, i_burst_count}),
.wrreq (i_addr_valid),
.rdreq (rd_req_en),
.usedw (),
.empty (rd_req_empty),
.full (req_overflow),
.q ({avm_address[AWIDTH - 1: AWIDTH - INPUT_AW], avm_burstcount}),
.almost_empty (req_fifo_ae),
.almost_full (req_fifo_af),
.aclr (reset)
);
/*------------------------------
Generate output data
--------------------------------*/
reg offset_valid;
reg [1:0] o_valid_pre;
wire rd_next_page_en, downstream_stall, wait_data, offset_stall, data_stall, valid_hold;
generate
if(USECACHING) begin : ENABLE_CACHE
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
logic [MWIDTH-1:0] reused_data[2] ;
reg [CACHE_ADDR_W-1:0] R_cache_addr, R_cache_next;
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_cache_addr, i_in_cache, i_new_page};
assign {d_2nd_valid, d_shift, d_second, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_cache_addr, i_in_cache, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
reg second_part_in_cache;
wire [WIDTH-1:0] c0_data_h, rd_data_h, c0_data_mux, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] c1_data_l, rd_data_l;
wire get_new_offset, offset_backpressure_stall ;
wire [CACHE_ADDR_W-1:0] caddr_next;
wire [1:0] rw_wire;
reg [1:0] rw;
reg [WIDTH-ALIGNMENT_WIDTH-1:0] R_c1_data_l;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rw_wire[0] = d_cache_addr == R_cache_addr & R_rd_data;
assign rw_wire[1] = caddr_next == R_cache_addr & R_rd_data;
assign c0_data_h = rw[0]? rd_data[MWIDTH-1:MWIDTH-WIDTH] : reused_data[0][MWIDTH-1:MWIDTH-WIDTH];
assign c1_data_l = rw[1]? R_c1_data_l : reused_data[1][WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign c0_data_mux = rw[0]? rd_data >> R_offset*ALIGNMENT_WIDTH : reused_data[0] >> R_offset*ALIGNMENT_WIDTH ;
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign caddr_next = d_cache_addr+1;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int[R_shift[2]*ALIGNMENT_WIDTH +: WIDTH];
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(R_rd_data) cache[R_cache_addr] <= rd_data;
if(get_new_offset) begin
{R_in_cache, R_offset, R_shift[0], R_second} <= {|d_in_cache, d_offset, d_shift, d_second};
R_cache_addr <= d_cache_addr;
R_cache_next <= caddr_next;
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
second_part_in_cache <= !d_in_cache[0] & d_in_cache[1];
R_2nd_valid[1] <= R_2nd_valid[0];
`ifdef SIM_ONLY
if(d_in_cache[0]) reused_data[0] <= rw_wire[0]? 'x : cache[d_cache_addr];
reused_data[1] <= rw_wire[1]? 'x : cache[caddr_next];
`else
if(d_in_cache[0]) reused_data[0] <= cache[d_cache_addr];
reused_data[1] <= cache[caddr_next];
`endif
if(d_in_cache[1]) R_c1_data_l <= rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
end
// work-around to deal with read-during-write
if(!downstream_stall & (|d_in_cache)) rw <= rw_wire & d_in_cache;
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_in_cache) begin
data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= c1_data_l;
data_int[WIDTH-1:0] <= second_part_in_cache? rd_data_h : R_need_2nd_page? c0_data_h : c0_data_mux;
end
else begin
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
end
R_shift[2] <= (R_in_cache | !R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end UNALIGNED
else begin : GEN_ALIGNED
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = R_in_cache? reused_data[0][WIDTH-1:0] : rd_data[WIDTH-1:0];
else assign o_readdata = R_in_cache? reused_data[0] >> R_offset*WORD_WIDTH: rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) begin
R_cache_addr <= d_cache_addr;
R_in_cache <= d_in_cache & !(R_rd_data & R_cache_addr == d_cache_addr);
R_offset <= d_offset;
// registered cache input and output to infer megafunction RAM
`ifdef SIM_ONLY // for simulation accuracy
reused_data[0] <= (d_cache_addr == R_cache_addr & R_rd_data)? 'x : cache[d_cache_addr]; // read during write
`else
reused_data[0] <= cache[d_cache_addr];
`endif
end
else if(R_rd_data & R_cache_addr == d_cache_addr) R_in_cache <= 1'b0; // read during write
if(R_rd_data) cache[R_cache_addr] <= rd_data; // update cache
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end ALIGNED
end // end USECACHING
else begin : DISABLE_CACHE
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_new_page};
assign {d_2nd_valid, d_shift, d_second, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
wire [WIDTH-1:0] rd_data_h, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] rd_data_l;
wire get_new_offset, offset_backpressure_stall;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int >> R_shift[2]*ALIGNMENT_WIDTH;
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(get_new_offset) begin
{R_offset, R_shift[0], R_second} <= {d_offset, d_shift, d_second};
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
R_2nd_valid[1] <= R_2nd_valid[0];
end
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
R_shift[2] <= (!R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end GEN_UNALIGNED
else begin : GEN_ALIGNED
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = rd_data[WIDTH-1:0];
else assign o_readdata = rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) R_offset <= d_offset;
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end GEN_ALIGNED
end // end DISABLE_CACHE
endgenerate
assign downstream_stall = i_stall & valid_hold;
assign rd_next_page_en = offset_valid & rd_next_page;
assign rd_offset = !offset_stall;
assign rd_data_fifo = rd_next_page_en & !data_stall;
always@(posedge clk or posedge reset)begin
if(reset) begin
offset_valid <= 1'b0;
R_rd_data <= 1'b0;
end
else begin
if(rd_offset) offset_valid <= !offset_fifo_empty;
R_rd_data <= rd_data_fifo & !rd_data_empty;
end
end
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (WIDE_FIFO_DEPTH),
.almost_full_value(WIDE_FIFO_DEPTH_THRESH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (MWIDTH),
.lpm_widthu (WIDE_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON")
) rd_back_wfifo (
.clock (clk),
.data (avm_readdata),
.wrreq (avm_readdatavalid),
.rdreq (rd_data_fifo),
.usedw (),
.empty (rd_data_empty),
.full (),
.q (rd_data),
.almost_empty (),
.almost_full (),
.aclr (reset)
);
endmodule
module acl_stall_free_coalescer (
clk, // clock
reset, // reset
i_valid, // valid address
i_empty, // request FIFO is empty
i_addr, // input address
o_page_addr, // output page address
o_page_addr_valid, // page address valid
o_num_burst, // number of burst
o_new_page
);
parameter AW = 1,
PAGE_AW = 1,
MAX_BURST = 1,
TIME_OUT = 1,
MAX_THREAD = 1,
CACHE_LAST = 0,
DISABLE_COALESCE = 0;
localparam BURST_CNT_WIDTH = $clog2(MAX_BURST+1);
localparam TIME_OUT_W = $clog2(TIME_OUT+1);
localparam THREAD_W = $clog2(MAX_THREAD+1);
input clk;
input reset;
input i_valid;
input i_empty;
input [AW-1:0] i_addr;
// all output signals are registered to help P&R
output reg [PAGE_AW-1:0] o_page_addr;
output reg o_page_addr_valid;
output reg [BURST_CNT_WIDTH-1:0] o_num_burst;
output reg o_new_page;
logic init;
wire match_current_wire, match_next_wire, reset_cnt;
reg [BURST_CNT_WIDTH-1:0] num_burst;
reg valid_burst;
wire [PAGE_AW-1:0] page_addr;
reg [PAGE_AW-1:0] R_page_addr = 0;
reg [PAGE_AW-1:0] R_page_addr_next = 0;
reg [PAGE_AW-1:0] addr_hold = 0;
reg [3:0] delay_cnt; // it takes 5 clock cycles from o_page_addr_valid to being read out from FIFO (if avm_stall = 0), assuming 3 extra clock cycles to reach global mem
reg [TIME_OUT_W-1:0] time_out_cnt = 0;
reg [THREAD_W-1:0] thread_cnt = 0;
wire time_out;
wire max_thread;
assign page_addr = i_addr[AW-1:AW-PAGE_AW]; // page address
assign match_current_wire = page_addr == R_page_addr;
assign max_thread = thread_cnt[THREAD_W-1] & i_empty;
assign time_out = time_out_cnt[TIME_OUT_W-1] & i_empty;
assign reset_cnt = valid_burst & (
num_burst[BURST_CNT_WIDTH-1] // reach max burst
| time_out
| max_thread
| !match_current_wire & !match_next_wire & !init & i_valid ); // new burst
generate
if(MAX_BURST == 1) begin : BURST_ONE
assign match_next_wire = 1'b0;
end
else begin : BURST_N
assign match_next_wire = page_addr == R_page_addr_next & !init & i_valid & (|page_addr[BURST_CNT_WIDTH-2:0]);
end
if(DISABLE_COALESCE) begin : GEN_DISABLE_COALESCE
always@(*) begin
o_page_addr = page_addr;
o_page_addr_valid = i_valid;
o_num_burst = 1;
o_new_page = 1'b1;
end
end
else begin : ENABLE_COALESCE
always@(posedge clk) begin
if(i_valid) begin
R_page_addr <= page_addr;
R_page_addr_next <= page_addr + 1'b1;
end
o_num_burst <= num_burst;
o_page_addr <= addr_hold;
if(i_valid | reset_cnt) time_out_cnt <= 0; // nop is valid thread, should reset time_out counter too
else if(!time_out_cnt[TIME_OUT_W-1] & valid_burst) time_out_cnt <= time_out_cnt + 1;
if(reset_cnt) thread_cnt <= i_valid;
else if(i_valid & !thread_cnt[THREAD_W-1]) thread_cnt <= thread_cnt + 1;
if(o_page_addr_valid) delay_cnt <= 1;
else if(!delay_cnt[3]) delay_cnt <= delay_cnt + 1;
if(reset_cnt) begin
num_burst <= i_valid & !match_current_wire;
addr_hold <= page_addr;
end
else if(i_valid) begin
num_burst <= (!valid_burst & !match_current_wire | init)? 1 : num_burst + match_next_wire;
if(!valid_burst | init) addr_hold <= page_addr;
end
o_new_page <= (!match_current_wire| init) & i_valid;
end
always@(posedge clk or posedge reset) begin
if(reset) begin
o_page_addr_valid <= 1'b0;
valid_burst <= 1'b0;
end
else begin
if(reset_cnt) valid_burst <= i_valid & !match_current_wire;
else if(i_valid) begin
if(!valid_burst & !match_current_wire | init) valid_burst <= 1'b1;
else if(match_next_wire) valid_burst <= 1'b1;
end
o_page_addr_valid <= reset_cnt;
end
end
end
if(CACHE_LAST) begin : GEN_ENABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & !o_page_addr_valid & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
else begin : GEN_DISABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & delay_cnt[3] & !o_page_addr_valid & i_empty & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
endgenerate
endmodule
module lsu_bursting_write
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable
);
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // The max number of live threads
parameter MEMORY_SIDE_MEM_LATENCY=32; // The latency to get to the iface (no response needed from DDR, we generate writeack right before the iface).
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam ALIGNMENT_ABYTES=2**ALIGNMENT_ABITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
input [WIDTH_BYTES-1:0] i_byteenable;
// Byte enable control
reg reg_lsu_i_valid, reg_lsu_i_thread_valid;
reg [AWIDTH-1:0] reg_lsu_i_address;
reg [WIDTH-1:0] reg_lsu_i_writedata;
reg [WIDTH_BYTES-1:0] reg_lsu_i_byte_enable;
reg reg_common_burst, reg_lsu_i_2nd_en;
reg reg_i_nop;
reg [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] reg_lsu_i_2nd_offset;
reg [WIDTH-1:0]reg_lsu_i_2nd_data;
reg [WIDTH_BYTES-1:0] reg_lsu_i_2nd_byte_en;
wire stall_signal_directly_from_lsu;
assign o_stall = reg_lsu_i_valid & stall_signal_directly_from_lsu;
// --------------- Pipeline stage : Burst Checking --------------------
always@(posedge clk or posedge reset)
begin
if (reset)
begin
reg_lsu_i_valid <= 1'b0;
reg_lsu_i_thread_valid <= 1'b0;
end
else
begin
if (~o_stall) begin
reg_lsu_i_valid <= i_valid;
reg_lsu_i_thread_valid <= i_thread_valid;
end
end
end
always@(posedge clk) begin
if (~o_stall & i_valid & ~i_nop) reg_lsu_i_address <= i_address;
if (~o_stall) begin
reg_i_nop <= i_nop;
reg_lsu_i_writedata <= i_writedata;
reg_lsu_i_byte_enable <= i_byteenable;
reg_lsu_i_2nd_offset <= i_2nd_offset;
reg_lsu_i_2nd_en <= i_2nd_en;
reg_lsu_i_2nd_data <= i_2nd_data;
reg_lsu_i_2nd_byte_en <= i_2nd_byte_en;
reg_common_burst <= i_nop | (reg_lsu_i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1] == i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1]);
end
end
// -------------------------------------------------------------------
lsu_bursting_write_internal #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.UNALIGN(UNALIGN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_write (
.clk(clk),
.clk2x(clk2x),
.reset(reset),
.i_nop(reg_i_nop),
.o_stall(stall_signal_directly_from_lsu),
.i_valid(reg_lsu_i_valid),
.i_thread_valid(reg_lsu_i_thread_valid),
.i_address(reg_lsu_i_address),
.i_writedata(reg_lsu_i_writedata),
.i_2nd_offset(reg_lsu_i_2nd_offset),
.i_2nd_data(reg_lsu_i_2nd_data),
.i_2nd_byte_en(reg_lsu_i_2nd_byte_en),
.i_2nd_en(reg_lsu_i_2nd_en),
.i_stall(i_stall),
.o_valid(o_valid),
.o_active(o_active),
.i_byteenable(reg_lsu_i_byte_enable),
.avm_address(avm_address),
.avm_write(avm_write),
.avm_writeack(avm_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest),
.common_burst(reg_common_burst)
);
endmodule
//
// Burst coalesced write module
// Again, top level comments later
//
module lsu_bursting_write_internal
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
o_active, //Debugging signal
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable,
common_burst
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter MEMORY_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
// WARNING: Kernels will hang if InstrDataDep claims that a store
// has more capacity than this number
//
parameter MAX_CAPACITY=128; // Must be a power-of-2 to keep things simple
// Derived parameters
localparam MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
//
// Notice that in the non write ack case, the number of threads seems to be twice the sensible number
// This is because MAX_THREADS is usually the limiter on the counter width. Once one request is assemembled,
// we want to be able to start piplining another burst. Thus the factor of 2.
// The MEMORY_SIDE_MEM_LATENCY will further increase this depth if the compiler
// thinks the lsu will see a lot of contention on the Avalon side.
//
localparam __WRITE_FIFO_DEPTH = (WIDTH_BYTES==MWIDTH_BYTES) ? 3*MAX_BURST : 2*MAX_BURST;
// No reason this should need more than max MLAB depth
localparam _WRITE_FIFO_DEPTH = ( __WRITE_FIFO_DEPTH < 64 ) ? __WRITE_FIFO_DEPTH : 64;
// Need at least 4 to account for fifo push-to-pop latency
localparam WRITE_FIFO_DEPTH = ( _WRITE_FIFO_DEPTH > 8 ) ? _WRITE_FIFO_DEPTH : 8;
// If writeack, make this equal to
localparam MAX_THREADS=(USE_WRITE_ACK ? KERNEL_SIDE_MEM_LATENCY - MEMORY_SIDE_MEM_LATENCY : (2*MWIDTH_BYTES/WIDTH_BYTES*MAX_BURST)); // Maximum # of threads to group into a burst request
//
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH=8*SEGMENT_WIDTH_BYTES;
localparam NUM_WORD = MWIDTH_BYTES/SEGMENT_WIDTH_BYTES;
localparam UNALIGN_BITS = $clog2(WIDTH_BYTES)-ALIGNMENT_ABITS;
// Constants
localparam COUNTER_WIDTH=(($clog2(MAX_THREADS)+1 < $clog2(MAX_CAPACITY+1)) ?
$clog2(MAX_CAPACITY+1) : ($clog2(MAX_THREADS)+1)); // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Byte enable control
input [WIDTH_BYTES-1:0] i_byteenable;
// Help from outside
input common_burst;
/***************
* Architecture *
***************/
wire [WIDTH_BYTES-1:0] word_byte_enable;
wire [WIDTH-1:0] word_bit_enable, word2_bit_enable;
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire c_page_done;
wire c_nop;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
// Replicated version of the occ and stores counters that decrement instead of increment
// This allows me to check the topmost bit to determine if the counter is non-empty
reg [COUNTER_WIDTH-1:0] nop_cnt;
reg [COUNTER_WIDTH-1:0] occ_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire w_fifo_full;
wire [BURSTCOUNT_WIDTH-1:0] c_burstcount;
// Track the current item in the write burst since we issue c_burstcount burst reqs
reg [BURSTCOUNT_WIDTH-1:0] burstcounter;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
assign word_byte_enable = i_nop? '0: (USE_BYTE_EN ? i_byteenable :{WIDTH_BYTES{1'b1}}) ;
generate
genvar byte_num;
for( byte_num = 0; byte_num < WIDTH_BYTES; byte_num++)
begin : biten
assign word_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{word_byte_enable[byte_num]}};
assign word2_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{i_2nd_byte_en[byte_num]}};
end
endgenerate
wire oc_full;
wire cnt_valid;
wire coalescer_active;
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
bursting_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(16),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.MAXBURSTCOUNT(MAX_BURST),
.MAX_THREADS(MAX_THREADS)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full && !w_fifo_full),
.i_nop(i_nop),
.o_stall(c_stall),
.o_start_nop(c_nop), // new burst starts with nop
.o_new_page(c_new_page),
.o_page_done(c_page_done),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(w_fifo_full),
.o_burstcount(c_burstcount),
.common_burst(common_burst),
.o_active(coalescer_active)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
if(UNALIGN) begin : GEN_UNALIGN
assign cnt_valid = i_thread_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_bite = {MWIDTH{1'b0}};
if(i_2nd_en) begin
wm_wide_wdata[WIDTH-1:0] = i_2nd_data;
wm_wide_wdata = wm_wide_wdata << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_be[WIDTH_BYTES-1:0] = i_2nd_byte_en;
wm_wide_be = wm_wide_be << (i_2nd_offset*SEGMENT_WIDTH_BYTES);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_bite[WIDTH-1:0] = word2_bit_enable;
wm_wide_bite = wm_wide_bite << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
end
else begin
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end // end GEN_UNALIGN
else begin: GEN_ALIGN
assign cnt_valid = i_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end
else
begin
assign cnt_valid = i_valid;
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = word_byte_enable;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = word_bit_enable;
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
wire [COUNTER_WIDTH-1:0] num_threads_written;
// This FIFO stores the actual data to be written
//
//
wire w_data_fifo_full, req_fifo_empty;
wire wr_page = c_page_done & !w_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH+MWIDTH+MWIDTH_BYTES),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo (
.clock(clk),
.resetn(~reset),
.data_in( {wm_writedata,wm_byteenable} ),
.valid_in( wr_page ),
.data_out( {avm_writedata,avm_byteenable} ),
.stall_in( ~write_accepted ),
.stall_out( w_data_fifo_full ),
.empty(req_fifo_empty)
);
// This FIFO stores the number of valid's to release with each writeack
//
wire w_ack_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH),
.DEPTH(2*WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) ack_fifo (
.clock(clk),
.resetn(~reset),
.data_in( next_counter),
.valid_in( wr_page ),
.data_out( num_threads_written ),
.stall_in( !avm_writeack),
.stall_out( w_ack_fifo_full )
);
// This FIFO hold the request information { address & burstcount }
//
wire w_fifo_stall_in;
assign w_fifo_stall_in = !(write_accepted && (burstcounter == avm_burstcount));
wire w_request_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(PAGE_SELECT_BITS+BURSTCOUNT_WIDTH),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo2 (
.clock(clk),
.resetn(~reset),
.data_in( {c_req_addr,c_burstcount} ),
.valid_in( c_req_valid & !w_fifo_full ), // The basical coalescer stalls on w_fifo_full holding c_req_valid high
.data_out( {avm_address[AWIDTH-1: BYTE_SELECT_BITS],avm_burstcount} ),
.valid_out( avm_write ),
.stall_in( w_fifo_stall_in ),
.stall_out( w_request_fifo_full )
);
assign avm_address[BYTE_SELECT_BITS-1:0] = '0;
// The w_fifo_full is the OR of the data or request fifo's being full
assign w_fifo_full = w_data_fifo_full | w_request_fifo_full | w_ack_fifo_full;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
reg pending_nop;
wire pending_cc = nop_cnt != occ_counter;
wire burst_start_nop = cnt_valid & c_nop & !o_stall;
wire start_with_nop = !pending_cc && i_nop && cnt_valid && !o_stall; // nop starts when there are no pending writes
wire normal_cc_valid = cnt_valid && !o_stall && !i_nop;
wire clear_nop_cnt = normal_cc_valid || !pending_cc;
assign input_accepted = cnt_valid && !o_stall && !(c_nop || start_with_nop);
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
wire [8:0] ack_pending = {1'b1, {COUNTER_WIDTH{1'b0}}} - ack_counter;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
occ_counter_neg <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter_neg <= '0;
nop_cnt <= '0;
burstcounter <= 6'b000001;
o_active <= 1'b0;
pending_nop <= 1'b0;
end
else
begin
if(clear_nop_cnt) begin
nop_cnt <= '0;
pending_nop <= 1'b0;
end
else if(!start_with_nop) begin
nop_cnt <= nop_cnt + burst_start_nop;
if(burst_start_nop) pending_nop <= 1'b1;
end
occ_counter <= occ_counter + (cnt_valid && !o_stall) - output_acknowledged;
occ_counter_neg <= occ_counter_neg - (cnt_valid && !o_stall) + output_acknowledged;
next_counter <= input_accepted + (c_page_done ? {COUNTER_WIDTH{1'b0}} : next_counter) + (normal_cc_valid? nop_cnt : 0);
if(USE_WRITE_ACK) begin
ack_counter <= ack_counter
- (avm_writeack? num_threads_written : 0)
- ( (!pending_cc & !normal_cc_valid)? nop_cnt : 0)
- start_with_nop
+ output_acknowledged;
o_active <= occ_counter_neg[COUNTER_WIDTH-1];
end
else begin
ack_counter <= ack_counter - (cnt_valid && !o_stall) + output_acknowledged;
ack_counter_neg <= ack_counter_neg - wr_page + avm_writeack;
o_active <= occ_counter_neg[COUNTER_WIDTH-1] | ack_counter_neg[COUNTER_WIDTH-1] | coalescer_active; // do not use num_threads_written, because it takes extra resource
end
burstcounter <= write_accepted ? ((burstcounter == avm_burstcount) ? 6'b000001 : burstcounter+1) : burstcounter;
end
end
assign oc_full = occ_counter[COUNTER_WIDTH-1];
// Pipeline control signals
assign o_stall = oc_full || c_stall || w_fifo_full;
assign o_valid = ack_counter[COUNTER_WIDTH-1];
endmodule
// BURST COALESCING MODULE
//
// Similar to the basic coalescer but supports checking if accesses are in consecutive DRAM "pages"
// Supports the ad-hocly discovered protocols for bursting efficiently with avalaon
// - Don't burst from an ODD address
// - If not on a burst boundary, then just burst up to the next burst bondary
//
// Yes, I know, this could be incorporated into the basic coalescer. But that's really not my "thing"
//
module bursting_coalescer
(
clk, reset, i_page_addr, i_nop, i_valid, o_stall, o_new_page, o_page_done, o_req_addr, o_burstcount,
o_req_valid, i_stall, o_start_nop,
common_burst,
// For the purposes of maintaining latency correctly, we need to know if total # of threads
// accepted by the caching LSU
i_input_accepted_from_wrapper_lsu,
i_reset_timeout,
o_active
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8;
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter MAXBURSTCOUNT=32; // This isn't the max supported by Avalon, but the max that the instantiating module needs
parameter MAX_THREADS=64; // Must be a power of 2
parameter USECACHING=0;
localparam SLAVE_MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
localparam THREAD_COUNTER_WIDTH=$clog2(MAX_THREADS+1);
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_nop;
input i_valid;
output o_stall;
output o_new_page;
output o_page_done;
output o_start_nop;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
output [BURSTCOUNT_WIDTH-1:0] o_burstcount;
input i_stall;
input common_burst;
input i_input_accepted_from_wrapper_lsu;
input i_reset_timeout;
output o_active;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr_p1;
reg [BURSTCOUNT_WIDTH-1:0] burstcount;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
reg [THREAD_COUNTER_WIDTH-1:0] thread_counter;
generate if(USECACHING)
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)] | thread_counter[THREAD_COUNTER_WIDTH-1];
end
else
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)];
end
endgenerate
// Internal signal logic
wire match_burst_address;
wire match_next_page;
wire match_current_page;
generate
if ( BURSTCOUNT_WIDTH > 1 )
begin
assign match_next_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]) && (|last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]);
assign match_current_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr[BURSTCOUNT_WIDTH-2:0]);
end
else
begin
assign match_next_page = 1'b0;
assign match_current_page = 1'b1;
end
endgenerate
assign match_burst_address = common_burst;//(i_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1] == last_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1]);
assign match = (match_burst_address && (match_current_page || match_next_page)) && !thread_counter[THREAD_COUNTER_WIDTH-1];
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
wire input_accepted = i_valid && !o_stall;
assign o_start_nop = i_nop & ready;
assign o_active = valid;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr_p1 <= {PAGE_ADDR_WIDTH{1'b0}};
burstcount <= 1;
valid <= 1'b0;
timeout_counter <= 0;
thread_counter <= {THREAD_COUNTER_WIDTH{1'b0}};
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
last_page_addr <= ready ? i_page_addr : (input_accepted && match_next_page ? i_page_addr : last_page_addr );
last_page_addr_p1 <= ready ? i_page_addr+1 : (input_accepted && match_next_page ? i_page_addr+1 : last_page_addr_p1 );
valid <= ready ? i_valid & !i_nop : valid; // burst should not start with nop thread
burstcount <= ready ? 6'b000001 : (input_accepted && match_next_page ? burstcount+1 : burstcount );
thread_counter <= ready ? 1 : (USECACHING ?
(i_input_accepted_from_wrapper_lsu && !thread_counter[THREAD_COUNTER_WIDTH-1] ? thread_counter+1 : thread_counter ) :
(input_accepted ? thread_counter+1 : thread_counter));
if( USECACHING && i_reset_timeout || !USECACHING && i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = !match && !ready && i_valid;
// We're starting a new page (used by loads)
assign o_new_page = ready || i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
assign o_req_addr = page_addr;
assign o_burstcount = burstcount;
assign o_req_valid = valid && !waiting;
// We're just finished with a page (used by stores)
assign o_page_done = valid && !waiting && !i_stall || !ready && i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module generates the finish signal for the entire kernel.
// There are two main ports on this module:
// 1. From work-group dispatcher: to detect when a work-GROUP is issued
// It is ASSUMED that the work-group dispatcher issues at most one work-group
// per cycle.
// 2. From exit points of each kernel copy: to detect when a work-ITEM is completed.
module acl_kernel_finish_detector #(
parameter integer NUM_COPIES = 1, // >0
parameter integer WG_SIZE_W = 1, // >0
parameter integer GLOBAL_ID_W = 32 // >0, number of bits for one global id dimension
)
(
input logic clock,
input logic resetn,
input logic start,
input logic [WG_SIZE_W-1:0] wg_size,
// From work-group dispatcher. It is ASSUMED that
// at most one work-group is dispatched per cycle.
input logic [NUM_COPIES-1:0] wg_dispatch_valid_out,
input logic [NUM_COPIES-1:0] wg_dispatch_stall_in,
input logic dispatched_all_groups,
// From copies of the kernel pipeline.
input logic [NUM_COPIES-1:0] kernel_copy_valid_out,
input logic [NUM_COPIES-1:0] kernel_copy_stall_in,
input logic pending_writes,
// The finish signal is a single-cycle pulse.
output logic finish
);
localparam NUM_GLOBAL_DIMS = 3;
localparam MAX_NDRANGE_SIZE_W = NUM_GLOBAL_DIMS * GLOBAL_ID_W;
// Count the total number of work-items in the entire ND-range. This count
// is incremented as work-groups are issued.
// This value is not final until dispatched_all_groups has been asserted.
logic [MAX_NDRANGE_SIZE_W-1:0] ndrange_items;
logic wg_dispatched;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_items <= '0;
else if( start ) // ASSUME start and wg_dispatched are mutually exclusive
ndrange_items <= '0;
else if( wg_dispatched )
// This is where the one work-group per cycle assumption is used.
ndrange_items <= ndrange_items + wg_size;
end
// Here we ASSUME that at most one work-group is dispatched per cycle.
// This depends on the acl_work_group_dispatcher.
assign wg_dispatched = |(wg_dispatch_valid_out & ~wg_dispatch_stall_in);
// Count the number of work-items that have exited all kernel pipelines.
logic [NUM_COPIES-1:0] kernel_copy_item_exit;
logic [MAX_NDRANGE_SIZE_W-1:0] completed_items;
logic [$clog2(NUM_COPIES+1)-1:0] completed_items_incr_comb, completed_items_incr;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
begin
kernel_copy_item_exit <= '0;
completed_items_incr <= '0;
end
else
begin
kernel_copy_item_exit <= kernel_copy_valid_out & ~kernel_copy_stall_in;
completed_items_incr <= completed_items_incr_comb;
end
end
// This is not the best representation, but hopefully synthesis will do something
// intelligent here (e.g. use compressors?). Assuming that the number of
// copies will never be that high to have to pipeline this addition.
always @(*)
begin
completed_items_incr_comb = '0;
for( integer i = 0; i < NUM_COPIES; ++i )
completed_items_incr_comb = completed_items_incr_comb + kernel_copy_item_exit[i];
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
completed_items <= '0;
else if( start ) // ASSUME that work-items do not complete on the same cycle as start
completed_items <= '0;
else
completed_items <= completed_items + completed_items_incr;
end
// Determine if the ND-range has completed. This is true when
// the ndrange_items counter is complete (i.e. dispatched_all_groups)
// and the completed_items counter is equal to the ndrang_items counter.
logic ndrange_done;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_done <= 1'b0;
else if( start )
ndrange_done <= 1'b0;
else
// ASSUMING that dispatched_all_groups is asserted at least one cycle
// after the last work-group is issued
ndrange_done <= dispatched_all_groups & (ndrange_items == completed_items);
end
// The finish output needs to be a one-cycle pulse when the ndrange is completed
// AND there are no pending writes.
logic finish_asserted;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish <= 1'b0;
else
finish <= ~finish_asserted & ndrange_done & ~pending_writes;
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish_asserted <= 1'b0;
else if( start )
finish_asserted <= 1'b0;
else if( finish )
finish_asserted <= 1'b1;
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
// This module generates the finish signal for the entire kernel.
// There are two main ports on this module:
// 1. From work-group dispatcher: to detect when a work-GROUP is issued
// It is ASSUMED that the work-group dispatcher issues at most one work-group
// per cycle.
// 2. From exit points of each kernel copy: to detect when a work-ITEM is completed.
module acl_kernel_finish_detector #(
parameter integer NUM_COPIES = 1, // >0
parameter integer WG_SIZE_W = 1, // >0
parameter integer GLOBAL_ID_W = 32 // >0, number of bits for one global id dimension
)
(
input logic clock,
input logic resetn,
input logic start,
input logic [WG_SIZE_W-1:0] wg_size,
// From work-group dispatcher. It is ASSUMED that
// at most one work-group is dispatched per cycle.
input logic [NUM_COPIES-1:0] wg_dispatch_valid_out,
input logic [NUM_COPIES-1:0] wg_dispatch_stall_in,
input logic dispatched_all_groups,
// From copies of the kernel pipeline.
input logic [NUM_COPIES-1:0] kernel_copy_valid_out,
input logic [NUM_COPIES-1:0] kernel_copy_stall_in,
input logic pending_writes,
// The finish signal is a single-cycle pulse.
output logic finish
);
localparam NUM_GLOBAL_DIMS = 3;
localparam MAX_NDRANGE_SIZE_W = NUM_GLOBAL_DIMS * GLOBAL_ID_W;
// Count the total number of work-items in the entire ND-range. This count
// is incremented as work-groups are issued.
// This value is not final until dispatched_all_groups has been asserted.
logic [MAX_NDRANGE_SIZE_W-1:0] ndrange_items;
logic wg_dispatched;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_items <= '0;
else if( start ) // ASSUME start and wg_dispatched are mutually exclusive
ndrange_items <= '0;
else if( wg_dispatched )
// This is where the one work-group per cycle assumption is used.
ndrange_items <= ndrange_items + wg_size;
end
// Here we ASSUME that at most one work-group is dispatched per cycle.
// This depends on the acl_work_group_dispatcher.
assign wg_dispatched = |(wg_dispatch_valid_out & ~wg_dispatch_stall_in);
// Count the number of work-items that have exited all kernel pipelines.
logic [NUM_COPIES-1:0] kernel_copy_item_exit;
logic [MAX_NDRANGE_SIZE_W-1:0] completed_items;
logic [$clog2(NUM_COPIES+1)-1:0] completed_items_incr_comb, completed_items_incr;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
begin
kernel_copy_item_exit <= '0;
completed_items_incr <= '0;
end
else
begin
kernel_copy_item_exit <= kernel_copy_valid_out & ~kernel_copy_stall_in;
completed_items_incr <= completed_items_incr_comb;
end
end
// This is not the best representation, but hopefully synthesis will do something
// intelligent here (e.g. use compressors?). Assuming that the number of
// copies will never be that high to have to pipeline this addition.
always @(*)
begin
completed_items_incr_comb = '0;
for( integer i = 0; i < NUM_COPIES; ++i )
completed_items_incr_comb = completed_items_incr_comb + kernel_copy_item_exit[i];
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
completed_items <= '0;
else if( start ) // ASSUME that work-items do not complete on the same cycle as start
completed_items <= '0;
else
completed_items <= completed_items + completed_items_incr;
end
// Determine if the ND-range has completed. This is true when
// the ndrange_items counter is complete (i.e. dispatched_all_groups)
// and the completed_items counter is equal to the ndrang_items counter.
logic ndrange_done;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_done <= 1'b0;
else if( start )
ndrange_done <= 1'b0;
else
// ASSUMING that dispatched_all_groups is asserted at least one cycle
// after the last work-group is issued
ndrange_done <= dispatched_all_groups & (ndrange_items == completed_items);
end
// The finish output needs to be a one-cycle pulse when the ndrange is completed
// AND there are no pending writes.
logic finish_asserted;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish <= 1'b0;
else
finish <= ~finish_asserted & ndrange_done & ~pending_writes;
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish_asserted <= 1'b0;
else if( start )
finish_asserted <= 1'b0;
else if( finish )
finish_asserted <= 1'b1;
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for simple memory access. See lsu_top.v.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: No
// (see lsu_top.v for details)
//
// Description: Simple un-pipelined memory access. Low throughput.
//
// Simple read unit:
// Accept read requests on the upstream interface. When a request is
// received, set the pending register to true to stall any subsequent
// requests until the transaction is complete. Since an avalon master
// cannot stall a response, staging registers are used at the output to
// provide a storage location until the downstream block is ready to accept
// data. Once the output registers are cleared and there are no pending
// requests, accept a new transaction.
module lsu_simple_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, // Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
// - indicates how many bits of the address
// are '0' due to the request alignment
parameter HIGH_FMAX=1;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam MIN_BYTE_SELECT_BITS = BYTE_SELECT_BITS == 0 ? 1 : BYTE_SELECT_BITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
reg pending;
wire read_accepted;
wire rdata_accepted;
wire sr_stall;
wire ready;
wire [WIDTH-1:0] rdata;
wire [MIN_BYTE_SELECT_BITS-1:0] byte_address;
reg [MIN_BYTE_SELECT_BITS-1:0] byte_select;
// Ready for new data if we have access to the downstream registers and there
// is no pending memory transaction
assign ready = !sr_stall && !pending;
wire [AWIDTH-1:0] f_avm_address;
wire f_avm_read;
wire f_avm_waitrequest;
// Avalon signals - passed through from inputs
assign f_avm_address = (i_address[AWIDTH-1:BYTE_SELECT_BITS] << BYTE_SELECT_BITS);
assign f_avm_read = i_valid && ready;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Upstream stall if we aren't ready for new data, or the avalon interface
// is stalling.
assign o_stall = f_avm_waitrequest || !ready;
// Pick out the byte address
// Explicitly set alignment address bits to 0 to help synthesis optimizations.
generate
if (BYTE_SELECT_BITS == 0) begin
assign byte_address = 1'b0;
end
else begin
assign byte_address = ((i_address[MIN_BYTE_SELECT_BITS-1:0] >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS);
end
endgenerate
// State registers
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
pending <= 1'b0;
byte_select <= 'x; // don't need to reset
end
else
begin
// A requst remains pending until we receive valid data; and a request
// becomes pending if we accept a new valid input
pending <= pending ? !avm_readdatavalid : (i_valid && !o_stall && !avm_readdatavalid);
// Remember which bytes to select out of the wider global memory bus.
byte_select <= pending ? byte_select : byte_address;
end
end
// Mux in the appropriate response bits
assign rdata = avm_readdata[8*byte_select +: WIDTH];
// Output staging register - required so that we can guarantee there is
// a place to store the readdata response
acl_staging_reg #(
.WIDTH(WIDTH)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(rdata),
.i_valid(avm_readdatavalid),
.o_stall(sr_stall),
.o_data(o_readdata),
.o_valid(o_valid),
.i_stall (i_stall)
);
generate
if(HIGH_FMAX)
begin
// Pipeline the interface
acl_data_fifo #(
.DATA_WIDTH(AWIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in(f_avm_address),
.valid_in(f_avm_read),
.data_out(avm_address),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( f_avm_waitrequest )
);
end
else
begin
// No interface pipelining
assign f_avm_waitrequest = avm_waitrequest;
assign avm_address = f_avm_address;
assign avm_read = f_avm_read;
end
endgenerate
assign o_active=pending;
endmodule
// Simple write unit:
// Accept write requests on the upstream interface. When a request is
// received, pass it through to the avalon bus. Once avalon accepts
// the request, set the output valid bit to true and stall until
// the downstream block acknowledges the successful write.
module lsu_simple_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, // Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the request
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
parameter USE_BYTE_EN=0;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
/***************
* Architecture *
***************/
reg write_pending;
wire write_accepted;
wire ready;
wire sr_stall;
// Avalon interface
assign avm_address = ((i_address >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid;
// Mux in the correct data
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
else
begin
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[0 +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
endgenerate
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
write_pending <= 1'b0;
end
else
begin
write_pending <= (write_accepted || write_pending) && !avm_writeack;
end
end
// Control logic
assign ready = !sr_stall && !write_pending;
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall = !ready || avm_waitrequest;
// Output staging register - required so that we can guarantee there is
// a place to store the valid bit
acl_staging_reg #(
.WIDTH(1)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(1'b0),
.i_valid(avm_writeack),
.o_stall(sr_stall),
.o_data(),
.o_valid(o_valid),
.i_stall (i_stall)
);
assign o_active=write_pending;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//
// Top level module for simple memory access. See lsu_top.v.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: No
// (see lsu_top.v for details)
//
// Description: Simple un-pipelined memory access. Low throughput.
//
// Simple read unit:
// Accept read requests on the upstream interface. When a request is
// received, set the pending register to true to stall any subsequent
// requests until the transaction is complete. Since an avalon master
// cannot stall a response, staging registers are used at the output to
// provide a storage location until the downstream block is ready to accept
// data. Once the output registers are cleared and there are no pending
// requests, accept a new transaction.
module lsu_simple_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, // Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
// - indicates how many bits of the address
// are '0' due to the request alignment
parameter HIGH_FMAX=1;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam MIN_BYTE_SELECT_BITS = BYTE_SELECT_BITS == 0 ? 1 : BYTE_SELECT_BITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
reg pending;
wire read_accepted;
wire rdata_accepted;
wire sr_stall;
wire ready;
wire [WIDTH-1:0] rdata;
wire [MIN_BYTE_SELECT_BITS-1:0] byte_address;
reg [MIN_BYTE_SELECT_BITS-1:0] byte_select;
// Ready for new data if we have access to the downstream registers and there
// is no pending memory transaction
assign ready = !sr_stall && !pending;
wire [AWIDTH-1:0] f_avm_address;
wire f_avm_read;
wire f_avm_waitrequest;
// Avalon signals - passed through from inputs
assign f_avm_address = (i_address[AWIDTH-1:BYTE_SELECT_BITS] << BYTE_SELECT_BITS);
assign f_avm_read = i_valid && ready;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Upstream stall if we aren't ready for new data, or the avalon interface
// is stalling.
assign o_stall = f_avm_waitrequest || !ready;
// Pick out the byte address
// Explicitly set alignment address bits to 0 to help synthesis optimizations.
generate
if (BYTE_SELECT_BITS == 0) begin
assign byte_address = 1'b0;
end
else begin
assign byte_address = ((i_address[MIN_BYTE_SELECT_BITS-1:0] >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS);
end
endgenerate
// State registers
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
pending <= 1'b0;
byte_select <= 'x; // don't need to reset
end
else
begin
// A requst remains pending until we receive valid data; and a request
// becomes pending if we accept a new valid input
pending <= pending ? !avm_readdatavalid : (i_valid && !o_stall && !avm_readdatavalid);
// Remember which bytes to select out of the wider global memory bus.
byte_select <= pending ? byte_select : byte_address;
end
end
// Mux in the appropriate response bits
assign rdata = avm_readdata[8*byte_select +: WIDTH];
// Output staging register - required so that we can guarantee there is
// a place to store the readdata response
acl_staging_reg #(
.WIDTH(WIDTH)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(rdata),
.i_valid(avm_readdatavalid),
.o_stall(sr_stall),
.o_data(o_readdata),
.o_valid(o_valid),
.i_stall (i_stall)
);
generate
if(HIGH_FMAX)
begin
// Pipeline the interface
acl_data_fifo #(
.DATA_WIDTH(AWIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in(f_avm_address),
.valid_in(f_avm_read),
.data_out(avm_address),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( f_avm_waitrequest )
);
end
else
begin
// No interface pipelining
assign f_avm_waitrequest = avm_waitrequest;
assign avm_address = f_avm_address;
assign avm_read = f_avm_read;
end
endgenerate
assign o_active=pending;
endmodule
// Simple write unit:
// Accept write requests on the upstream interface. When a request is
// received, pass it through to the avalon bus. Once avalon accepts
// the request, set the output valid bit to true and stall until
// the downstream block acknowledges the successful write.
module lsu_simple_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, // Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the request
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
parameter USE_BYTE_EN=0;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
/***************
* Architecture *
***************/
reg write_pending;
wire write_accepted;
wire ready;
wire sr_stall;
// Avalon interface
assign avm_address = ((i_address >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid;
// Mux in the correct data
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
else
begin
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[0 +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
endgenerate
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
write_pending <= 1'b0;
end
else
begin
write_pending <= (write_accepted || write_pending) && !avm_writeack;
end
end
// Control logic
assign ready = !sr_stall && !write_pending;
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall = !ready || avm_waitrequest;
// Output staging register - required so that we can guarantee there is
// a place to store the valid bit
acl_staging_reg #(
.WIDTH(1)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(1'b0),
.i_valid(avm_writeack),
.o_stall(sr_stall),
.o_data(),
.o_valid(o_valid),
.i_stall (i_stall)
);
assign o_active=write_pending;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// 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 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.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports.
//
//===----------------------------------------------------------------------===//
module acl_fifo (
clock,
resetn,
data_in,
data_out,
valid_in,
valid_out,
stall_in,
stall_out,
usedw,
empty,
full,
almost_full);
function integer my_local_log;
input [31:0] value;
for (my_local_log=0; value>0; my_local_log=my_local_log+1)
value = value>>1;
endfunction
parameter DATA_WIDTH = 32;
parameter DEPTH = 256;
parameter NUM_BITS_USED_WORDS = DEPTH == 1 ? 1 : my_local_log(DEPTH-1);
parameter ALMOST_FULL_VALUE = 0;
input clock, stall_in, valid_in, resetn;
output stall_out, valid_out;
input [DATA_WIDTH-1:0] data_in;
output [DATA_WIDTH-1:0] data_out;
output [NUM_BITS_USED_WORDS-1:0] usedw;
output empty, full, almost_full;
// add a register stage prior to the acl_fifo.
//reg [DATA_WIDTH-1:0] data_input /* synthesis preserve */;
//reg valid_input /* synthesis preserve */;
//always@(posedge clock or negedge resetn)
//begin
// if (~resetn)
// begin
// data_input <= {DATA_WIDTH{1'bx}};
// valid_input <= 1'b0;
// end
// else if (~valid_input | ~full)
// begin
// valid_input <= valid_in;
// data_input <= data_in;
// end
//end
scfifo scfifo_component (
.clock (clock),
.data (data_in),
.rdreq ((~stall_in) & (~empty)),
.sclr (),
.wrreq (valid_in & (~full)),
.empty (empty),
.full (full),
.q (data_out),
.aclr (~resetn),
.almost_empty (),
.almost_full (almost_full),
.usedw (usedw));
defparam
scfifo_component.add_ram_output_register = "ON",
scfifo_component.intended_device_family = "Stratix IV",
scfifo_component.lpm_numwords = DEPTH,
scfifo_component.lpm_showahead = "ON",
scfifo_component.lpm_type = "scfifo",
scfifo_component.lpm_width = DATA_WIDTH,
scfifo_component.lpm_widthu = NUM_BITS_USED_WORDS,
scfifo_component.overflow_checking = "ON",
scfifo_component.underflow_checking = "ON",
scfifo_component.use_eab = "ON",
scfifo_component.almost_full_value = ALMOST_FULL_VALUE;
assign stall_out = full;
assign valid_out = ~empty;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
`timescale 1ns/10ps
`verilog
`suppress_faults
`nosuppress_faults
`enable_portfaults
`disable_portfaults
`delay_mode_distributed
`delay_mode_path
`delay_mode_unit
`delay_mode_zero
`default_decay_time 1
`default_decay_time 1.0
`default_decay_time infinite
// unsupported (recommended not to): `default_trireg_strength 10
`default_nettype wire
// unsupported: `default_nettype tri
// unsupported: `default_nettype tri0
// unsupported: `default_nettype wand
// unsupported: `default_nettype triand
// unsupported: `default_nettype wor
// unsupported: `default_nettype trior
// unsupported: `default_nettype trireg
`default_nettype none
`autoexpand_vectornets
`accelerate
`noaccelerate
`expand_vectornets
`noexpand_vectornets
`remove_gatenames
`noremove_gatenames
`remove_netnames
`noremove_netnames
`resetall
// unsupported: `unconnected_drive pull1
// unsupported: `unconnected_drive pull0
`nounconnected_drive
`line 100 "hallo.v" 0
// unsupported: `uselib file=../moto_lib.v
// unsupported: `uselib dir=../lib.dir libext=.v
module t;
initial begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
`timescale 1ns/10ps
`verilog
`suppress_faults
`nosuppress_faults
`enable_portfaults
`disable_portfaults
`delay_mode_distributed
`delay_mode_path
`delay_mode_unit
`delay_mode_zero
`default_decay_time 1
`default_decay_time 1.0
`default_decay_time infinite
// unsupported (recommended not to): `default_trireg_strength 10
`default_nettype wire
// unsupported: `default_nettype tri
// unsupported: `default_nettype tri0
// unsupported: `default_nettype wand
// unsupported: `default_nettype triand
// unsupported: `default_nettype wor
// unsupported: `default_nettype trior
// unsupported: `default_nettype trireg
`default_nettype none
`autoexpand_vectornets
`accelerate
`noaccelerate
`expand_vectornets
`noexpand_vectornets
`remove_gatenames
`noremove_gatenames
`remove_netnames
`noremove_netnames
`resetall
// unsupported: `unconnected_drive pull1
// unsupported: `unconnected_drive pull0
`nounconnected_drive
`line 100 "hallo.v" 0
// unsupported: `uselib file=../moto_lib.v
// unsupported: `uselib dir=../lib.dir libext=.v
module t;
initial begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.