text
stringlengths
938
1.05M
// (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 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
`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 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
// (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
// (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_wrp #( 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 // If the fifo depth is zero, the module will perform the write ack here, // otherwise it will take the write ack from the input s_writeack. parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables) parameter integer PIPELINE = 1 // 0|1 ) ( input clock, input resetn, acl_arb_intf m_intf, input logic s_writeack, acl_ic_wrp_intf wrp_intf, output logic stall ); generate if( NUM_MASTERS > 1 ) begin // This slave endpoint may not directly talk to the ACTUAL slave. In // this case we need a fifo to store which master each write ack should // go to. If FIFO_DEPTH is 0 then we assume the writeack can be // generated right here (the way it was done originally) if( FIFO_DEPTH > 0 ) begin // We don't have to worry about bursts, we'll fifo each transaction // since writeack behaves like readdatavalid logic rf_empty, rf_full; acl_ll_fifo #( .WIDTH( ID_W ), .DEPTH( FIFO_DEPTH ) ) write_fifo( .clk( clock ), .reset( ~resetn ), .data_in( m_intf.req.id ), .write( ~m_intf.stall & m_intf.req.write ), .data_out( wrp_intf.id ), .read( wrp_intf.ack & ~rf_empty), .empty( rf_empty ), .full( rf_full ) ); // Register slave writeack to guarantee fifo output is ready always @( posedge clock or negedge resetn ) begin if( !resetn ) wrp_intf.ack <= 1'b0; else wrp_intf.ack <= s_writeack; end assign stall = rf_full; end else if( PIPELINE == 1 ) begin assign stall = 1'b0; always @( posedge clock or negedge resetn ) if( !resetn ) begin wrp_intf.ack <= 1'b0; wrp_intf.id <= 'x; // don't need to reset end else begin // Always register the id. The ack signal acts as the enable. wrp_intf.id <= m_intf.req.id; wrp_intf.ack <= 1'b0; if( ~m_intf.stall & m_intf.req.write ) // A valid write cycle. Ack it. wrp_intf.ack <= 1'b1; end end else begin assign wrp_intf.id = m_intf.req.id; assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write; assign stall = 1'b0; end end else // NUM_MASTERS == 1 begin // Only one master so don't need to check the id. if ( FIFO_DEPTH == 0 ) begin assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write; assign stall = 1'b0; end else begin assign wrp_intf.ack = s_writeack; assign stall = 1'b0; end end endgenerate 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
// (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:
// 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
// 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. // 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. // 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 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. module acl_ic_wrp_reg ( input logic clock, input logic resetn, acl_ic_wrp_intf wrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_wrp_intf wrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin wrp_out.ack <= 1'b0; wrp_out.id <= 'x; end else begin wrp_out.ack <= wrp_in.ack; wrp_out.id <= wrp_in.id; 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_wrp_reg ( input logic clock, input logic resetn, acl_ic_wrp_intf wrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_wrp_intf wrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin wrp_out.ack <= 1'b0; wrp_out.id <= 'x; end else begin wrp_out.ack <= wrp_in.ack; wrp_out.id <= wrp_in.id; 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_wrp_reg ( input logic clock, input logic resetn, acl_ic_wrp_intf wrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_wrp_intf wrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin wrp_out.ack <= 1'b0; wrp_out.id <= 'x; end else begin wrp_out.ack <= wrp_in.ack; wrp_out.id <= wrp_in.id; end 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) $ *)
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
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
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2010 by Wilson Snyder. module t; integer v = 19; initial begin if (v==1) begin end else if (v==2) begin end else if (v==3) begin end else if (v==4) begin end else if (v==5) begin end else if (v==6) begin end else if (v==7) begin end else if (v==8) begin end else if (v==9) begin end else if (v==10) begin end else if (v==11) begin end // Warn about this one else if (v==12) begin end end initial begin unique0 if (v==1) begin end else if (v==2) begin end else if (v==3) begin end else if (v==4) begin end else if (v==5) begin end else if (v==6) begin end else if (v==7) begin end else if (v==8) begin end else if (v==9) begin end else if (v==10) begin end else if (v==11) begin end // Warn about this one else if (v==12) begin 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. // // 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. // // 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
(***********************************************************************) (* 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 *) (***********************************************************************) (**************************************************************) (* FSetDecide.v *) (* *) (* Author: Aaron Bohannon *) (**************************************************************) (** This file implements a decision procedure for a certain class of propositions involving finite sets. *) Require Import Decidable DecidableTypeEx FSetFacts. (** First, a version for Weak Sets in functorial presentation *) Module WDecide_fun (E : DecidableType)(Import M : WSfun E). Module F := FSetFacts.WFacts_fun 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 FSet-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 FSetLogicalFacts. 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 FSetLogicalFacts. Import FSetLogicalFacts. (** * 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 FSetDecideAuxiliary. (** ** 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-FSet-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 FSet_elt_Prop : Prop -> Prop := | eq_Prop : forall (S : Type) (x y : S), FSet_elt_Prop (x = y) | eq_elt_prop : forall x y, FSet_elt_Prop (E.eq x y) | In_elt_prop : forall x s, FSet_elt_Prop (In x s) | True_elt_prop : FSet_elt_Prop True | False_elt_prop : FSet_elt_Prop False | conj_elt_prop : forall P Q, FSet_elt_Prop P -> FSet_elt_Prop Q -> FSet_elt_Prop (P /\ Q) | disj_elt_prop : forall P Q, FSet_elt_Prop P -> FSet_elt_Prop Q -> FSet_elt_Prop (P \/ Q) | impl_elt_prop : forall P Q, FSet_elt_Prop P -> FSet_elt_Prop Q -> FSet_elt_Prop (P -> Q) | not_elt_prop : forall P, FSet_elt_Prop P -> FSet_elt_Prop (~ P). Inductive FSet_Prop : Prop -> Prop := | elt_FSet_Prop : forall P, FSet_elt_Prop P -> FSet_Prop P | Empty_FSet_Prop : forall s, FSet_Prop (Empty s) | Subset_FSet_Prop : forall s1 s2, FSet_Prop (Subset s1 s2) | Equal_FSet_Prop : forall s1 s2, FSet_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 FSet_elt_Prop FSet_Prop : FSet_Prop. Ltac discard_nonFSet := 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 (FSet_Prop P) holds by (auto 100 with FSet_Prop) then fail else clear H end). (** ** Turning Set Operators into Propositional Connectives The lemmas from [FSetFacts] 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 FSet 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 [FSet_decidability] will be given to the [push_neg] tactic from the module [Negation]. *) Hint Resolve dec_In dec_eq : FSet_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 substFSet := 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_FSet_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 substFSet; 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_FSet_hypotheses; autorewrite with set_simpl set_eq_simpl in *; push not in * using FSet_decidability; substFSet; assert_decidability; auto; (intuition fsetdec_rec) || fail 1 "because the goal is beyond the scope of this tactic". End FSetDecideAuxiliary. Import FSetDecideAuxiliary. (** * 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_nonFSet] and [assert_decidability] tactics to do a much better job. *) decompose records; discard_nonFSet; (** 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 [FSet_elt_Prop], noting that any [FSet_elt_Prop] is decidable. *) pull not using FSet_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 (FSet_elt_Prop P) holds by (auto 100 with FSet_Prop) then (contradict H; fsetdec_body) else fsetdec_body | |- _ => fsetdec_body end. (** * Examples *) Module FSetDecideTestCases. 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 FSetDecideTestCases. End WDecide_fun. Require Import FSetInterface. (** 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:WS) := !WDecide_fun M.E M. Module Decide := WDecide.
// (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. // 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. // This module dispatches group ids to possibly multiple work item iterators. // Each work-item iterator should be separated by a fifo from the dispatcher. module acl_work_group_dispatcher #( parameter WIDTH = 32, // width of all the counters parameter NUM_COPIES = 1, // number of kernel copies to manage parameter RUN_FOREVER = 0 // flag for infinitely running kernel ) ( input clock, input resetn, input start, // Assert to restart the iterators // Populated during kernel startup input [WIDTH-1:0] num_groups[2:0], input [WIDTH-1:0] local_size[2:0], // Handshaking with iterators for each kernel copy input [NUM_COPIES-1:0] stall_in, output [NUM_COPIES-1:0] valid_out, // Export group_id to iterators. output reg [WIDTH-1:0] group_id_out[2:0], output reg [WIDTH-1:0] global_id_base_out[2:0], output start_out, // High when all groups have been dispatched to id iterators output reg dispatched_all_groups ); ////////////////////////////////// // Group id register updates. reg started; // one cycle delayed after start goes high. stays high reg delayed_start; // two cycles delayed after start goes high. stays high reg [WIDTH-1:0] max_group_id[2:0]; reg [WIDTH-1:0] group_id[2:0]; wire last_group_id[2:0]; assign last_group_id[0] = (group_id[0] == max_group_id[0] ); assign last_group_id[1] = (group_id[1] == max_group_id[1] ); assign last_group_id[2] = (group_id[2] == max_group_id[2] ); wire last_group = last_group_id[0] & last_group_id[1] & last_group_id[2]; wire group_id_ready; wire bump_group_id[2:0]; assign bump_group_id[0] = 1'b1; assign bump_group_id[1] = last_group_id[0]; assign bump_group_id[2] = last_group_id[0] && last_group_id[1]; always @(posedge clock or negedge resetn) begin if ( ~resetn ) begin group_id[0] <= {WIDTH{1'b0}}; group_id[1] <= {WIDTH{1'b0}}; group_id[2] <= {WIDTH{1'b0}}; global_id_base_out[0] <= {WIDTH{1'b0}}; global_id_base_out[1] <= {WIDTH{1'b0}}; global_id_base_out[2] <= {WIDTH{1'b0}}; max_group_id[0] <= {WIDTH{1'b0}}; max_group_id[1] <= {WIDTH{1'b0}}; max_group_id[2] <= {WIDTH{1'b0}}; started <= 1'b0; delayed_start <= 1'b0; dispatched_all_groups <= 1'b0; end else if ( start ) begin group_id[0] <= {WIDTH{1'b0}}; group_id[1] <= {WIDTH{1'b0}}; group_id[2] <= {WIDTH{1'b0}}; global_id_base_out[0] <= {WIDTH{1'b0}}; global_id_base_out[1] <= {WIDTH{1'b0}}; global_id_base_out[2] <= {WIDTH{1'b0}}; max_group_id[0] <= num_groups[0] - 2'b01; max_group_id[1] <= num_groups[1] - 2'b01; max_group_id[2] <= num_groups[2] - 2'b01; started <= 1'b1; delayed_start <= started; dispatched_all_groups <= 1'b0; end else // We presume that start and issue are mutually exclusive. begin if ( started & stall_in != {NUM_COPIES{1'b1}} & ~dispatched_all_groups ) begin if ( bump_group_id[0] ) group_id[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (group_id[0] + 2'b01); if ( bump_group_id[1] ) group_id[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (group_id[1] + 2'b01); if ( bump_group_id[2] ) group_id[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (group_id[2] + 2'b01); // increment global_id_base here so it's always equal to // group_id x local_size. // without using any multipliers. if ( bump_group_id[0] ) global_id_base_out[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (global_id_base_out[0] + local_size[0]); if ( bump_group_id[1] ) global_id_base_out[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (global_id_base_out[1] + local_size[1]); if ( bump_group_id[2] ) global_id_base_out[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (global_id_base_out[2] + local_size[2]); if ( last_group && RUN_FOREVER == 0 ) dispatched_all_groups <= 1'b1; end // reset these registers so that next kernel invocation will work. if ( dispatched_all_groups ) begin started <= 1'b0; delayed_start <= 1'b0; end end end // will have 1 at the lowest position where stall_in has 0. wire [NUM_COPIES-1:0] single_one_from_stall_in = ~stall_in & (stall_in + 1'b1); assign group_id_ready = delayed_start & ~dispatched_all_groups; assign start_out = start; assign group_id_out = group_id; assign valid_out = single_one_from_stall_in & {NUM_COPIES{group_id_ready}}; 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 dispatches group ids to possibly multiple work item iterators. // Each work-item iterator should be separated by a fifo from the dispatcher. module acl_work_group_dispatcher #( parameter WIDTH = 32, // width of all the counters parameter NUM_COPIES = 1, // number of kernel copies to manage parameter RUN_FOREVER = 0 // flag for infinitely running kernel ) ( input clock, input resetn, input start, // Assert to restart the iterators // Populated during kernel startup input [WIDTH-1:0] num_groups[2:0], input [WIDTH-1:0] local_size[2:0], // Handshaking with iterators for each kernel copy input [NUM_COPIES-1:0] stall_in, output [NUM_COPIES-1:0] valid_out, // Export group_id to iterators. output reg [WIDTH-1:0] group_id_out[2:0], output reg [WIDTH-1:0] global_id_base_out[2:0], output start_out, // High when all groups have been dispatched to id iterators output reg dispatched_all_groups ); ////////////////////////////////// // Group id register updates. reg started; // one cycle delayed after start goes high. stays high reg delayed_start; // two cycles delayed after start goes high. stays high reg [WIDTH-1:0] max_group_id[2:0]; reg [WIDTH-1:0] group_id[2:0]; wire last_group_id[2:0]; assign last_group_id[0] = (group_id[0] == max_group_id[0] ); assign last_group_id[1] = (group_id[1] == max_group_id[1] ); assign last_group_id[2] = (group_id[2] == max_group_id[2] ); wire last_group = last_group_id[0] & last_group_id[1] & last_group_id[2]; wire group_id_ready; wire bump_group_id[2:0]; assign bump_group_id[0] = 1'b1; assign bump_group_id[1] = last_group_id[0]; assign bump_group_id[2] = last_group_id[0] && last_group_id[1]; always @(posedge clock or negedge resetn) begin if ( ~resetn ) begin group_id[0] <= {WIDTH{1'b0}}; group_id[1] <= {WIDTH{1'b0}}; group_id[2] <= {WIDTH{1'b0}}; global_id_base_out[0] <= {WIDTH{1'b0}}; global_id_base_out[1] <= {WIDTH{1'b0}}; global_id_base_out[2] <= {WIDTH{1'b0}}; max_group_id[0] <= {WIDTH{1'b0}}; max_group_id[1] <= {WIDTH{1'b0}}; max_group_id[2] <= {WIDTH{1'b0}}; started <= 1'b0; delayed_start <= 1'b0; dispatched_all_groups <= 1'b0; end else if ( start ) begin group_id[0] <= {WIDTH{1'b0}}; group_id[1] <= {WIDTH{1'b0}}; group_id[2] <= {WIDTH{1'b0}}; global_id_base_out[0] <= {WIDTH{1'b0}}; global_id_base_out[1] <= {WIDTH{1'b0}}; global_id_base_out[2] <= {WIDTH{1'b0}}; max_group_id[0] <= num_groups[0] - 2'b01; max_group_id[1] <= num_groups[1] - 2'b01; max_group_id[2] <= num_groups[2] - 2'b01; started <= 1'b1; delayed_start <= started; dispatched_all_groups <= 1'b0; end else // We presume that start and issue are mutually exclusive. begin if ( started & stall_in != {NUM_COPIES{1'b1}} & ~dispatched_all_groups ) begin if ( bump_group_id[0] ) group_id[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (group_id[0] + 2'b01); if ( bump_group_id[1] ) group_id[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (group_id[1] + 2'b01); if ( bump_group_id[2] ) group_id[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (group_id[2] + 2'b01); // increment global_id_base here so it's always equal to // group_id x local_size. // without using any multipliers. if ( bump_group_id[0] ) global_id_base_out[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (global_id_base_out[0] + local_size[0]); if ( bump_group_id[1] ) global_id_base_out[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (global_id_base_out[1] + local_size[1]); if ( bump_group_id[2] ) global_id_base_out[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (global_id_base_out[2] + local_size[2]); if ( last_group && RUN_FOREVER == 0 ) dispatched_all_groups <= 1'b1; end // reset these registers so that next kernel invocation will work. if ( dispatched_all_groups ) begin started <= 1'b0; delayed_start <= 1'b0; end end end // will have 1 at the lowest position where stall_in has 0. wire [NUM_COPIES-1:0] single_one_from_stall_in = ~stall_in & (stall_in + 1'b1); assign group_id_ready = delayed_start & ~dispatched_all_groups; assign start_out = start; assign group_id_out = group_id; assign valid_out = single_one_from_stall_in & {NUM_COPIES{group_id_ready}}; 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. module acl_atomics_arb_stall #( // Configuration parameter integer STALL_CYCLES = 6 ) ( input logic clock, input logic resetn, acl_arb_intf in_intf, acl_arb_intf out_intf ); /****************** * Local Variables * ******************/ reg shift_register [0:STALL_CYCLES-1]; wire atomic; wire stall; integer t; /****************** * Local Variables * ******************/ assign out_intf.req.request = ( in_intf.req.request & ~stall ); // mask request assign out_intf.req.read = ( in_intf.req.read & ~stall ); // mask read assign out_intf.req.write = ( in_intf.req.write & ~stall ); // mask write assign out_intf.req.writedata = in_intf.req.writedata; assign out_intf.req.burstcount = in_intf.req.burstcount; assign out_intf.req.address = in_intf.req.address; assign out_intf.req.byteenable = in_intf.req.byteenable; assign out_intf.req.id = in_intf.req.id; assign in_intf.stall = ( out_intf.stall | stall ); /***************** * Detect Atomic * ******************/ assign atomic = ( out_intf.req.request == 1'b1 && out_intf.req.read == 1'b1 && out_intf.req.writedata[0:0] == 1'b1 ) ? 1'b1 : 1'b0; always@(posedge clock or negedge resetn) begin if ( !resetn ) begin shift_register[0] <= 1'b0; end else begin shift_register[0] <= atomic; end end /***************** * Shift Register * ******************/ always@(posedge clock or negedge resetn) begin for (t=1; t< STALL_CYCLES; t=t+1) begin if ( !resetn ) begin shift_register[t] <= 1'b0; end else begin shift_register[t] <= shift_register[t-1]; end end end /*************** * Detect Stall * ***************/ assign stall = ( shift_register[STALL_CYCLES-1] == 1'b1 ); 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_atomics_arb_stall #( // Configuration parameter integer STALL_CYCLES = 6 ) ( input logic clock, input logic resetn, acl_arb_intf in_intf, acl_arb_intf out_intf ); /****************** * Local Variables * ******************/ reg shift_register [0:STALL_CYCLES-1]; wire atomic; wire stall; integer t; /****************** * Local Variables * ******************/ assign out_intf.req.request = ( in_intf.req.request & ~stall ); // mask request assign out_intf.req.read = ( in_intf.req.read & ~stall ); // mask read assign out_intf.req.write = ( in_intf.req.write & ~stall ); // mask write assign out_intf.req.writedata = in_intf.req.writedata; assign out_intf.req.burstcount = in_intf.req.burstcount; assign out_intf.req.address = in_intf.req.address; assign out_intf.req.byteenable = in_intf.req.byteenable; assign out_intf.req.id = in_intf.req.id; assign in_intf.stall = ( out_intf.stall | stall ); /***************** * Detect Atomic * ******************/ assign atomic = ( out_intf.req.request == 1'b1 && out_intf.req.read == 1'b1 && out_intf.req.writedata[0:0] == 1'b1 ) ? 1'b1 : 1'b0; always@(posedge clock or negedge resetn) begin if ( !resetn ) begin shift_register[0] <= 1'b0; end else begin shift_register[0] <= atomic; end end /***************** * Shift Register * ******************/ always@(posedge clock or negedge resetn) begin for (t=1; t< STALL_CYCLES; t=t+1) begin if ( !resetn ) begin shift_register[t] <= 1'b0; end else begin shift_register[t] <= shift_register[t-1]; end end end /*************** * Detect Stall * ***************/ assign stall = ( shift_register[STALL_CYCLES-1] == 1'b1 ); 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_atomics_arb_stall #( // Configuration parameter integer STALL_CYCLES = 6 ) ( input logic clock, input logic resetn, acl_arb_intf in_intf, acl_arb_intf out_intf ); /****************** * Local Variables * ******************/ reg shift_register [0:STALL_CYCLES-1]; wire atomic; wire stall; integer t; /****************** * Local Variables * ******************/ assign out_intf.req.request = ( in_intf.req.request & ~stall ); // mask request assign out_intf.req.read = ( in_intf.req.read & ~stall ); // mask read assign out_intf.req.write = ( in_intf.req.write & ~stall ); // mask write assign out_intf.req.writedata = in_intf.req.writedata; assign out_intf.req.burstcount = in_intf.req.burstcount; assign out_intf.req.address = in_intf.req.address; assign out_intf.req.byteenable = in_intf.req.byteenable; assign out_intf.req.id = in_intf.req.id; assign in_intf.stall = ( out_intf.stall | stall ); /***************** * Detect Atomic * ******************/ assign atomic = ( out_intf.req.request == 1'b1 && out_intf.req.read == 1'b1 && out_intf.req.writedata[0:0] == 1'b1 ) ? 1'b1 : 1'b0; always@(posedge clock or negedge resetn) begin if ( !resetn ) begin shift_register[0] <= 1'b0; end else begin shift_register[0] <= atomic; end end /***************** * Shift Register * ******************/ always@(posedge clock or negedge resetn) begin for (t=1; t< STALL_CYCLES; t=t+1) begin if ( !resetn ) begin shift_register[t] <= 1'b0; end else begin shift_register[t] <= shift_register[t-1]; end end end /*************** * Detect Stall * ***************/ assign stall = ( shift_register[STALL_CYCLES-1] == 1'b1 ); 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_atomics_arb_stall #( // Configuration parameter integer STALL_CYCLES = 6 ) ( input logic clock, input logic resetn, acl_arb_intf in_intf, acl_arb_intf out_intf ); /****************** * Local Variables * ******************/ reg shift_register [0:STALL_CYCLES-1]; wire atomic; wire stall; integer t; /****************** * Local Variables * ******************/ assign out_intf.req.request = ( in_intf.req.request & ~stall ); // mask request assign out_intf.req.read = ( in_intf.req.read & ~stall ); // mask read assign out_intf.req.write = ( in_intf.req.write & ~stall ); // mask write assign out_intf.req.writedata = in_intf.req.writedata; assign out_intf.req.burstcount = in_intf.req.burstcount; assign out_intf.req.address = in_intf.req.address; assign out_intf.req.byteenable = in_intf.req.byteenable; assign out_intf.req.id = in_intf.req.id; assign in_intf.stall = ( out_intf.stall | stall ); /***************** * Detect Atomic * ******************/ assign atomic = ( out_intf.req.request == 1'b1 && out_intf.req.read == 1'b1 && out_intf.req.writedata[0:0] == 1'b1 ) ? 1'b1 : 1'b0; always@(posedge clock or negedge resetn) begin if ( !resetn ) begin shift_register[0] <= 1'b0; end else begin shift_register[0] <= atomic; end end /***************** * Shift Register * ******************/ always@(posedge clock or negedge resetn) begin for (t=1; t< STALL_CYCLES; t=t+1) begin if ( !resetn ) begin shift_register[t] <= 1'b0; end else begin shift_register[t] <= shift_register[t-1]; end end end /*************** * Detect Stall * ***************/ assign stall = ( shift_register[STALL_CYCLES-1] == 1'b1 ); 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_atomics_arb_stall #( // Configuration parameter integer STALL_CYCLES = 6 ) ( input logic clock, input logic resetn, acl_arb_intf in_intf, acl_arb_intf out_intf ); /****************** * Local Variables * ******************/ reg shift_register [0:STALL_CYCLES-1]; wire atomic; wire stall; integer t; /****************** * Local Variables * ******************/ assign out_intf.req.request = ( in_intf.req.request & ~stall ); // mask request assign out_intf.req.read = ( in_intf.req.read & ~stall ); // mask read assign out_intf.req.write = ( in_intf.req.write & ~stall ); // mask write assign out_intf.req.writedata = in_intf.req.writedata; assign out_intf.req.burstcount = in_intf.req.burstcount; assign out_intf.req.address = in_intf.req.address; assign out_intf.req.byteenable = in_intf.req.byteenable; assign out_intf.req.id = in_intf.req.id; assign in_intf.stall = ( out_intf.stall | stall ); /***************** * Detect Atomic * ******************/ assign atomic = ( out_intf.req.request == 1'b1 && out_intf.req.read == 1'b1 && out_intf.req.writedata[0:0] == 1'b1 ) ? 1'b1 : 1'b0; always@(posedge clock or negedge resetn) begin if ( !resetn ) begin shift_register[0] <= 1'b0; end else begin shift_register[0] <= atomic; end end /***************** * Shift Register * ******************/ always@(posedge clock or negedge resetn) begin for (t=1; t< STALL_CYCLES; t=t+1) begin if ( !resetn ) begin shift_register[t] <= 1'b0; end else begin shift_register[t] <= shift_register[t-1]; end end end /*************** * Detect Stall * ***************/ assign stall = ( shift_register[STALL_CYCLES-1] == 1'b1 ); 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
// (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_rrp_reg ( input logic clock, input logic resetn, acl_ic_rrp_intf rrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_rrp_intf rrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin rrp_out.datavalid <= 1'b0; rrp_out.id <= 'x; rrp_out.data <= 'x; end else begin rrp_out.datavalid <= rrp_in.datavalid; rrp_out.id <= rrp_in.id; rrp_out.data <= rrp_in.data; 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_rrp_reg ( input logic clock, input logic resetn, acl_ic_rrp_intf rrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_rrp_intf rrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin rrp_out.datavalid <= 1'b0; rrp_out.id <= 'x; rrp_out.data <= 'x; end else begin rrp_out.datavalid <= rrp_in.datavalid; rrp_out.id <= rrp_in.id; rrp_out.data <= rrp_in.data; 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_rrp_reg ( input logic clock, input logic resetn, acl_ic_rrp_intf rrp_in, (* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_rrp_intf rrp_out ); always @(posedge clock or negedge resetn) if( ~resetn ) begin rrp_out.datavalid <= 1'b0; rrp_out.id <= 'x; rrp_out.data <= 'x; end else begin rrp_out.datavalid <= rrp_in.datavalid; rrp_out.id <= rrp_in.id; rrp_out.data <= rrp_in.data; 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
// (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. //===----------------------------------------------------------------------===// // // C backend 'pipeline' primitive // //===----------------------------------------------------------------------===// module acl_pipeline ( clock, resetn, data_in, valid_out, stall_in, stall_out, valid_in, data_out, initeration_in, initeration_stall_out, initeration_valid_in, not_exitcond_in, not_exitcond_stall_out, not_exitcond_valid_in, pipeline_valid_out, pipeline_stall_in, exiting_valid_out ); parameter FIFO_DEPTH = 1; parameter string STYLE = "SPECULATIVE"; // "NON_SPECULATIVE"/"SPECULATIVE" input clock, resetn, stall_in, valid_in, initeration_valid_in, not_exitcond_valid_in, pipeline_stall_in; output stall_out, valid_out, initeration_stall_out, not_exitcond_stall_out, pipeline_valid_out; input data_in, initeration_in, not_exitcond_in; output data_out; output exiting_valid_out; generate // Instantiate 2 pops and 1 push if (STYLE == "SPECULATIVE") begin wire valid_pop1, valid_pop2; wire stall_push, stall_pop2; wire data_pop2, data_push; acl_pop pop1( .clock(clock), .resetn(resetn), .dir(data_in), .predicate(1'b0), .data_in(1'b1), .valid_out(valid_pop1), .stall_in(stall_pop2), .stall_out(stall_out), .valid_in(valid_in), .data_out(data_pop2), .feedback_in(initeration_in), .feedback_valid_in(initeration_valid_in), .feedback_stall_out(initeration_stall_out) ); defparam pop1.DATA_WIDTH = 1; acl_pop pop2( .clock(clock), .resetn(resetn), .dir(data_pop2), .predicate(1'b0), .data_in(1'b0), .valid_out(valid_pop2), .stall_in(stall_push), .stall_out(stall_pop2), .valid_in(valid_pop1), .data_out(data_push), .feedback_in(~not_exitcond_in), .feedback_valid_in(not_exitcond_valid_in), .feedback_stall_out(not_exitcond_stall_out) ); defparam pop2.DATA_WIDTH = 1; wire p_out, p_valid_out, p_stall_in; acl_push push( .clock(clock), .resetn(resetn), .dir(1'b1), .predicate(1'b0), .data_in(~data_push), .valid_out(valid_out), .stall_in(stall_in), .stall_out(stall_push), .valid_in(valid_pop2), .data_out(data_out), .feedback_out(p_out), .feedback_valid_out(p_valid_out), .feedback_stall_in(p_stall_in) ); // signal when to spawn a new iteration assign pipeline_valid_out = p_out & p_valid_out; assign p_stall_in = pipeline_stall_in; // signal when the last iteration is exiting assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in; defparam push.DATA_WIDTH = 1; defparam push.FIFO_DEPTH = FIFO_DEPTH; end // Instantiate 1 pop and 1 push else begin ////////////////////////////////////////////////////// // If there is no speculation, directly connect // exit condition to valid wire valid_pop2; wire stall_push; wire data_push; wire p_out, p_valid_out, p_stall_in; assign p_out = not_exitcond_in; assign p_valid_out = not_exitcond_valid_in ; assign not_exitcond_stall_out = p_stall_in; acl_staging_reg asr( .clk(clock), .reset(~resetn), .i_valid( valid_in ), .o_stall(stall_out), .o_valid( valid_out), .i_stall(stall_in) ); // signal when to spawn a new iteration assign pipeline_valid_out = p_out & p_valid_out; assign p_stall_in = pipeline_stall_in; // signal when the last iteration is exiting assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in; assign initeration_stall_out = 1'b0; // never stall 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. //===----------------------------------------------------------------------===// // // C backend 'push' primitive // // Upstream are signals that go to the feedback (snk node is a acl_pop), // downstream are signals that continue into our "normal" pipeline. // // dir indicates if you want to push it to the feedback // 1 - push to feedback // 0 - bypass, just push out to downstream //===----------------------------------------------------------------------===// module acl_push ( clock, resetn, // interface from kernel pipeline, input stream dir, data_in, valid_in, stall_out, predicate, // interface to kernel pipeline, downstream valid_out, stall_in, data_out, // interface to pipeline feedback, upstream feedback_out, feedback_valid_out, feedback_stall_in ); parameter DATA_WIDTH = 32; parameter FIFO_DEPTH = 1; parameter MIN_FIFO_LATENCY = 0; // style can be "REGULAR", for a regular push // or "TOKEN" for a special fifo that hands out tokens parameter string STYLE = "REGULAR"; // "REGULAR"/"TOKEN" parameter STALLFREE = 0; input clock, resetn, stall_in, valid_in, feedback_stall_in; output stall_out, valid_out, feedback_valid_out; input [DATA_WIDTH-1:0] data_in; input dir; input predicate; output [DATA_WIDTH-1:0] data_out, feedback_out; wire [DATA_WIDTH-1:0] feedback; wire data_downstream, data_upstream; wire push_upstream; assign push_upstream = dir & ~predicate; assign data_upstream = valid_in & push_upstream; assign data_downstream = valid_in; wire feedback_stall, feedback_valid; reg consumed_downstream, consumed_upstream; assign valid_out = data_downstream & !consumed_downstream; assign feedback_valid = data_upstream & !consumed_upstream; assign data_out = data_in; assign feedback = data_in; //assign stall_out = valid_in & ( ~(data_downstream & ~stall_in) & ~(data_upstream & ~feedback_stall)); // assign stall_out = valid_in & ( ~(data_downstream & ~stall_in) | ~(data_upstream & ~feedback_stall)); assign stall_out = stall_in | (feedback_stall & push_upstream ); always @(posedge clock or negedge resetn) begin if (!resetn) begin consumed_downstream <= 1'b0; consumed_upstream <= 1'b0; end else begin if (consumed_downstream) consumed_downstream <= stall_out; else consumed_downstream <= stall_out & (data_downstream & ~stall_in); if (consumed_upstream) consumed_upstream <= stall_out; else consumed_upstream <= stall_out & (data_upstream & ~feedback_stall); end end localparam TYPE = MIN_FIFO_LATENCY < 1 ? (FIFO_DEPTH < 8 ? "zl_reg" : "zl_ram") : (MIN_FIFO_LATENCY < 3 ? (FIFO_DEPTH < 8 ? "ll_reg" : "ll_ram") : (FIFO_DEPTH < 8 ? "ll_reg" : "ram")); generate if ( STYLE == "TOKEN" ) begin acl_token_fifo_counter #( .DEPTH(FIFO_DEPTH) ) fifo ( .clock(clock), .resetn(resetn), .data_out(feedback_out), .valid_in(feedback_valid), .valid_out(feedback_valid_out), .stall_in(feedback_stall_in), .stall_out(feedback_stall) ); end else if (FIFO_DEPTH == 0) begin // if no FIFO depth is requested, just connect // feedback directly to output assign feedback_out = feedback; assign feedback_valid_out = feedback_valid; assign feedback_stall = feedback_stall_in; end else if (FIFO_DEPTH == 1 && MIN_FIFO_LATENCY == 0) begin // simply add a staging register if the requested depth is 1 // and the latency must be 0 acl_staging_reg #( .WIDTH(DATA_WIDTH) ) staging_reg ( .clk(clock), .reset(~resetn), .i_data(feedback), .i_valid(feedback_valid), .o_stall(feedback_stall), .o_data(feedback_out), .o_valid(feedback_valid_out), .i_stall(feedback_stall_in) ); end else begin // only allow full write in stall free clusters if you're an ll_reg // otherwise, comb cycles can form, since stall_out depends on // stall_in the acl_data_fifo. To make up for the last space, we // add a capacity of 1 to the FIFO localparam OFFSET = ( (TYPE == "ll_reg") && !STALLFREE ) ? 1 : 0; localparam ALLOW_FULL_WRITE = ( (TYPE == "ll_reg") && !STALLFREE ) ? 0 : 1; acl_data_fifo #( .DATA_WIDTH(DATA_WIDTH), .DEPTH(((TYPE == "ram") || (TYPE == "ll_ram") || (TYPE == "zl_ram")) ? FIFO_DEPTH + 1 : FIFO_DEPTH + OFFSET), .IMPL(TYPE), .ALLOW_FULL_WRITE(ALLOW_FULL_WRITE) ) fifo ( .clock(clock), .resetn(resetn), .data_in(feedback), .data_out(feedback_out), .valid_in(feedback_valid), .valid_out(feedback_valid_out), .stall_in(feedback_stall_in), .stall_out(feedback_stall) ); end endgenerate endmodule
//===----------------------------------------------------------------------===// // // Parameterized FIFO with input and output registers and ACL pipeline // protocol ports. This "FIFO" stores no data and only hands out a sequence of // numbers from 0..DEPTH-1 (tokens) in round robin fashion. // //===----------------------------------------------------------------------===// module acl_token_fifo_counter #( parameter integer DEPTH = 32, // >0 parameter integer STRICT_DEPTH = 1, // 0|1 parameter integer ALLOW_FULL_WRITE = 0 // 0|1 ) ( clock, resetn, data_out, // the width of this signal is set by this module, it is the // responsibility of the top module to make sure the signal // widths match across this interface. valid_in, valid_out, stall_in, stall_out, empty, full ); // This fifo is based on acl_valid_fifo // However, there are 2 differences: // 1. The fifo is intialized as full // 2. We keep another counter to serve as the actual token // STRICT_DEPTH increases FIFO depth to a power of 2 + 1 depth. // No data, so just build a counter to count the number of valids stored in this "FIFO". // // The counter is constructed to count up to a MINIMUM value of DEPTH entries. // * Logical range of the counter C0 is [0, DEPTH]. // * empty = (C0 <= 0) // * full = (C0 >= DEPTH) // // To have efficient detection of the empty condition (C0 == 0), the range is offset // by -1 so that a negative number indicates empty. // * Logical range of the counter C1 is [-1, DEPTH-1]. // * empty = (C1 < 0) // * full = (C1 >= DEPTH-1) // The size of counter C1 is $clog2((DEPTH-1) + 1) + 1 => $clog2(DEPTH) + 1. // // To have efficient detection of the full condition (C1 >= DEPTH-1), change the // full condition to C1 == 2^$clog2(DEPTH-1), which is DEPTH-1 rounded up // to the next power of 2. This is only done if STRICT_DEPTH == 0, otherwise // the full condition is comparison vs. DEPTH-1. // * Logical range of the counter C2 is [-1, 2^$clog2(DEPTH-1)] // * empty = (C2 < 0) // * full = (C2 == 2^$clog2(DEPTH - 1)) // The size of counter C2 is $clog2(DEPTH-1) + 2. // * empty = MSB // * full = ~[MSB] & [MSB-1] localparam COUNTER_WIDTH = (STRICT_DEPTH == 0) ? ((DEPTH > 1 ? $clog2(DEPTH-1) : 0) + 2) : ($clog2(DEPTH) + 1); input clock; input resetn; output [COUNTER_WIDTH-1:0] data_out; input valid_in; output valid_out; input stall_in; output stall_out; output empty; output full; logic [COUNTER_WIDTH - 1:0] valid_counter /* synthesis maxfan=1 dont_merge */; logic incr, decr; // The logical range for the token is [0,REAL_DEPTH-1], where REAL_DEPTH // is the actual depth of the fifo taking STRICT_DEPTH into account // This counter is 1-bit less wide than valid_counter because it is // unsigned logic [COUNTER_WIDTH - 2:0] token; logic token_max; assign data_out = token; assign token_max = (STRICT_DEPTH == 0) ? (~token[$bits(token) - 1] & token[$bits(token) - 2]) : (token == DEPTH - 1); assign empty = valid_counter[$bits(valid_counter) - 1]; assign full = (STRICT_DEPTH == 0) ? (~valid_counter[$bits(valid_counter) - 1] & valid_counter[$bits(valid_counter) - 2]) : (valid_counter == DEPTH - 1); assign incr = valid_in & ~stall_out; // push assign decr = valid_out & ~stall_in; // pop assign valid_out = ~empty; assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full; always @( posedge clock or negedge resetn ) if( !resetn ) begin valid_counter <= (STRICT_DEPTH == 0) ? (2^$clog2(DEPTH-1)) : DEPTH - 1; // full token <= 0; end else begin valid_counter <= valid_counter + incr - decr; if (decr) // increment token, if popping token <= token_max ? 0 : token+1; end 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_top #( parameter reconf_width = 64, parameter device_family = "Stratix V", 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, parameter ENABLE_MIF = 0, parameter MIF_FILE_NAME = "" ) ( //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 ); localparam MIF_ADDR_REG = 6'b011111; localparam START_REG = 6'b000010; generate if (ENABLE_MIF == 1) begin:mif_reconfig // Generate Reconfig with MIF // MIF-related regs/wires reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr; reg reconfig_mgmt_read; reg reconfig_mgmt_write; reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata; wire reconfig_mgmt_waitrequest; wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata; wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr; wire mif2reconfig_busy; wire mif2reconfig_read; wire mif2reconfig_write; wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; reg mif_select; reg user_start; wire reconfig2mif_start_out; assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start; // Don't output readdata if MIF streaming is taking place assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata; always @(posedge mgmt_clk) begin if (mgmt_reset) begin reconfig_mgmt_addr <= 0; reconfig_mgmt_read <= 0; reconfig_mgmt_write <= 0; reconfig_mgmt_writedata <= 0; user_start <= 0; end else begin reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address; reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read; reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_write; reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata; user_start <= (mgmt_address == START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0; end end always @(*) begin if (mgmt_reset) begin mif_select <= 0; end else begin mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0; end end altera_pll_reconfig_mif_reader #( .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS), .DEVICE_FAMILY(device_family), .ENABLE_MIF(ENABLE_MIF), .MIF_FILE_NAME(MIF_FILE_NAME) ) altera_pll_reconfig_mif_reader_inst0 ( .mif_clk(mgmt_clk), .mif_rst(mgmt_reset), //Altera_PLL Reconfig interface //inputs .reconfig_busy(reconfig_mgmt_waitrequest), .reconfig_read_data(reconfig_mgmt_readdata), //outputs .reconfig_write_data(mif2reconfig_writedata), .reconfig_addr(mif2reconfig_addr), .reconfig_write(mif2reconfig_write), .reconfig_read(mif2reconfig_read), //MIF Ctrl Interface //inputs .mif_base_addr(mif_base_addr), .mif_start(reconfig2mif_start_out), //outputs .mif_busy(mif2reconfig_busy) ); // ------ END MIF-RELATED MANAGEMENT ------ altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(reconfig_mgmt_readdata), .mgmt_waitrequest(reconfig_mgmt_waitrequest), //User data inputs .mgmt_address(reconfig_mgmt_addr), .mgmt_read(reconfig_mgmt_read), .mgmt_write(reconfig_mgmt_write), .mgmt_writedata(reconfig_mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig with MIF else begin:reconfig_core // Generate Reconfig core only wire reconfig2mif_start_out; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(mgmt_readdata), .mgmt_waitrequest(mgmt_waitrequest), //User data inputs .mgmt_address(mgmt_address), .mgmt_read(mgmt_read), .mgmt_write(mgmt_write), .mgmt_writedata(mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig core only 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_top #( parameter reconf_width = 64, parameter device_family = "Stratix V", 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, parameter ENABLE_MIF = 0, parameter MIF_FILE_NAME = "" ) ( //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 ); localparam MIF_ADDR_REG = 6'b011111; localparam START_REG = 6'b000010; generate if (ENABLE_MIF == 1) begin:mif_reconfig // Generate Reconfig with MIF // MIF-related regs/wires reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr; reg reconfig_mgmt_read; reg reconfig_mgmt_write; reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata; wire reconfig_mgmt_waitrequest; wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata; wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr; wire mif2reconfig_busy; wire mif2reconfig_read; wire mif2reconfig_write; wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; reg mif_select; reg user_start; wire reconfig2mif_start_out; assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start; // Don't output readdata if MIF streaming is taking place assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata; always @(posedge mgmt_clk) begin if (mgmt_reset) begin reconfig_mgmt_addr <= 0; reconfig_mgmt_read <= 0; reconfig_mgmt_write <= 0; reconfig_mgmt_writedata <= 0; user_start <= 0; end else begin reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address; reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read; reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_write; reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata; user_start <= (mgmt_address == START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0; end end always @(*) begin if (mgmt_reset) begin mif_select <= 0; end else begin mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0; end end altera_pll_reconfig_mif_reader #( .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS), .DEVICE_FAMILY(device_family), .ENABLE_MIF(ENABLE_MIF), .MIF_FILE_NAME(MIF_FILE_NAME) ) altera_pll_reconfig_mif_reader_inst0 ( .mif_clk(mgmt_clk), .mif_rst(mgmt_reset), //Altera_PLL Reconfig interface //inputs .reconfig_busy(reconfig_mgmt_waitrequest), .reconfig_read_data(reconfig_mgmt_readdata), //outputs .reconfig_write_data(mif2reconfig_writedata), .reconfig_addr(mif2reconfig_addr), .reconfig_write(mif2reconfig_write), .reconfig_read(mif2reconfig_read), //MIF Ctrl Interface //inputs .mif_base_addr(mif_base_addr), .mif_start(reconfig2mif_start_out), //outputs .mif_busy(mif2reconfig_busy) ); // ------ END MIF-RELATED MANAGEMENT ------ altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(reconfig_mgmt_readdata), .mgmt_waitrequest(reconfig_mgmt_waitrequest), //User data inputs .mgmt_address(reconfig_mgmt_addr), .mgmt_read(reconfig_mgmt_read), .mgmt_write(reconfig_mgmt_write), .mgmt_writedata(reconfig_mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig with MIF else begin:reconfig_core // Generate Reconfig core only wire reconfig2mif_start_out; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(mgmt_readdata), .mgmt_waitrequest(mgmt_waitrequest), //User data inputs .mgmt_address(mgmt_address), .mgmt_read(mgmt_read), .mgmt_write(mgmt_write), .mgmt_writedata(mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig core only 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_top #( parameter reconf_width = 64, parameter device_family = "Stratix V", 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, parameter ENABLE_MIF = 0, parameter MIF_FILE_NAME = "" ) ( //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 ); localparam MIF_ADDR_REG = 6'b011111; localparam START_REG = 6'b000010; generate if (ENABLE_MIF == 1) begin:mif_reconfig // Generate Reconfig with MIF // MIF-related regs/wires reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr; reg reconfig_mgmt_read; reg reconfig_mgmt_write; reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata; wire reconfig_mgmt_waitrequest; wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata; wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr; wire mif2reconfig_busy; wire mif2reconfig_read; wire mif2reconfig_write; wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; reg mif_select; reg user_start; wire reconfig2mif_start_out; assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start; // Don't output readdata if MIF streaming is taking place assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata; always @(posedge mgmt_clk) begin if (mgmt_reset) begin reconfig_mgmt_addr <= 0; reconfig_mgmt_read <= 0; reconfig_mgmt_write <= 0; reconfig_mgmt_writedata <= 0; user_start <= 0; end else begin reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address; reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read; reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_write; reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata; user_start <= (mgmt_address == START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0; end end always @(*) begin if (mgmt_reset) begin mif_select <= 0; end else begin mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0; end end altera_pll_reconfig_mif_reader #( .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS), .DEVICE_FAMILY(device_family), .ENABLE_MIF(ENABLE_MIF), .MIF_FILE_NAME(MIF_FILE_NAME) ) altera_pll_reconfig_mif_reader_inst0 ( .mif_clk(mgmt_clk), .mif_rst(mgmt_reset), //Altera_PLL Reconfig interface //inputs .reconfig_busy(reconfig_mgmt_waitrequest), .reconfig_read_data(reconfig_mgmt_readdata), //outputs .reconfig_write_data(mif2reconfig_writedata), .reconfig_addr(mif2reconfig_addr), .reconfig_write(mif2reconfig_write), .reconfig_read(mif2reconfig_read), //MIF Ctrl Interface //inputs .mif_base_addr(mif_base_addr), .mif_start(reconfig2mif_start_out), //outputs .mif_busy(mif2reconfig_busy) ); // ------ END MIF-RELATED MANAGEMENT ------ altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(reconfig_mgmt_readdata), .mgmt_waitrequest(reconfig_mgmt_waitrequest), //User data inputs .mgmt_address(reconfig_mgmt_addr), .mgmt_read(reconfig_mgmt_read), .mgmt_write(reconfig_mgmt_write), .mgmt_writedata(reconfig_mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig with MIF else begin:reconfig_core // Generate Reconfig core only wire reconfig2mif_start_out; wire [ROM_ADDR_WIDTH-1:0] mif_base_addr; altera_pll_reconfig_core #( .reconf_width(reconf_width), .device_family(device_family), .RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH), .RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH), .ROM_ADDR_WIDTH(ROM_ADDR_WIDTH), .ROM_DATA_WIDTH(ROM_DATA_WIDTH), .ROM_NUM_WORDS(ROM_NUM_WORDS) ) altera_pll_reconfig_core_inst0 ( //inputs .mgmt_clk(mgmt_clk), .mgmt_reset(mgmt_reset), //PLL interface conduits .reconfig_to_pll(reconfig_to_pll), .reconfig_from_pll(reconfig_from_pll), //User data outputs .mgmt_readdata(mgmt_readdata), .mgmt_waitrequest(mgmt_waitrequest), //User data inputs .mgmt_address(mgmt_address), .mgmt_read(mgmt_read), .mgmt_write(mgmt_write), .mgmt_writedata(mgmt_writedata), // other .mif_start_out(reconfig2mif_start_out), .mif_base_addr(mif_base_addr) ); end // End generate reconfig core only 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_mem_router #( parameter integer DATA_W = 256, parameter integer BURSTCOUNT_W = 6, parameter integer ADDRESS_W = 32, parameter integer BYTEENA_W = DATA_W / 8, parameter integer NUM_BANKS = 2 ) ( input logic clock, input logic resetn, // Bank select (one-hot) input logic [NUM_BANKS-1:0] bank_select, // Master input logic m_arb_request, input logic m_arb_read, input logic m_arb_write, input logic [DATA_W-1:0] m_arb_writedata, input logic [BURSTCOUNT_W-1:0] m_arb_burstcount, input logic [ADDRESS_W-1:0] m_arb_address, input logic [BYTEENA_W-1:0] m_arb_byteenable, output logic m_arb_stall, output logic m_wrp_ack, output logic m_rrp_datavalid, output logic [DATA_W-1:0] m_rrp_data, // To each bank output logic b_arb_request [NUM_BANKS], output logic b_arb_read [NUM_BANKS], output logic b_arb_write [NUM_BANKS], output logic [DATA_W-1:0] b_arb_writedata [NUM_BANKS], output logic [BURSTCOUNT_W-1:0] b_arb_burstcount [NUM_BANKS], output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] b_arb_address [NUM_BANKS], output logic [BYTEENA_W-1:0] b_arb_byteenable [NUM_BANKS], input logic b_arb_stall [NUM_BANKS], input logic b_wrp_ack [NUM_BANKS], input logic b_rrp_datavalid [NUM_BANKS], input logic [DATA_W-1:0] b_rrp_data [NUM_BANKS] ); integer i; localparam PENDING_COUNT_WIDTH=11; reg [PENDING_COUNT_WIDTH-1:0] b_pending_count[NUM_BANKS]; logic [NUM_BANKS-1:0] pending; //Given a bank number, makes sure no other bank has pending requests function [0:0] none_pending ( input integer i ); none_pending = ~|(pending & ~({{PENDING_COUNT_WIDTH-1{1'b0}},1'b1}<<i)); endfunction always_comb begin m_arb_stall = 1'b0; m_wrp_ack = 1'b0; m_rrp_datavalid = 1'b0; m_rrp_data = '0; for( i = 0; i < NUM_BANKS; i = i + 1 ) begin:bank b_arb_request[i] = m_arb_request & bank_select[i] & none_pending(i); b_arb_read[i] = m_arb_read & bank_select[i] & none_pending(i); b_arb_write[i] = m_arb_write & bank_select[i] & none_pending(i); b_arb_writedata[i] = m_arb_writedata; b_arb_burstcount[i] = m_arb_burstcount; b_arb_address[i] = m_arb_address[ADDRESS_W-$clog2(NUM_BANKS)-1:0]; b_arb_byteenable[i] = m_arb_byteenable; m_arb_stall |= (b_arb_stall[i] | !none_pending(i)) & bank_select[i]; m_wrp_ack |= b_wrp_ack[i]; m_rrp_datavalid |= b_rrp_datavalid[i]; m_rrp_data |= (b_rrp_datavalid[i] ? b_rrp_data[i] : '0); end end wire add_burst[NUM_BANKS]; wire incr[NUM_BANKS]; wire decr_rd[NUM_BANKS]; wire decr_wr[NUM_BANKS]; reg [BURSTCOUNT_W-1:0] next_incr[NUM_BANKS]; reg [1:0] next_decr[NUM_BANKS]; reg [NUM_BANKS-1:0] last_banksel; always@(posedge clock or negedge resetn) if (!resetn) last_banksel <= {NUM_BANKS{1'b0}}; else last_banksel <= {NUM_BANKS{m_arb_request}} & bank_select; // A counter tracks how many outstanding word transfers are needed. When a // request is accepted its burstcount is added to the counter. When data // is returned or writeack'ed, the counter is decremented. // This used to be simple - but manual retiming makes it less so generate genvar b; for ( b = 0; b < NUM_BANKS; b = b + 1 ) begin:bankgen assign add_burst[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_read[b]; assign incr[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_write[b]; assign decr_rd[b] = b_rrp_datavalid[b]; assign decr_wr[b] = b_wrp_ack[b]; always@(posedge clock or negedge resetn) if (!resetn) begin next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = 2'b0; end else begin if (add_burst[b]) next_incr[b] = m_arb_burstcount; else if (incr[b]) next_incr[b] = 2'b01; else next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = decr_rd[b] + decr_wr[b]; end always@(posedge clock or negedge resetn) if (!resetn) begin b_pending_count[b] <= {PENDING_COUNT_WIDTH{1'b0}}; end else begin b_pending_count[b] <= b_pending_count[b] + next_incr[b] - next_decr[b]; end always_comb begin pending[b] = |b_pending_count[b] || last_banksel[b]; 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. module acl_ic_mem_router #( parameter integer DATA_W = 256, parameter integer BURSTCOUNT_W = 6, parameter integer ADDRESS_W = 32, parameter integer BYTEENA_W = DATA_W / 8, parameter integer NUM_BANKS = 2 ) ( input logic clock, input logic resetn, // Bank select (one-hot) input logic [NUM_BANKS-1:0] bank_select, // Master input logic m_arb_request, input logic m_arb_read, input logic m_arb_write, input logic [DATA_W-1:0] m_arb_writedata, input logic [BURSTCOUNT_W-1:0] m_arb_burstcount, input logic [ADDRESS_W-1:0] m_arb_address, input logic [BYTEENA_W-1:0] m_arb_byteenable, output logic m_arb_stall, output logic m_wrp_ack, output logic m_rrp_datavalid, output logic [DATA_W-1:0] m_rrp_data, // To each bank output logic b_arb_request [NUM_BANKS], output logic b_arb_read [NUM_BANKS], output logic b_arb_write [NUM_BANKS], output logic [DATA_W-1:0] b_arb_writedata [NUM_BANKS], output logic [BURSTCOUNT_W-1:0] b_arb_burstcount [NUM_BANKS], output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] b_arb_address [NUM_BANKS], output logic [BYTEENA_W-1:0] b_arb_byteenable [NUM_BANKS], input logic b_arb_stall [NUM_BANKS], input logic b_wrp_ack [NUM_BANKS], input logic b_rrp_datavalid [NUM_BANKS], input logic [DATA_W-1:0] b_rrp_data [NUM_BANKS] ); integer i; localparam PENDING_COUNT_WIDTH=11; reg [PENDING_COUNT_WIDTH-1:0] b_pending_count[NUM_BANKS]; logic [NUM_BANKS-1:0] pending; //Given a bank number, makes sure no other bank has pending requests function [0:0] none_pending ( input integer i ); none_pending = ~|(pending & ~({{PENDING_COUNT_WIDTH-1{1'b0}},1'b1}<<i)); endfunction always_comb begin m_arb_stall = 1'b0; m_wrp_ack = 1'b0; m_rrp_datavalid = 1'b0; m_rrp_data = '0; for( i = 0; i < NUM_BANKS; i = i + 1 ) begin:bank b_arb_request[i] = m_arb_request & bank_select[i] & none_pending(i); b_arb_read[i] = m_arb_read & bank_select[i] & none_pending(i); b_arb_write[i] = m_arb_write & bank_select[i] & none_pending(i); b_arb_writedata[i] = m_arb_writedata; b_arb_burstcount[i] = m_arb_burstcount; b_arb_address[i] = m_arb_address[ADDRESS_W-$clog2(NUM_BANKS)-1:0]; b_arb_byteenable[i] = m_arb_byteenable; m_arb_stall |= (b_arb_stall[i] | !none_pending(i)) & bank_select[i]; m_wrp_ack |= b_wrp_ack[i]; m_rrp_datavalid |= b_rrp_datavalid[i]; m_rrp_data |= (b_rrp_datavalid[i] ? b_rrp_data[i] : '0); end end wire add_burst[NUM_BANKS]; wire incr[NUM_BANKS]; wire decr_rd[NUM_BANKS]; wire decr_wr[NUM_BANKS]; reg [BURSTCOUNT_W-1:0] next_incr[NUM_BANKS]; reg [1:0] next_decr[NUM_BANKS]; reg [NUM_BANKS-1:0] last_banksel; always@(posedge clock or negedge resetn) if (!resetn) last_banksel <= {NUM_BANKS{1'b0}}; else last_banksel <= {NUM_BANKS{m_arb_request}} & bank_select; // A counter tracks how many outstanding word transfers are needed. When a // request is accepted its burstcount is added to the counter. When data // is returned or writeack'ed, the counter is decremented. // This used to be simple - but manual retiming makes it less so generate genvar b; for ( b = 0; b < NUM_BANKS; b = b + 1 ) begin:bankgen assign add_burst[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_read[b]; assign incr[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_write[b]; assign decr_rd[b] = b_rrp_datavalid[b]; assign decr_wr[b] = b_wrp_ack[b]; always@(posedge clock or negedge resetn) if (!resetn) begin next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = 2'b0; end else begin if (add_burst[b]) next_incr[b] = m_arb_burstcount; else if (incr[b]) next_incr[b] = 2'b01; else next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = decr_rd[b] + decr_wr[b]; end always@(posedge clock or negedge resetn) if (!resetn) begin b_pending_count[b] <= {PENDING_COUNT_WIDTH{1'b0}}; end else begin b_pending_count[b] <= b_pending_count[b] + next_incr[b] - next_decr[b]; end always_comb begin pending[b] = |b_pending_count[b] || last_banksel[b]; 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. module acl_ic_mem_router #( parameter integer DATA_W = 256, parameter integer BURSTCOUNT_W = 6, parameter integer ADDRESS_W = 32, parameter integer BYTEENA_W = DATA_W / 8, parameter integer NUM_BANKS = 2 ) ( input logic clock, input logic resetn, // Bank select (one-hot) input logic [NUM_BANKS-1:0] bank_select, // Master input logic m_arb_request, input logic m_arb_read, input logic m_arb_write, input logic [DATA_W-1:0] m_arb_writedata, input logic [BURSTCOUNT_W-1:0] m_arb_burstcount, input logic [ADDRESS_W-1:0] m_arb_address, input logic [BYTEENA_W-1:0] m_arb_byteenable, output logic m_arb_stall, output logic m_wrp_ack, output logic m_rrp_datavalid, output logic [DATA_W-1:0] m_rrp_data, // To each bank output logic b_arb_request [NUM_BANKS], output logic b_arb_read [NUM_BANKS], output logic b_arb_write [NUM_BANKS], output logic [DATA_W-1:0] b_arb_writedata [NUM_BANKS], output logic [BURSTCOUNT_W-1:0] b_arb_burstcount [NUM_BANKS], output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] b_arb_address [NUM_BANKS], output logic [BYTEENA_W-1:0] b_arb_byteenable [NUM_BANKS], input logic b_arb_stall [NUM_BANKS], input logic b_wrp_ack [NUM_BANKS], input logic b_rrp_datavalid [NUM_BANKS], input logic [DATA_W-1:0] b_rrp_data [NUM_BANKS] ); integer i; localparam PENDING_COUNT_WIDTH=11; reg [PENDING_COUNT_WIDTH-1:0] b_pending_count[NUM_BANKS]; logic [NUM_BANKS-1:0] pending; //Given a bank number, makes sure no other bank has pending requests function [0:0] none_pending ( input integer i ); none_pending = ~|(pending & ~({{PENDING_COUNT_WIDTH-1{1'b0}},1'b1}<<i)); endfunction always_comb begin m_arb_stall = 1'b0; m_wrp_ack = 1'b0; m_rrp_datavalid = 1'b0; m_rrp_data = '0; for( i = 0; i < NUM_BANKS; i = i + 1 ) begin:bank b_arb_request[i] = m_arb_request & bank_select[i] & none_pending(i); b_arb_read[i] = m_arb_read & bank_select[i] & none_pending(i); b_arb_write[i] = m_arb_write & bank_select[i] & none_pending(i); b_arb_writedata[i] = m_arb_writedata; b_arb_burstcount[i] = m_arb_burstcount; b_arb_address[i] = m_arb_address[ADDRESS_W-$clog2(NUM_BANKS)-1:0]; b_arb_byteenable[i] = m_arb_byteenable; m_arb_stall |= (b_arb_stall[i] | !none_pending(i)) & bank_select[i]; m_wrp_ack |= b_wrp_ack[i]; m_rrp_datavalid |= b_rrp_datavalid[i]; m_rrp_data |= (b_rrp_datavalid[i] ? b_rrp_data[i] : '0); end end wire add_burst[NUM_BANKS]; wire incr[NUM_BANKS]; wire decr_rd[NUM_BANKS]; wire decr_wr[NUM_BANKS]; reg [BURSTCOUNT_W-1:0] next_incr[NUM_BANKS]; reg [1:0] next_decr[NUM_BANKS]; reg [NUM_BANKS-1:0] last_banksel; always@(posedge clock or negedge resetn) if (!resetn) last_banksel <= {NUM_BANKS{1'b0}}; else last_banksel <= {NUM_BANKS{m_arb_request}} & bank_select; // A counter tracks how many outstanding word transfers are needed. When a // request is accepted its burstcount is added to the counter. When data // is returned or writeack'ed, the counter is decremented. // This used to be simple - but manual retiming makes it less so generate genvar b; for ( b = 0; b < NUM_BANKS; b = b + 1 ) begin:bankgen assign add_burst[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_read[b]; assign incr[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_write[b]; assign decr_rd[b] = b_rrp_datavalid[b]; assign decr_wr[b] = b_wrp_ack[b]; always@(posedge clock or negedge resetn) if (!resetn) begin next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = 2'b0; end else begin if (add_burst[b]) next_incr[b] = m_arb_burstcount; else if (incr[b]) next_incr[b] = 2'b01; else next_incr[b] = {BURSTCOUNT_W{1'b0}}; next_decr[b] = decr_rd[b] + decr_wr[b]; end always@(posedge clock or negedge resetn) if (!resetn) begin b_pending_count[b] <= {PENDING_COUNT_WIDTH{1'b0}}; end else begin b_pending_count[b] <= b_pending_count[b] + next_incr[b] - next_decr[b]; end always_comb begin pending[b] = |b_pending_count[b] || last_banksel[b]; 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 Iztok Jeras. module t (/*AUTOARG*/ // Inputs clk ); input clk; parameter SIZE = 8; integer cnt = 0; logic [SIZE-1:0] vld_for; logic vld_if = 1'b0; logic vld_else = 1'b0; genvar i; // event counter always @ (posedge clk) begin cnt <= cnt + 1; end // finish report always @ (posedge clk) if (cnt==SIZE) begin : if_cnt_finish $write("*-* All Finished *-*\n"); $finish; end : if_cnt_finish_bad generate for (i=0; i<SIZE; i=i+1) begin : generate_for always @ (posedge clk) if (cnt == i) vld_for[i] <= 1'b1; end : generate_for_bad endgenerate generate if (SIZE>0) begin : generate_if_if always @ (posedge clk) vld_if <= 1'b1; end : generate_if_if_bad else begin : generate_if_else always @ (posedge clk) vld_else <= 1'b1; end : generate_if_else_bad endgenerate endmodule : t_bad
// This file ONLY is placed into the Public Domain, for any use, // without warranty, 2008 by Lane Brooks module top (input SEL, input[1:0] A, output W, output X, output Y, output Z); mux mux2 (.A(A), .SEL(SEL), .Z(W)); pass mux1 (.A(A), .SEL(SEL), .Z(X)); tbuf mux0[1:0] (.A(A), .OE({SEL,!SEL}), .Z(Y)); assign Z = ( SEL) ? A[1] : 1'bz; tbuf tbuf (.A(A[0]), .OE(!SEL), .Z(Z)); endmodule module pass (input[1:0] A, input SEL, output Z); tbuf tbuf1 (.A(A[1]), .OE(SEL), .Z(Z)); tbuf tbuf0 (.A(A[0]), .OE(!SEL),.Z(Z)); endmodule module tbuf (input A, input OE, output Z); `ifdef T_BUFIF0 bufif0 (Z, A, !OE); `elsif T_BUFIF1 bufif1 (Z, A, OE); `elsif T_NOTIF0 notif0 (Z, !A, !OE); `elsif T_NOTIF1 notif1 (Z, !A, OE); `elsif T_PMOS pmos (Z, A, !OE); `elsif T_NMOS nmos (Z, A, OE); `elsif T_COND assign Z = (OE) ? A : 1'bz; `else `error "Unknown test name" `endif endmodule module mux (input[1:0] A, input SEL, output Z); assign Z = (SEL) ? A[1] : 1'bz; assign Z = (!SEL)? A[0] : 1'bz; assign Z = 1'bz; endmodule
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: // Engineer: // // Create Date: 04/27/2016 08:26:13 AM // Design Name: // Module Name: Mux_8x1 // Project Name: // Target Devices: // Tool Versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // ////////////////////////////////////////////////////////////////////////////////// module Mux_8x1 ( //Input Signals input wire [2:0] select, input wire [7:0] ch_0, input wire [7:0] ch_1, input wire [7:0] ch_2, input wire [7:0] ch_3, input wire [7:0] ch_4, input wire [7:0] ch_5, input wire [7:0] ch_6, input wire [7:0] ch_7, //Output Signals output reg [7:0] data_out ); always @* begin case(select) 3'b111: data_out = ch_0; 3'b110: data_out = ch_1; 3'b101: data_out = ch_2; 3'b100: data_out = ch_3; 3'b011: data_out = ch_4; 3'b010: data_out = ch_5; 3'b001: data_out = ch_6; 3'b000: data_out = ch_7; default : data_out = ch_0; endcase end endmodule
// Wide load/store unit // Instantiates a top-level LSU module lsu_wide_wrapper ( 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_req_cache_hit_count, profile_extra_unaligned_reqs ); /************* * 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 parameter KERNEL_SIDE_MEM_LATENCY=1; // Latency in cycles parameter MEMORY_SIDE_MEM_LATENCY=1; // Latency in cycles 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 parameter ADDRSPACE=0; // Profiling parameter ACL_PROFILE=0; // Set to 1 to enable stall/valid profiling parameter ACL_PROFILE_ID=1; // Each LSU needs a unique ID parameter ACL_PROFILE_INCREMENT_WIDTH=64; // 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 parameter 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); localparam LSU_WIDTH = (WIDTH > MWIDTH) ? MWIDTH: WIDTH; // Width of the actual LSU when wider than MWIDTH or nonaligned localparam LSU_WIDTH_BYTES = LSU_WIDTH/8; localparam WIDTH_RATIO = (WIDTH_BYTES/LSU_WIDTH_BYTES); localparam WIDE_INDEX_WIDTH = $clog2(WIDTH_RATIO); // 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") || 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_req_cache_hit_count; output logic profile_extra_unaligned_reqs; // If we are a non-streaming read, do width adaption at avalon interface so we dont stall during data re-use localparam ADAPT_AT_AVM = 1; generate if(ADAPT_AT_AVM) begin wire [ AWIDTH-1:0] avm_address_wrapped; wire avm_read_wrapped; wire [WIDTH-1:0] avm_readdata_wrapped; wire avm_write_wrapped; wire avm_writeack_wrapped; wire [BURSTCOUNT_WIDTH-WIDE_INDEX_WIDTH-1:0] avm_burstcount_wrapped; wire [WIDTH-1:0] avm_writedata_wrapped; wire [WIDTH_BYTES-1:0]avm_byteenable_wrapped; wire avm_waitrequest_wrapped; reg avm_readdatavalid_wrapped; lsu_top lsu_wide ( .clock(clock), .clock2x(clock2x), .resetn(resetn), .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_wrapped), .avm_read(avm_read_wrapped), .avm_readdata(avm_readdata_wrapped), .avm_write(avm_write_wrapped), .avm_writeack(avm_writeack_wrapped), .avm_burstcount(avm_burstcount_wrapped), .avm_writedata(avm_writedata_wrapped), .avm_byteenable(avm_byteenable_wrapped), .avm_waitrequest(avm_waitrequest_wrapped), .avm_readdatavalid(avm_readdatavalid_wrapped), .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 = WIDTH_BYTES; defparam lsu_wide.WRITEDATAWIDTH_BYTES = WIDTH_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-WIDE_INDEX_WIDTH; 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; ///we handle NOPs in the wrapper 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 = WIDTH; defparam lsu_wide.MEMORY_SIDE_MEM_LATENCY = MEMORY_SIDE_MEM_LATENCY; defparam lsu_wide.KERNEL_SIDE_MEM_LATENCY = KERNEL_SIDE_MEM_LATENCY; defparam lsu_wide.WRITEDATAWIDTH = WIDTH; 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; //upstream control signals wire done; wire ready; reg in_progress; reg [WIDE_INDEX_WIDTH-1:0] index; //downstream control signals wire new_data; wire done_output; reg output_ready; reg [WIDE_INDEX_WIDTH-1:0] output_index; reg [WIDTH-1:0] readdata_shiftreg; reg [ AWIDTH-1:0] avm_address_reg; reg avm_read_reg; reg [WIDTH-1:0] avm_readdata_reg; reg avm_write_reg; reg [BURSTCOUNT_WIDTH-WIDE_INDEX_WIDTH-1:0] avm_burstcount_reg; reg [WIDTH-1:0] avm_writedata_reg; reg [WIDTH_BYTES-1:0]avm_byteenable_reg; if(READ) begin assign avm_writedata = 0; assign avm_byteenable = 0; assign avm_address = avm_address_wrapped; assign avm_burstcount = avm_burstcount_wrapped*WIDTH_RATIO; assign avm_write = 0; assign avm_read = avm_read_wrapped; assign avm_waitrequest_wrapped = avm_waitrequest; //downstream interface assign new_data = avm_readdatavalid; //we are accepting another MWIDTH item from the interconnect assign done_output = new_data && (output_index >= (WIDTH_RATIO-1)); //the output data will be ready next cycle always@(posedge clock or negedge resetn) begin if(!resetn) output_index <= 1'b0; else //increase index when we take new data output_index <= new_data ? (output_index+1)%(WIDTH_RATIO): output_index; end always@(posedge clock or negedge resetn) begin if(!resetn) begin readdata_shiftreg <= 0; output_ready <= 0; end else begin //shift data in if we are taking new data readdata_shiftreg <= new_data ? {avm_readdata,readdata_shiftreg[WIDTH-1:MWIDTH]} : readdata_shiftreg; output_ready <= done_output ; end end assign avm_readdata_wrapped = readdata_shiftreg; assign avm_readdatavalid_wrapped = output_ready; end else begin //write //break write into multiple cycles assign done = in_progress && (index >= (WIDTH_RATIO-1)) && !avm_waitrequest; //we are finishing a transaction assign ready = (!in_progress || done); // logic can take a new transaction //if we accept a new item from the lsu assign start = (avm_write_wrapped) && (!in_progress || done); //we are starting a new transaction, do not start if predicated always@(posedge clock or negedge resetn) begin if(!resetn) begin in_progress <= 0; index <= 0; end else begin // bursting = bursting ? !done : start && (avm_burstcount_wrapped > 0); in_progress <= start || (in_progress && !done); //if starting or done set to 0, else increment if LSU is accepting data index <= (start || !in_progress) ? 1'b0 : ( avm_waitrequest ? index :index+1); end end reg [ WIDE_INDEX_WIDTH-1:0] write_ack_count; //count write_acks always@(posedge clock or negedge resetn) begin if(!resetn) begin write_ack_count <= 0; end else if (avm_writeack) begin write_ack_count <= write_ack_count+1; end else begin write_ack_count <= write_ack_count; end end assign avm_writeack_wrapped = (write_ack_count == {WIDE_INDEX_WIDTH{1'b1}} - 1 ) && avm_writeack; //store transaction inputs to registers always@(posedge clock or negedge resetn) begin if(!resetn) begin avm_address_reg <= 0; avm_writedata_reg <= 0; avm_byteenable_reg <= 0; avm_burstcount_reg <= 0; end else if (start) begin avm_address_reg <= avm_address_wrapped; avm_writedata_reg <= avm_writedata_wrapped; avm_byteenable_reg <= avm_byteenable_wrapped; avm_burstcount_reg <= avm_burstcount_wrapped; end else begin avm_address_reg <= avm_address_reg; avm_writedata_reg <= avm_writedata_reg; avm_byteenable_reg <= avm_byteenable_reg; avm_burstcount_reg <= avm_burstcount_reg; end end //let an item through when we finish it assign avm_waitrequest_wrapped = !ready; assign avm_writedata = avm_writedata_reg[((index+1)*MWIDTH-1)-:MWIDTH]; assign avm_byteenable = avm_byteenable_reg[((index+1)*MWIDTH_BYTES-1)-:MWIDTH_BYTES]; assign avm_address = avm_address_reg; assign avm_burstcount = avm_burstcount_reg*WIDTH_RATIO; assign avm_write = in_progress; assign avm_read = 0; end end else begin 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-way bidirectional connection: // altera message_off 10665 module acl_ic_slave_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 NUM_MASTERS = 1, // > 0 parameter integer PIPELINE_RETURN_PATHS = 1, // 0|1 parameter integer WRP_FIFO_DEPTH = 0, // >= 0 (0 disables) parameter integer RRP_FIFO_DEPTH = 1, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0) parameter integer RRP_USE_LL_FIFO = 1, // 0|1 parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles // if >0 effectively RRP_FIFO_DEPTH=SLAVE_FIXED_LATENCY+1 parameter integer SEPARATE_READ_WRITE_STALLS = 0 // 0|1 ) ( input logic clock, input logic resetn, // Arbitrated master. acl_arb_intf m_intf, // Slave. acl_arb_intf s_intf, input logic s_readdatavalid, input logic [DATA_W-1:0] s_readdata, input logic s_writeack, // Write return path. acl_ic_wrp_intf wrp_intf, // Read return path. acl_ic_rrp_intf rrp_intf ); logic wrp_stall, rrp_stall; generate if( SEPARATE_READ_WRITE_STALLS == 0 ) begin // Need specific sensitivity list instead of always_comb // otherwise Modelsim will encounter an infinite loop. always @(s_intf.stall, m_intf.req, rrp_stall, wrp_stall) begin // Arbitration request. s_intf.req = m_intf.req; if( rrp_stall | wrp_stall ) begin s_intf.req.read = 1'b0; s_intf.req.write = 1'b0; end // Stall signals. m_intf.stall = s_intf.stall | rrp_stall | wrp_stall; end end else begin // Need specific sensitivity list instead of always_comb // otherwise Modelsim will encounter an infinite loop. always @(s_intf.stall, m_intf.req, rrp_stall, wrp_stall) begin // Arbitration request. s_intf.req = m_intf.req; if( rrp_stall ) s_intf.req.read = 1'b0; if( wrp_stall ) s_intf.req.write = 1'b0; // Stall signals. m_intf.stall = s_intf.stall; if( m_intf.req.request & m_intf.req.read & rrp_stall ) m_intf.stall = 1'b1; if( m_intf.req.request & m_intf.req.write & wrp_stall ) m_intf.stall = 1'b1; end end endgenerate // Write return path. acl_ic_slave_wrp #( .DATA_W(DATA_W), .BURSTCOUNT_W(BURSTCOUNT_W), .ADDRESS_W(ADDRESS_W), .BYTEENA_W(BYTEENA_W), .ID_W(ID_W), .FIFO_DEPTH(WRP_FIFO_DEPTH), .NUM_MASTERS(NUM_MASTERS), .PIPELINE(PIPELINE_RETURN_PATHS) ) wrp ( .clock( clock ), .resetn( resetn ), .m_intf( m_intf ), .wrp_intf( wrp_intf ), .s_writeack( s_writeack ), .stall( wrp_stall ) ); // Read return path. acl_ic_slave_rrp #( .DATA_W(DATA_W), .BURSTCOUNT_W(BURSTCOUNT_W), .ADDRESS_W(ADDRESS_W), .BYTEENA_W(BYTEENA_W), .ID_W(ID_W), .FIFO_DEPTH(RRP_FIFO_DEPTH), .USE_LL_FIFO(RRP_USE_LL_FIFO), .SLAVE_FIXED_LATENCY(SLAVE_FIXED_LATENCY), .NUM_MASTERS(NUM_MASTERS), .PIPELINE(PIPELINE_RETURN_PATHS) ) rrp ( .clock( clock ), .resetn( resetn ), .m_intf( m_intf ), .s_readdatavalid( s_readdatavalid ), .s_readdata( s_readdata ), .rrp_intf( rrp_intf ), .stall( rrp_stall ) ); 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. /***************** * Writes a 2-D signal into an In-System Modifiable Memory that can be read out * over JTAG * * After running the design use the accompanying tcl script to generate a .csv * of the data: * quartus_stp -t acl_debug_mem.tcl *****************/ module acl_debug_mem #( parameter WIDTH=16, parameter SIZE=10 ) ( input logic clk, input logic resetn, input logic write, input logic [WIDTH-1:0] data[SIZE] ); /****************** * LOCAL PARAMETERS *******************/ localparam ADDRWIDTH=$clog2(SIZE); /****************** * SIGNALS *******************/ logic [ADDRWIDTH-1:0] addr; logic do_write; /****************** * ARCHITECTURE *******************/ always@(posedge clk or negedge resetn) if (!resetn) addr <= {ADDRWIDTH{1'b0}}; else if (addr != {ADDRWIDTH{1'b0}}) addr <= addr + 2'b01; else if (write) addr <= addr + 2'b01; assign do_write = write | (addr != {ADDRWIDTH{1'b0}}); // Instantiate In-System Modifiable Memory altsyncram altsyncram_component ( .address_a (addr), .clock0 (clk), .data_a (data[addr]), .wren_a (do_write), .q_a (), .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_b (1'b1), .eccstatus (), .q_b (), .rden_a (1'b1), .rden_b (1'b1), .wren_b (1'b0)); defparam altsyncram_component.clock_enable_input_a = "BYPASS", altsyncram_component.clock_enable_output_a = "BYPASS", altsyncram_component.intended_device_family = "Stratix IV", altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=YES,INSTANCE_NAME=ACLDEBUGMEM", altsyncram_component.lpm_type = "altsyncram", altsyncram_component.numwords_a = SIZE, altsyncram_component.widthad_a = ADDRWIDTH, altsyncram_component.width_a = WIDTH, altsyncram_component.operation_mode = "SINGLE_PORT", altsyncram_component.outdata_aclr_a = "NONE", altsyncram_component.read_during_write_mode_port_a = "DONT_CARE", altsyncram_component.width_byteena_a = 1; 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; // Test: tri t; bufif1 (t, crc[1], cyc[1:0]==2'b00); bufif1 (t, crc[2], cyc[1:0]==2'b10); tri0 t0; bufif1 (t0, crc[1], cyc[1:0]==2'b00); bufif1 (t0, crc[2], cyc[1:0]==2'b10); tri1 t1; bufif1 (t1, crc[1], cyc[1:0]==2'b00); bufif1 (t1, crc[2], cyc[1:0]==2'b10); tri t2; t_tri2 t_tri2 (.t2, .d(crc[1]), .oe(cyc[1:0]==2'b00)); bufif1 (t2, crc[2], cyc[1:0]==2'b10); tri t3; t_tri3 t_tri3 (.t3, .d(crc[1]), .oe(cyc[1:0]==2'b00)); bufif1 (t3, crc[2], cyc[1:0]==2'b10); wire [63:0] result = {51'h0, t3, 3'h0,t2, 3'h0,t1, 3'h0,t0}; // 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'h04f91df71371e950 if (sum !== `EXPECTED_SUM) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module t_tri2 (/*AUTOARG*/ // Outputs t2, // Inputs d, oe ); output t2; input d; input oe; tri1 t2; bufif1 (t2, d, oe); endmodule module t_tri3 (/*AUTOARG*/ // Outputs t3, // Inputs d, oe ); output tri1 t3; input d; input oe; bufif1 (t3, d, oe); 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_avm_to_ic #( parameter integer DATA_W = 256, parameter integer WRITEDATA_W = 256, parameter integer BURSTCOUNT_W = 6, parameter integer ADDRESS_W = 32, parameter integer BYTEENA_W = DATA_W / 8, parameter integer ID_W = 1, parameter ADDR_SHIFT=1 // shift the address? ) ( // AVM interface input logic avm_read, input logic avm_write, input logic [WRITEDATA_W-1:0] avm_writedata, input logic [BURSTCOUNT_W-1:0] avm_burstcount, input logic [ADDRESS_W-1:0] avm_address, input logic [BYTEENA_W-1:0] avm_byteenable, output logic avm_waitrequest, output logic avm_readdatavalid, output logic [WRITEDATA_W-1:0] avm_readdata, output logic avm_writeack, // not a true Avalon signal // IC interface output logic ic_arb_request, output logic ic_arb_read, output logic ic_arb_write, output logic [WRITEDATA_W-1:0] ic_arb_writedata, output logic [BURSTCOUNT_W-1:0] ic_arb_burstcount, output logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address, output logic [BYTEENA_W-1:0] ic_arb_byteenable, output logic [ID_W-1:0] ic_arb_id, input logic ic_arb_stall, input logic ic_wrp_ack, input logic ic_rrp_datavalid, input logic [WRITEDATA_W-1:0] ic_rrp_data ); // The logic for ic_arb_request (below) makes a MAJOR ASSUMPTION: // avm_write will never be deasserted in the MIDDLE of a write burst // (read bursts are fine since they are single cycle requests) // // For proper burst functionality, ic_arb_request must remain asserted // for the ENTIRE duration of a burst request, otherwise the burst may be // interrupted and lead to all sorts of chaos. At this time, LSUs do not // deassert avm_write in the middle of a write burst, so this assumption // is valid. // // If there comes a time when this assumption is no longer valid, // logic needs to be added to detect when a burst begins/ends. assign ic_arb_request = avm_read | avm_write; assign ic_arb_read = avm_read; assign ic_arb_write = avm_write; assign ic_arb_writedata = avm_writedata; assign ic_arb_burstcount = avm_burstcount; generate if(ADDR_SHIFT==1) begin assign ic_arb_address = avm_address[ADDRESS_W-1:$clog2(DATA_W / 8)]; end else begin assign ic_arb_address = avm_address[ADDRESS_W-$clog2(DATA_W / 8)-1:0]; end endgenerate assign ic_arb_byteenable = avm_byteenable; assign avm_waitrequest = ic_arb_stall; assign avm_readdatavalid = ic_rrp_datavalid; assign avm_readdata = ic_rrp_data; assign avm_writeack = ic_wrp_ack; 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_avm_to_ic #( parameter integer DATA_W = 256, parameter integer WRITEDATA_W = 256, parameter integer BURSTCOUNT_W = 6, parameter integer ADDRESS_W = 32, parameter integer BYTEENA_W = DATA_W / 8, parameter integer ID_W = 1, parameter ADDR_SHIFT=1 // shift the address? ) ( // AVM interface input logic avm_read, input logic avm_write, input logic [WRITEDATA_W-1:0] avm_writedata, input logic [BURSTCOUNT_W-1:0] avm_burstcount, input logic [ADDRESS_W-1:0] avm_address, input logic [BYTEENA_W-1:0] avm_byteenable, output logic avm_waitrequest, output logic avm_readdatavalid, output logic [WRITEDATA_W-1:0] avm_readdata, output logic avm_writeack, // not a true Avalon signal // IC interface output logic ic_arb_request, output logic ic_arb_read, output logic ic_arb_write, output logic [WRITEDATA_W-1:0] ic_arb_writedata, output logic [BURSTCOUNT_W-1:0] ic_arb_burstcount, output logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address, output logic [BYTEENA_W-1:0] ic_arb_byteenable, output logic [ID_W-1:0] ic_arb_id, input logic ic_arb_stall, input logic ic_wrp_ack, input logic ic_rrp_datavalid, input logic [WRITEDATA_W-1:0] ic_rrp_data ); // The logic for ic_arb_request (below) makes a MAJOR ASSUMPTION: // avm_write will never be deasserted in the MIDDLE of a write burst // (read bursts are fine since they are single cycle requests) // // For proper burst functionality, ic_arb_request must remain asserted // for the ENTIRE duration of a burst request, otherwise the burst may be // interrupted and lead to all sorts of chaos. At this time, LSUs do not // deassert avm_write in the middle of a write burst, so this assumption // is valid. // // If there comes a time when this assumption is no longer valid, // logic needs to be added to detect when a burst begins/ends. assign ic_arb_request = avm_read | avm_write; assign ic_arb_read = avm_read; assign ic_arb_write = avm_write; assign ic_arb_writedata = avm_writedata; assign ic_arb_burstcount = avm_burstcount; generate if(ADDR_SHIFT==1) begin assign ic_arb_address = avm_address[ADDRESS_W-1:$clog2(DATA_W / 8)]; end else begin assign ic_arb_address = avm_address[ADDRESS_W-$clog2(DATA_W / 8)-1:0]; end endgenerate assign ic_arb_byteenable = avm_byteenable; assign avm_waitrequest = ic_arb_stall; assign avm_readdatavalid = ic_rrp_datavalid; assign avm_readdata = ic_rrp_data; assign avm_writeack = ic_wrp_ack; 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 FIFO // One cycle latency from all inputs to all outputs // Storage implemented in registers, not memory. module acl_ll_fifo(clk, reset, data_in, write, data_out, read, empty, full, almost_full); /* Parameters */ parameter WIDTH = 32; parameter DEPTH = 32; parameter ALMOST_FULL_VALUE = 0; /* Ports */ input clk; input reset; input [WIDTH-1:0] data_in; input write; output [WIDTH-1:0] data_out; input read; output empty; output full; output almost_full; /* Architecture */ // One-hot write-pointer bit (indicates next position to write at), // last bit indicates the FIFO is full reg [DEPTH:0] wptr; // Replicated copy of the stall / valid logic reg [DEPTH:0] wptr_copy /* synthesis dont_merge */; // FIFO data registers reg [DEPTH-1:0][WIDTH-1:0] data; // Write pointer updates: wire wptr_hold; // Hold the value wire wptr_dir; // Direction to shift // Data register updates: wire [DEPTH-1:0] data_hold; // Hold the value wire [DEPTH-1:0] data_new; // Write the new data value in // Write location is constant unless the occupancy changes assign wptr_hold = !(read ^ write); assign wptr_dir = read; // Hold the value unless we are reading, or writing to this // location genvar i; generate for(i = 0; i < DEPTH; i++) begin : data_mux assign data_hold[i] = !(read | (write & wptr[i])); assign data_new[i] = !read | wptr[i+1]; end endgenerate // The data registers generate for(i = 0; i < DEPTH-1; i++) begin : data_reg always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[i] <= {WIDTH{1'b0}}; else data[i] <= data_hold[i] ? data[i] : data_new[i] ? data_in : data[i+1]; end end endgenerate always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[DEPTH-1] <= {WIDTH{1'b0}}; else data[DEPTH-1] <= data_hold[DEPTH-1] ? data[DEPTH-1] : data_in; end // The write pointer always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin wptr <= {{DEPTH{1'b0}}, 1'b1}; wptr_copy <= {{DEPTH{1'b0}}, 1'b1}; end else begin wptr <= wptr_hold ? wptr : wptr_dir ? {1'b0, wptr[DEPTH:1]} : {wptr[DEPTH-1:0], 1'b0}; wptr_copy <= wptr_hold ? wptr_copy : wptr_dir ? {1'b0, wptr_copy[DEPTH:1]} : {wptr_copy[DEPTH-1:0], 1'b0}; end end // Outputs assign empty = wptr_copy[0]; assign full = wptr_copy[DEPTH]; assign almost_full = wptr_copy[DEPTH - ALMOST_FULL_VALUE]; assign data_out = data[0]; 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 FIFO // One cycle latency from all inputs to all outputs // Storage implemented in registers, not memory. module acl_ll_fifo(clk, reset, data_in, write, data_out, read, empty, full, almost_full); /* Parameters */ parameter WIDTH = 32; parameter DEPTH = 32; parameter ALMOST_FULL_VALUE = 0; /* Ports */ input clk; input reset; input [WIDTH-1:0] data_in; input write; output [WIDTH-1:0] data_out; input read; output empty; output full; output almost_full; /* Architecture */ // One-hot write-pointer bit (indicates next position to write at), // last bit indicates the FIFO is full reg [DEPTH:0] wptr; // Replicated copy of the stall / valid logic reg [DEPTH:0] wptr_copy /* synthesis dont_merge */; // FIFO data registers reg [DEPTH-1:0][WIDTH-1:0] data; // Write pointer updates: wire wptr_hold; // Hold the value wire wptr_dir; // Direction to shift // Data register updates: wire [DEPTH-1:0] data_hold; // Hold the value wire [DEPTH-1:0] data_new; // Write the new data value in // Write location is constant unless the occupancy changes assign wptr_hold = !(read ^ write); assign wptr_dir = read; // Hold the value unless we are reading, or writing to this // location genvar i; generate for(i = 0; i < DEPTH; i++) begin : data_mux assign data_hold[i] = !(read | (write & wptr[i])); assign data_new[i] = !read | wptr[i+1]; end endgenerate // The data registers generate for(i = 0; i < DEPTH-1; i++) begin : data_reg always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[i] <= {WIDTH{1'b0}}; else data[i] <= data_hold[i] ? data[i] : data_new[i] ? data_in : data[i+1]; end end endgenerate always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[DEPTH-1] <= {WIDTH{1'b0}}; else data[DEPTH-1] <= data_hold[DEPTH-1] ? data[DEPTH-1] : data_in; end // The write pointer always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin wptr <= {{DEPTH{1'b0}}, 1'b1}; wptr_copy <= {{DEPTH{1'b0}}, 1'b1}; end else begin wptr <= wptr_hold ? wptr : wptr_dir ? {1'b0, wptr[DEPTH:1]} : {wptr[DEPTH-1:0], 1'b0}; wptr_copy <= wptr_hold ? wptr_copy : wptr_dir ? {1'b0, wptr_copy[DEPTH:1]} : {wptr_copy[DEPTH-1:0], 1'b0}; end end // Outputs assign empty = wptr_copy[0]; assign full = wptr_copy[DEPTH]; assign almost_full = wptr_copy[DEPTH - ALMOST_FULL_VALUE]; assign data_out = data[0]; 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 FIFO // One cycle latency from all inputs to all outputs // Storage implemented in registers, not memory. module acl_ll_fifo(clk, reset, data_in, write, data_out, read, empty, full, almost_full); /* Parameters */ parameter WIDTH = 32; parameter DEPTH = 32; parameter ALMOST_FULL_VALUE = 0; /* Ports */ input clk; input reset; input [WIDTH-1:0] data_in; input write; output [WIDTH-1:0] data_out; input read; output empty; output full; output almost_full; /* Architecture */ // One-hot write-pointer bit (indicates next position to write at), // last bit indicates the FIFO is full reg [DEPTH:0] wptr; // Replicated copy of the stall / valid logic reg [DEPTH:0] wptr_copy /* synthesis dont_merge */; // FIFO data registers reg [DEPTH-1:0][WIDTH-1:0] data; // Write pointer updates: wire wptr_hold; // Hold the value wire wptr_dir; // Direction to shift // Data register updates: wire [DEPTH-1:0] data_hold; // Hold the value wire [DEPTH-1:0] data_new; // Write the new data value in // Write location is constant unless the occupancy changes assign wptr_hold = !(read ^ write); assign wptr_dir = read; // Hold the value unless we are reading, or writing to this // location genvar i; generate for(i = 0; i < DEPTH; i++) begin : data_mux assign data_hold[i] = !(read | (write & wptr[i])); assign data_new[i] = !read | wptr[i+1]; end endgenerate // The data registers generate for(i = 0; i < DEPTH-1; i++) begin : data_reg always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[i] <= {WIDTH{1'b0}}; else data[i] <= data_hold[i] ? data[i] : data_new[i] ? data_in : data[i+1]; end end endgenerate always@(posedge clk or posedge reset) begin if(reset == 1'b1) data[DEPTH-1] <= {WIDTH{1'b0}}; else data[DEPTH-1] <= data_hold[DEPTH-1] ? data[DEPTH-1] : data_in; end // The write pointer always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin wptr <= {{DEPTH{1'b0}}, 1'b1}; wptr_copy <= {{DEPTH{1'b0}}, 1'b1}; end else begin wptr <= wptr_hold ? wptr : wptr_dir ? {1'b0, wptr[DEPTH:1]} : {wptr[DEPTH-1:0], 1'b0}; wptr_copy <= wptr_hold ? wptr_copy : wptr_dir ? {1'b0, wptr_copy[DEPTH:1]} : {wptr_copy[DEPTH-1:0], 1'b0}; end end // Outputs assign empty = wptr_copy[0]; assign full = wptr_copy[DEPTH]; assign almost_full = wptr_copy[DEPTH - ALMOST_FULL_VALUE]; assign data_out = data[0]; 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 a n-entry n-exit loop limiter module, n=1, 2, ... module acl_loop_limiter #( parameter ENTRY_WIDTH = 8,// 1 - n EXIT_WIDTH = 8, // 0 - n THRESHOLD = 100, THRESHOLD_NO_DELAY = 0, // Delay from i_valid/stall to o_valid/stall; // default is 0, because setting it to 1 will hurt FMAX // e.g. Assuming at clock cycle n, the internal counter is full (valid_allow=0); i_stall and i_stall_exit both remain 0 // | THRESHOLD_NO_DELAY = 0 | THRESHOLD_NO_DELAY = 1 //time i_valid i_valid_exit | valid_allow o_valid | valid_allow o_valid //n 2'b11 2'b01 | 0 2'b00 | 0 2'b01 //n+1 2'b11 2'b00 | 1 2'b01 | 0 2'b00 PEXIT_WIDTH = (EXIT_WIDTH == 0)? 1 : EXIT_WIDTH // to avoid negative index(modelsim compile error) )( input clock, input resetn, input [ENTRY_WIDTH-1:0] i_valid, input [ENTRY_WIDTH-1:0] i_stall, input [PEXIT_WIDTH-1:0] i_valid_exit, input [PEXIT_WIDTH-1:0] i_stall_exit, output [ENTRY_WIDTH-1:0] o_valid, output [ENTRY_WIDTH-1:0] o_stall ); localparam ADD_WIDTH = $clog2(ENTRY_WIDTH + 1); localparam SUB_WIDTH = $clog2(PEXIT_WIDTH + 1); localparam THRESHOLD_W = $clog2(THRESHOLD + 1); integer i; wire [ENTRY_WIDTH-1:0] inc_bin; wire [ADD_WIDTH-1:0] inc_wire [ENTRY_WIDTH]; wire [PEXIT_WIDTH-1:0] dec_bin; wire [SUB_WIDTH-1:0] dec_wire [PEXIT_WIDTH]; wire [ADD_WIDTH-1:0] inc_value [ENTRY_WIDTH]; wire decrease_allow; wire [THRESHOLD_W:0] valid_allow_wire; reg [THRESHOLD_W-1:0] counter_next, valid_allow; wire [ENTRY_WIDTH-1:0] limit_mask; wire [ENTRY_WIDTH-1:0] accept_inc_bin; assign decrease_allow = inc_value[ENTRY_WIDTH-1] > dec_wire[PEXIT_WIDTH-1]; assign valid_allow_wire = valid_allow + dec_wire[PEXIT_WIDTH-1] - inc_value[ENTRY_WIDTH-1]; always @(*) begin if(decrease_allow) counter_next = valid_allow_wire[THRESHOLD_W]? 0 : valid_allow_wire[THRESHOLD_W-1:0]; else counter_next = (valid_allow_wire > THRESHOLD)? THRESHOLD : valid_allow_wire[THRESHOLD_W-1:0]; end //valid_allow_temp is used only when THRESHOLD_NO_DELAY = 1 wire [THRESHOLD_W:0] valid_allow_temp; assign valid_allow_temp = valid_allow + dec_wire[PEXIT_WIDTH-1]; genvar z; generate for(z=0; z<ENTRY_WIDTH; z=z+1) begin : GEN_COMB_ENTRY assign inc_bin[z] = ~i_stall[z] & i_valid[z]; assign inc_wire[z] = (z==0)? i_valid[0] : inc_wire[z-1] + i_valid[z]; // set mask bit n to 1 if the sum of (~i_stall[z] & i_valid[z], z=0, 1, ..., n) is smaller or equal to the number of output valid bits allowed. assign limit_mask[z] = inc_wire[z] <= (THRESHOLD_NO_DELAY? valid_allow_temp : valid_allow); assign accept_inc_bin[z] = inc_bin[z] & limit_mask[z]; assign inc_value[z] = (z==0)? accept_inc_bin[0] : inc_value[z-1] + accept_inc_bin[z]; assign o_valid[z] = limit_mask[z] & i_valid[z]; assign o_stall[z] = (ENTRY_WIDTH == 1)? (valid_allow == 0 | i_stall[z]) : (!o_valid[z] | i_stall[z]); end for(z=0; z<PEXIT_WIDTH; z=z+1) begin : GEN_COMB_EXIT assign dec_bin[z] = !i_stall_exit[z] & i_valid_exit[z]; assign dec_wire[z] = (z==0)? dec_bin[0] : dec_wire[z-1] + dec_bin[z]; end endgenerate // Synchrounous always @(posedge clock or negedge resetn) begin if(!resetn) begin valid_allow <= THRESHOLD; end else begin // update the internal counter valid_allow <= counter_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. // This is a n-entry n-exit loop limiter module, n=1, 2, ... module acl_loop_limiter #( parameter ENTRY_WIDTH = 8,// 1 - n EXIT_WIDTH = 8, // 0 - n THRESHOLD = 100, THRESHOLD_NO_DELAY = 0, // Delay from i_valid/stall to o_valid/stall; // default is 0, because setting it to 1 will hurt FMAX // e.g. Assuming at clock cycle n, the internal counter is full (valid_allow=0); i_stall and i_stall_exit both remain 0 // | THRESHOLD_NO_DELAY = 0 | THRESHOLD_NO_DELAY = 1 //time i_valid i_valid_exit | valid_allow o_valid | valid_allow o_valid //n 2'b11 2'b01 | 0 2'b00 | 0 2'b01 //n+1 2'b11 2'b00 | 1 2'b01 | 0 2'b00 PEXIT_WIDTH = (EXIT_WIDTH == 0)? 1 : EXIT_WIDTH // to avoid negative index(modelsim compile error) )( input clock, input resetn, input [ENTRY_WIDTH-1:0] i_valid, input [ENTRY_WIDTH-1:0] i_stall, input [PEXIT_WIDTH-1:0] i_valid_exit, input [PEXIT_WIDTH-1:0] i_stall_exit, output [ENTRY_WIDTH-1:0] o_valid, output [ENTRY_WIDTH-1:0] o_stall ); localparam ADD_WIDTH = $clog2(ENTRY_WIDTH + 1); localparam SUB_WIDTH = $clog2(PEXIT_WIDTH + 1); localparam THRESHOLD_W = $clog2(THRESHOLD + 1); integer i; wire [ENTRY_WIDTH-1:0] inc_bin; wire [ADD_WIDTH-1:0] inc_wire [ENTRY_WIDTH]; wire [PEXIT_WIDTH-1:0] dec_bin; wire [SUB_WIDTH-1:0] dec_wire [PEXIT_WIDTH]; wire [ADD_WIDTH-1:0] inc_value [ENTRY_WIDTH]; wire decrease_allow; wire [THRESHOLD_W:0] valid_allow_wire; reg [THRESHOLD_W-1:0] counter_next, valid_allow; wire [ENTRY_WIDTH-1:0] limit_mask; wire [ENTRY_WIDTH-1:0] accept_inc_bin; assign decrease_allow = inc_value[ENTRY_WIDTH-1] > dec_wire[PEXIT_WIDTH-1]; assign valid_allow_wire = valid_allow + dec_wire[PEXIT_WIDTH-1] - inc_value[ENTRY_WIDTH-1]; always @(*) begin if(decrease_allow) counter_next = valid_allow_wire[THRESHOLD_W]? 0 : valid_allow_wire[THRESHOLD_W-1:0]; else counter_next = (valid_allow_wire > THRESHOLD)? THRESHOLD : valid_allow_wire[THRESHOLD_W-1:0]; end //valid_allow_temp is used only when THRESHOLD_NO_DELAY = 1 wire [THRESHOLD_W:0] valid_allow_temp; assign valid_allow_temp = valid_allow + dec_wire[PEXIT_WIDTH-1]; genvar z; generate for(z=0; z<ENTRY_WIDTH; z=z+1) begin : GEN_COMB_ENTRY assign inc_bin[z] = ~i_stall[z] & i_valid[z]; assign inc_wire[z] = (z==0)? i_valid[0] : inc_wire[z-1] + i_valid[z]; // set mask bit n to 1 if the sum of (~i_stall[z] & i_valid[z], z=0, 1, ..., n) is smaller or equal to the number of output valid bits allowed. assign limit_mask[z] = inc_wire[z] <= (THRESHOLD_NO_DELAY? valid_allow_temp : valid_allow); assign accept_inc_bin[z] = inc_bin[z] & limit_mask[z]; assign inc_value[z] = (z==0)? accept_inc_bin[0] : inc_value[z-1] + accept_inc_bin[z]; assign o_valid[z] = limit_mask[z] & i_valid[z]; assign o_stall[z] = (ENTRY_WIDTH == 1)? (valid_allow == 0 | i_stall[z]) : (!o_valid[z] | i_stall[z]); end for(z=0; z<PEXIT_WIDTH; z=z+1) begin : GEN_COMB_EXIT assign dec_bin[z] = !i_stall_exit[z] & i_valid_exit[z]; assign dec_wire[z] = (z==0)? dec_bin[0] : dec_wire[z-1] + dec_bin[z]; end endgenerate // Synchrounous always @(posedge clock or negedge resetn) begin if(!resetn) begin valid_allow <= THRESHOLD; end else begin // update the internal counter valid_allow <= counter_next; end end endmodule
(** * Norm: Normalization of STLC *) (* Chapter maintained by Andrew Tolmach *) (* (Based on TAPL Ch. 12.) *) Require Export Smallstep. Hint Constructors multi. (** (This chapter is optional.) In this chapter, we consider another fundamental theoretical property of the simply typed lambda-calculus: the fact that the evaluation of a well-typed program is guaranteed to halt in a finite number of steps---i.e., every well-typed term is _normalizable_. Unlike the type-safety properties we have considered so far, the normalization property does not extend to full-blown programming languages, because these languages nearly always extend the simply typed lambda-calculus with constructs, such as general recursion (as we discussed in the MoreStlc chapter) or recursive types, that can be used to write nonterminating programs. However, the issue of normalization reappears at the level of _types_ when we consider the metatheory of polymorphic versions of the lambda calculus such as F_omega: in this system, the language of types effectively contains a copy of the simply typed lambda-calculus, and the termination of the typechecking algorithm will hinge on the fact that a ``normalization'' operation on type expressions is guaranteed to terminate. Another reason for studying normalization proofs is that they are some of the most beautiful---and mind-blowing---mathematics to be found in the type theory literature, often (as here) involving the fundamental proof technique of _logical relations_. The calculus we shall consider here is the simply typed lambda-calculus over a single base type [bool] and with pairs. We'll give full details of the development for the basic lambda-calculus terms treating [bool] as an uninterpreted base type, and leave the extension to the boolean operators and pairs to the reader. Even for the base calculus, normalization is not entirely trivial to prove, since each reduction of a term can duplicate redexes in subterms. *) (** **** Exercise: 1 star *) (** Where do we fail if we attempt to prove normalization by a straightforward induction on the size of a well-typed term? *) (* FILL IN HERE *) (** [] *) (* ###################################################################### *) (** * Language *) (** We begin by repeating the relevant language definition, which is similar to those in the MoreStlc chapter, and supporting results including type preservation and step determinism. (We won't need progress.) You may just wish to skip down to the Normalization section... *) (* ###################################################################### *) (** *** Syntax and Operational Semantics *) Inductive ty : Type := | TBool : ty | TArrow : ty -> ty -> ty | TProd : ty -> ty -> ty . Tactic Notation "T_cases" tactic(first) ident(c) := first; [ Case_aux c "TBool" | Case_aux c "TArrow" | Case_aux c "TProd" ]. Inductive tm : Type := (* pure STLC *) | tvar : id -> tm | tapp : tm -> tm -> tm | tabs : id -> ty -> tm -> tm (* pairs *) | tpair : tm -> tm -> tm | tfst : tm -> tm | tsnd : tm -> tm (* booleans *) | ttrue : tm | tfalse : tm | tif : tm -> tm -> tm -> tm. (* i.e., [if t0 then t1 else t2] *) Tactic Notation "t_cases" tactic(first) ident(c) := first; [ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs" | Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd" | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ]. (* ###################################################################### *) (** *** 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) | tpair t1 t2 => tpair (subst x s t1) (subst x s t2) | tfst t1 => tfst (subst x s t1) | tsnd t1 => tsnd (subst x s t1) | ttrue => ttrue | tfalse => tfalse | tif t0 t1 t2 => tif (subst x s t0) (subst x s t1) (subst x s t2) end. Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20). (* ###################################################################### *) (** *** Reduction *) Inductive value : tm -> Prop := | v_abs : forall x T11 t12, value (tabs x T11 t12) | v_pair : forall v1 v2, value v1 -> value v2 -> value (tpair v1 v2) | v_true : value ttrue | v_false : value tfalse . Hint Constructors value. Reserved Notation "t1 '==>' t2" (at level 40). Inductive step : tm -> tm -> Prop := | ST_AppAbs : forall x T11 t12 v2, value v2 -> (tapp (tabs x T11 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') (* pairs *) | ST_Pair1 : forall t1 t1' t2, t1 ==> t1' -> (tpair t1 t2) ==> (tpair t1' t2) | ST_Pair2 : forall v1 t2 t2', value v1 -> t2 ==> t2' -> (tpair v1 t2) ==> (tpair v1 t2') | ST_Fst : forall t1 t1', t1 ==> t1' -> (tfst t1) ==> (tfst t1') | ST_FstPair : forall v1 v2, value v1 -> value v2 -> (tfst (tpair v1 v2)) ==> v1 | ST_Snd : forall t1 t1', t1 ==> t1' -> (tsnd t1) ==> (tsnd t1') | ST_SndPair : forall v1 v2, value v1 -> value v2 -> (tsnd (tpair v1 v2)) ==> v2 (* booleans *) | ST_IfTrue : forall t1 t2, (tif ttrue t1 t2) ==> t1 | ST_IfFalse : forall t1 t2, (tif tfalse t1 t2) ==> t2 | ST_If : forall t0 t0' t1 t2, t0 ==> t0' -> (tif t0 t1 t2) ==> (tif t0' t1 t2) 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_Pair1" | Case_aux c "ST_Pair2" | Case_aux c "ST_Fst" | Case_aux c "ST_FstPair" | Case_aux c "ST_Snd" | Case_aux c "ST_SndPair" | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ]. Notation multistep := (multi step). Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40). Hint Constructors step. Notation step_normal_form := (normal_form step). Lemma value__normal : forall t, value t -> step_normal_form t. Proof with eauto. intros t H; induction H; intros [t' ST]; inversion ST... Qed. (* ###################################################################### *) (** *** Typing *) Definition context := partial_map ty. Inductive has_type : context -> tm -> ty -> Prop := (* Typing rules for proper terms *) | T_Var : forall Gamma x T, Gamma x = Some T -> has_type Gamma (tvar x) T | T_Abs : forall Gamma x T11 T12 t12, 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 (* pairs *) | T_Pair : forall Gamma t1 t2 T1 T2, has_type Gamma t1 T1 -> has_type Gamma t2 T2 -> has_type Gamma (tpair t1 t2) (TProd T1 T2) | T_Fst : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tfst t) T1 | T_Snd : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tsnd t) T2 (* booleans *) | T_True : forall Gamma, has_type Gamma ttrue TBool | T_False : forall Gamma, has_type Gamma tfalse TBool | T_If : forall Gamma t0 t1 t2 T, has_type Gamma t0 TBool -> has_type Gamma t1 T -> has_type Gamma t2 T -> has_type Gamma (tif t0 t1 t2) 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_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd" | Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If" ]. Hint Extern 2 (has_type _ (tapp _ _) _) => eapply T_App; auto. Hint Extern 2 (_ = _) => compute; reflexivity. (* ###################################################################### *) (** *** 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) (* pairs *) | afi_pair1 : forall x t1 t2, appears_free_in x t1 -> appears_free_in x (tpair t1 t2) | afi_pair2 : forall x t1 t2, appears_free_in x t2 -> appears_free_in x (tpair t1 t2) | afi_fst : forall x t, appears_free_in x t -> appears_free_in x (tfst t) | afi_snd : forall x t, appears_free_in x t -> appears_free_in x (tsnd t) (* booleans *) | afi_if0 : forall x t0 t1 t2, appears_free_in x t0 -> appears_free_in x (tif t0 t1 t2) | afi_if1 : forall x t0 t1 t2, appears_free_in x t1 -> appears_free_in x (tif t0 t1 t2) | afi_if2 : forall x t0 t1 t2, appears_free_in x t2 -> appears_free_in x (tif t0 t1 t2) . Hint Constructors appears_free_in. Definition closed (t:tm) := forall x, ~ appears_free_in x t. 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 y Hafi. unfold extend. destruct (eq_id_dec x y)... Case "T_Pair". apply T_Pair... Case "T_If". eapply T_If... 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; inversion Hafi; subst... Case "T_Abs". destruct IHHtyp as [T' Hctx]... exists T'. unfold extend in Hctx. rewrite neq_id in Hctx... Qed. Corollary typable_empty__closed : forall t T, has_type empty t T -> closed t. Proof. intros. unfold closed. intros x H1. destruct (free_in_context _ _ _ _ H1 H) as [T' C]. inversion C. 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. (* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then Gamma |- ([x:=v]t) S. *) intros Gamma x U v t S Htypt Htypv. generalize dependent Gamma. generalize dependent S. (* Proof: By induction on the term t. Most cases follow directly from the IH, with the exception of tvar and tabs. The former aren't automatic because we must reason about how the variables interact. *) t_cases (induction t) Case; intros S Gamma Htypt; simpl; inversion Htypt; subst... Case "tvar". simpl. rename i into y. (* If t = y, we know that [empty |- v : U] and [Gamma,x:U |- y : S] and, by inversion, [extend Gamma x U y = Some S]. We want to show that [Gamma |- [x:=v]y : S]. There are two cases to consider: either [x=y] or [x<>y]. *) destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then we know that [U = S], and that [[x:=v]y = v]. So what we really must show is that if [empty |- v : U] then [Gamma |- v : U]. We have already proven a more general version of this theorem, called context invariance. *) subst. unfold extend in H1. rewrite eq_id in H1. inversion H1; subst. clear H1. eapply context_invariance... intros x Hcontra. destruct (free_in_context _ _ S empty Hcontra) as [T' HT']... inversion HT'. SCase "x<>y". (* If [x <> y], then [Gamma y = Some S] and the substitution has no effect. We can show that [Gamma |- y : S] by [T_Var]. *) apply T_Var... unfold extend in H1. rewrite neq_id in H1... Case "tabs". rename i into y. rename t into T11. (* If [t = tabs y T11 t0], then we know that [Gamma,x:U |- tabs y T11 t0 : T11->T12] [Gamma,x:U,y:T11 |- t0 : T12] [empty |- v : U] As our IH, we know that forall S Gamma, [Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 S]. We can calculate that [x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0) And we must show that [Gamma |- [x:=v]t : T11->T12]. We know we will do so using [T_Abs], so it remains to be shown that: [Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12] We consider two cases: [x = y] and [x <> y]. *) apply T_Abs... destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then the substitution has no effect. Context invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are equivalent. Since the former context shows that [t0 : T12], so does the latter. *) eapply context_invariance... subst. intros x Hafi. unfold extend. destruct (eq_id_dec y x)... SCase "x<>y". (* If [x <> y], then the IH and context invariance allow us to show that [Gamma,x:U,y:T11 |- t0 : T12] => [Gamma,y:T11,x:U |- t0 : T12] => [Gamma,y:T11 |- [x:=v]t0 : T12] *) apply IHt. eapply context_invariance... intros z Hafi. unfold extend. destruct (eq_id_dec y z)... subst. rewrite neq_id... 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. (* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *) remember (@empty ty) as Gamma. generalize dependent HeqGamma. generalize dependent t'. (* Proof: By induction on the given typing derivation. Many cases are contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *) has_type_cases (induction HT) Case; intros t' HeqGamma HE; subst; inversion HE; subst... Case "T_App". (* If the last rule used was [T_App], then [t = t1 t2], and three rules could have been used to show [t ==> t']: [ST_App1], [ST_App2], and [ST_AppAbs]. In the first two cases, the result follows directly from the IH. *) inversion HE; subst... SCase "ST_AppAbs". (* For the third case, suppose [t1 = tabs x T11 t12] and [t2 = v2]. We must show that [empty |- [x:=v2]t12 : T2]. We know by assumption that [empty |- tabs x T11 t12 : T1->T2] and by inversion [x:T1 |- t12 : T2] We have already proven that substitution_preserves_typing and [empty |- v2 : T1] by assumption, so we are done. *) apply substitution_preserves_typing with T1... inversion HT1... Case "T_Fst". inversion HT... Case "T_Snd". inversion HT... Qed. (** [] *) (* ###################################################################### *) (** *** Determinism *) Lemma step_deterministic : deterministic step. Proof with eauto. unfold deterministic. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** * Normalization *) (** Now for the actual normalization proof. Our goal is to prove that every well-typed term evaluates to a normal form. In fact, it turns out to be convenient to prove something slightly stronger, namely that every well-typed term evaluates to a _value_. This follows from the weaker property anyway via the Progress lemma (why?) but otherwise we don't need Progress, and we didn't bother re-proving it above. Here's the key definition: *) Definition halts (t:tm) : Prop := exists t', t ==>* t' /\ value t'. (** A trivial fact: *) Lemma value_halts : forall v, value v -> halts v. Proof. intros v H. unfold halts. exists v. split. apply multi_refl. assumption. Qed. (** The key issue in the normalization proof (as in many proofs by induction) is finding a strong enough induction hypothesis. To this end, we begin by defining, for each type [T], a set [R_T] of closed terms of type [T]. We will specify these sets using a relation [R] and write [R T t] when [t] is in [R_T]. (The sets [R_T] are sometimes called _saturated sets_ or _reducibility candidates_.) Here is the definition of [R] for the base language: - [R bool t] iff [t] is a closed term of type [bool] and [t] halts in a value - [R (T1 -> T2) t] iff [t] is a closed term of type [T1 -> T2] and [t] halts in a value _and_ for any term [s] such that [R T1 s], we have [R T2 (t s)]. *) (** This definition gives us the strengthened induction hypothesis that we need. Our primary goal is to show that all _programs_ ---i.e., all closed terms of base type---halt. But closed terms of base type can contain subterms of functional type, so we need to know something about these as well. Moreover, it is not enough to know that these subterms halt, because the application of a normalized function to a normalized argument involves a substitution, which may enable more evaluation steps. So we need a stronger condition for terms of functional type: not only should they halt themselves, but, when applied to halting arguments, they should yield halting results. The form of [R] is characteristic of the _logical relations_ proof technique. (Since we are just dealing with unary relations here, we could perhaps more properly say _logical predicates_.) If we want to prove some property [P] of all closed terms of type [A], we proceed by proving, by induction on types, that all terms of type [A] _possess_ property [P], all terms of type [A->A] _preserve_ property [P], all terms of type [(A->A)->(A->A)] _preserve the property of preserving_ property [P], and so on. We do this by defining a family of predicates, indexed by types. For the base type [A], the predicate is just [P]. For functional types, it says that the function should map values satisfying the predicate at the input type to values satisfying the predicate at the output type. When we come to formalize the definition of [R] in Coq, we hit a problem. The most obvious formulation would be as a parameterized Inductive proposition like this: Inductive R : ty -> tm -> Prop := | R_bool : forall b t, has_type empty t TBool -> halts t -> R TBool t | R_arrow : forall T1 T2 t, has_type empty t (TArrow T1 T2) -> halts t -> (forall s, R T1 s -> R T2 (tapp t s)) -> R (TArrow T1 T2) t. Unfortunately, Coq rejects this definition because it violates the _strict positivity requirement_ for inductive definitions, which says that the type being defined must not occur to the left of an arrow in the type of a constructor argument. Here, it is the third argument to [R_arrow], namely [(forall s, R T1 s -> R TS (tapp t s))], and specifically the [R T1 s] part, that violates this rule. (The outermost arrows separating the constructor arguments don't count when applying this rule; otherwise we could never have genuinely inductive predicates at all!) The reason for the rule is that types defined with non-positive recursion can be used to build non-terminating functions, which as we know would be a disaster for Coq's logical soundness. Even though the relation we want in this case might be perfectly innocent, Coq still rejects it because it fails the positivity test. Fortunately, it turns out that we _can_ define [R] using a [Fixpoint]: *) Fixpoint R (T:ty) (t:tm) {struct T} : Prop := has_type empty t T /\ halts t /\ (match T with | TBool => True | TArrow T1 T2 => (forall s, R T1 s -> R T2 (tapp t s)) (* FILL IN HERE *) | TProd T1 T2 => False (* ... and delete this line *) end). (** As immediate consequences of this definition, we have that every element of every set [R_T] halts in a value and is closed with type [t] :*) Lemma R_halts : forall {T} {t}, R T t -> halts t. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. Lemma R_typable_empty : forall {T} {t}, R T t -> has_type empty t T. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. (** Now we proceed to show the main result, which is that every well-typed term of type [T] is an element of [R_T]. Together with [R_halts], that will show that every well-typed term halts in a value. *) (* ###################################################################### *) (** ** Membership in [R_T] is invariant under evaluation *) (** We start with a preliminary lemma that shows a kind of strong preservation property, namely that membership in [R_T] is _invariant_ under evaluation. We will need this property in both directions, i.e. both to show that a term in [R_T] stays in [R_T] when it takes a forward step, and to show that any term that ends up in [R_T] after a step must have been in [R_T] to begin with. First of all, an easy preliminary lemma. Note that in the forward direction the proof depends on the fact that our language is determinstic. This lemma might still be true for non-deterministic languages, but the proof would be harder! *) Lemma step_preserves_halting : forall t t', (t ==> t') -> (halts t <-> halts t'). Proof. intros t t' ST. unfold halts. split. Case "->". intros [t'' [STM V]]. inversion STM; subst. apply ex_falso_quodlibet. apply value__normal in V. unfold normal_form in V. apply V. exists t'. auto. rewrite (step_deterministic _ _ _ ST H). exists t''. split; assumption. Case "<-". intros [t'0 [STM V]]. exists t'0. split; eauto. Qed. (** Now the main lemma, which comes in two parts, one for each direction. Each proceeds by induction on the structure of the type [T]. In fact, this is where we make fundamental use of the structure of types. One requirement for staying in [R_T] is to stay in type [T]. In the forward direction, we get this from ordinary type Preservation. *) Lemma step_preserves_R : forall T t t', (t ==> t') -> R T t -> R T t'. Proof. induction T; intros t t' E Rt; unfold R; fold R; unfold R in Rt; fold R in Rt; destruct Rt as [typable_empty_t [halts_t RRt]]. (* TBool *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. auto. (* TArrow *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. intros. eapply IHT2. apply ST_App1. apply E. apply RRt; auto. (* FILL IN HERE *) Admitted. (** The generalization to multiple steps is trivial: *) Lemma multistep_preserves_R : forall T t t', (t ==>* t') -> R T t -> R T t'. Proof. intros T t t' STM; induction STM; intros. assumption. apply IHSTM. eapply step_preserves_R. apply H. assumption. Qed. (** In the reverse direction, we must add the fact that [t] has type [T] before stepping as an additional hypothesis. *) Lemma step_preserves_R' : forall T t t', has_type empty t T -> (t ==> t') -> R T t' -> R T t. Proof. (* FILL IN HERE *) Admitted. Lemma multistep_preserves_R' : forall T t t', has_type empty t T -> (t ==>* t') -> R T t' -> R T t. Proof. intros T t t' HT STM. induction STM; intros. assumption. eapply step_preserves_R'. assumption. apply H. apply IHSTM. eapply preservation; eauto. auto. Qed. (* ###################################################################### *) (** ** Closed instances of terms of type [T] belong to [R_T] *) (** Now we proceed to show that every term of type [T] belongs to [R_T]. Here, the induction will be on typing derivations (it would be surprising to see a proof about well-typed terms that did not somewhere involve induction on typing derivations!). The only technical difficulty here is in dealing with the abstraction case. Since we are arguing by induction, the demonstration that a term [tabs x T1 t2] belongs to [R_(T1->T2)] should involve applying the induction hypothesis to show that [t2] belongs to [R_(T2)]. But [R_(T2)] is defined to be a set of _closed_ terms, while [t2] may contain [x] free, so this does not make sense. This problem is resolved by using a standard trick to suitably generalize the induction hypothesis: instead of proving a statement involving a closed term, we generalize it to cover all closed _instances_ of an open term [t]. Informally, the statement of the lemma will look like this: If [x1:T1,..xn:Tn |- t : T] and [v1,...,vn] are values such that [R T1 v1], [R T2 v2], ..., [R Tn vn], then [R T ([x1:=v1][x2:=v2]...[xn:=vn]t)]. The proof will proceed by induction on the typing derivation [x1:T1,..xn:Tn |- t : T]; the most interesting case will be the one for abstraction. *) (* ###################################################################### *) (** *** Multisubstitutions, multi-extensions, and instantiations *) (** However, before we can proceed to formalize the statement and proof of the lemma, we'll need to build some (rather tedious) machinery to deal with the fact that we are performing _multiple_ substitutions on term [t] and _multiple_ extensions of the typing context. In particular, we must be precise about the order in which the substitutions occur and how they act on each other. Often these details are simply elided in informal paper proofs, but of course Coq won't let us do that. Since here we are substituting closed terms, we don't need to worry about how one substitution might affect the term put in place by another. But we still do need to worry about the _order_ of substitutions, because it is quite possible for the same identifier to appear multiple times among the [x1,...xn] with different associated [vi] and [Ti]. To make everything precise, we will assume that environments are extended from left to right, and multiple substitutions are performed from right to left. To see that this is consistent, suppose we have an environment written as [...,y:bool,...,y:nat,...] and a corresponding term substitution written as [...[y:=(tbool true)]...[y:=(tnat 3)]...t]. Since environments are extended from left to right, the binding [y:nat] hides the binding [y:bool]; since substitutions are performed right to left, we do the substitution [y:=(tnat 3)] first, so that the substitution [y:=(tbool true)] has no effect. Substitution thus correctly preserves the type of the term. With these points in mind, the following definitions should make sense. A _multisubstitution_ is the result of applying a list of substitutions, which we call an _environment_. *) Definition env := list (id * tm). Fixpoint msubst (ss:env) (t:tm) {struct ss} : tm := match ss with | nil => t | ((x,s)::ss') => msubst ss' ([x:=s]t) end. (** We need similar machinery to talk about repeated extension of a typing context using a list of (identifier, type) pairs, which we call a _type assignment_. *) Definition tass := list (id * ty). Fixpoint mextend (Gamma : context) (xts : tass) := match xts with | nil => Gamma | ((x,v)::xts') => extend (mextend Gamma xts') x v end. (** We will need some simple operations that work uniformly on environments and type assigments *) Fixpoint lookup {X:Set} (k : id) (l : list (id * X)) {struct l} : option X := match l with | nil => None | (j,x) :: l' => if eq_id_dec j k then Some x else lookup k l' end. Fixpoint drop {X:Set} (n:id) (nxs:list (id * X)) {struct nxs} : list (id * X) := match nxs with | nil => nil | ((n',x)::nxs') => if eq_id_dec n' n then drop n nxs' else (n',x)::(drop n nxs') end. (** An _instantiation_ combines a type assignment and a value environment with the same domains, where corresponding elements are in R *) Inductive instantiation : tass -> env -> Prop := | V_nil : instantiation nil nil | V_cons : forall x T v c e, value v -> R T v -> instantiation c e -> instantiation ((x,T)::c) ((x,v)::e). (** We now proceed to prove various properties of these definitions. *) (* ###################################################################### *) (** *** More Substitution Facts *) (** First we need some additional lemmas on (ordinary) substitution. *) Lemma vacuous_substitution : forall t x, ~ appears_free_in x t -> forall t', [x:=t']t = t. Proof with eauto. (* FILL IN HERE *) Admitted. Lemma subst_closed: forall t, closed t -> forall x t', [x:=t']t = t. Proof. intros. apply vacuous_substitution. apply H. Qed. Lemma subst_not_afi : forall t x v, closed v -> ~ appears_free_in x ([x:=v]t). Proof with eauto. (* rather slow this way *) unfold closed, not. t_cases (induction t) Case; intros x v P A; simpl in A. Case "tvar". destruct (eq_id_dec x i)... inversion A; subst. auto. Case "tapp". inversion A; subst... Case "tabs". destruct (eq_id_dec x i)... inversion A; subst... inversion A; subst... Case "tpair". inversion A; subst... Case "tfst". inversion A; subst... Case "tsnd". inversion A; subst... Case "ttrue". inversion A. Case "tfalse". inversion A. Case "tif". inversion A; subst... Qed. Lemma duplicate_subst : forall t' x t v, closed v -> [x:=t]([x:=v]t') = [x:=v]t'. Proof. intros. eapply vacuous_substitution. apply subst_not_afi. auto. Qed. Lemma swap_subst : forall t x x1 v v1, x <> x1 -> closed v -> closed v1 -> [x1:=v1]([x:=v]t) = [x:=v]([x1:=v1]t). Proof with eauto. t_cases (induction t) Case; intros; simpl. Case "tvar". destruct (eq_id_dec x i); destruct (eq_id_dec x1 i). subst. apply ex_falso_quodlibet... subst. simpl. rewrite eq_id. apply subst_closed... subst. simpl. rewrite eq_id. rewrite subst_closed... simpl. rewrite neq_id... rewrite neq_id... (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Properties of multi-substitutions *) Lemma msubst_closed: forall t, closed t -> forall ss, msubst ss t = t. Proof. induction ss. reflexivity. destruct a. simpl. rewrite subst_closed; assumption. Qed. (** Closed environments are those that contain only closed terms. *) Fixpoint closed_env (env:env) {struct env} := match env with | nil => True | (x,t)::env' => closed t /\ closed_env env' end. (** Next come a series of lemmas charcterizing how [msubst] of closed terms distributes over [subst] and over each term form *) Lemma subst_msubst: forall env x v t, closed v -> closed_env env -> msubst env ([x:=v]t) = [x:=v](msubst (drop x env) t). Proof. induction env0; intros. auto. destruct a. simpl. inversion H0. fold closed_env in H2. destruct (eq_id_dec i x). subst. rewrite duplicate_subst; auto. simpl. rewrite swap_subst; eauto. Qed. Lemma msubst_var: forall ss x, closed_env ss -> msubst ss (tvar x) = match lookup x ss with | Some t => t | None => tvar x end. Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x). apply msubst_closed. inversion H; auto. apply IHss. inversion H; auto. Qed. Lemma msubst_abs: forall ss x T t, msubst ss (tabs x T t) = tabs x T (msubst (drop x ss) t). Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x); simpl; auto. Qed. Lemma msubst_app : forall ss t1 t2, msubst ss (tapp t1 t2) = tapp (msubst ss t1) (msubst ss t2). Proof. induction ss; intros. reflexivity. destruct a. simpl. rewrite <- IHss. auto. Qed. (** You'll need similar functions for the other term constructors. *) (* FILL IN HERE *) (* ###################################################################### *) (** *** Properties of multi-extensions *) (** We need to connect the behavior of type assignments with that of their corresponding contexts. *) Lemma mextend_lookup : forall (c : tass) (x:id), lookup x c = (mextend empty c) x. Proof. induction c; intros. auto. destruct a. unfold lookup, mextend, extend. destruct (eq_id_dec i x); auto. Qed. Lemma mextend_drop : forall (c: tass) Gamma x x', mextend Gamma (drop x c) x' = if eq_id_dec x x' then Gamma x' else mextend Gamma c x'. induction c; intros. destruct (eq_id_dec x x'); auto. destruct a. simpl. destruct (eq_id_dec i x). subst. rewrite IHc. destruct (eq_id_dec x x'). auto. unfold extend. rewrite neq_id; auto. simpl. unfold extend. destruct (eq_id_dec i x'). subst. destruct (eq_id_dec x x'). subst. exfalso. auto. auto. auto. Qed. (* ###################################################################### *) (** *** Properties of Instantiations *) (** These are strightforward. *) Lemma instantiation_domains_match: forall {c} {e}, instantiation c e -> forall {x} {T}, lookup x c = Some T -> exists t, lookup x e = Some t. Proof. intros c e V. induction V; intros x0 T0 C. solve by inversion . simpl in *. destruct (eq_id_dec x x0); eauto. Qed. Lemma instantiation_env_closed : forall c e, instantiation c e -> closed_env e. Proof. intros c e V; induction V; intros. econstructor. unfold closed_env. fold closed_env. split. eapply typable_empty__closed. eapply R_typable_empty. eauto. auto. Qed. Lemma instantiation_R : forall c e, instantiation c e -> forall x t T, lookup x c = Some T -> lookup x e = Some t -> R T t. Proof. intros c e V. induction V; intros x' t' T' G E. solve by inversion. unfold lookup in *. destruct (eq_id_dec x x'). inversion G; inversion E; subst. auto. eauto. Qed. Lemma instantiation_drop : forall c env, instantiation c env -> forall x, instantiation (drop x c) (drop x env). Proof. intros c e V. induction V. intros. simpl. constructor. intros. unfold drop. destruct (eq_id_dec x x0); auto. constructor; eauto. Qed. (* ###################################################################### *) (** *** Congruence lemmas on multistep *) (** We'll need just a few of these; add them as the demand arises. *) Lemma multistep_App2 : forall v t t', value v -> (t ==>* t') -> (tapp v t) ==>* (tapp v t'). Proof. intros v t t' V STM. induction STM. apply multi_refl. eapply multi_step. apply ST_App2; eauto. auto. Qed. (* FILL IN HERE *) (* ###################################################################### *) (** *** The R Lemma. *) (** We finally put everything together. The key lemma about preservation of typing under substitution can be lifted to multi-substitutions: *) Lemma msubst_preserves_typing : forall c e, instantiation c e -> forall Gamma t S, has_type (mextend Gamma c) t S -> has_type Gamma (msubst e t) S. Proof. induction 1; intros. simpl in H. simpl. auto. simpl in H2. simpl. apply IHinstantiation. eapply substitution_preserves_typing; eauto. apply (R_typable_empty H0). Qed. (** And at long last, the main lemma. *) Lemma msubst_R : forall c env t T, has_type (mextend empty c) t T -> instantiation c env -> R T (msubst env t). Proof. intros c env0 t T HT V. generalize dependent env0. (* We need to generalize the hypothesis a bit before setting up the induction. *) remember (mextend empty c) as Gamma. assert (forall x, Gamma x = lookup x c). intros. rewrite HeqGamma. rewrite mextend_lookup. auto. clear HeqGamma. generalize dependent c. has_type_cases (induction HT) Case; intros. Case "T_Var". rewrite H0 in H. destruct (instantiation_domains_match V H) as [t P]. eapply instantiation_R; eauto. rewrite msubst_var. rewrite P. auto. eapply instantiation_env_closed; eauto. Case "T_Abs". rewrite msubst_abs. (* We'll need variants of the following fact several times, so its simplest to establish it just once. *) assert (WT: has_type empty (tabs x T11 (msubst (drop x env0) t12)) (TArrow T11 T12)). eapply T_Abs. eapply msubst_preserves_typing. eapply instantiation_drop; eauto. eapply context_invariance. apply HT. intros. unfold extend. rewrite mextend_drop. destruct (eq_id_dec x x0). auto. rewrite H. clear - c n. induction c. simpl. rewrite neq_id; auto. simpl. destruct a. unfold extend. destruct (eq_id_dec i x0); auto. unfold R. fold R. split. auto. split. apply value_halts. apply v_abs. intros. destruct (R_halts H0) as [v [P Q]]. pose proof (multistep_preserves_R _ _ _ P H0). apply multistep_preserves_R' with (msubst ((x,v)::env0) t12). eapply T_App. eauto. apply R_typable_empty; auto. eapply multi_trans. eapply multistep_App2; eauto. eapply multi_R. simpl. rewrite subst_msubst. eapply ST_AppAbs; eauto. eapply typable_empty__closed. apply (R_typable_empty H1). eapply instantiation_env_closed; eauto. eapply (IHHT ((x,T11)::c)). intros. unfold extend, lookup. destruct (eq_id_dec x x0); auto. constructor; auto. Case "T_App". rewrite msubst_app. destruct (IHHT1 c H env0 V) as [_ [_ P1]]. pose proof (IHHT2 c H env0 V) as P2. fold R in P1. auto. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Normalization Theorem *) Theorem normalization : forall t T, has_type empty t T -> halts t. Proof. intros. replace t with (msubst nil t) by reflexivity. apply (@R_halts T). apply (msubst_R nil); eauto. eapply V_nil. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * Norm: Normalization of STLC *) (* Chapter maintained by Andrew Tolmach *) (* (Based on TAPL Ch. 12.) *) Require Export Smallstep. Hint Constructors multi. (** (This chapter is optional.) In this chapter, we consider another fundamental theoretical property of the simply typed lambda-calculus: the fact that the evaluation of a well-typed program is guaranteed to halt in a finite number of steps---i.e., every well-typed term is _normalizable_. Unlike the type-safety properties we have considered so far, the normalization property does not extend to full-blown programming languages, because these languages nearly always extend the simply typed lambda-calculus with constructs, such as general recursion (as we discussed in the MoreStlc chapter) or recursive types, that can be used to write nonterminating programs. However, the issue of normalization reappears at the level of _types_ when we consider the metatheory of polymorphic versions of the lambda calculus such as F_omega: in this system, the language of types effectively contains a copy of the simply typed lambda-calculus, and the termination of the typechecking algorithm will hinge on the fact that a ``normalization'' operation on type expressions is guaranteed to terminate. Another reason for studying normalization proofs is that they are some of the most beautiful---and mind-blowing---mathematics to be found in the type theory literature, often (as here) involving the fundamental proof technique of _logical relations_. The calculus we shall consider here is the simply typed lambda-calculus over a single base type [bool] and with pairs. We'll give full details of the development for the basic lambda-calculus terms treating [bool] as an uninterpreted base type, and leave the extension to the boolean operators and pairs to the reader. Even for the base calculus, normalization is not entirely trivial to prove, since each reduction of a term can duplicate redexes in subterms. *) (** **** Exercise: 1 star *) (** Where do we fail if we attempt to prove normalization by a straightforward induction on the size of a well-typed term? *) (* FILL IN HERE *) (** [] *) (* ###################################################################### *) (** * Language *) (** We begin by repeating the relevant language definition, which is similar to those in the MoreStlc chapter, and supporting results including type preservation and step determinism. (We won't need progress.) You may just wish to skip down to the Normalization section... *) (* ###################################################################### *) (** *** Syntax and Operational Semantics *) Inductive ty : Type := | TBool : ty | TArrow : ty -> ty -> ty | TProd : ty -> ty -> ty . Tactic Notation "T_cases" tactic(first) ident(c) := first; [ Case_aux c "TBool" | Case_aux c "TArrow" | Case_aux c "TProd" ]. Inductive tm : Type := (* pure STLC *) | tvar : id -> tm | tapp : tm -> tm -> tm | tabs : id -> ty -> tm -> tm (* pairs *) | tpair : tm -> tm -> tm | tfst : tm -> tm | tsnd : tm -> tm (* booleans *) | ttrue : tm | tfalse : tm | tif : tm -> tm -> tm -> tm. (* i.e., [if t0 then t1 else t2] *) Tactic Notation "t_cases" tactic(first) ident(c) := first; [ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs" | Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd" | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ]. (* ###################################################################### *) (** *** 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) | tpair t1 t2 => tpair (subst x s t1) (subst x s t2) | tfst t1 => tfst (subst x s t1) | tsnd t1 => tsnd (subst x s t1) | ttrue => ttrue | tfalse => tfalse | tif t0 t1 t2 => tif (subst x s t0) (subst x s t1) (subst x s t2) end. Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20). (* ###################################################################### *) (** *** Reduction *) Inductive value : tm -> Prop := | v_abs : forall x T11 t12, value (tabs x T11 t12) | v_pair : forall v1 v2, value v1 -> value v2 -> value (tpair v1 v2) | v_true : value ttrue | v_false : value tfalse . Hint Constructors value. Reserved Notation "t1 '==>' t2" (at level 40). Inductive step : tm -> tm -> Prop := | ST_AppAbs : forall x T11 t12 v2, value v2 -> (tapp (tabs x T11 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') (* pairs *) | ST_Pair1 : forall t1 t1' t2, t1 ==> t1' -> (tpair t1 t2) ==> (tpair t1' t2) | ST_Pair2 : forall v1 t2 t2', value v1 -> t2 ==> t2' -> (tpair v1 t2) ==> (tpair v1 t2') | ST_Fst : forall t1 t1', t1 ==> t1' -> (tfst t1) ==> (tfst t1') | ST_FstPair : forall v1 v2, value v1 -> value v2 -> (tfst (tpair v1 v2)) ==> v1 | ST_Snd : forall t1 t1', t1 ==> t1' -> (tsnd t1) ==> (tsnd t1') | ST_SndPair : forall v1 v2, value v1 -> value v2 -> (tsnd (tpair v1 v2)) ==> v2 (* booleans *) | ST_IfTrue : forall t1 t2, (tif ttrue t1 t2) ==> t1 | ST_IfFalse : forall t1 t2, (tif tfalse t1 t2) ==> t2 | ST_If : forall t0 t0' t1 t2, t0 ==> t0' -> (tif t0 t1 t2) ==> (tif t0' t1 t2) 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_Pair1" | Case_aux c "ST_Pair2" | Case_aux c "ST_Fst" | Case_aux c "ST_FstPair" | Case_aux c "ST_Snd" | Case_aux c "ST_SndPair" | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ]. Notation multistep := (multi step). Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40). Hint Constructors step. Notation step_normal_form := (normal_form step). Lemma value__normal : forall t, value t -> step_normal_form t. Proof with eauto. intros t H; induction H; intros [t' ST]; inversion ST... Qed. (* ###################################################################### *) (** *** Typing *) Definition context := partial_map ty. Inductive has_type : context -> tm -> ty -> Prop := (* Typing rules for proper terms *) | T_Var : forall Gamma x T, Gamma x = Some T -> has_type Gamma (tvar x) T | T_Abs : forall Gamma x T11 T12 t12, 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 (* pairs *) | T_Pair : forall Gamma t1 t2 T1 T2, has_type Gamma t1 T1 -> has_type Gamma t2 T2 -> has_type Gamma (tpair t1 t2) (TProd T1 T2) | T_Fst : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tfst t) T1 | T_Snd : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tsnd t) T2 (* booleans *) | T_True : forall Gamma, has_type Gamma ttrue TBool | T_False : forall Gamma, has_type Gamma tfalse TBool | T_If : forall Gamma t0 t1 t2 T, has_type Gamma t0 TBool -> has_type Gamma t1 T -> has_type Gamma t2 T -> has_type Gamma (tif t0 t1 t2) 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_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd" | Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If" ]. Hint Extern 2 (has_type _ (tapp _ _) _) => eapply T_App; auto. Hint Extern 2 (_ = _) => compute; reflexivity. (* ###################################################################### *) (** *** 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) (* pairs *) | afi_pair1 : forall x t1 t2, appears_free_in x t1 -> appears_free_in x (tpair t1 t2) | afi_pair2 : forall x t1 t2, appears_free_in x t2 -> appears_free_in x (tpair t1 t2) | afi_fst : forall x t, appears_free_in x t -> appears_free_in x (tfst t) | afi_snd : forall x t, appears_free_in x t -> appears_free_in x (tsnd t) (* booleans *) | afi_if0 : forall x t0 t1 t2, appears_free_in x t0 -> appears_free_in x (tif t0 t1 t2) | afi_if1 : forall x t0 t1 t2, appears_free_in x t1 -> appears_free_in x (tif t0 t1 t2) | afi_if2 : forall x t0 t1 t2, appears_free_in x t2 -> appears_free_in x (tif t0 t1 t2) . Hint Constructors appears_free_in. Definition closed (t:tm) := forall x, ~ appears_free_in x t. 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 y Hafi. unfold extend. destruct (eq_id_dec x y)... Case "T_Pair". apply T_Pair... Case "T_If". eapply T_If... 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; inversion Hafi; subst... Case "T_Abs". destruct IHHtyp as [T' Hctx]... exists T'. unfold extend in Hctx. rewrite neq_id in Hctx... Qed. Corollary typable_empty__closed : forall t T, has_type empty t T -> closed t. Proof. intros. unfold closed. intros x H1. destruct (free_in_context _ _ _ _ H1 H) as [T' C]. inversion C. 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. (* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then Gamma |- ([x:=v]t) S. *) intros Gamma x U v t S Htypt Htypv. generalize dependent Gamma. generalize dependent S. (* Proof: By induction on the term t. Most cases follow directly from the IH, with the exception of tvar and tabs. The former aren't automatic because we must reason about how the variables interact. *) t_cases (induction t) Case; intros S Gamma Htypt; simpl; inversion Htypt; subst... Case "tvar". simpl. rename i into y. (* If t = y, we know that [empty |- v : U] and [Gamma,x:U |- y : S] and, by inversion, [extend Gamma x U y = Some S]. We want to show that [Gamma |- [x:=v]y : S]. There are two cases to consider: either [x=y] or [x<>y]. *) destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then we know that [U = S], and that [[x:=v]y = v]. So what we really must show is that if [empty |- v : U] then [Gamma |- v : U]. We have already proven a more general version of this theorem, called context invariance. *) subst. unfold extend in H1. rewrite eq_id in H1. inversion H1; subst. clear H1. eapply context_invariance... intros x Hcontra. destruct (free_in_context _ _ S empty Hcontra) as [T' HT']... inversion HT'. SCase "x<>y". (* If [x <> y], then [Gamma y = Some S] and the substitution has no effect. We can show that [Gamma |- y : S] by [T_Var]. *) apply T_Var... unfold extend in H1. rewrite neq_id in H1... Case "tabs". rename i into y. rename t into T11. (* If [t = tabs y T11 t0], then we know that [Gamma,x:U |- tabs y T11 t0 : T11->T12] [Gamma,x:U,y:T11 |- t0 : T12] [empty |- v : U] As our IH, we know that forall S Gamma, [Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 S]. We can calculate that [x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0) And we must show that [Gamma |- [x:=v]t : T11->T12]. We know we will do so using [T_Abs], so it remains to be shown that: [Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12] We consider two cases: [x = y] and [x <> y]. *) apply T_Abs... destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then the substitution has no effect. Context invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are equivalent. Since the former context shows that [t0 : T12], so does the latter. *) eapply context_invariance... subst. intros x Hafi. unfold extend. destruct (eq_id_dec y x)... SCase "x<>y". (* If [x <> y], then the IH and context invariance allow us to show that [Gamma,x:U,y:T11 |- t0 : T12] => [Gamma,y:T11,x:U |- t0 : T12] => [Gamma,y:T11 |- [x:=v]t0 : T12] *) apply IHt. eapply context_invariance... intros z Hafi. unfold extend. destruct (eq_id_dec y z)... subst. rewrite neq_id... 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. (* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *) remember (@empty ty) as Gamma. generalize dependent HeqGamma. generalize dependent t'. (* Proof: By induction on the given typing derivation. Many cases are contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *) has_type_cases (induction HT) Case; intros t' HeqGamma HE; subst; inversion HE; subst... Case "T_App". (* If the last rule used was [T_App], then [t = t1 t2], and three rules could have been used to show [t ==> t']: [ST_App1], [ST_App2], and [ST_AppAbs]. In the first two cases, the result follows directly from the IH. *) inversion HE; subst... SCase "ST_AppAbs". (* For the third case, suppose [t1 = tabs x T11 t12] and [t2 = v2]. We must show that [empty |- [x:=v2]t12 : T2]. We know by assumption that [empty |- tabs x T11 t12 : T1->T2] and by inversion [x:T1 |- t12 : T2] We have already proven that substitution_preserves_typing and [empty |- v2 : T1] by assumption, so we are done. *) apply substitution_preserves_typing with T1... inversion HT1... Case "T_Fst". inversion HT... Case "T_Snd". inversion HT... Qed. (** [] *) (* ###################################################################### *) (** *** Determinism *) Lemma step_deterministic : deterministic step. Proof with eauto. unfold deterministic. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** * Normalization *) (** Now for the actual normalization proof. Our goal is to prove that every well-typed term evaluates to a normal form. In fact, it turns out to be convenient to prove something slightly stronger, namely that every well-typed term evaluates to a _value_. This follows from the weaker property anyway via the Progress lemma (why?) but otherwise we don't need Progress, and we didn't bother re-proving it above. Here's the key definition: *) Definition halts (t:tm) : Prop := exists t', t ==>* t' /\ value t'. (** A trivial fact: *) Lemma value_halts : forall v, value v -> halts v. Proof. intros v H. unfold halts. exists v. split. apply multi_refl. assumption. Qed. (** The key issue in the normalization proof (as in many proofs by induction) is finding a strong enough induction hypothesis. To this end, we begin by defining, for each type [T], a set [R_T] of closed terms of type [T]. We will specify these sets using a relation [R] and write [R T t] when [t] is in [R_T]. (The sets [R_T] are sometimes called _saturated sets_ or _reducibility candidates_.) Here is the definition of [R] for the base language: - [R bool t] iff [t] is a closed term of type [bool] and [t] halts in a value - [R (T1 -> T2) t] iff [t] is a closed term of type [T1 -> T2] and [t] halts in a value _and_ for any term [s] such that [R T1 s], we have [R T2 (t s)]. *) (** This definition gives us the strengthened induction hypothesis that we need. Our primary goal is to show that all _programs_ ---i.e., all closed terms of base type---halt. But closed terms of base type can contain subterms of functional type, so we need to know something about these as well. Moreover, it is not enough to know that these subterms halt, because the application of a normalized function to a normalized argument involves a substitution, which may enable more evaluation steps. So we need a stronger condition for terms of functional type: not only should they halt themselves, but, when applied to halting arguments, they should yield halting results. The form of [R] is characteristic of the _logical relations_ proof technique. (Since we are just dealing with unary relations here, we could perhaps more properly say _logical predicates_.) If we want to prove some property [P] of all closed terms of type [A], we proceed by proving, by induction on types, that all terms of type [A] _possess_ property [P], all terms of type [A->A] _preserve_ property [P], all terms of type [(A->A)->(A->A)] _preserve the property of preserving_ property [P], and so on. We do this by defining a family of predicates, indexed by types. For the base type [A], the predicate is just [P]. For functional types, it says that the function should map values satisfying the predicate at the input type to values satisfying the predicate at the output type. When we come to formalize the definition of [R] in Coq, we hit a problem. The most obvious formulation would be as a parameterized Inductive proposition like this: Inductive R : ty -> tm -> Prop := | R_bool : forall b t, has_type empty t TBool -> halts t -> R TBool t | R_arrow : forall T1 T2 t, has_type empty t (TArrow T1 T2) -> halts t -> (forall s, R T1 s -> R T2 (tapp t s)) -> R (TArrow T1 T2) t. Unfortunately, Coq rejects this definition because it violates the _strict positivity requirement_ for inductive definitions, which says that the type being defined must not occur to the left of an arrow in the type of a constructor argument. Here, it is the third argument to [R_arrow], namely [(forall s, R T1 s -> R TS (tapp t s))], and specifically the [R T1 s] part, that violates this rule. (The outermost arrows separating the constructor arguments don't count when applying this rule; otherwise we could never have genuinely inductive predicates at all!) The reason for the rule is that types defined with non-positive recursion can be used to build non-terminating functions, which as we know would be a disaster for Coq's logical soundness. Even though the relation we want in this case might be perfectly innocent, Coq still rejects it because it fails the positivity test. Fortunately, it turns out that we _can_ define [R] using a [Fixpoint]: *) Fixpoint R (T:ty) (t:tm) {struct T} : Prop := has_type empty t T /\ halts t /\ (match T with | TBool => True | TArrow T1 T2 => (forall s, R T1 s -> R T2 (tapp t s)) (* FILL IN HERE *) | TProd T1 T2 => False (* ... and delete this line *) end). (** As immediate consequences of this definition, we have that every element of every set [R_T] halts in a value and is closed with type [t] :*) Lemma R_halts : forall {T} {t}, R T t -> halts t. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. Lemma R_typable_empty : forall {T} {t}, R T t -> has_type empty t T. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. (** Now we proceed to show the main result, which is that every well-typed term of type [T] is an element of [R_T]. Together with [R_halts], that will show that every well-typed term halts in a value. *) (* ###################################################################### *) (** ** Membership in [R_T] is invariant under evaluation *) (** We start with a preliminary lemma that shows a kind of strong preservation property, namely that membership in [R_T] is _invariant_ under evaluation. We will need this property in both directions, i.e. both to show that a term in [R_T] stays in [R_T] when it takes a forward step, and to show that any term that ends up in [R_T] after a step must have been in [R_T] to begin with. First of all, an easy preliminary lemma. Note that in the forward direction the proof depends on the fact that our language is determinstic. This lemma might still be true for non-deterministic languages, but the proof would be harder! *) Lemma step_preserves_halting : forall t t', (t ==> t') -> (halts t <-> halts t'). Proof. intros t t' ST. unfold halts. split. Case "->". intros [t'' [STM V]]. inversion STM; subst. apply ex_falso_quodlibet. apply value__normal in V. unfold normal_form in V. apply V. exists t'. auto. rewrite (step_deterministic _ _ _ ST H). exists t''. split; assumption. Case "<-". intros [t'0 [STM V]]. exists t'0. split; eauto. Qed. (** Now the main lemma, which comes in two parts, one for each direction. Each proceeds by induction on the structure of the type [T]. In fact, this is where we make fundamental use of the structure of types. One requirement for staying in [R_T] is to stay in type [T]. In the forward direction, we get this from ordinary type Preservation. *) Lemma step_preserves_R : forall T t t', (t ==> t') -> R T t -> R T t'. Proof. induction T; intros t t' E Rt; unfold R; fold R; unfold R in Rt; fold R in Rt; destruct Rt as [typable_empty_t [halts_t RRt]]. (* TBool *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. auto. (* TArrow *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. intros. eapply IHT2. apply ST_App1. apply E. apply RRt; auto. (* FILL IN HERE *) Admitted. (** The generalization to multiple steps is trivial: *) Lemma multistep_preserves_R : forall T t t', (t ==>* t') -> R T t -> R T t'. Proof. intros T t t' STM; induction STM; intros. assumption. apply IHSTM. eapply step_preserves_R. apply H. assumption. Qed. (** In the reverse direction, we must add the fact that [t] has type [T] before stepping as an additional hypothesis. *) Lemma step_preserves_R' : forall T t t', has_type empty t T -> (t ==> t') -> R T t' -> R T t. Proof. (* FILL IN HERE *) Admitted. Lemma multistep_preserves_R' : forall T t t', has_type empty t T -> (t ==>* t') -> R T t' -> R T t. Proof. intros T t t' HT STM. induction STM; intros. assumption. eapply step_preserves_R'. assumption. apply H. apply IHSTM. eapply preservation; eauto. auto. Qed. (* ###################################################################### *) (** ** Closed instances of terms of type [T] belong to [R_T] *) (** Now we proceed to show that every term of type [T] belongs to [R_T]. Here, the induction will be on typing derivations (it would be surprising to see a proof about well-typed terms that did not somewhere involve induction on typing derivations!). The only technical difficulty here is in dealing with the abstraction case. Since we are arguing by induction, the demonstration that a term [tabs x T1 t2] belongs to [R_(T1->T2)] should involve applying the induction hypothesis to show that [t2] belongs to [R_(T2)]. But [R_(T2)] is defined to be a set of _closed_ terms, while [t2] may contain [x] free, so this does not make sense. This problem is resolved by using a standard trick to suitably generalize the induction hypothesis: instead of proving a statement involving a closed term, we generalize it to cover all closed _instances_ of an open term [t]. Informally, the statement of the lemma will look like this: If [x1:T1,..xn:Tn |- t : T] and [v1,...,vn] are values such that [R T1 v1], [R T2 v2], ..., [R Tn vn], then [R T ([x1:=v1][x2:=v2]...[xn:=vn]t)]. The proof will proceed by induction on the typing derivation [x1:T1,..xn:Tn |- t : T]; the most interesting case will be the one for abstraction. *) (* ###################################################################### *) (** *** Multisubstitutions, multi-extensions, and instantiations *) (** However, before we can proceed to formalize the statement and proof of the lemma, we'll need to build some (rather tedious) machinery to deal with the fact that we are performing _multiple_ substitutions on term [t] and _multiple_ extensions of the typing context. In particular, we must be precise about the order in which the substitutions occur and how they act on each other. Often these details are simply elided in informal paper proofs, but of course Coq won't let us do that. Since here we are substituting closed terms, we don't need to worry about how one substitution might affect the term put in place by another. But we still do need to worry about the _order_ of substitutions, because it is quite possible for the same identifier to appear multiple times among the [x1,...xn] with different associated [vi] and [Ti]. To make everything precise, we will assume that environments are extended from left to right, and multiple substitutions are performed from right to left. To see that this is consistent, suppose we have an environment written as [...,y:bool,...,y:nat,...] and a corresponding term substitution written as [...[y:=(tbool true)]...[y:=(tnat 3)]...t]. Since environments are extended from left to right, the binding [y:nat] hides the binding [y:bool]; since substitutions are performed right to left, we do the substitution [y:=(tnat 3)] first, so that the substitution [y:=(tbool true)] has no effect. Substitution thus correctly preserves the type of the term. With these points in mind, the following definitions should make sense. A _multisubstitution_ is the result of applying a list of substitutions, which we call an _environment_. *) Definition env := list (id * tm). Fixpoint msubst (ss:env) (t:tm) {struct ss} : tm := match ss with | nil => t | ((x,s)::ss') => msubst ss' ([x:=s]t) end. (** We need similar machinery to talk about repeated extension of a typing context using a list of (identifier, type) pairs, which we call a _type assignment_. *) Definition tass := list (id * ty). Fixpoint mextend (Gamma : context) (xts : tass) := match xts with | nil => Gamma | ((x,v)::xts') => extend (mextend Gamma xts') x v end. (** We will need some simple operations that work uniformly on environments and type assigments *) Fixpoint lookup {X:Set} (k : id) (l : list (id * X)) {struct l} : option X := match l with | nil => None | (j,x) :: l' => if eq_id_dec j k then Some x else lookup k l' end. Fixpoint drop {X:Set} (n:id) (nxs:list (id * X)) {struct nxs} : list (id * X) := match nxs with | nil => nil | ((n',x)::nxs') => if eq_id_dec n' n then drop n nxs' else (n',x)::(drop n nxs') end. (** An _instantiation_ combines a type assignment and a value environment with the same domains, where corresponding elements are in R *) Inductive instantiation : tass -> env -> Prop := | V_nil : instantiation nil nil | V_cons : forall x T v c e, value v -> R T v -> instantiation c e -> instantiation ((x,T)::c) ((x,v)::e). (** We now proceed to prove various properties of these definitions. *) (* ###################################################################### *) (** *** More Substitution Facts *) (** First we need some additional lemmas on (ordinary) substitution. *) Lemma vacuous_substitution : forall t x, ~ appears_free_in x t -> forall t', [x:=t']t = t. Proof with eauto. (* FILL IN HERE *) Admitted. Lemma subst_closed: forall t, closed t -> forall x t', [x:=t']t = t. Proof. intros. apply vacuous_substitution. apply H. Qed. Lemma subst_not_afi : forall t x v, closed v -> ~ appears_free_in x ([x:=v]t). Proof with eauto. (* rather slow this way *) unfold closed, not. t_cases (induction t) Case; intros x v P A; simpl in A. Case "tvar". destruct (eq_id_dec x i)... inversion A; subst. auto. Case "tapp". inversion A; subst... Case "tabs". destruct (eq_id_dec x i)... inversion A; subst... inversion A; subst... Case "tpair". inversion A; subst... Case "tfst". inversion A; subst... Case "tsnd". inversion A; subst... Case "ttrue". inversion A. Case "tfalse". inversion A. Case "tif". inversion A; subst... Qed. Lemma duplicate_subst : forall t' x t v, closed v -> [x:=t]([x:=v]t') = [x:=v]t'. Proof. intros. eapply vacuous_substitution. apply subst_not_afi. auto. Qed. Lemma swap_subst : forall t x x1 v v1, x <> x1 -> closed v -> closed v1 -> [x1:=v1]([x:=v]t) = [x:=v]([x1:=v1]t). Proof with eauto. t_cases (induction t) Case; intros; simpl. Case "tvar". destruct (eq_id_dec x i); destruct (eq_id_dec x1 i). subst. apply ex_falso_quodlibet... subst. simpl. rewrite eq_id. apply subst_closed... subst. simpl. rewrite eq_id. rewrite subst_closed... simpl. rewrite neq_id... rewrite neq_id... (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Properties of multi-substitutions *) Lemma msubst_closed: forall t, closed t -> forall ss, msubst ss t = t. Proof. induction ss. reflexivity. destruct a. simpl. rewrite subst_closed; assumption. Qed. (** Closed environments are those that contain only closed terms. *) Fixpoint closed_env (env:env) {struct env} := match env with | nil => True | (x,t)::env' => closed t /\ closed_env env' end. (** Next come a series of lemmas charcterizing how [msubst] of closed terms distributes over [subst] and over each term form *) Lemma subst_msubst: forall env x v t, closed v -> closed_env env -> msubst env ([x:=v]t) = [x:=v](msubst (drop x env) t). Proof. induction env0; intros. auto. destruct a. simpl. inversion H0. fold closed_env in H2. destruct (eq_id_dec i x). subst. rewrite duplicate_subst; auto. simpl. rewrite swap_subst; eauto. Qed. Lemma msubst_var: forall ss x, closed_env ss -> msubst ss (tvar x) = match lookup x ss with | Some t => t | None => tvar x end. Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x). apply msubst_closed. inversion H; auto. apply IHss. inversion H; auto. Qed. Lemma msubst_abs: forall ss x T t, msubst ss (tabs x T t) = tabs x T (msubst (drop x ss) t). Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x); simpl; auto. Qed. Lemma msubst_app : forall ss t1 t2, msubst ss (tapp t1 t2) = tapp (msubst ss t1) (msubst ss t2). Proof. induction ss; intros. reflexivity. destruct a. simpl. rewrite <- IHss. auto. Qed. (** You'll need similar functions for the other term constructors. *) (* FILL IN HERE *) (* ###################################################################### *) (** *** Properties of multi-extensions *) (** We need to connect the behavior of type assignments with that of their corresponding contexts. *) Lemma mextend_lookup : forall (c : tass) (x:id), lookup x c = (mextend empty c) x. Proof. induction c; intros. auto. destruct a. unfold lookup, mextend, extend. destruct (eq_id_dec i x); auto. Qed. Lemma mextend_drop : forall (c: tass) Gamma x x', mextend Gamma (drop x c) x' = if eq_id_dec x x' then Gamma x' else mextend Gamma c x'. induction c; intros. destruct (eq_id_dec x x'); auto. destruct a. simpl. destruct (eq_id_dec i x). subst. rewrite IHc. destruct (eq_id_dec x x'). auto. unfold extend. rewrite neq_id; auto. simpl. unfold extend. destruct (eq_id_dec i x'). subst. destruct (eq_id_dec x x'). subst. exfalso. auto. auto. auto. Qed. (* ###################################################################### *) (** *** Properties of Instantiations *) (** These are strightforward. *) Lemma instantiation_domains_match: forall {c} {e}, instantiation c e -> forall {x} {T}, lookup x c = Some T -> exists t, lookup x e = Some t. Proof. intros c e V. induction V; intros x0 T0 C. solve by inversion . simpl in *. destruct (eq_id_dec x x0); eauto. Qed. Lemma instantiation_env_closed : forall c e, instantiation c e -> closed_env e. Proof. intros c e V; induction V; intros. econstructor. unfold closed_env. fold closed_env. split. eapply typable_empty__closed. eapply R_typable_empty. eauto. auto. Qed. Lemma instantiation_R : forall c e, instantiation c e -> forall x t T, lookup x c = Some T -> lookup x e = Some t -> R T t. Proof. intros c e V. induction V; intros x' t' T' G E. solve by inversion. unfold lookup in *. destruct (eq_id_dec x x'). inversion G; inversion E; subst. auto. eauto. Qed. Lemma instantiation_drop : forall c env, instantiation c env -> forall x, instantiation (drop x c) (drop x env). Proof. intros c e V. induction V. intros. simpl. constructor. intros. unfold drop. destruct (eq_id_dec x x0); auto. constructor; eauto. Qed. (* ###################################################################### *) (** *** Congruence lemmas on multistep *) (** We'll need just a few of these; add them as the demand arises. *) Lemma multistep_App2 : forall v t t', value v -> (t ==>* t') -> (tapp v t) ==>* (tapp v t'). Proof. intros v t t' V STM. induction STM. apply multi_refl. eapply multi_step. apply ST_App2; eauto. auto. Qed. (* FILL IN HERE *) (* ###################################################################### *) (** *** The R Lemma. *) (** We finally put everything together. The key lemma about preservation of typing under substitution can be lifted to multi-substitutions: *) Lemma msubst_preserves_typing : forall c e, instantiation c e -> forall Gamma t S, has_type (mextend Gamma c) t S -> has_type Gamma (msubst e t) S. Proof. induction 1; intros. simpl in H. simpl. auto. simpl in H2. simpl. apply IHinstantiation. eapply substitution_preserves_typing; eauto. apply (R_typable_empty H0). Qed. (** And at long last, the main lemma. *) Lemma msubst_R : forall c env t T, has_type (mextend empty c) t T -> instantiation c env -> R T (msubst env t). Proof. intros c env0 t T HT V. generalize dependent env0. (* We need to generalize the hypothesis a bit before setting up the induction. *) remember (mextend empty c) as Gamma. assert (forall x, Gamma x = lookup x c). intros. rewrite HeqGamma. rewrite mextend_lookup. auto. clear HeqGamma. generalize dependent c. has_type_cases (induction HT) Case; intros. Case "T_Var". rewrite H0 in H. destruct (instantiation_domains_match V H) as [t P]. eapply instantiation_R; eauto. rewrite msubst_var. rewrite P. auto. eapply instantiation_env_closed; eauto. Case "T_Abs". rewrite msubst_abs. (* We'll need variants of the following fact several times, so its simplest to establish it just once. *) assert (WT: has_type empty (tabs x T11 (msubst (drop x env0) t12)) (TArrow T11 T12)). eapply T_Abs. eapply msubst_preserves_typing. eapply instantiation_drop; eauto. eapply context_invariance. apply HT. intros. unfold extend. rewrite mextend_drop. destruct (eq_id_dec x x0). auto. rewrite H. clear - c n. induction c. simpl. rewrite neq_id; auto. simpl. destruct a. unfold extend. destruct (eq_id_dec i x0); auto. unfold R. fold R. split. auto. split. apply value_halts. apply v_abs. intros. destruct (R_halts H0) as [v [P Q]]. pose proof (multistep_preserves_R _ _ _ P H0). apply multistep_preserves_R' with (msubst ((x,v)::env0) t12). eapply T_App. eauto. apply R_typable_empty; auto. eapply multi_trans. eapply multistep_App2; eauto. eapply multi_R. simpl. rewrite subst_msubst. eapply ST_AppAbs; eauto. eapply typable_empty__closed. apply (R_typable_empty H1). eapply instantiation_env_closed; eauto. eapply (IHHT ((x,T11)::c)). intros. unfold extend, lookup. destruct (eq_id_dec x x0); auto. constructor; auto. Case "T_App". rewrite msubst_app. destruct (IHHT1 c H env0 V) as [_ [_ P1]]. pose proof (IHHT2 c H env0 V) as P2. fold R in P1. auto. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Normalization Theorem *) Theorem normalization : forall t T, has_type empty t T -> halts t. Proof. intros. replace t with (msubst nil t) by reflexivity. apply (@R_halts T). apply (msubst_R nil); eauto. eapply V_nil. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * Norm: Normalization of STLC *) (* Chapter maintained by Andrew Tolmach *) (* (Based on TAPL Ch. 12.) *) Require Export Smallstep. Hint Constructors multi. (** (This chapter is optional.) In this chapter, we consider another fundamental theoretical property of the simply typed lambda-calculus: the fact that the evaluation of a well-typed program is guaranteed to halt in a finite number of steps---i.e., every well-typed term is _normalizable_. Unlike the type-safety properties we have considered so far, the normalization property does not extend to full-blown programming languages, because these languages nearly always extend the simply typed lambda-calculus with constructs, such as general recursion (as we discussed in the MoreStlc chapter) or recursive types, that can be used to write nonterminating programs. However, the issue of normalization reappears at the level of _types_ when we consider the metatheory of polymorphic versions of the lambda calculus such as F_omega: in this system, the language of types effectively contains a copy of the simply typed lambda-calculus, and the termination of the typechecking algorithm will hinge on the fact that a ``normalization'' operation on type expressions is guaranteed to terminate. Another reason for studying normalization proofs is that they are some of the most beautiful---and mind-blowing---mathematics to be found in the type theory literature, often (as here) involving the fundamental proof technique of _logical relations_. The calculus we shall consider here is the simply typed lambda-calculus over a single base type [bool] and with pairs. We'll give full details of the development for the basic lambda-calculus terms treating [bool] as an uninterpreted base type, and leave the extension to the boolean operators and pairs to the reader. Even for the base calculus, normalization is not entirely trivial to prove, since each reduction of a term can duplicate redexes in subterms. *) (** **** Exercise: 1 star *) (** Where do we fail if we attempt to prove normalization by a straightforward induction on the size of a well-typed term? *) (* FILL IN HERE *) (** [] *) (* ###################################################################### *) (** * Language *) (** We begin by repeating the relevant language definition, which is similar to those in the MoreStlc chapter, and supporting results including type preservation and step determinism. (We won't need progress.) You may just wish to skip down to the Normalization section... *) (* ###################################################################### *) (** *** Syntax and Operational Semantics *) Inductive ty : Type := | TBool : ty | TArrow : ty -> ty -> ty | TProd : ty -> ty -> ty . Tactic Notation "T_cases" tactic(first) ident(c) := first; [ Case_aux c "TBool" | Case_aux c "TArrow" | Case_aux c "TProd" ]. Inductive tm : Type := (* pure STLC *) | tvar : id -> tm | tapp : tm -> tm -> tm | tabs : id -> ty -> tm -> tm (* pairs *) | tpair : tm -> tm -> tm | tfst : tm -> tm | tsnd : tm -> tm (* booleans *) | ttrue : tm | tfalse : tm | tif : tm -> tm -> tm -> tm. (* i.e., [if t0 then t1 else t2] *) Tactic Notation "t_cases" tactic(first) ident(c) := first; [ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs" | Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd" | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ]. (* ###################################################################### *) (** *** 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) | tpair t1 t2 => tpair (subst x s t1) (subst x s t2) | tfst t1 => tfst (subst x s t1) | tsnd t1 => tsnd (subst x s t1) | ttrue => ttrue | tfalse => tfalse | tif t0 t1 t2 => tif (subst x s t0) (subst x s t1) (subst x s t2) end. Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20). (* ###################################################################### *) (** *** Reduction *) Inductive value : tm -> Prop := | v_abs : forall x T11 t12, value (tabs x T11 t12) | v_pair : forall v1 v2, value v1 -> value v2 -> value (tpair v1 v2) | v_true : value ttrue | v_false : value tfalse . Hint Constructors value. Reserved Notation "t1 '==>' t2" (at level 40). Inductive step : tm -> tm -> Prop := | ST_AppAbs : forall x T11 t12 v2, value v2 -> (tapp (tabs x T11 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') (* pairs *) | ST_Pair1 : forall t1 t1' t2, t1 ==> t1' -> (tpair t1 t2) ==> (tpair t1' t2) | ST_Pair2 : forall v1 t2 t2', value v1 -> t2 ==> t2' -> (tpair v1 t2) ==> (tpair v1 t2') | ST_Fst : forall t1 t1', t1 ==> t1' -> (tfst t1) ==> (tfst t1') | ST_FstPair : forall v1 v2, value v1 -> value v2 -> (tfst (tpair v1 v2)) ==> v1 | ST_Snd : forall t1 t1', t1 ==> t1' -> (tsnd t1) ==> (tsnd t1') | ST_SndPair : forall v1 v2, value v1 -> value v2 -> (tsnd (tpair v1 v2)) ==> v2 (* booleans *) | ST_IfTrue : forall t1 t2, (tif ttrue t1 t2) ==> t1 | ST_IfFalse : forall t1 t2, (tif tfalse t1 t2) ==> t2 | ST_If : forall t0 t0' t1 t2, t0 ==> t0' -> (tif t0 t1 t2) ==> (tif t0' t1 t2) 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_Pair1" | Case_aux c "ST_Pair2" | Case_aux c "ST_Fst" | Case_aux c "ST_FstPair" | Case_aux c "ST_Snd" | Case_aux c "ST_SndPair" | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ]. Notation multistep := (multi step). Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40). Hint Constructors step. Notation step_normal_form := (normal_form step). Lemma value__normal : forall t, value t -> step_normal_form t. Proof with eauto. intros t H; induction H; intros [t' ST]; inversion ST... Qed. (* ###################################################################### *) (** *** Typing *) Definition context := partial_map ty. Inductive has_type : context -> tm -> ty -> Prop := (* Typing rules for proper terms *) | T_Var : forall Gamma x T, Gamma x = Some T -> has_type Gamma (tvar x) T | T_Abs : forall Gamma x T11 T12 t12, 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 (* pairs *) | T_Pair : forall Gamma t1 t2 T1 T2, has_type Gamma t1 T1 -> has_type Gamma t2 T2 -> has_type Gamma (tpair t1 t2) (TProd T1 T2) | T_Fst : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tfst t) T1 | T_Snd : forall Gamma t T1 T2, has_type Gamma t (TProd T1 T2) -> has_type Gamma (tsnd t) T2 (* booleans *) | T_True : forall Gamma, has_type Gamma ttrue TBool | T_False : forall Gamma, has_type Gamma tfalse TBool | T_If : forall Gamma t0 t1 t2 T, has_type Gamma t0 TBool -> has_type Gamma t1 T -> has_type Gamma t2 T -> has_type Gamma (tif t0 t1 t2) 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_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd" | Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If" ]. Hint Extern 2 (has_type _ (tapp _ _) _) => eapply T_App; auto. Hint Extern 2 (_ = _) => compute; reflexivity. (* ###################################################################### *) (** *** 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) (* pairs *) | afi_pair1 : forall x t1 t2, appears_free_in x t1 -> appears_free_in x (tpair t1 t2) | afi_pair2 : forall x t1 t2, appears_free_in x t2 -> appears_free_in x (tpair t1 t2) | afi_fst : forall x t, appears_free_in x t -> appears_free_in x (tfst t) | afi_snd : forall x t, appears_free_in x t -> appears_free_in x (tsnd t) (* booleans *) | afi_if0 : forall x t0 t1 t2, appears_free_in x t0 -> appears_free_in x (tif t0 t1 t2) | afi_if1 : forall x t0 t1 t2, appears_free_in x t1 -> appears_free_in x (tif t0 t1 t2) | afi_if2 : forall x t0 t1 t2, appears_free_in x t2 -> appears_free_in x (tif t0 t1 t2) . Hint Constructors appears_free_in. Definition closed (t:tm) := forall x, ~ appears_free_in x t. 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 y Hafi. unfold extend. destruct (eq_id_dec x y)... Case "T_Pair". apply T_Pair... Case "T_If". eapply T_If... 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; inversion Hafi; subst... Case "T_Abs". destruct IHHtyp as [T' Hctx]... exists T'. unfold extend in Hctx. rewrite neq_id in Hctx... Qed. Corollary typable_empty__closed : forall t T, has_type empty t T -> closed t. Proof. intros. unfold closed. intros x H1. destruct (free_in_context _ _ _ _ H1 H) as [T' C]. inversion C. 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. (* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then Gamma |- ([x:=v]t) S. *) intros Gamma x U v t S Htypt Htypv. generalize dependent Gamma. generalize dependent S. (* Proof: By induction on the term t. Most cases follow directly from the IH, with the exception of tvar and tabs. The former aren't automatic because we must reason about how the variables interact. *) t_cases (induction t) Case; intros S Gamma Htypt; simpl; inversion Htypt; subst... Case "tvar". simpl. rename i into y. (* If t = y, we know that [empty |- v : U] and [Gamma,x:U |- y : S] and, by inversion, [extend Gamma x U y = Some S]. We want to show that [Gamma |- [x:=v]y : S]. There are two cases to consider: either [x=y] or [x<>y]. *) destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then we know that [U = S], and that [[x:=v]y = v]. So what we really must show is that if [empty |- v : U] then [Gamma |- v : U]. We have already proven a more general version of this theorem, called context invariance. *) subst. unfold extend in H1. rewrite eq_id in H1. inversion H1; subst. clear H1. eapply context_invariance... intros x Hcontra. destruct (free_in_context _ _ S empty Hcontra) as [T' HT']... inversion HT'. SCase "x<>y". (* If [x <> y], then [Gamma y = Some S] and the substitution has no effect. We can show that [Gamma |- y : S] by [T_Var]. *) apply T_Var... unfold extend in H1. rewrite neq_id in H1... Case "tabs". rename i into y. rename t into T11. (* If [t = tabs y T11 t0], then we know that [Gamma,x:U |- tabs y T11 t0 : T11->T12] [Gamma,x:U,y:T11 |- t0 : T12] [empty |- v : U] As our IH, we know that forall S Gamma, [Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 S]. We can calculate that [x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0) And we must show that [Gamma |- [x:=v]t : T11->T12]. We know we will do so using [T_Abs], so it remains to be shown that: [Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12] We consider two cases: [x = y] and [x <> y]. *) apply T_Abs... destruct (eq_id_dec x y). SCase "x=y". (* If [x = y], then the substitution has no effect. Context invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are equivalent. Since the former context shows that [t0 : T12], so does the latter. *) eapply context_invariance... subst. intros x Hafi. unfold extend. destruct (eq_id_dec y x)... SCase "x<>y". (* If [x <> y], then the IH and context invariance allow us to show that [Gamma,x:U,y:T11 |- t0 : T12] => [Gamma,y:T11,x:U |- t0 : T12] => [Gamma,y:T11 |- [x:=v]t0 : T12] *) apply IHt. eapply context_invariance... intros z Hafi. unfold extend. destruct (eq_id_dec y z)... subst. rewrite neq_id... 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. (* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *) remember (@empty ty) as Gamma. generalize dependent HeqGamma. generalize dependent t'. (* Proof: By induction on the given typing derivation. Many cases are contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *) has_type_cases (induction HT) Case; intros t' HeqGamma HE; subst; inversion HE; subst... Case "T_App". (* If the last rule used was [T_App], then [t = t1 t2], and three rules could have been used to show [t ==> t']: [ST_App1], [ST_App2], and [ST_AppAbs]. In the first two cases, the result follows directly from the IH. *) inversion HE; subst... SCase "ST_AppAbs". (* For the third case, suppose [t1 = tabs x T11 t12] and [t2 = v2]. We must show that [empty |- [x:=v2]t12 : T2]. We know by assumption that [empty |- tabs x T11 t12 : T1->T2] and by inversion [x:T1 |- t12 : T2] We have already proven that substitution_preserves_typing and [empty |- v2 : T1] by assumption, so we are done. *) apply substitution_preserves_typing with T1... inversion HT1... Case "T_Fst". inversion HT... Case "T_Snd". inversion HT... Qed. (** [] *) (* ###################################################################### *) (** *** Determinism *) Lemma step_deterministic : deterministic step. Proof with eauto. unfold deterministic. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** * Normalization *) (** Now for the actual normalization proof. Our goal is to prove that every well-typed term evaluates to a normal form. In fact, it turns out to be convenient to prove something slightly stronger, namely that every well-typed term evaluates to a _value_. This follows from the weaker property anyway via the Progress lemma (why?) but otherwise we don't need Progress, and we didn't bother re-proving it above. Here's the key definition: *) Definition halts (t:tm) : Prop := exists t', t ==>* t' /\ value t'. (** A trivial fact: *) Lemma value_halts : forall v, value v -> halts v. Proof. intros v H. unfold halts. exists v. split. apply multi_refl. assumption. Qed. (** The key issue in the normalization proof (as in many proofs by induction) is finding a strong enough induction hypothesis. To this end, we begin by defining, for each type [T], a set [R_T] of closed terms of type [T]. We will specify these sets using a relation [R] and write [R T t] when [t] is in [R_T]. (The sets [R_T] are sometimes called _saturated sets_ or _reducibility candidates_.) Here is the definition of [R] for the base language: - [R bool t] iff [t] is a closed term of type [bool] and [t] halts in a value - [R (T1 -> T2) t] iff [t] is a closed term of type [T1 -> T2] and [t] halts in a value _and_ for any term [s] such that [R T1 s], we have [R T2 (t s)]. *) (** This definition gives us the strengthened induction hypothesis that we need. Our primary goal is to show that all _programs_ ---i.e., all closed terms of base type---halt. But closed terms of base type can contain subterms of functional type, so we need to know something about these as well. Moreover, it is not enough to know that these subterms halt, because the application of a normalized function to a normalized argument involves a substitution, which may enable more evaluation steps. So we need a stronger condition for terms of functional type: not only should they halt themselves, but, when applied to halting arguments, they should yield halting results. The form of [R] is characteristic of the _logical relations_ proof technique. (Since we are just dealing with unary relations here, we could perhaps more properly say _logical predicates_.) If we want to prove some property [P] of all closed terms of type [A], we proceed by proving, by induction on types, that all terms of type [A] _possess_ property [P], all terms of type [A->A] _preserve_ property [P], all terms of type [(A->A)->(A->A)] _preserve the property of preserving_ property [P], and so on. We do this by defining a family of predicates, indexed by types. For the base type [A], the predicate is just [P]. For functional types, it says that the function should map values satisfying the predicate at the input type to values satisfying the predicate at the output type. When we come to formalize the definition of [R] in Coq, we hit a problem. The most obvious formulation would be as a parameterized Inductive proposition like this: Inductive R : ty -> tm -> Prop := | R_bool : forall b t, has_type empty t TBool -> halts t -> R TBool t | R_arrow : forall T1 T2 t, has_type empty t (TArrow T1 T2) -> halts t -> (forall s, R T1 s -> R T2 (tapp t s)) -> R (TArrow T1 T2) t. Unfortunately, Coq rejects this definition because it violates the _strict positivity requirement_ for inductive definitions, which says that the type being defined must not occur to the left of an arrow in the type of a constructor argument. Here, it is the third argument to [R_arrow], namely [(forall s, R T1 s -> R TS (tapp t s))], and specifically the [R T1 s] part, that violates this rule. (The outermost arrows separating the constructor arguments don't count when applying this rule; otherwise we could never have genuinely inductive predicates at all!) The reason for the rule is that types defined with non-positive recursion can be used to build non-terminating functions, which as we know would be a disaster for Coq's logical soundness. Even though the relation we want in this case might be perfectly innocent, Coq still rejects it because it fails the positivity test. Fortunately, it turns out that we _can_ define [R] using a [Fixpoint]: *) Fixpoint R (T:ty) (t:tm) {struct T} : Prop := has_type empty t T /\ halts t /\ (match T with | TBool => True | TArrow T1 T2 => (forall s, R T1 s -> R T2 (tapp t s)) (* FILL IN HERE *) | TProd T1 T2 => False (* ... and delete this line *) end). (** As immediate consequences of this definition, we have that every element of every set [R_T] halts in a value and is closed with type [t] :*) Lemma R_halts : forall {T} {t}, R T t -> halts t. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. Lemma R_typable_empty : forall {T} {t}, R T t -> has_type empty t T. Proof. intros. destruct T; unfold R in H; inversion H; inversion H1; assumption. Qed. (** Now we proceed to show the main result, which is that every well-typed term of type [T] is an element of [R_T]. Together with [R_halts], that will show that every well-typed term halts in a value. *) (* ###################################################################### *) (** ** Membership in [R_T] is invariant under evaluation *) (** We start with a preliminary lemma that shows a kind of strong preservation property, namely that membership in [R_T] is _invariant_ under evaluation. We will need this property in both directions, i.e. both to show that a term in [R_T] stays in [R_T] when it takes a forward step, and to show that any term that ends up in [R_T] after a step must have been in [R_T] to begin with. First of all, an easy preliminary lemma. Note that in the forward direction the proof depends on the fact that our language is determinstic. This lemma might still be true for non-deterministic languages, but the proof would be harder! *) Lemma step_preserves_halting : forall t t', (t ==> t') -> (halts t <-> halts t'). Proof. intros t t' ST. unfold halts. split. Case "->". intros [t'' [STM V]]. inversion STM; subst. apply ex_falso_quodlibet. apply value__normal in V. unfold normal_form in V. apply V. exists t'. auto. rewrite (step_deterministic _ _ _ ST H). exists t''. split; assumption. Case "<-". intros [t'0 [STM V]]. exists t'0. split; eauto. Qed. (** Now the main lemma, which comes in two parts, one for each direction. Each proceeds by induction on the structure of the type [T]. In fact, this is where we make fundamental use of the structure of types. One requirement for staying in [R_T] is to stay in type [T]. In the forward direction, we get this from ordinary type Preservation. *) Lemma step_preserves_R : forall T t t', (t ==> t') -> R T t -> R T t'. Proof. induction T; intros t t' E Rt; unfold R; fold R; unfold R in Rt; fold R in Rt; destruct Rt as [typable_empty_t [halts_t RRt]]. (* TBool *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. auto. (* TArrow *) split. eapply preservation; eauto. split. apply (step_preserves_halting _ _ E); eauto. intros. eapply IHT2. apply ST_App1. apply E. apply RRt; auto. (* FILL IN HERE *) Admitted. (** The generalization to multiple steps is trivial: *) Lemma multistep_preserves_R : forall T t t', (t ==>* t') -> R T t -> R T t'. Proof. intros T t t' STM; induction STM; intros. assumption. apply IHSTM. eapply step_preserves_R. apply H. assumption. Qed. (** In the reverse direction, we must add the fact that [t] has type [T] before stepping as an additional hypothesis. *) Lemma step_preserves_R' : forall T t t', has_type empty t T -> (t ==> t') -> R T t' -> R T t. Proof. (* FILL IN HERE *) Admitted. Lemma multistep_preserves_R' : forall T t t', has_type empty t T -> (t ==>* t') -> R T t' -> R T t. Proof. intros T t t' HT STM. induction STM; intros. assumption. eapply step_preserves_R'. assumption. apply H. apply IHSTM. eapply preservation; eauto. auto. Qed. (* ###################################################################### *) (** ** Closed instances of terms of type [T] belong to [R_T] *) (** Now we proceed to show that every term of type [T] belongs to [R_T]. Here, the induction will be on typing derivations (it would be surprising to see a proof about well-typed terms that did not somewhere involve induction on typing derivations!). The only technical difficulty here is in dealing with the abstraction case. Since we are arguing by induction, the demonstration that a term [tabs x T1 t2] belongs to [R_(T1->T2)] should involve applying the induction hypothesis to show that [t2] belongs to [R_(T2)]. But [R_(T2)] is defined to be a set of _closed_ terms, while [t2] may contain [x] free, so this does not make sense. This problem is resolved by using a standard trick to suitably generalize the induction hypothesis: instead of proving a statement involving a closed term, we generalize it to cover all closed _instances_ of an open term [t]. Informally, the statement of the lemma will look like this: If [x1:T1,..xn:Tn |- t : T] and [v1,...,vn] are values such that [R T1 v1], [R T2 v2], ..., [R Tn vn], then [R T ([x1:=v1][x2:=v2]...[xn:=vn]t)]. The proof will proceed by induction on the typing derivation [x1:T1,..xn:Tn |- t : T]; the most interesting case will be the one for abstraction. *) (* ###################################################################### *) (** *** Multisubstitutions, multi-extensions, and instantiations *) (** However, before we can proceed to formalize the statement and proof of the lemma, we'll need to build some (rather tedious) machinery to deal with the fact that we are performing _multiple_ substitutions on term [t] and _multiple_ extensions of the typing context. In particular, we must be precise about the order in which the substitutions occur and how they act on each other. Often these details are simply elided in informal paper proofs, but of course Coq won't let us do that. Since here we are substituting closed terms, we don't need to worry about how one substitution might affect the term put in place by another. But we still do need to worry about the _order_ of substitutions, because it is quite possible for the same identifier to appear multiple times among the [x1,...xn] with different associated [vi] and [Ti]. To make everything precise, we will assume that environments are extended from left to right, and multiple substitutions are performed from right to left. To see that this is consistent, suppose we have an environment written as [...,y:bool,...,y:nat,...] and a corresponding term substitution written as [...[y:=(tbool true)]...[y:=(tnat 3)]...t]. Since environments are extended from left to right, the binding [y:nat] hides the binding [y:bool]; since substitutions are performed right to left, we do the substitution [y:=(tnat 3)] first, so that the substitution [y:=(tbool true)] has no effect. Substitution thus correctly preserves the type of the term. With these points in mind, the following definitions should make sense. A _multisubstitution_ is the result of applying a list of substitutions, which we call an _environment_. *) Definition env := list (id * tm). Fixpoint msubst (ss:env) (t:tm) {struct ss} : tm := match ss with | nil => t | ((x,s)::ss') => msubst ss' ([x:=s]t) end. (** We need similar machinery to talk about repeated extension of a typing context using a list of (identifier, type) pairs, which we call a _type assignment_. *) Definition tass := list (id * ty). Fixpoint mextend (Gamma : context) (xts : tass) := match xts with | nil => Gamma | ((x,v)::xts') => extend (mextend Gamma xts') x v end. (** We will need some simple operations that work uniformly on environments and type assigments *) Fixpoint lookup {X:Set} (k : id) (l : list (id * X)) {struct l} : option X := match l with | nil => None | (j,x) :: l' => if eq_id_dec j k then Some x else lookup k l' end. Fixpoint drop {X:Set} (n:id) (nxs:list (id * X)) {struct nxs} : list (id * X) := match nxs with | nil => nil | ((n',x)::nxs') => if eq_id_dec n' n then drop n nxs' else (n',x)::(drop n nxs') end. (** An _instantiation_ combines a type assignment and a value environment with the same domains, where corresponding elements are in R *) Inductive instantiation : tass -> env -> Prop := | V_nil : instantiation nil nil | V_cons : forall x T v c e, value v -> R T v -> instantiation c e -> instantiation ((x,T)::c) ((x,v)::e). (** We now proceed to prove various properties of these definitions. *) (* ###################################################################### *) (** *** More Substitution Facts *) (** First we need some additional lemmas on (ordinary) substitution. *) Lemma vacuous_substitution : forall t x, ~ appears_free_in x t -> forall t', [x:=t']t = t. Proof with eauto. (* FILL IN HERE *) Admitted. Lemma subst_closed: forall t, closed t -> forall x t', [x:=t']t = t. Proof. intros. apply vacuous_substitution. apply H. Qed. Lemma subst_not_afi : forall t x v, closed v -> ~ appears_free_in x ([x:=v]t). Proof with eauto. (* rather slow this way *) unfold closed, not. t_cases (induction t) Case; intros x v P A; simpl in A. Case "tvar". destruct (eq_id_dec x i)... inversion A; subst. auto. Case "tapp". inversion A; subst... Case "tabs". destruct (eq_id_dec x i)... inversion A; subst... inversion A; subst... Case "tpair". inversion A; subst... Case "tfst". inversion A; subst... Case "tsnd". inversion A; subst... Case "ttrue". inversion A. Case "tfalse". inversion A. Case "tif". inversion A; subst... Qed. Lemma duplicate_subst : forall t' x t v, closed v -> [x:=t]([x:=v]t') = [x:=v]t'. Proof. intros. eapply vacuous_substitution. apply subst_not_afi. auto. Qed. Lemma swap_subst : forall t x x1 v v1, x <> x1 -> closed v -> closed v1 -> [x1:=v1]([x:=v]t) = [x:=v]([x1:=v1]t). Proof with eauto. t_cases (induction t) Case; intros; simpl. Case "tvar". destruct (eq_id_dec x i); destruct (eq_id_dec x1 i). subst. apply ex_falso_quodlibet... subst. simpl. rewrite eq_id. apply subst_closed... subst. simpl. rewrite eq_id. rewrite subst_closed... simpl. rewrite neq_id... rewrite neq_id... (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Properties of multi-substitutions *) Lemma msubst_closed: forall t, closed t -> forall ss, msubst ss t = t. Proof. induction ss. reflexivity. destruct a. simpl. rewrite subst_closed; assumption. Qed. (** Closed environments are those that contain only closed terms. *) Fixpoint closed_env (env:env) {struct env} := match env with | nil => True | (x,t)::env' => closed t /\ closed_env env' end. (** Next come a series of lemmas charcterizing how [msubst] of closed terms distributes over [subst] and over each term form *) Lemma subst_msubst: forall env x v t, closed v -> closed_env env -> msubst env ([x:=v]t) = [x:=v](msubst (drop x env) t). Proof. induction env0; intros. auto. destruct a. simpl. inversion H0. fold closed_env in H2. destruct (eq_id_dec i x). subst. rewrite duplicate_subst; auto. simpl. rewrite swap_subst; eauto. Qed. Lemma msubst_var: forall ss x, closed_env ss -> msubst ss (tvar x) = match lookup x ss with | Some t => t | None => tvar x end. Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x). apply msubst_closed. inversion H; auto. apply IHss. inversion H; auto. Qed. Lemma msubst_abs: forall ss x T t, msubst ss (tabs x T t) = tabs x T (msubst (drop x ss) t). Proof. induction ss; intros. reflexivity. destruct a. simpl. destruct (eq_id_dec i x); simpl; auto. Qed. Lemma msubst_app : forall ss t1 t2, msubst ss (tapp t1 t2) = tapp (msubst ss t1) (msubst ss t2). Proof. induction ss; intros. reflexivity. destruct a. simpl. rewrite <- IHss. auto. Qed. (** You'll need similar functions for the other term constructors. *) (* FILL IN HERE *) (* ###################################################################### *) (** *** Properties of multi-extensions *) (** We need to connect the behavior of type assignments with that of their corresponding contexts. *) Lemma mextend_lookup : forall (c : tass) (x:id), lookup x c = (mextend empty c) x. Proof. induction c; intros. auto. destruct a. unfold lookup, mextend, extend. destruct (eq_id_dec i x); auto. Qed. Lemma mextend_drop : forall (c: tass) Gamma x x', mextend Gamma (drop x c) x' = if eq_id_dec x x' then Gamma x' else mextend Gamma c x'. induction c; intros. destruct (eq_id_dec x x'); auto. destruct a. simpl. destruct (eq_id_dec i x). subst. rewrite IHc. destruct (eq_id_dec x x'). auto. unfold extend. rewrite neq_id; auto. simpl. unfold extend. destruct (eq_id_dec i x'). subst. destruct (eq_id_dec x x'). subst. exfalso. auto. auto. auto. Qed. (* ###################################################################### *) (** *** Properties of Instantiations *) (** These are strightforward. *) Lemma instantiation_domains_match: forall {c} {e}, instantiation c e -> forall {x} {T}, lookup x c = Some T -> exists t, lookup x e = Some t. Proof. intros c e V. induction V; intros x0 T0 C. solve by inversion . simpl in *. destruct (eq_id_dec x x0); eauto. Qed. Lemma instantiation_env_closed : forall c e, instantiation c e -> closed_env e. Proof. intros c e V; induction V; intros. econstructor. unfold closed_env. fold closed_env. split. eapply typable_empty__closed. eapply R_typable_empty. eauto. auto. Qed. Lemma instantiation_R : forall c e, instantiation c e -> forall x t T, lookup x c = Some T -> lookup x e = Some t -> R T t. Proof. intros c e V. induction V; intros x' t' T' G E. solve by inversion. unfold lookup in *. destruct (eq_id_dec x x'). inversion G; inversion E; subst. auto. eauto. Qed. Lemma instantiation_drop : forall c env, instantiation c env -> forall x, instantiation (drop x c) (drop x env). Proof. intros c e V. induction V. intros. simpl. constructor. intros. unfold drop. destruct (eq_id_dec x x0); auto. constructor; eauto. Qed. (* ###################################################################### *) (** *** Congruence lemmas on multistep *) (** We'll need just a few of these; add them as the demand arises. *) Lemma multistep_App2 : forall v t t', value v -> (t ==>* t') -> (tapp v t) ==>* (tapp v t'). Proof. intros v t t' V STM. induction STM. apply multi_refl. eapply multi_step. apply ST_App2; eauto. auto. Qed. (* FILL IN HERE *) (* ###################################################################### *) (** *** The R Lemma. *) (** We finally put everything together. The key lemma about preservation of typing under substitution can be lifted to multi-substitutions: *) Lemma msubst_preserves_typing : forall c e, instantiation c e -> forall Gamma t S, has_type (mextend Gamma c) t S -> has_type Gamma (msubst e t) S. Proof. induction 1; intros. simpl in H. simpl. auto. simpl in H2. simpl. apply IHinstantiation. eapply substitution_preserves_typing; eauto. apply (R_typable_empty H0). Qed. (** And at long last, the main lemma. *) Lemma msubst_R : forall c env t T, has_type (mextend empty c) t T -> instantiation c env -> R T (msubst env t). Proof. intros c env0 t T HT V. generalize dependent env0. (* We need to generalize the hypothesis a bit before setting up the induction. *) remember (mextend empty c) as Gamma. assert (forall x, Gamma x = lookup x c). intros. rewrite HeqGamma. rewrite mextend_lookup. auto. clear HeqGamma. generalize dependent c. has_type_cases (induction HT) Case; intros. Case "T_Var". rewrite H0 in H. destruct (instantiation_domains_match V H) as [t P]. eapply instantiation_R; eauto. rewrite msubst_var. rewrite P. auto. eapply instantiation_env_closed; eauto. Case "T_Abs". rewrite msubst_abs. (* We'll need variants of the following fact several times, so its simplest to establish it just once. *) assert (WT: has_type empty (tabs x T11 (msubst (drop x env0) t12)) (TArrow T11 T12)). eapply T_Abs. eapply msubst_preserves_typing. eapply instantiation_drop; eauto. eapply context_invariance. apply HT. intros. unfold extend. rewrite mextend_drop. destruct (eq_id_dec x x0). auto. rewrite H. clear - c n. induction c. simpl. rewrite neq_id; auto. simpl. destruct a. unfold extend. destruct (eq_id_dec i x0); auto. unfold R. fold R. split. auto. split. apply value_halts. apply v_abs. intros. destruct (R_halts H0) as [v [P Q]]. pose proof (multistep_preserves_R _ _ _ P H0). apply multistep_preserves_R' with (msubst ((x,v)::env0) t12). eapply T_App. eauto. apply R_typable_empty; auto. eapply multi_trans. eapply multistep_App2; eauto. eapply multi_R. simpl. rewrite subst_msubst. eapply ST_AppAbs; eauto. eapply typable_empty__closed. apply (R_typable_empty H1). eapply instantiation_env_closed; eauto. eapply (IHHT ((x,T11)::c)). intros. unfold extend, lookup. destruct (eq_id_dec x x0); auto. constructor; auto. Case "T_App". rewrite msubst_app. destruct (IHHT1 c H env0 V) as [_ [_ P1]]. pose proof (IHHT2 c H env0 V) as P2. fold R in P1. auto. (* FILL IN HERE *) Admitted. (* ###################################################################### *) (** *** Normalization Theorem *) Theorem normalization : forall t T, has_type empty t T -> halts t. Proof. intros. replace t with (msubst nil t) by reflexivity. apply (@R_halts T). apply (msubst_R nil); eauto. eapply V_nil. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
// DESCRIPTION: Verilator: Verilog Test for generate IF constants // // The given generate loop should have a constant expression as argument. This // test checks it really does evaluate as constant. // 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 (4'b1111)) 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 if ((SIZE < 8'h04) && MASK[0]) begin always @(posedge clk) begin `ifdef TEST_VERBOSE $write ("Generate IF MASK[0] = %d\n", MASK[0]); `endif end end endgenerate endmodule
module lsu_non_aligned_write ( clk, clk2x, reset, o_stall, i_valid, i_address, i_writedata, i_stall, i_byteenable, o_valid, o_active, //Debugging signal avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, avm_burstcount, i_nop ); 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 threads parameter MEMORY_SIDE_MEM_LATENCY=32; 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; localparam WIDTH=8*WIDTH_BYTES; localparam MWIDTH=8*MWIDTH_BYTES; localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES); localparam NUM_OUTPUT_WORD = MWIDTH_BYTES/WIDTH_BYTES; localparam NUM_OUTPUT_WORD_W = $clog2(NUM_OUTPUT_WORD); localparam UNALIGNED_BITS=$clog2(WIDTH_BYTES)-ALIGNMENT_ABITS; /******** * Ports * ********/ // Standard global signals input clk; input clk2x; 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 reg o_active; // Byte enable control input [WIDTH_BYTES-1:0] i_byteenable; // 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 i_nop; reg reg_lsu_i_valid; reg [AWIDTH-BYTE_SELECT_BITS-1:0] page_addr_next; reg [AWIDTH-1:0] reg_lsu_i_address; reg [WIDTH-1:0] reg_lsu_i_writedata; reg reg_nop; reg reg_consecutive; reg [WIDTH_BYTES-1:0] reg_word_byte_enable; reg [UNALIGNED_BITS-1:0] shift = 0; wire stall_int; assign o_stall = reg_lsu_i_valid & stall_int; // --------------- Pipeline stage : Consecutive Address Checking -------------------- always@(posedge clk or posedge reset) begin if (reset) reg_lsu_i_valid <= 1'b0; else if (~o_stall) reg_lsu_i_valid <= i_valid; end always@(posedge clk) begin if (~o_stall & i_valid & ~i_nop) begin reg_lsu_i_address <= i_address; page_addr_next <= i_address[AWIDTH-1:BYTE_SELECT_BITS] + 1'b1; shift <= i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS]; reg_lsu_i_writedata <= i_writedata; reg_word_byte_enable <= USE_BYTE_EN? (i_nop? '0 : i_byteenable) : '1; end if (~o_stall) begin reg_nop <= i_nop; reg_consecutive <= !i_nop & page_addr_next === i_address[AWIDTH-1:BYTE_SELECT_BITS] // to simplify logic in lsu_bursting_write // the new writedata does not overlap with the previous one & i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS] > shift; end end // ------------------------------------------------------------------- lsu_non_aligned_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(1), .HIGH_FMAX(HIGH_FMAX) ) non_aligned_write ( .clk(clk), .clk2x(clk2x), .reset(reset), .o_stall(stall_int), .i_valid(reg_lsu_i_valid), .i_address(reg_lsu_i_address), .i_writedata(reg_lsu_i_writedata), .i_stall(i_stall), .i_byteenable(reg_word_byte_enable), .o_valid(o_valid), .o_active(o_active), .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), .i_nop(reg_nop), .consecutive(reg_consecutive) ); endmodule // // Non-aligned write wrapper for LSUs // module lsu_non_aligned_write_internal ( clk, clk2x, reset, o_stall, i_valid, i_address, i_writedata, i_stall, i_byteenable, o_valid, o_active, //Debugging signal avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, avm_burstcount, i_nop, consecutive ); // Paramaters to pass down to lsu_top // 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=160; // Determines the max number of live requests. parameter MEMORY_SIDE_MEM_LATENCY=0; // Determines the max number of live requests. parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port parameter USECACHING=0; parameter USE_WRITE_ACK=0; parameter TIMEOUT=8; parameter HIGH_FMAX=1; parameter USE_BYTE_EN=0; localparam WIDTH=WIDTH_BYTES*8; localparam MWIDTH=MWIDTH_BYTES*8; localparam TRACKING_FIFO_DEPTH=KERNEL_SIDE_MEM_LATENCY+1; localparam WIDTH_ABITS=$clog2(WIDTH_BYTES); localparam TIMEOUTBITS=$clog2(TIMEOUT); localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES); // // Suppose that we vectorize 4 ways and are accessing a float4 but are only guaranteed float alignment // // WIDTH_BYTES=16 --> $clog2(WIDTH_BYTES) = 4 // ALIGNMENT_ABITS --> 2 // UNALIGNED_BITS --> 2 // // +----+----+----+----+----+----+ // | X | Y | Z | W | A | B | // +----+----+----+----+----+----+ // 0000 0100 1000 1100 ... // // float4 access at 1000 // requires two aligned access // 0000 -> mux out Z , W // 10000 -> mux out A , B // localparam UNALIGNED_BITS=$clog2(WIDTH_BYTES)-ALIGNMENT_ABITS; // How much alignment are we guaranteed in terms of bits // float -> ALIGNMENT_ABITS=2 -> 4 bytes -> 32 bits localparam ALIGNMENT_DBYTES=2**ALIGNMENT_ABITS; localparam ALIGNMENT_DBITS=8*ALIGNMENT_DBYTES; localparam NUM_WORD = MWIDTH_BYTES/ALIGNMENT_DBYTES; // -------- Interface Declarations ------------ // Standard global signals input clk; input clk2x; input reset; input i_nop; // 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; // Byte enable control input [WIDTH_BYTES-1:0] i_byteenable; // 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; // help from outside to track addresses input consecutive; // ------- Bursting LSU instantiation --------- wire lsu_o_stall; wire lsu_i_valid; wire [AWIDTH-1:0] lsu_i_address; wire [2*WIDTH-1:0] lsu_i_writedata; wire [2*WIDTH_BYTES-1:0] lsu_i_byte_enable; wire [AWIDTH-BYTE_SELECT_BITS-1:0] i_page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS]; wire [BYTE_SELECT_BITS-1:0] i_byte_offset=i_address[BYTE_SELECT_BITS-1:0]; reg reg_lsu_i_valid, reg_lsu_i_nop, thread_valid; reg [AWIDTH-1:0] reg_lsu_i_address; reg [WIDTH-1:0] reg_lsu_i_writedata, data_2nd; reg [WIDTH_BYTES-1:0] reg_lsu_i_byte_enable, byte_en_2nd; wire [UNALIGNED_BITS-1:0] shift; wire is_access_aligned; logic issue_2nd_word; wire stall_int; assign lsu_o_stall = reg_lsu_i_valid & stall_int; // Stall out if we // 1. can't accept the request right now because of fifo fullness or lsu stalls // 2. we need to issue the 2nd word from previous requests before proceeding to this one assign o_stall = lsu_o_stall | issue_2nd_word & !i_nop & !consecutive; // --------- Module Internal State ------------- reg [AWIDTH-BYTE_SELECT_BITS-1:0] next_page_addr; // The actual requested address going into the LSU assign lsu_i_address[AWIDTH-1:BYTE_SELECT_BITS] = issue_2nd_word? next_page_addr : i_page_addr; assign lsu_i_address[BYTE_SELECT_BITS-1:0] = issue_2nd_word? '0 : is_access_aligned? i_address[BYTE_SELECT_BITS-1:0] : {i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS] - shift, {ALIGNMENT_ABITS{1'b0}}}; // The actual data to be written and corresponding byte/bit enables assign shift = i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS]; assign lsu_i_byte_enable = {{WIDTH_BYTES{1'b0}},i_byteenable} << {shift, {ALIGNMENT_ABITS{1'b0}}}; assign lsu_i_writedata = {{WIDTH{1'b0}},i_writedata} << {shift, {ALIGNMENT_ABITS{1'b0}}, 3'd0}; // Is this request access already aligned .. then no need to do anything special assign is_access_aligned = (i_address[BYTE_SELECT_BITS-1:0]+ WIDTH_BYTES) <= MWIDTH_BYTES; assign request = issue_2nd_word | i_valid; assign lsu_i_valid = i_valid | issue_2nd_word; // When do we need to issue the 2nd word? // The previous address needed a 2nd word and the current requested address isn't // consecutive with the previous // --- Pipeline before going into the LSU --- always@(posedge clk or posedge reset) begin if (reset) begin reg_lsu_i_valid <= 1'b0; thread_valid <= 1'b0; issue_2nd_word <= 1'b0; end else begin if (~lsu_o_stall) begin reg_lsu_i_valid <= lsu_i_valid; thread_valid <= i_valid & (!issue_2nd_word | i_nop | consecutive); // issue_2nd_word should not generate o_valid issue_2nd_word <= i_valid & !o_stall & !i_nop & !is_access_aligned; end else if(!stall_int) issue_2nd_word <= 1'b0; end end // --- ------------------------------------- reg [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0]i_2nd_offset; reg [WIDTH-1:0] i_2nd_data; reg [WIDTH_BYTES-1:0] i_2nd_byte_en; reg i_2nd_en; always @(posedge clk) begin if(i_valid & ~i_nop & ~o_stall) next_page_addr <= i_page_addr + 1'b1; if(~lsu_o_stall) begin reg_lsu_i_address <= lsu_i_address; reg_lsu_i_nop <= issue_2nd_word? 1'b0 : i_nop; data_2nd <= lsu_i_writedata[2*WIDTH-1:WIDTH]; byte_en_2nd <= lsu_i_byte_enable[2*WIDTH_BYTES-1:WIDTH_BYTES]; reg_lsu_i_writedata <= issue_2nd_word ? data_2nd: is_access_aligned? i_writedata : lsu_i_writedata[WIDTH-1:0]; reg_lsu_i_byte_enable <= issue_2nd_word ? byte_en_2nd: is_access_aligned? i_byteenable : lsu_i_byte_enable[WIDTH_BYTES-1:0]; i_2nd_en <= issue_2nd_word & consecutive; i_2nd_offset <= i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS]; i_2nd_data <= i_writedata; i_2nd_byte_en <= i_byteenable; end end 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), .BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH), .ALIGNMENT_ABITS(ALIGNMENT_ABITS), .USE_WRITE_ACK(USE_WRITE_ACK), .USE_BYTE_EN(1'b1), .UNALIGN(1), .HIGH_FMAX(HIGH_FMAX) ) bursting_write ( .clk(clk), .clk2x(clk2x), .reset(reset), .i_nop(reg_lsu_i_nop), .o_stall(stall_int), .i_valid(reg_lsu_i_valid), .i_thread_valid(thread_valid), .i_address(reg_lsu_i_address), .i_writedata(reg_lsu_i_writedata), .i_2nd_offset(i_2nd_offset), .i_2nd_data(i_2nd_data), .i_2nd_byte_en(i_2nd_byte_en), .i_2nd_en(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) ); endmodule
module lsu_non_aligned_write ( clk, clk2x, reset, o_stall, i_valid, i_address, i_writedata, i_stall, i_byteenable, o_valid, o_active, //Debugging signal avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, avm_burstcount, i_nop ); 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 threads parameter MEMORY_SIDE_MEM_LATENCY=32; 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; localparam WIDTH=8*WIDTH_BYTES; localparam MWIDTH=8*MWIDTH_BYTES; localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES); localparam NUM_OUTPUT_WORD = MWIDTH_BYTES/WIDTH_BYTES; localparam NUM_OUTPUT_WORD_W = $clog2(NUM_OUTPUT_WORD); localparam UNALIGNED_BITS=$clog2(WIDTH_BYTES)-ALIGNMENT_ABITS; /******** * Ports * ********/ // Standard global signals input clk; input clk2x; 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 reg o_active; // Byte enable control input [WIDTH_BYTES-1:0] i_byteenable; // 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 i_nop; reg reg_lsu_i_valid; reg [AWIDTH-BYTE_SELECT_BITS-1:0] page_addr_next; reg [AWIDTH-1:0] reg_lsu_i_address; reg [WIDTH-1:0] reg_lsu_i_writedata; reg reg_nop; reg reg_consecutive; reg [WIDTH_BYTES-1:0] reg_word_byte_enable; reg [UNALIGNED_BITS-1:0] shift = 0; wire stall_int; assign o_stall = reg_lsu_i_valid & stall_int; // --------------- Pipeline stage : Consecutive Address Checking -------------------- always@(posedge clk or posedge reset) begin if (reset) reg_lsu_i_valid <= 1'b0; else if (~o_stall) reg_lsu_i_valid <= i_valid; end always@(posedge clk) begin if (~o_stall & i_valid & ~i_nop) begin reg_lsu_i_address <= i_address; page_addr_next <= i_address[AWIDTH-1:BYTE_SELECT_BITS] + 1'b1; shift <= i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS]; reg_lsu_i_writedata <= i_writedata; reg_word_byte_enable <= USE_BYTE_EN? (i_nop? '0 : i_byteenable) : '1; end if (~o_stall) begin reg_nop <= i_nop; reg_consecutive <= !i_nop & page_addr_next === i_address[AWIDTH-1:BYTE_SELECT_BITS] // to simplify logic in lsu_bursting_write // the new writedata does not overlap with the previous one & i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS] > shift; end end // ------------------------------------------------------------------- lsu_non_aligned_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(1), .HIGH_FMAX(HIGH_FMAX) ) non_aligned_write ( .clk(clk), .clk2x(clk2x), .reset(reset), .o_stall(stall_int), .i_valid(reg_lsu_i_valid), .i_address(reg_lsu_i_address), .i_writedata(reg_lsu_i_writedata), .i_stall(i_stall), .i_byteenable(reg_word_byte_enable), .o_valid(o_valid), .o_active(o_active), .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), .i_nop(reg_nop), .consecutive(reg_consecutive) ); endmodule // // Non-aligned write wrapper for LSUs // module lsu_non_aligned_write_internal ( clk, clk2x, reset, o_stall, i_valid, i_address, i_writedata, i_stall, i_byteenable, o_valid, o_active, //Debugging signal avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, avm_burstcount, i_nop, consecutive ); // Paramaters to pass down to lsu_top // 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=160; // Determines the max number of live requests. parameter MEMORY_SIDE_MEM_LATENCY=0; // Determines the max number of live requests. parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port parameter USECACHING=0; parameter USE_WRITE_ACK=0; parameter TIMEOUT=8; parameter HIGH_FMAX=1; parameter USE_BYTE_EN=0; localparam WIDTH=WIDTH_BYTES*8; localparam MWIDTH=MWIDTH_BYTES*8; localparam TRACKING_FIFO_DEPTH=KERNEL_SIDE_MEM_LATENCY+1; localparam WIDTH_ABITS=$clog2(WIDTH_BYTES); localparam TIMEOUTBITS=$clog2(TIMEOUT); localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES); // // Suppose that we vectorize 4 ways and are accessing a float4 but are only guaranteed float alignment // // WIDTH_BYTES=16 --> $clog2(WIDTH_BYTES) = 4 // ALIGNMENT_ABITS --> 2 // UNALIGNED_BITS --> 2 // // +----+----+----+----+----+----+ // | X | Y | Z | W | A | B | // +----+----+----+----+----+----+ // 0000 0100 1000 1100 ... // // float4 access at 1000 // requires two aligned access // 0000 -> mux out Z , W // 10000 -> mux out A , B // localparam UNALIGNED_BITS=$clog2(WIDTH_BYTES)-ALIGNMENT_ABITS; // How much alignment are we guaranteed in terms of bits // float -> ALIGNMENT_ABITS=2 -> 4 bytes -> 32 bits localparam ALIGNMENT_DBYTES=2**ALIGNMENT_ABITS; localparam ALIGNMENT_DBITS=8*ALIGNMENT_DBYTES; localparam NUM_WORD = MWIDTH_BYTES/ALIGNMENT_DBYTES; // -------- Interface Declarations ------------ // Standard global signals input clk; input clk2x; input reset; input i_nop; // 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; // Byte enable control input [WIDTH_BYTES-1:0] i_byteenable; // 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; // help from outside to track addresses input consecutive; // ------- Bursting LSU instantiation --------- wire lsu_o_stall; wire lsu_i_valid; wire [AWIDTH-1:0] lsu_i_address; wire [2*WIDTH-1:0] lsu_i_writedata; wire [2*WIDTH_BYTES-1:0] lsu_i_byte_enable; wire [AWIDTH-BYTE_SELECT_BITS-1:0] i_page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS]; wire [BYTE_SELECT_BITS-1:0] i_byte_offset=i_address[BYTE_SELECT_BITS-1:0]; reg reg_lsu_i_valid, reg_lsu_i_nop, thread_valid; reg [AWIDTH-1:0] reg_lsu_i_address; reg [WIDTH-1:0] reg_lsu_i_writedata, data_2nd; reg [WIDTH_BYTES-1:0] reg_lsu_i_byte_enable, byte_en_2nd; wire [UNALIGNED_BITS-1:0] shift; wire is_access_aligned; logic issue_2nd_word; wire stall_int; assign lsu_o_stall = reg_lsu_i_valid & stall_int; // Stall out if we // 1. can't accept the request right now because of fifo fullness or lsu stalls // 2. we need to issue the 2nd word from previous requests before proceeding to this one assign o_stall = lsu_o_stall | issue_2nd_word & !i_nop & !consecutive; // --------- Module Internal State ------------- reg [AWIDTH-BYTE_SELECT_BITS-1:0] next_page_addr; // The actual requested address going into the LSU assign lsu_i_address[AWIDTH-1:BYTE_SELECT_BITS] = issue_2nd_word? next_page_addr : i_page_addr; assign lsu_i_address[BYTE_SELECT_BITS-1:0] = issue_2nd_word? '0 : is_access_aligned? i_address[BYTE_SELECT_BITS-1:0] : {i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS] - shift, {ALIGNMENT_ABITS{1'b0}}}; // The actual data to be written and corresponding byte/bit enables assign shift = i_address[ALIGNMENT_ABITS+UNALIGNED_BITS-1:ALIGNMENT_ABITS]; assign lsu_i_byte_enable = {{WIDTH_BYTES{1'b0}},i_byteenable} << {shift, {ALIGNMENT_ABITS{1'b0}}}; assign lsu_i_writedata = {{WIDTH{1'b0}},i_writedata} << {shift, {ALIGNMENT_ABITS{1'b0}}, 3'd0}; // Is this request access already aligned .. then no need to do anything special assign is_access_aligned = (i_address[BYTE_SELECT_BITS-1:0]+ WIDTH_BYTES) <= MWIDTH_BYTES; assign request = issue_2nd_word | i_valid; assign lsu_i_valid = i_valid | issue_2nd_word; // When do we need to issue the 2nd word? // The previous address needed a 2nd word and the current requested address isn't // consecutive with the previous // --- Pipeline before going into the LSU --- always@(posedge clk or posedge reset) begin if (reset) begin reg_lsu_i_valid <= 1'b0; thread_valid <= 1'b0; issue_2nd_word <= 1'b0; end else begin if (~lsu_o_stall) begin reg_lsu_i_valid <= lsu_i_valid; thread_valid <= i_valid & (!issue_2nd_word | i_nop | consecutive); // issue_2nd_word should not generate o_valid issue_2nd_word <= i_valid & !o_stall & !i_nop & !is_access_aligned; end else if(!stall_int) issue_2nd_word <= 1'b0; end end // --- ------------------------------------- reg [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0]i_2nd_offset; reg [WIDTH-1:0] i_2nd_data; reg [WIDTH_BYTES-1:0] i_2nd_byte_en; reg i_2nd_en; always @(posedge clk) begin if(i_valid & ~i_nop & ~o_stall) next_page_addr <= i_page_addr + 1'b1; if(~lsu_o_stall) begin reg_lsu_i_address <= lsu_i_address; reg_lsu_i_nop <= issue_2nd_word? 1'b0 : i_nop; data_2nd <= lsu_i_writedata[2*WIDTH-1:WIDTH]; byte_en_2nd <= lsu_i_byte_enable[2*WIDTH_BYTES-1:WIDTH_BYTES]; reg_lsu_i_writedata <= issue_2nd_word ? data_2nd: is_access_aligned? i_writedata : lsu_i_writedata[WIDTH-1:0]; reg_lsu_i_byte_enable <= issue_2nd_word ? byte_en_2nd: is_access_aligned? i_byteenable : lsu_i_byte_enable[WIDTH_BYTES-1:0]; i_2nd_en <= issue_2nd_word & consecutive; i_2nd_offset <= i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS]; i_2nd_data <= i_writedata; i_2nd_byte_en <= i_byteenable; end end 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), .BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH), .ALIGNMENT_ABITS(ALIGNMENT_ABITS), .USE_WRITE_ACK(USE_WRITE_ACK), .USE_BYTE_EN(1'b1), .UNALIGN(1), .HIGH_FMAX(HIGH_FMAX) ) bursting_write ( .clk(clk), .clk2x(clk2x), .reset(reset), .i_nop(reg_lsu_i_nop), .o_stall(stall_int), .i_valid(reg_lsu_i_valid), .i_thread_valid(thread_valid), .i_address(reg_lsu_i_address), .i_writedata(reg_lsu_i_writedata), .i_2nd_offset(i_2nd_offset), .i_2nd_data(i_2nd_data), .i_2nd_byte_en(i_2nd_byte_en), .i_2nd_en(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) ); 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. // Generates global and local ids for given set of group ids. // Need one of these for each kernel instance. module acl_id_iterator #( parameter WIDTH = 32 // width of all the counters ) ( input clock, input resetn, input start, // handshaking with work group dispatcher input valid_in, output stall_out, // handshaking with kernel instance input stall_in, output valid_out, // comes from group dispatcher input [WIDTH-1:0] group_id_in[2:0], input [WIDTH-1:0] global_id_base_in[2:0], // kernel parameters from the higher level input [WIDTH-1:0] local_size[2:0], input [WIDTH-1:0] global_size[2:0], // actual outputs output [WIDTH-1:0] local_id[2:0], output [WIDTH-1:0] global_id[2:0], output [WIDTH-1:0] group_id[2:0] ); // Storing group id vector and global id offsets vector. // Global id offsets help work item iterators calculate global // ids without using multipliers. localparam FIFO_WIDTH = 2 * 3 * WIDTH; localparam FIFO_DEPTH = 4; wire last_in_group; wire issue = valid_out & !stall_in; reg just_seen_last_in_group; wire [WIDTH-1:0] global_id_from_iter[2:0]; reg [WIDTH-1:0] global_id_base[2:0]; // takes one cycle for the work iterm iterator to register // global_id_base. During that cycle, just use global_id_base // directly. wire use_base = just_seen_last_in_group; assign global_id[0] = use_base ? global_id_base[0] : global_id_from_iter[0]; assign global_id[1] = use_base ? global_id_base[1] : global_id_from_iter[1]; assign global_id[2] = use_base ? global_id_base[2] : global_id_from_iter[2]; // Group ids (and global id offsets) are stored in a fifo. acl_fifo #( .DATA_WIDTH(FIFO_WIDTH), .DEPTH(FIFO_DEPTH) ) group_id_fifo ( .clock(clock), .resetn(resetn), .data_in ( {group_id_in[2], group_id_in[1], group_id_in[0], global_id_base_in[2], global_id_base_in[1], global_id_base_in[0]} ), .data_out( {group_id[2], group_id[1], group_id[0], global_id_base[2], global_id_base[1], global_id_base[0]} ), .valid_in(valid_in), .stall_out(stall_out), .valid_out(valid_out), .stall_in(!last_in_group | !issue) ); acl_work_item_iterator #( .WIDTH(WIDTH) ) work_item_iterator ( .clock(clock), .resetn(resetn), .start(start), .issue(issue), .local_size(local_size), .global_size(global_size), .global_id_base(global_id_base), .local_id(local_id), .global_id(global_id_from_iter), .last_in_group(last_in_group) ); // goes high one cycle after last_in_group. stays high until // next cycle where 'issue' is high. 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 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 buffered streaming accesses. // // Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: No, Pipelined: ? // (see lsu_top.v for details) // // Description: Streaming units may be used when all requests are guaranteed // to be in order with no NOP instructions in between (NOP // requests at the end are permitted and garbage data is // returned). Requests are buffered or pre-fetched so the // back-end must verify that the requests are hazard-safe. /*****************************************************************************/ // Streaming read unit: // Pre-fetch a stream of size data words beginning at base_address. The // inputs are assumed to be valid once the first i_valid signal is asserted. // Once all data is consumed, further requests are verified to be NOP // requests in which case garbage data is returned and the thread passes // through the unit. /*****************************************************************************/ module lsu_streaming_read ( clk, reset, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata, o_active, //Debugging signal base_address, size, avm_address, avm_burstcount, avm_read, avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid ); /************* * 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 MEMORY_SIDE_MEM_LATENCY=1; // 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); // Parameterize the FIFO depth based on the "drain" rate of the return FIFO // In the worst case you need memory latency + burstcount, but if the kernel // is slow to pull data out we can overlap the next burst with that. Also // since you can't backpressure responses, you need at least a full burst // of space. // Note the burst_read_master requires a fifo depth >= MAXBURSTCOUNT + 5. This // hardcoded 5 latency could result in half the bandwidth when burst and // latency is small, hence double it so we can double buffer. localparam _FIFO_DEPTH = MAXBURSTCOUNT + 10 + ((MEMORY_SIDE_MEM_LATENCY * WIDTH_BYTES + MWIDTH_BYTES - 1) / MWIDTH_BYTES); // This fifo doesn't affect the pipeline, round to power of 2 localparam FIFO_DEPTH = 2**$clog2(_FIFO_DEPTH); localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH); /******** * Ports * ********/ // Standard globals input clk; input reset; // Upstream pipeline interface output o_stall; input i_valid; input i_nop; input [AWIDTH-1:0] base_address; input [31:0] size; // 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; // FIFO Isolation to outside world wire f_avm_read; wire f_avm_waitrequest; wire [AWIDTH-1:0] f_avm_address; wire [BURSTCOUNT_WIDTH-1:0] f_avm_burstcount; acl_data_fifo #( .DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH), .DEPTH(2), .IMPL("ll_reg") ) avm_buffer ( .clock(clk), .resetn(!reset), .data_in( {f_avm_address,f_avm_burstcount} ), .valid_in( f_avm_read ), .data_out( {avm_address,avm_burstcount} ), .valid_out( avm_read ), .stall_in( avm_waitrequest ), .stall_out( f_avm_waitrequest ) ); /*************** * Architecture * ***************/ // Address alignment signals wire [AWIDTH-1:0] aligned_base_address; wire [AWIDTH-1:0] base_offset; // Read master signals wire rm_done; wire rm_valid; wire rm_go; wire [MWIDTH-1:0] rm_data; wire [AWIDTH-1:0] rm_base_address; wire [AWIDTH-1:0] rm_last_address; wire [31:0] rm_size; wire rm_ack; // Number of threads remaining reg [31:0] threads_rem; // Need an input register to break up some of the compex computation reg i_reg_valid; reg i_reg_nop; reg [AWIDTH-1:0] reg_base_address; reg [31:0] reg_size; reg [31:0] reg_rm_size_partial; wire [AWIDTH-1:0] aligned_base_address_partial; wire [AWIDTH-1:0] base_offset_partial; assign aligned_base_address_partial = ((base_address >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS); assign base_offset_partial = aligned_base_address_partial[MBYTE_SELECT_BITS-1:0]; always@(posedge clk or posedge reset) begin if (reset == 1'b1) begin i_reg_valid <= 1'b0; reg_base_address <= 'x; reg_size <= 'x; reg_rm_size_partial <= 'x; i_reg_nop <= 'x; end else begin if (!o_stall) begin i_reg_nop <= i_nop; i_reg_valid <= i_valid; reg_base_address <= base_address; reg_size <= size; reg_rm_size_partial = (size << BYTE_SELECT_BITS) + base_offset_partial; end end end // Track the number of threads we have yet to process always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin threads_rem <= 0; end else begin threads_rem <= (rm_go ? reg_size : threads_rem) - (o_valid && !i_stall && !i_reg_nop); end end // Force address alignment bits to 0. They should already be 0, but forcing // them to 0 here lets Quartus see the alignment and optimize the design assign aligned_base_address = ((reg_base_address >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS); // Compute the last address to burst from. In this case, alignment is not // for Quartus optimization but to properly compute the MWIDTH sized burst. assign rm_base_address = ((aligned_base_address >> MBYTE_SELECT_BITS) << MBYTE_SELECT_BITS); // Requests come in based on WIDTH sized words. The memory bus is MWIDTH // sized, so we need to fix up the read-length and base-address alignment // before using the lsu_burst_read_master. assign base_offset = aligned_base_address[MBYTE_SELECT_BITS-1:0]; assign rm_size = ((reg_rm_size_partial + MWIDTH_BYTES - 1) >> MBYTE_SELECT_BITS) << MBYTE_SELECT_BITS; // Load in a new set of parameters if a new ND-Range is beginning (determined // by checking if the current ND-Range completed or the read_master is // currently inactive). assign rm_go = i_reg_valid && (threads_rem == 0) && !rm_valid && !i_reg_nop; lsu_burst_read_master #( .DATAWIDTH( MWIDTH ), .MAXBURSTCOUNT( MAXBURSTCOUNT ), .BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ), .BYTEENABLEWIDTH( MWIDTH_BYTES ), .ADDRESSWIDTH( AWIDTH ), .FIFODEPTH( FIFO_DEPTH ), .FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ), .FIFOUSEMEMORY( 1 ) ) read_master ( .clk(clk), .reset(reset), .o_active(o_active), .control_fixed_location( 1'b0 ), .control_read_base( rm_base_address ), .control_read_length( rm_size ), .control_go( rm_go ), .control_done( rm_done ), .control_early_done(), .user_read_buffer( rm_ack ), .user_buffer_data( rm_data ), .user_data_available( rm_valid ), .master_address( f_avm_address ), .master_read( f_avm_read ), .master_byteenable( avm_byteenable ), .master_readdata( avm_readdata ), .master_readdatavalid( avm_readdatavalid ), .master_burstcount( f_avm_burstcount ), .master_waitrequest( f_avm_waitrequest ) ); generate if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS) begin // Width adapting signals reg [MBYTE_SELECT_BITS-BYTE_SELECT_BITS-1:0] wa_word_counter; // Width adapting logic - a counter is used to track which word is active from // each MWIDTH sized line from main memory. The counter is initialized from // the lower address bits of the initial request. always@(posedge clk or posedge reset) begin if(reset == 1'b1) wa_word_counter <= 0; else wa_word_counter <= rm_go ? aligned_base_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] : wa_word_counter + (o_valid && !i_reg_nop && !i_stall); end // Must eject last word if all threads are done assign rm_ack = (threads_rem==1 || &wa_word_counter) && (o_valid && !i_stall); assign o_readdata = rm_data[wa_word_counter * WIDTH +: WIDTH]; end else begin // Widths are matched, every request is a new memory word assign rm_ack = o_valid && !i_stall; assign o_readdata = rm_data; end endgenerate // Stall requests if we don't have valid data assign o_valid = (i_reg_valid && (rm_valid || i_reg_nop)); assign o_stall = ((!rm_valid && !i_reg_nop) || i_stall) && i_reg_valid; endmodule /*****************************************************************************/ // Streaming write unit: // The number of write requests is known ahead of time and it is assumed // that the back-end has verified that there are no hazards. Write requests // are buffered until sufficient data is availble to generate a large burst // write request. // // Since the burst-master doesn't support width adaptation, the first and last // words are written by the wrapper unit. // // Based off code for the "write_burst_master" template available on the Altera // website. /*****************************************************************************/ module lsu_streaming_write ( clk, reset, o_stall, i_valid, i_stall, i_writedata, i_nop, i_byteenable, o_valid, o_active, //Debugging signal base_address, size, avm_address, avm_burstcount, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest ); /************* * 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 MEMORY_SIDE_MEM_LATENCY=1; // For stores this will only account for arbitration delay parameter USE_BYTE_EN=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 __FIFO_DEPTH=2*MAXBURSTCOUNT + (MEMORY_SIDE_MEM_LATENCY * WIDTH + MWIDTH - 1) / MWIDTH; localparam _FIFO_DEPTH= ( __FIFO_DEPTH > MAXBURSTCOUNT+4 ) ? __FIFO_DEPTH : MAXBURSTCOUNT+5; // This fifo doesn't affect the pipeline, round to power of 2 localparam FIFO_DEPTH= 2**($clog2(_FIFO_DEPTH)); localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH); localparam NUM_FIFOS = MWIDTH / WIDTH; localparam FIFO_ID_WIDTH = (NUM_FIFOS == 1) ? 1 : $clog2(NUM_FIFOS); // Things just get messy if we let the FIFO ID be 0 bits wide /******** * Ports * ********/ // Standard globals input clk; input reset; // Upstream pipeline interface output o_stall; input i_valid; input [WIDTH-1:0] i_writedata; input i_nop; input [AWIDTH-1:0] base_address; input [31:0] size; input [WIDTH_BYTES-1:0] i_byteenable; // Downstream pipeline interface output reg o_valid; input i_stall; output o_active; // internal wires for registering o_valid wire o_valid_int; wire i_stall_int; // Avalon interface output [AWIDTH-1:0] avm_address; output [BURSTCOUNT_WIDTH-1:0] avm_burstcount; output avm_write; input avm_writeack; output [MWIDTH-1:0] avm_writedata; output [MWIDTH_BYTES-1:0] avm_byteenable; input avm_waitrequest; // FIFO Isolation to outside world wire f_avm_write; wire [MWIDTH-1:0] f_avm_writedata; wire [MWIDTH_BYTES-1:0] f_avm_byteenable; wire f_avm_waitrequest; wire [AWIDTH-1:0] f_avm_address; wire [BURSTCOUNT_WIDTH-1:0] f_avm_burstcount; acl_data_fifo #( .DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH+MWIDTH+MWIDTH_BYTES), .DEPTH(2), .IMPL("ll_reg") ) avm_buffer ( .clock(clk), .resetn(!reset), .data_in( {f_avm_address,f_avm_burstcount,f_avm_byteenable,f_avm_writedata} ), .valid_in( f_avm_write ), .data_out( {avm_address,avm_burstcount,avm_byteenable,avm_writedata} ), .valid_out( avm_write ), .stall_in( avm_waitrequest ), .stall_out( f_avm_waitrequest ) ); /*************** * Architecture * ***************/ wire [AWIDTH-1:0] aligned_base_address; wire [AWIDTH-1:0] last_word_address; wire [AWIDTH-1:0] base_offset; wire go; // Address calculations wire [AWIDTH-1:0] a_base_address; wire [31:0] a_size; // Configuration registers wire c_done; reg [31:0] c_length; // This is a re-encoded version of c_lenght that is always equal to c_length-1 // This lets us just test the MSB for c_length_reenc == -1 ( c_lenght = 0 ) // TODO: This means that we can't support the full 32 bit range reg [31:0] c_length_reenc; reg [31:0] ack_counter; // Write master signals reg wm_first_xfer; reg [AWIDTH-1:0] wm_address; // burstcount counts the total number of words in the current burst reg [BURSTCOUNT_WIDTH-1:0] wm_burstcount; // burst_counter counts the number of words remaining in the current burst reg [BURSTCOUNT_WIDTH-1:0] wm_burst_counter; // Special byte masks for the first word and last word transmitted reg fw_in_enable; reg fw_out_enable; reg [MWIDTH_BYTES-1:0] fw_byteenable; wire lw_out_enable; reg [MWIDTH_BYTES-1:0] lw_byteenable; // Burst calculations - first short burst wire [AWIDTH-1:0] fsb_boundary_offset; wire fsb_enable; wire [BURSTCOUNT_WIDTH-1:0] fsb_count; wire fsb_ready; // Burst calculations - last short burst wire lsb_enable; wire [BURSTCOUNT_WIDTH-1:0] lsb_count; wire lsb_ready; // Burst calculations - standard 'middle' burst wire b_ready; // Signals tracking the burst request wire burst_begin; wire [BURSTCOUNT_WIDTH-1:0] burst_count; wire write_accepted; // FIFO signals wire [FIFO_ID_WIDTH-1:0] fifo_next_word; reg [FIFO_ID_WIDTH-1:0] fifo_next_word_reg; wire fifo_full; wire [FIFO_DEPTH_LOG2-1:0] fifo_used; wire [MWIDTH-1:0] fifo_data_out; wire [MWIDTH_BYTES-1:0] fifo_byteenable_out; wire [NUM_FIFOS-1:0][FIFO_DEPTH_LOG2-1:0] fifo_used_n; wire [NUM_FIFOS-1:0] fifo_full_n; wire [MWIDTH_BYTES-1:0] fifo_byteenable; wire [NUM_FIFOS-1:0] fifo_wrreq_n; // Number of threads remaining reg [2:0] valid_in_d; reg [31:0] threads_remaining_to_be_serviced; // Number of threads that are being "serviced" // We need this counter to ensure that we stall subsequent groups // of threads until we're completely finished writing the inital group reg [31:0] threads_rem; // Track the number of threads we have yet to see - there is a 3 cycle // latency on the data storage FIFOs, so delay the valid in signal to compensate always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin valid_in_d <= 3'b000; threads_rem <= 0; end else begin valid_in_d <= { (i_valid && !o_stall && !i_nop), valid_in_d[2:1] }; threads_rem <= (go ? size : threads_rem) - valid_in_d[0]; end end // Force address alignment bits to 0. They should already be 0, but forcing // them to 0 here lets Quartus see the alignment and optimize the design assign aligned_base_address = ((base_address >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS); // The address of the last word we will write to assign last_word_address = aligned_base_address + ((size - 1) << BYTE_SELECT_BITS); // Zero off any offset bits to find the first MWIDTH aligned burst address assign a_base_address = ((aligned_base_address >> MBYTE_SELECT_BITS) << MBYTE_SELECT_BITS); // The offset (in words) from an aligned MWIDTH address assign base_offset = (aligned_base_address[MBYTE_SELECT_BITS-1:0] >> BYTE_SELECT_BITS); // The total size (in bytes) of the transaction is (size + base_offset) * bytes rounded up to // the next MWIDTH aligned size assign a_size = (((((size + base_offset) << BYTE_SELECT_BITS) + {MBYTE_SELECT_BITS{1'b1}}) >> MBYTE_SELECT_BITS) << MBYTE_SELECT_BITS); // Begin bursting when the first valid thread arrives - assumed to be when a // valid thread arrives and the unit is idle. assign go = i_valid && !o_stall && !i_nop && c_done; // Control registers and registered avalon outputs always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin wm_first_xfer <= 1'b0; wm_address <= {AWIDTH{1'b0}}; c_length <= {32{1'b0}}; c_length_reenc <= {32{1'b1}}; wm_burstcount <= {BURSTCOUNT_WIDTH{1'b0}}; wm_burst_counter <= {BURSTCOUNT_WIDTH{1'b0}}; fw_byteenable <= {MWIDTH_BYTES{1'b0}}; lw_byteenable <= {MWIDTH_BYTES{1'b0}}; fw_in_enable <= 1'b0; fw_out_enable <= 1'b0; threads_remaining_to_be_serviced <= {32{1'b0}}; end else begin wm_burstcount <= burst_begin ? burst_count : wm_burstcount; lw_byteenable <= (fifo_byteenable[0] ? {MWIDTH_BYTES{1'b0}} : lw_byteenable) | fifo_byteenable; // Registers that depend on the 'go' signal if(go == 1'b1) begin wm_first_xfer <= 1'b1; wm_address <= a_base_address; c_length <= a_size; c_length_reenc <= a_size-1; wm_burst_counter <= {BURSTCOUNT_WIDTH{1'b0}}; fw_byteenable <= fifo_byteenable; if(NUM_FIFOS > 1) begin // If WIDTH == MWIDTH then there's no alignment issues to worry about fw_in_enable <= (!(i_valid && !o_stall && !i_nop) || (fifo_next_word != {FIFO_ID_WIDTH{1'b1}})); fw_out_enable <= 1'b1; end // When go is high, we've serviced our first thread (size-1) remaining // but i'll subract and extra 1 so i can check for (-1) instead of 0 threads_remaining_to_be_serviced <= size-2; end else begin wm_first_xfer <= !burst_begin && wm_first_xfer; wm_address <= (!wm_first_xfer && burst_begin) ? (wm_address + (wm_burstcount << MBYTE_SELECT_BITS)) : (wm_address); c_length <= write_accepted ? c_length - MWIDTH_BYTES : c_length; c_length_reenc <= write_accepted ? c_length_reenc - MWIDTH_BYTES : c_length_reenc; wm_burst_counter <= burst_begin ? burst_count : (wm_burst_counter - write_accepted); fw_byteenable <= fw_byteenable | ({MWIDTH_BYTES{fw_in_enable}} & fifo_byteenable); fw_in_enable <= fw_in_enable && (!(i_valid && !o_stall && !i_nop) || (fifo_next_word != {FIFO_ID_WIDTH{1'b1}})); fw_out_enable <= fw_out_enable && !write_accepted; // Keep track of the number of threads serviced threads_remaining_to_be_serviced <= (i_valid && !o_stall && !i_nop) ? (threads_remaining_to_be_serviced - 1) : threads_remaining_to_be_serviced; end end end // Last word is being transmitted when there is only one burst left, and the burstcount is 1 assign lw_out_enable = (c_length <= MWIDTH_BYTES); // Bursting is done when length is zero assign c_done = c_length_reenc[31]; // First short burst - Only active on the first transfer (if applicable) // Handles the first portion of the transfer which may not be aligned to a // burst boundary. assign fsb_boundary_offset = (wm_address >> MBYTE_SELECT_BITS) & (MAXBURSTCOUNT-1); assign fsb_enable = (fsb_boundary_offset != 0) && wm_first_xfer; assign fsb_count = (fsb_boundary_offset[0]) ? 1 : // Need to post a burst of 1 to get to a multiple of 2 (((MAXBURSTCOUNT - fsb_boundary_offset) < (c_length >> MBYTE_SELECT_BITS)) ? (MAXBURSTCOUNT - fsb_boundary_offset) : lsb_count); assign fsb_ready = (fifo_used > fsb_count) || (fifo_used == fsb_count) && (wm_burst_counter == 0); // Last short burst - Only active on the last transfer (if applicable). // Handles the last burst which may be less than MAXBURSTCOUNT. assign lsb_enable = (c_length <= (MAXBURSTCOUNT << MBYTE_SELECT_BITS)); assign lsb_count = (c_length >> MBYTE_SELECT_BITS); assign lsb_ready = (threads_rem == 0); // Standard bursts - always bursting MAXBURSTLENGTH assign b_ready = (fifo_used > MAXBURSTCOUNT) || ((fifo_used == MAXBURSTCOUNT) && (wm_burst_counter == 0)); // Begin a new burst whenever one of the burst stages is ready with burst data // and the previous burst is complete or about to complete assign burst_begin = ((fsb_enable && fsb_ready) || (lsb_enable && lsb_ready) || (b_ready)) && !c_done && ((wm_burst_counter == 0) || ((wm_burst_counter == 1) && !f_avm_waitrequest && (c_length > (MAXBURSTCOUNT << MBYTE_SELECT_BITS)))); assign burst_count = fsb_enable ? fsb_count : lsb_enable ? lsb_count : MAXBURSTCOUNT; // Increment the address when a transfer is successful assign write_accepted = f_avm_write && !f_avm_waitrequest; // The next fifo that will accept data assign fifo_next_word = go ? base_offset : fifo_next_word_reg; always@(posedge clk or posedge reset) begin if(reset == 1'b1) begin fifo_next_word_reg <= {FIFO_ID_WIDTH{1'b0}}; end else begin if(NUM_FIFOS > 1) fifo_next_word_reg <= (i_valid && !o_stall) ? fifo_next_word + 1 : fifo_next_word; end end wire [NUM_FIFOS-1:0] fifo_empty; //disables read on FIFOs not used for the first or last cycle wire [NUM_FIFOS-1:0] fifo_read_enable; // The fifos! genvar n; generate for(n=0; n<NUM_FIFOS; n++) begin : fifo_n if (USE_BYTE_EN) begin scfifo #( .lpm_width( WIDTH+WIDTH_BYTES ), .lpm_widthu( FIFO_DEPTH_LOG2 ), .lpm_numwords( FIFO_DEPTH ), .lpm_showahead( "ON" ), .almost_full_value( FIFO_DEPTH - 2 ), .use_eab( "ON" ), .add_ram_output_register( "OFF" ), .underflow_checking( "OFF" ), .overflow_checking( "OFF" ) ) data_fifo ( .clock( clk ), .aclr( reset ), .usedw( fifo_used_n[n] ), .data( {i_writedata,i_byteenable }), .almost_full( fifo_full_n[n] ), .q( { fifo_data_out[n*WIDTH +: WIDTH],fifo_byteenable_out[n*WIDTH_BYTES +: WIDTH_BYTES]} ), .rdreq( write_accepted && fifo_read_enable[n] ), .wrreq( fifo_wrreq_n[n] ), .almost_empty(), .empty(fifo_empty[n]), .full(), .sclr() ); end else begin scfifo #( .lpm_width( WIDTH ), .lpm_widthu( FIFO_DEPTH_LOG2 ), .lpm_numwords( FIFO_DEPTH ), .lpm_showahead( "ON" ), .almost_full_value( FIFO_DEPTH - 2 ), .use_eab( "ON" ), .add_ram_output_register( "OFF" ), .underflow_checking( "OFF" ), .overflow_checking( "OFF" ) ) data_fifo ( .clock( clk ), .aclr( reset ), .usedw( fifo_used_n[n] ), .data( i_writedata ), .almost_full( fifo_full_n[n] ), .q( fifo_data_out[n*WIDTH +: WIDTH] ), .rdreq( write_accepted && fifo_read_enable[n] ), .wrreq( fifo_wrreq_n[n] ), .almost_empty(), .empty(fifo_empty[n]), .full(), .sclr() ); assign fifo_byteenable_out[n*WIDTH_BYTES +: WIDTH_BYTES] = {WIDTH_BYTES{ 1'b1}}; end assign fifo_wrreq_n[n] = i_valid && !o_stall && !i_nop && (fifo_next_word == n); assign fifo_byteenable[n*WIDTH_BYTES +: WIDTH_BYTES] = {WIDTH_BYTES{ fifo_wrreq_n[n] }}; assign fifo_read_enable[n] = fw_out_enable ? fw_byteenable[n*WIDTH_BYTES] : (lw_out_enable ? lw_byteenable[n*WIDTH_BYTES] :1'b1); end endgenerate // Only the last fifo's full/used signals matter to the rest of the design assign fifo_full = fifo_full_n[NUM_FIFOS-1]; assign fifo_used = fifo_used_n[NUM_FIFOS-1]; // Push some signals out to the avalon bus assign f_avm_write = !c_done && (wm_burst_counter != 0); assign f_avm_address = wm_address; assign f_avm_burstcount = wm_burstcount; assign f_avm_writedata = fifo_data_out; assign f_avm_byteenable = fw_out_enable ? fw_byteenable & fifo_byteenable_out: (lw_out_enable ? lw_byteenable : {MWIDTH_BYTES{1'b1}}) & fifo_byteenable_out ; // Pipeline signals // Added, when we are NOT done tranferring all data, but we've seen all the threads in this stream request // then we need to stall the next group assign o_stall = fifo_full || i_stall_int || (!c_done && threads_remaining_to_be_serviced[31]); assign o_valid_int = i_valid && !fifo_full && !o_stall; assign i_stall_int = o_valid && i_stall; // Making o_valid a register to avoid direct dependence // between i_stall and o_valid. always@(posedge clk or posedge reset) begin if(reset == 1'b1) o_valid <= {1'b0}; else if (!i_stall_int) o_valid = o_valid_int; else o_valid = o_valid; end assign o_active = |(~fifo_empty); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module dma_cmd_fifo # ( parameter P_FIFO_DATA_WIDTH = 50, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input dma_cmd_wr_en, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data0, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data1, output dma_cmd_wr_rdy_n, input rd_clk, input rd_rst_n, input rd_en, output [P_FIFO_DATA_WIDTH-1:0] rd_data, output empty_n ); localparam P_FIFO_ALLOC_WIDTH = 1; //128 bits localparam S_IDLE = 3'b001; localparam S_WRITE_0 = 3'b010; localparam S_WRITE_1 = 3'b100; reg [2:0] cur_state; reg [2:0] next_state; localparam S_SYNC_STAGE0 = 3'b001; localparam S_SYNC_STAGE1 = 3'b010; localparam S_SYNC_STAGE2 = 3'b100; reg [2:0] cur_wr_state; reg [2:0] next_wr_state; reg [2:0] cur_rd_state; reg [2:0] next_rd_state; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_addr; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr_p1; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_addr; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; reg r_wr_en; reg r_wr_data_sel; reg [P_FIFO_DATA_WIDTH-1:0] r_wr_data; wire w_full_n; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data0; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data1; reg r_dma_cmd_wr_rdy_n; assign dma_cmd_wr_rdy_n = r_dma_cmd_wr_rdy_n | ~w_full_n; always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_state <= S_IDLE; else cur_state <= next_state; end always @ (*) begin case(cur_state) S_IDLE: begin if(dma_cmd_wr_en == 1) next_state <= S_WRITE_0; else next_state <= S_IDLE; end S_WRITE_0: begin next_state <= S_WRITE_1; end S_WRITE_1: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge wr_clk) begin case(cur_state) S_IDLE: begin r_dma_cmd_wr_data0 <= dma_cmd_wr_data0; r_dma_cmd_wr_data1 <= dma_cmd_wr_data1; end S_WRITE_0: begin end S_WRITE_1: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end S_WRITE_0: begin r_wr_en <= 1; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 1; end S_WRITE_1: begin r_wr_en <= 1; r_wr_data_sel <= 1; r_dma_cmd_wr_rdy_n <= 1; end default: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end endcase end always @ (*) begin if(r_wr_data_sel == 0) r_wr_data <= r_dma_cmd_wr_data0; else r_wr_data <= r_dma_cmd_wr_data1; end assign w_full_n = ~((r_rear_addr[P_FIFO_DEPTH_WIDTH] ^ r_front_sync_addr[P_FIFO_DEPTH_WIDTH]) & (r_rear_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH] == r_front_sync_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH])); always @(posedge wr_clk or negedge wr_rst_n) begin if (wr_rst_n == 0) begin r_rear_addr <= 0; end else begin if (r_wr_en == 1) r_rear_addr <= r_rear_addr + 1; end end assign empty_n = ~(r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH] == r_rear_sync_addr); always @(posedge rd_clk or negedge rd_rst_n) begin if (rd_rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; end else begin if (rd_en == 1) begin r_front_addr <= r_front_addr_p1; r_front_addr_p1 <= r_front_addr_p1 + 1; end end end assign w_front_addr = (rd_en == 1) ? r_front_addr_p1[P_FIFO_DEPTH_WIDTH-1:0] : r_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; ///////////////////////////////////////////////////////////////////////////////////////////// always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_wr_state <= S_SYNC_STAGE0; else cur_wr_state <= next_wr_state; end always @(posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) r_rear_sync_en <= 0; else r_rear_sync_en <= r_rear_sync; end always @(posedge wr_clk) begin r_front_sync_en_d1 <= r_front_sync_en; r_front_sync_en_d2 <= r_front_sync_en_d1; end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin if(r_front_sync_en_d2 == 1) next_wr_state <= S_SYNC_STAGE1; else next_wr_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_wr_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_front_sync_en_d2 == 0) next_wr_state <= S_SYNC_STAGE0; else next_wr_state <= S_SYNC_STAGE2; end default: begin next_wr_state <= S_SYNC_STAGE0; end endcase end always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) begin r_rear_sync_data <= 0; r_front_sync_addr <= 0; end else begin case(cur_wr_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_rear_sync_data <= r_rear_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_front_sync_addr <= r_front_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin r_rear_sync <= 0; end S_SYNC_STAGE1: begin r_rear_sync <= 0; end S_SYNC_STAGE2: begin r_rear_sync <= 1; end default: begin r_rear_sync <= 0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) cur_rd_state <= S_SYNC_STAGE0; else cur_rd_state <= next_rd_state; end always @(posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) r_front_sync_en <= 0; else r_front_sync_en <= r_front_sync; end always @(posedge rd_clk) begin r_rear_sync_en_d1 <= r_rear_sync_en; r_rear_sync_en_d2 <= r_rear_sync_en_d1; end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin if(r_rear_sync_en_d2 == 1) next_rd_state <= S_SYNC_STAGE1; else next_rd_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_rd_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_rear_sync_en_d2 == 0) next_rd_state <= S_SYNC_STAGE0; else next_rd_state <= S_SYNC_STAGE2; end default: begin next_rd_state <= S_SYNC_STAGE0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) begin r_front_sync_data <= 0; r_rear_sync_addr <= 0; end else begin case(cur_rd_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_front_sync_data <= r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_rear_sync_addr <= r_rear_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin r_front_sync <= 1; end S_SYNC_STAGE1: begin r_front_sync <= 1; end S_SYNC_STAGE2: begin r_front_sync <= 0; end default: begin r_front_sync <= 0; end endcase end ///////////////////////////////////////////////////////////////////////////////////////////// localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_MODE = "WRITE_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_FIFO_DEPTH_WIDTH; generate wire [LP_ADDR_TOTAL_WITDH-1:0] rdaddr; wire [LP_ADDR_TOTAL_WITDH-1:0] wraddr; wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; if(LP_ADDR_ZERO_PAD_WITDH == 0) begin : CALC_ADDR assign rdaddr = w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; assign wraddr = r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]; end else begin wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; assign rdaddr = {zero_padding, w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]}; assign wraddr = {zero_padding, r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]}; end endgenerate BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_0( .DO (rd_data), .DI (r_wr_data), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (r_wr_en) ); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module dma_cmd_fifo # ( parameter P_FIFO_DATA_WIDTH = 50, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input dma_cmd_wr_en, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data0, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data1, output dma_cmd_wr_rdy_n, input rd_clk, input rd_rst_n, input rd_en, output [P_FIFO_DATA_WIDTH-1:0] rd_data, output empty_n ); localparam P_FIFO_ALLOC_WIDTH = 1; //128 bits localparam S_IDLE = 3'b001; localparam S_WRITE_0 = 3'b010; localparam S_WRITE_1 = 3'b100; reg [2:0] cur_state; reg [2:0] next_state; localparam S_SYNC_STAGE0 = 3'b001; localparam S_SYNC_STAGE1 = 3'b010; localparam S_SYNC_STAGE2 = 3'b100; reg [2:0] cur_wr_state; reg [2:0] next_wr_state; reg [2:0] cur_rd_state; reg [2:0] next_rd_state; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_addr; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr_p1; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_addr; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; reg r_wr_en; reg r_wr_data_sel; reg [P_FIFO_DATA_WIDTH-1:0] r_wr_data; wire w_full_n; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data0; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data1; reg r_dma_cmd_wr_rdy_n; assign dma_cmd_wr_rdy_n = r_dma_cmd_wr_rdy_n | ~w_full_n; always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_state <= S_IDLE; else cur_state <= next_state; end always @ (*) begin case(cur_state) S_IDLE: begin if(dma_cmd_wr_en == 1) next_state <= S_WRITE_0; else next_state <= S_IDLE; end S_WRITE_0: begin next_state <= S_WRITE_1; end S_WRITE_1: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge wr_clk) begin case(cur_state) S_IDLE: begin r_dma_cmd_wr_data0 <= dma_cmd_wr_data0; r_dma_cmd_wr_data1 <= dma_cmd_wr_data1; end S_WRITE_0: begin end S_WRITE_1: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end S_WRITE_0: begin r_wr_en <= 1; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 1; end S_WRITE_1: begin r_wr_en <= 1; r_wr_data_sel <= 1; r_dma_cmd_wr_rdy_n <= 1; end default: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end endcase end always @ (*) begin if(r_wr_data_sel == 0) r_wr_data <= r_dma_cmd_wr_data0; else r_wr_data <= r_dma_cmd_wr_data1; end assign w_full_n = ~((r_rear_addr[P_FIFO_DEPTH_WIDTH] ^ r_front_sync_addr[P_FIFO_DEPTH_WIDTH]) & (r_rear_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH] == r_front_sync_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH])); always @(posedge wr_clk or negedge wr_rst_n) begin if (wr_rst_n == 0) begin r_rear_addr <= 0; end else begin if (r_wr_en == 1) r_rear_addr <= r_rear_addr + 1; end end assign empty_n = ~(r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH] == r_rear_sync_addr); always @(posedge rd_clk or negedge rd_rst_n) begin if (rd_rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; end else begin if (rd_en == 1) begin r_front_addr <= r_front_addr_p1; r_front_addr_p1 <= r_front_addr_p1 + 1; end end end assign w_front_addr = (rd_en == 1) ? r_front_addr_p1[P_FIFO_DEPTH_WIDTH-1:0] : r_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; ///////////////////////////////////////////////////////////////////////////////////////////// always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_wr_state <= S_SYNC_STAGE0; else cur_wr_state <= next_wr_state; end always @(posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) r_rear_sync_en <= 0; else r_rear_sync_en <= r_rear_sync; end always @(posedge wr_clk) begin r_front_sync_en_d1 <= r_front_sync_en; r_front_sync_en_d2 <= r_front_sync_en_d1; end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin if(r_front_sync_en_d2 == 1) next_wr_state <= S_SYNC_STAGE1; else next_wr_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_wr_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_front_sync_en_d2 == 0) next_wr_state <= S_SYNC_STAGE0; else next_wr_state <= S_SYNC_STAGE2; end default: begin next_wr_state <= S_SYNC_STAGE0; end endcase end always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) begin r_rear_sync_data <= 0; r_front_sync_addr <= 0; end else begin case(cur_wr_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_rear_sync_data <= r_rear_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_front_sync_addr <= r_front_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin r_rear_sync <= 0; end S_SYNC_STAGE1: begin r_rear_sync <= 0; end S_SYNC_STAGE2: begin r_rear_sync <= 1; end default: begin r_rear_sync <= 0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) cur_rd_state <= S_SYNC_STAGE0; else cur_rd_state <= next_rd_state; end always @(posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) r_front_sync_en <= 0; else r_front_sync_en <= r_front_sync; end always @(posedge rd_clk) begin r_rear_sync_en_d1 <= r_rear_sync_en; r_rear_sync_en_d2 <= r_rear_sync_en_d1; end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin if(r_rear_sync_en_d2 == 1) next_rd_state <= S_SYNC_STAGE1; else next_rd_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_rd_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_rear_sync_en_d2 == 0) next_rd_state <= S_SYNC_STAGE0; else next_rd_state <= S_SYNC_STAGE2; end default: begin next_rd_state <= S_SYNC_STAGE0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) begin r_front_sync_data <= 0; r_rear_sync_addr <= 0; end else begin case(cur_rd_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_front_sync_data <= r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_rear_sync_addr <= r_rear_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin r_front_sync <= 1; end S_SYNC_STAGE1: begin r_front_sync <= 1; end S_SYNC_STAGE2: begin r_front_sync <= 0; end default: begin r_front_sync <= 0; end endcase end ///////////////////////////////////////////////////////////////////////////////////////////// localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_MODE = "WRITE_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_FIFO_DEPTH_WIDTH; generate wire [LP_ADDR_TOTAL_WITDH-1:0] rdaddr; wire [LP_ADDR_TOTAL_WITDH-1:0] wraddr; wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; if(LP_ADDR_ZERO_PAD_WITDH == 0) begin : CALC_ADDR assign rdaddr = w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; assign wraddr = r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]; end else begin wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; assign rdaddr = {zero_padding, w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]}; assign wraddr = {zero_padding, r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]}; end endgenerate BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_0( .DO (rd_data), .DI (r_wr_data), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (r_wr_en) ); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module dma_cmd_fifo # ( parameter P_FIFO_DATA_WIDTH = 50, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input dma_cmd_wr_en, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data0, input [P_FIFO_DATA_WIDTH-1:0] dma_cmd_wr_data1, output dma_cmd_wr_rdy_n, input rd_clk, input rd_rst_n, input rd_en, output [P_FIFO_DATA_WIDTH-1:0] rd_data, output empty_n ); localparam P_FIFO_ALLOC_WIDTH = 1; //128 bits localparam S_IDLE = 3'b001; localparam S_WRITE_0 = 3'b010; localparam S_WRITE_1 = 3'b100; reg [2:0] cur_state; reg [2:0] next_state; localparam S_SYNC_STAGE0 = 3'b001; localparam S_SYNC_STAGE1 = 3'b010; localparam S_SYNC_STAGE2 = 3'b100; reg [2:0] cur_wr_state; reg [2:0] next_wr_state; reg [2:0] cur_rd_state; reg [2:0] next_rd_state; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_addr; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr_p1; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync_en; reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_front_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH :P_FIFO_ALLOC_WIDTH] r_rear_sync_addr; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; reg r_wr_en; reg r_wr_data_sel; reg [P_FIFO_DATA_WIDTH-1:0] r_wr_data; wire w_full_n; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data0; reg [P_FIFO_DATA_WIDTH-1:0] r_dma_cmd_wr_data1; reg r_dma_cmd_wr_rdy_n; assign dma_cmd_wr_rdy_n = r_dma_cmd_wr_rdy_n | ~w_full_n; always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_state <= S_IDLE; else cur_state <= next_state; end always @ (*) begin case(cur_state) S_IDLE: begin if(dma_cmd_wr_en == 1) next_state <= S_WRITE_0; else next_state <= S_IDLE; end S_WRITE_0: begin next_state <= S_WRITE_1; end S_WRITE_1: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge wr_clk) begin case(cur_state) S_IDLE: begin r_dma_cmd_wr_data0 <= dma_cmd_wr_data0; r_dma_cmd_wr_data1 <= dma_cmd_wr_data1; end S_WRITE_0: begin end S_WRITE_1: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end S_WRITE_0: begin r_wr_en <= 1; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 1; end S_WRITE_1: begin r_wr_en <= 1; r_wr_data_sel <= 1; r_dma_cmd_wr_rdy_n <= 1; end default: begin r_wr_en <= 0; r_wr_data_sel <= 0; r_dma_cmd_wr_rdy_n <= 0; end endcase end always @ (*) begin if(r_wr_data_sel == 0) r_wr_data <= r_dma_cmd_wr_data0; else r_wr_data <= r_dma_cmd_wr_data1; end assign w_full_n = ~((r_rear_addr[P_FIFO_DEPTH_WIDTH] ^ r_front_sync_addr[P_FIFO_DEPTH_WIDTH]) & (r_rear_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH] == r_front_sync_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH])); always @(posedge wr_clk or negedge wr_rst_n) begin if (wr_rst_n == 0) begin r_rear_addr <= 0; end else begin if (r_wr_en == 1) r_rear_addr <= r_rear_addr + 1; end end assign empty_n = ~(r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH] == r_rear_sync_addr); always @(posedge rd_clk or negedge rd_rst_n) begin if (rd_rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; end else begin if (rd_en == 1) begin r_front_addr <= r_front_addr_p1; r_front_addr_p1 <= r_front_addr_p1 + 1; end end end assign w_front_addr = (rd_en == 1) ? r_front_addr_p1[P_FIFO_DEPTH_WIDTH-1:0] : r_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; ///////////////////////////////////////////////////////////////////////////////////////////// always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_wr_state <= S_SYNC_STAGE0; else cur_wr_state <= next_wr_state; end always @(posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) r_rear_sync_en <= 0; else r_rear_sync_en <= r_rear_sync; end always @(posedge wr_clk) begin r_front_sync_en_d1 <= r_front_sync_en; r_front_sync_en_d2 <= r_front_sync_en_d1; end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin if(r_front_sync_en_d2 == 1) next_wr_state <= S_SYNC_STAGE1; else next_wr_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_wr_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_front_sync_en_d2 == 0) next_wr_state <= S_SYNC_STAGE0; else next_wr_state <= S_SYNC_STAGE2; end default: begin next_wr_state <= S_SYNC_STAGE0; end endcase end always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) begin r_rear_sync_data <= 0; r_front_sync_addr <= 0; end else begin case(cur_wr_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_rear_sync_data <= r_rear_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_front_sync_addr <= r_front_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin r_rear_sync <= 0; end S_SYNC_STAGE1: begin r_rear_sync <= 0; end S_SYNC_STAGE2: begin r_rear_sync <= 1; end default: begin r_rear_sync <= 0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) cur_rd_state <= S_SYNC_STAGE0; else cur_rd_state <= next_rd_state; end always @(posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) r_front_sync_en <= 0; else r_front_sync_en <= r_front_sync; end always @(posedge rd_clk) begin r_rear_sync_en_d1 <= r_rear_sync_en; r_rear_sync_en_d2 <= r_rear_sync_en_d1; end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin if(r_rear_sync_en_d2 == 1) next_rd_state <= S_SYNC_STAGE1; else next_rd_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_rd_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_rear_sync_en_d2 == 0) next_rd_state <= S_SYNC_STAGE0; else next_rd_state <= S_SYNC_STAGE2; end default: begin next_rd_state <= S_SYNC_STAGE0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) begin r_front_sync_data <= 0; r_rear_sync_addr <= 0; end else begin case(cur_rd_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_front_sync_data <= r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]; r_rear_sync_addr <= r_rear_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin r_front_sync <= 1; end S_SYNC_STAGE1: begin r_front_sync <= 1; end S_SYNC_STAGE2: begin r_front_sync <= 0; end default: begin r_front_sync <= 0; end endcase end ///////////////////////////////////////////////////////////////////////////////////////////// localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_FIFO_DATA_WIDTH; localparam LP_WRITE_MODE = "WRITE_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_FIFO_DEPTH_WIDTH; generate wire [LP_ADDR_TOTAL_WITDH-1:0] rdaddr; wire [LP_ADDR_TOTAL_WITDH-1:0] wraddr; wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; if(LP_ADDR_ZERO_PAD_WITDH == 0) begin : CALC_ADDR assign rdaddr = w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; assign wraddr = r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]; end else begin wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; assign rdaddr = {zero_padding, w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]}; assign wraddr = {zero_padding, r_rear_addr[P_FIFO_DEPTH_WIDTH-1:0]}; end endgenerate BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_0( .DO (rd_data), .DI (r_wr_data), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (r_wr_en) ); 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; // Speced ignored: system calls. I think this is nasty, so we error instead. // Speced Illegal: inout/output/ref not allowed localparam B1 = f_bad_output(1,2); function integer f_bad_output(input [31:0] a, output [31:0] o); f_bad_output = 0; endfunction // Speced Illegal: void // Speced Illegal: dotted localparam EIGHT = 8; localparam B2 = f_bad_dotted(2); function integer f_bad_dotted(input [31:0] a); f_bad_dotted = t.EIGHT; endfunction // Speced Illegal: ref to non-local var integer modvar; localparam B3 = f_bad_nonparam(3); function integer f_bad_nonparam(input [31:0] a); f_bad_nonparam = modvar; endfunction // Speced Illegal: needs constant function itself // Our own - infinite loop localparam B4 = f_bad_infinite(3); function integer f_bad_infinite(input [31:0] a); while (1) begin f_bad_infinite = 0; end endfunction // Our own - stop localparam BSTOP = f_bad_stop(3); function integer f_bad_stop(input [31:0] a); $stop; endfunction endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_req # ( parameter P_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_read_req_size, output pcie_rx_cmd_rd_en, input [33:0] pcie_rx_cmd_rd_data, input pcie_rx_cmd_empty_n, output pcie_tag_alloc, output [7:0] pcie_alloc_tag, output [9:4] pcie_tag_alloc_len, input pcie_tag_full_n, input pcie_rx_fifo_full_n, output tx_dma_mrd_req, output [7:0] tx_dma_mrd_tag, output [11:2] tx_dma_mrd_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mrd_addr, input tx_dma_mrd_req_ack ); localparam LP_PCIE_TAG_PREFIX = 4'b0001; localparam LP_PCIE_MRD_DELAY = 8; localparam S_IDLE = 9'b000000001; localparam S_PCIE_RX_CMD_0 = 9'b000000010; localparam S_PCIE_RX_CMD_1 = 9'b000000100; localparam S_PCIE_CHK_NUM_MRD = 9'b000001000; localparam S_PCIE_MRD_REQ = 9'b000010000; localparam S_PCIE_MRD_ACK = 9'b000100000; localparam S_PCIE_MRD_DONE = 9'b001000000; localparam S_PCIE_MRD_DELAY = 9'b010000000; localparam S_PCIE_MRD_NEXT = 9'b100000000; reg [8:0] cur_state; reg [8:0] next_state; reg [2:0] r_pcie_max_read_req_size; reg r_pcie_rx_cmd_rd_en; reg [12:2] r_pcie_rx_len; reg [9:2] r_pcie_rx_cur_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_pcie_addr; reg [3:0] r_pcie_rx_tag; reg r_pcie_rx_tag_update; reg [5:0] r_pcie_mrd_delay; reg r_pcie_tag_alloc; reg r_tx_dma_mrd_req; assign pcie_rx_cmd_rd_en = r_pcie_rx_cmd_rd_en; assign pcie_tag_alloc = r_pcie_tag_alloc; assign pcie_alloc_tag = {LP_PCIE_TAG_PREFIX, r_pcie_rx_tag}; assign pcie_tag_alloc_len = r_pcie_rx_cur_len[9:4]; assign tx_dma_mrd_req = r_tx_dma_mrd_req; assign tx_dma_mrd_tag = {LP_PCIE_TAG_PREFIX, r_pcie_rx_tag}; assign tx_dma_mrd_len = {2'b0, r_pcie_rx_cur_len}; assign tx_dma_mrd_addr = r_pcie_addr; always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) cur_state <= S_IDLE; else cur_state <= next_state; end always @ (*) begin case(cur_state) S_IDLE: begin if(pcie_rx_cmd_empty_n == 1) next_state <= S_PCIE_RX_CMD_0; else next_state <= S_IDLE; end S_PCIE_RX_CMD_0: begin next_state <= S_PCIE_RX_CMD_1; end S_PCIE_RX_CMD_1: begin next_state <= S_PCIE_CHK_NUM_MRD; end S_PCIE_CHK_NUM_MRD: begin if(pcie_rx_fifo_full_n == 1 && pcie_tag_full_n == 1) next_state <= S_PCIE_MRD_REQ; else next_state <= S_PCIE_CHK_NUM_MRD; end S_PCIE_MRD_REQ: begin next_state <= S_PCIE_MRD_ACK; end S_PCIE_MRD_ACK: begin if(tx_dma_mrd_req_ack == 1) next_state <= S_PCIE_MRD_DONE; else next_state <= S_PCIE_MRD_ACK; end S_PCIE_MRD_DONE: begin next_state <= S_PCIE_MRD_DELAY; end S_PCIE_MRD_DELAY: begin if(r_pcie_mrd_delay == 0) next_state <= S_PCIE_MRD_NEXT; else next_state <= S_PCIE_MRD_DELAY; end S_PCIE_MRD_NEXT: begin if(r_pcie_rx_len == 0) next_state <= S_IDLE; else next_state <= S_PCIE_CHK_NUM_MRD; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) begin r_pcie_rx_tag <= 0; end else begin if(r_pcie_rx_tag_update == 1) r_pcie_rx_tag <= r_pcie_rx_tag + 1; end end always @ (posedge pcie_user_clk) begin r_pcie_max_read_req_size <= pcie_max_read_req_size; end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_RX_CMD_0: begin r_pcie_rx_len <= {pcie_rx_cmd_rd_data[10:2], 2'b0}; end S_PCIE_RX_CMD_1: begin case(r_pcie_max_read_req_size) 3'b010: begin if(r_pcie_rx_len[8:7] == 0 && r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b100; else r_pcie_rx_cur_len[9:7] <= {1'b0, r_pcie_rx_len[8:7]}; end 3'b001: begin if(r_pcie_rx_len[7] == 0 && r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b010; else r_pcie_rx_cur_len[9:7] <= {2'b0, r_pcie_rx_len[7]}; end default: begin if(r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b001; else r_pcie_rx_cur_len[9:7] <= 3'b000; end endcase r_pcie_rx_cur_len[6:2] <= r_pcie_rx_len[6:2]; r_pcie_addr <= {pcie_rx_cmd_rd_data[33:2], 2'b0}; end S_PCIE_CHK_NUM_MRD: begin end S_PCIE_MRD_REQ: begin end S_PCIE_MRD_ACK: begin end S_PCIE_MRD_DONE: begin r_pcie_addr <= r_pcie_addr + r_pcie_rx_cur_len; r_pcie_rx_len <= r_pcie_rx_len - r_pcie_rx_cur_len; case(r_pcie_max_read_req_size) 3'b010: r_pcie_rx_cur_len <= 8'h80; 3'b001: r_pcie_rx_cur_len <= 8'h40; default: r_pcie_rx_cur_len <= 8'h20; endcase r_pcie_mrd_delay <= LP_PCIE_MRD_DELAY; end S_PCIE_MRD_DELAY: begin r_pcie_mrd_delay <= r_pcie_mrd_delay - 1'b1; end S_PCIE_MRD_NEXT: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_RX_CMD_0: begin r_pcie_rx_cmd_rd_en <= 1; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_RX_CMD_1: begin r_pcie_rx_cmd_rd_en <= 1; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_CHK_NUM_MRD: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_REQ: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 1; r_tx_dma_mrd_req <= 1; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_ACK: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_DONE: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 1; end S_PCIE_MRD_DELAY: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_NEXT: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end default: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end endcase end endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_req # ( parameter P_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_read_req_size, output pcie_rx_cmd_rd_en, input [33:0] pcie_rx_cmd_rd_data, input pcie_rx_cmd_empty_n, output pcie_tag_alloc, output [7:0] pcie_alloc_tag, output [9:4] pcie_tag_alloc_len, input pcie_tag_full_n, input pcie_rx_fifo_full_n, output tx_dma_mrd_req, output [7:0] tx_dma_mrd_tag, output [11:2] tx_dma_mrd_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mrd_addr, input tx_dma_mrd_req_ack ); localparam LP_PCIE_TAG_PREFIX = 4'b0001; localparam LP_PCIE_MRD_DELAY = 8; localparam S_IDLE = 9'b000000001; localparam S_PCIE_RX_CMD_0 = 9'b000000010; localparam S_PCIE_RX_CMD_1 = 9'b000000100; localparam S_PCIE_CHK_NUM_MRD = 9'b000001000; localparam S_PCIE_MRD_REQ = 9'b000010000; localparam S_PCIE_MRD_ACK = 9'b000100000; localparam S_PCIE_MRD_DONE = 9'b001000000; localparam S_PCIE_MRD_DELAY = 9'b010000000; localparam S_PCIE_MRD_NEXT = 9'b100000000; reg [8:0] cur_state; reg [8:0] next_state; reg [2:0] r_pcie_max_read_req_size; reg r_pcie_rx_cmd_rd_en; reg [12:2] r_pcie_rx_len; reg [9:2] r_pcie_rx_cur_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_pcie_addr; reg [3:0] r_pcie_rx_tag; reg r_pcie_rx_tag_update; reg [5:0] r_pcie_mrd_delay; reg r_pcie_tag_alloc; reg r_tx_dma_mrd_req; assign pcie_rx_cmd_rd_en = r_pcie_rx_cmd_rd_en; assign pcie_tag_alloc = r_pcie_tag_alloc; assign pcie_alloc_tag = {LP_PCIE_TAG_PREFIX, r_pcie_rx_tag}; assign pcie_tag_alloc_len = r_pcie_rx_cur_len[9:4]; assign tx_dma_mrd_req = r_tx_dma_mrd_req; assign tx_dma_mrd_tag = {LP_PCIE_TAG_PREFIX, r_pcie_rx_tag}; assign tx_dma_mrd_len = {2'b0, r_pcie_rx_cur_len}; assign tx_dma_mrd_addr = r_pcie_addr; always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) cur_state <= S_IDLE; else cur_state <= next_state; end always @ (*) begin case(cur_state) S_IDLE: begin if(pcie_rx_cmd_empty_n == 1) next_state <= S_PCIE_RX_CMD_0; else next_state <= S_IDLE; end S_PCIE_RX_CMD_0: begin next_state <= S_PCIE_RX_CMD_1; end S_PCIE_RX_CMD_1: begin next_state <= S_PCIE_CHK_NUM_MRD; end S_PCIE_CHK_NUM_MRD: begin if(pcie_rx_fifo_full_n == 1 && pcie_tag_full_n == 1) next_state <= S_PCIE_MRD_REQ; else next_state <= S_PCIE_CHK_NUM_MRD; end S_PCIE_MRD_REQ: begin next_state <= S_PCIE_MRD_ACK; end S_PCIE_MRD_ACK: begin if(tx_dma_mrd_req_ack == 1) next_state <= S_PCIE_MRD_DONE; else next_state <= S_PCIE_MRD_ACK; end S_PCIE_MRD_DONE: begin next_state <= S_PCIE_MRD_DELAY; end S_PCIE_MRD_DELAY: begin if(r_pcie_mrd_delay == 0) next_state <= S_PCIE_MRD_NEXT; else next_state <= S_PCIE_MRD_DELAY; end S_PCIE_MRD_NEXT: begin if(r_pcie_rx_len == 0) next_state <= S_IDLE; else next_state <= S_PCIE_CHK_NUM_MRD; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) begin r_pcie_rx_tag <= 0; end else begin if(r_pcie_rx_tag_update == 1) r_pcie_rx_tag <= r_pcie_rx_tag + 1; end end always @ (posedge pcie_user_clk) begin r_pcie_max_read_req_size <= pcie_max_read_req_size; end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_RX_CMD_0: begin r_pcie_rx_len <= {pcie_rx_cmd_rd_data[10:2], 2'b0}; end S_PCIE_RX_CMD_1: begin case(r_pcie_max_read_req_size) 3'b010: begin if(r_pcie_rx_len[8:7] == 0 && r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b100; else r_pcie_rx_cur_len[9:7] <= {1'b0, r_pcie_rx_len[8:7]}; end 3'b001: begin if(r_pcie_rx_len[7] == 0 && r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b010; else r_pcie_rx_cur_len[9:7] <= {2'b0, r_pcie_rx_len[7]}; end default: begin if(r_pcie_rx_len[6:2] == 0) r_pcie_rx_cur_len[9:7] <= 3'b001; else r_pcie_rx_cur_len[9:7] <= 3'b000; end endcase r_pcie_rx_cur_len[6:2] <= r_pcie_rx_len[6:2]; r_pcie_addr <= {pcie_rx_cmd_rd_data[33:2], 2'b0}; end S_PCIE_CHK_NUM_MRD: begin end S_PCIE_MRD_REQ: begin end S_PCIE_MRD_ACK: begin end S_PCIE_MRD_DONE: begin r_pcie_addr <= r_pcie_addr + r_pcie_rx_cur_len; r_pcie_rx_len <= r_pcie_rx_len - r_pcie_rx_cur_len; case(r_pcie_max_read_req_size) 3'b010: r_pcie_rx_cur_len <= 8'h80; 3'b001: r_pcie_rx_cur_len <= 8'h40; default: r_pcie_rx_cur_len <= 8'h20; endcase r_pcie_mrd_delay <= LP_PCIE_MRD_DELAY; end S_PCIE_MRD_DELAY: begin r_pcie_mrd_delay <= r_pcie_mrd_delay - 1'b1; end S_PCIE_MRD_NEXT: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_RX_CMD_0: begin r_pcie_rx_cmd_rd_en <= 1; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_RX_CMD_1: begin r_pcie_rx_cmd_rd_en <= 1; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_CHK_NUM_MRD: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_REQ: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 1; r_tx_dma_mrd_req <= 1; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_ACK: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_DONE: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 1; end S_PCIE_MRD_DELAY: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end S_PCIE_MRD_NEXT: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end default: begin r_pcie_rx_cmd_rd_en <= 0; r_pcie_tag_alloc <= 0; r_tx_dma_mrd_req <= 0; r_pcie_rx_tag_update <= 0; end endcase end endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_tx_dma # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36, parameter C_M_AXI_DATA_WIDTH = 64 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_payload_size, input pcie_tx_cmd_wr_en, input [33:0] pcie_tx_cmd_wr_data, output pcie_tx_cmd_full_n, output tx_dma_mwr_req, output [7:0] tx_dma_mwr_tag, output [11:2] tx_dma_mwr_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mwr_addr, input tx_dma_mwr_req_ack, input tx_dma_mwr_data_last, input pcie_tx_dma_fifo_rd_en, output [C_PCIE_DATA_WIDTH-1:0] pcie_tx_dma_fifo_rd_data, output dma_tx_done_wr_en, output [20:0] dma_tx_done_wr_data, input dma_tx_done_wr_rdy_n, input dma_bus_clk, input dma_bus_rst_n, input pcie_tx_fifo_alloc_en, input [9:4] pcie_tx_fifo_alloc_len, input pcie_tx_fifo_wr_en, input [C_M_AXI_DATA_WIDTH-1:0] pcie_tx_fifo_wr_data, output pcie_tx_fifo_full_n ); wire w_pcie_tx_cmd_rd_en; wire [33:0] w_pcie_tx_cmd_rd_data; wire w_pcie_tx_cmd_empty_n; wire w_pcie_tx_fifo_free_en; wire [9:4] w_pcie_tx_fifo_free_len; wire w_pcie_tx_fifo_empty_n; pcie_tx_cmd_fifo pcie_tx_cmd_fifo_inst0 ( .clk (pcie_user_clk), .rst_n (pcie_user_rst_n), .wr_en (pcie_tx_cmd_wr_en), .wr_data (pcie_tx_cmd_wr_data), .full_n (pcie_tx_cmd_full_n), .rd_en (w_pcie_tx_cmd_rd_en), .rd_data (w_pcie_tx_cmd_rd_data), .empty_n (w_pcie_tx_cmd_empty_n) ); pcie_tx_fifo pcie_tx_fifo_inst0 ( .wr_clk (dma_bus_clk), .wr_rst_n (pcie_user_rst_n), .alloc_en (pcie_tx_fifo_alloc_en), .alloc_len (pcie_tx_fifo_alloc_len), .wr_en (pcie_tx_fifo_wr_en), .wr_data (pcie_tx_fifo_wr_data), .full_n (pcie_tx_fifo_full_n), .rd_clk (pcie_user_clk), .rd_rst_n (pcie_user_rst_n), .rd_en (pcie_tx_dma_fifo_rd_en), .rd_data (pcie_tx_dma_fifo_rd_data), .free_en (w_pcie_tx_fifo_free_en), .free_len (w_pcie_tx_fifo_free_len), .empty_n (w_pcie_tx_fifo_empty_n) ); pcie_tx_req # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH), .C_PCIE_ADDR_WIDTH (C_PCIE_ADDR_WIDTH) ) pcie_tx_req_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_max_payload_size (pcie_max_payload_size), .pcie_tx_cmd_rd_en (w_pcie_tx_cmd_rd_en), .pcie_tx_cmd_rd_data (w_pcie_tx_cmd_rd_data), .pcie_tx_cmd_empty_n (w_pcie_tx_cmd_empty_n), .pcie_tx_fifo_free_en (w_pcie_tx_fifo_free_en), .pcie_tx_fifo_free_len (w_pcie_tx_fifo_free_len), .pcie_tx_fifo_empty_n (w_pcie_tx_fifo_empty_n), .tx_dma_mwr_req (tx_dma_mwr_req), .tx_dma_mwr_tag (tx_dma_mwr_tag), .tx_dma_mwr_len (tx_dma_mwr_len), .tx_dma_mwr_addr (tx_dma_mwr_addr), .tx_dma_mwr_req_ack (tx_dma_mwr_req_ack), .tx_dma_mwr_data_last (tx_dma_mwr_data_last), .dma_tx_done_wr_en (dma_tx_done_wr_en), .dma_tx_done_wr_data (dma_tx_done_wr_data), .dma_tx_done_wr_rdy_n (dma_tx_done_wr_rdy_n) ); endmodule
// -*- verilog -*- // // USRP - Universal Software Radio Peripheral // // Copyright (C) 2003 Matt Ettus // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA // // Interface to Cypress FX2 bus // A packet is 512 Bytes. Each fifo line is 2 bytes // Fifo has 1024 or 2048 lines `include "../../firmware/include/fpga_regs_common.v" `include "../../firmware/include/fpga_regs_standard.v" module rx_buffer ( input usbclk, input bus_reset, // Not used in RX input reset, // DSP side reset (used here), do not reset registers input reset_regs, //Only reset registers output [15:0] usbdata, input RD, output wire have_pkt_rdy, output reg rx_overrun, input wire [3:0] channels, input wire [15:0] ch_0, input wire [15:0] ch_1, input wire [15:0] ch_2, input wire [15:0] ch_3, input wire [15:0] ch_4, input wire [15:0] ch_5, input wire [15:0] ch_6, input wire [15:0] ch_7, input rxclk, input rxstrobe, input clear_status, input [6:0] serial_addr, input [31:0] serial_data, input serial_strobe, output [15:0] debugbus ); wire [15:0] fifodata, fifodata_8; reg [15:0] fifodata_16; wire [11:0] rxfifolevel; wire rx_empty, rx_full; wire bypass_hb, want_q; wire [4:0] bitwidth; wire [3:0] bitshift; setting_reg #(`FR_RX_FORMAT) sr_rxformat(.clock(rxclk),.reset(reset_regs), .strobe(serial_strobe),.addr(serial_addr),.in(serial_data), .out({bypass_hb,want_q,bitwidth,bitshift})); // Receive FIFO (ADC --> USB) // 257 Bug Fix reg [8:0] read_count; always @(negedge usbclk) if(bus_reset) read_count <= #1 9'd0; else if(RD & ~read_count[8]) read_count <= #1 read_count + 9'd1; else read_count <= #1 RD ? read_count : 9'b0; // Detect overrun always @(posedge rxclk) if(reset) rx_overrun <= 1'b0; else if(rxstrobe & (store_next != 0)) rx_overrun <= 1'b1; else if(clear_status) rx_overrun <= 1'b0; reg [3:0] store_next; always @(posedge rxclk) if(reset) store_next <= #1 4'd0; else if(rxstrobe & (store_next == 0)) store_next <= #1 4'd1; else if(~rx_full & (store_next == channels)) store_next <= #1 4'd0; else if(~rx_full & (bitwidth == 5'd8) & (store_next == (channels>>1))) store_next <= #1 4'd0; else if(~rx_full & (store_next != 0)) store_next <= #1 store_next + 4'd1; assign fifodata = (bitwidth == 5'd8) ? fifodata_8 : fifodata_16; assign fifodata_8 = {round_8(top),round_8(bottom)}; reg [15:0] top,bottom; function [7:0] round_8; input [15:0] in_val; round_8 = in_val[15:8] + (in_val[15] & |in_val[7:0]); endfunction // round_8 always @* case(store_next) 4'd1 : begin bottom = ch_0; top = ch_1; end 4'd2 : begin bottom = ch_2; top = ch_3; end 4'd3 : begin bottom = ch_4; top = ch_5; end 4'd4 : begin bottom = ch_6; top = ch_7; end default : begin top = 16'hFFFF; bottom = 16'hFFFF; end endcase // case(store_next) always @* case(store_next) 4'd1 : fifodata_16 = ch_0; 4'd2 : fifodata_16 = ch_1; 4'd3 : fifodata_16 = ch_2; 4'd4 : fifodata_16 = ch_3; 4'd5 : fifodata_16 = ch_4; 4'd6 : fifodata_16 = ch_5; 4'd7 : fifodata_16 = ch_6; 4'd8 : fifodata_16 = ch_7; default : fifodata_16 = 16'hFFFF; endcase // case(store_next) fifo_4k rxfifo ( .data ( fifodata ), .wrreq (~rx_full & (store_next != 0)), .wrclk ( rxclk ), .q ( usbdata ), .rdreq ( RD & ~read_count[8] ), .rdclk ( ~usbclk ), .aclr ( reset ), // This one is asynchronous, so we can use either reset .rdempty ( rx_empty ), .rdusedw ( rxfifolevel ), .wrfull ( rx_full ), .wrusedw ( ) ); assign have_pkt_rdy = (rxfifolevel >= 256); // Debugging Aids assign debugbus[0] = RD; assign debugbus[1] = rx_overrun; assign debugbus[2] = read_count[8]; assign debugbus[3] = rx_full; assign debugbus[4] = rxstrobe; assign debugbus[5] = usbclk; assign debugbus[6] = have_pkt_rdy; assign debugbus[10:7] = store_next; //assign debugbus[15:11] = rxfifolevel[4:0]; assign debugbus[15:11] = bitwidth; endmodule // rx_buffer
// -*- verilog -*- // // USRP - Universal Software Radio Peripheral // // Copyright (C) 2003 Matt Ettus // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA // // Interface to Cypress FX2 bus // A packet is 512 Bytes. Each fifo line is 2 bytes // Fifo has 1024 or 2048 lines `include "../../firmware/include/fpga_regs_common.v" `include "../../firmware/include/fpga_regs_standard.v" module rx_buffer ( input usbclk, input bus_reset, // Not used in RX input reset, // DSP side reset (used here), do not reset registers input reset_regs, //Only reset registers output [15:0] usbdata, input RD, output wire have_pkt_rdy, output reg rx_overrun, input wire [3:0] channels, input wire [15:0] ch_0, input wire [15:0] ch_1, input wire [15:0] ch_2, input wire [15:0] ch_3, input wire [15:0] ch_4, input wire [15:0] ch_5, input wire [15:0] ch_6, input wire [15:0] ch_7, input rxclk, input rxstrobe, input clear_status, input [6:0] serial_addr, input [31:0] serial_data, input serial_strobe, output [15:0] debugbus ); wire [15:0] fifodata, fifodata_8; reg [15:0] fifodata_16; wire [11:0] rxfifolevel; wire rx_empty, rx_full; wire bypass_hb, want_q; wire [4:0] bitwidth; wire [3:0] bitshift; setting_reg #(`FR_RX_FORMAT) sr_rxformat(.clock(rxclk),.reset(reset_regs), .strobe(serial_strobe),.addr(serial_addr),.in(serial_data), .out({bypass_hb,want_q,bitwidth,bitshift})); // Receive FIFO (ADC --> USB) // 257 Bug Fix reg [8:0] read_count; always @(negedge usbclk) if(bus_reset) read_count <= #1 9'd0; else if(RD & ~read_count[8]) read_count <= #1 read_count + 9'd1; else read_count <= #1 RD ? read_count : 9'b0; // Detect overrun always @(posedge rxclk) if(reset) rx_overrun <= 1'b0; else if(rxstrobe & (store_next != 0)) rx_overrun <= 1'b1; else if(clear_status) rx_overrun <= 1'b0; reg [3:0] store_next; always @(posedge rxclk) if(reset) store_next <= #1 4'd0; else if(rxstrobe & (store_next == 0)) store_next <= #1 4'd1; else if(~rx_full & (store_next == channels)) store_next <= #1 4'd0; else if(~rx_full & (bitwidth == 5'd8) & (store_next == (channels>>1))) store_next <= #1 4'd0; else if(~rx_full & (store_next != 0)) store_next <= #1 store_next + 4'd1; assign fifodata = (bitwidth == 5'd8) ? fifodata_8 : fifodata_16; assign fifodata_8 = {round_8(top),round_8(bottom)}; reg [15:0] top,bottom; function [7:0] round_8; input [15:0] in_val; round_8 = in_val[15:8] + (in_val[15] & |in_val[7:0]); endfunction // round_8 always @* case(store_next) 4'd1 : begin bottom = ch_0; top = ch_1; end 4'd2 : begin bottom = ch_2; top = ch_3; end 4'd3 : begin bottom = ch_4; top = ch_5; end 4'd4 : begin bottom = ch_6; top = ch_7; end default : begin top = 16'hFFFF; bottom = 16'hFFFF; end endcase // case(store_next) always @* case(store_next) 4'd1 : fifodata_16 = ch_0; 4'd2 : fifodata_16 = ch_1; 4'd3 : fifodata_16 = ch_2; 4'd4 : fifodata_16 = ch_3; 4'd5 : fifodata_16 = ch_4; 4'd6 : fifodata_16 = ch_5; 4'd7 : fifodata_16 = ch_6; 4'd8 : fifodata_16 = ch_7; default : fifodata_16 = 16'hFFFF; endcase // case(store_next) fifo_4k rxfifo ( .data ( fifodata ), .wrreq (~rx_full & (store_next != 0)), .wrclk ( rxclk ), .q ( usbdata ), .rdreq ( RD & ~read_count[8] ), .rdclk ( ~usbclk ), .aclr ( reset ), // This one is asynchronous, so we can use either reset .rdempty ( rx_empty ), .rdusedw ( rxfifolevel ), .wrfull ( rx_full ), .wrusedw ( ) ); assign have_pkt_rdy = (rxfifolevel >= 256); // Debugging Aids assign debugbus[0] = RD; assign debugbus[1] = rx_overrun; assign debugbus[2] = read_count[8]; assign debugbus[3] = rx_full; assign debugbus[4] = rxstrobe; assign debugbus[5] = usbclk; assign debugbus[6] = have_pkt_rdy; assign debugbus[10:7] = store_next; //assign debugbus[15:11] = rxfifolevel[4:0]; assign debugbus[15:11] = bitwidth; endmodule // rx_buffer
// -*- verilog -*- // // USRP - Universal Software Radio Peripheral // // Copyright (C) 2003 Matt Ettus // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA // // Interface to Cypress FX2 bus // A packet is 512 Bytes. Each fifo line is 2 bytes // Fifo has 1024 or 2048 lines `include "../../firmware/include/fpga_regs_common.v" `include "../../firmware/include/fpga_regs_standard.v" module rx_buffer ( input usbclk, input bus_reset, // Not used in RX input reset, // DSP side reset (used here), do not reset registers input reset_regs, //Only reset registers output [15:0] usbdata, input RD, output wire have_pkt_rdy, output reg rx_overrun, input wire [3:0] channels, input wire [15:0] ch_0, input wire [15:0] ch_1, input wire [15:0] ch_2, input wire [15:0] ch_3, input wire [15:0] ch_4, input wire [15:0] ch_5, input wire [15:0] ch_6, input wire [15:0] ch_7, input rxclk, input rxstrobe, input clear_status, input [6:0] serial_addr, input [31:0] serial_data, input serial_strobe, output [15:0] debugbus ); wire [15:0] fifodata, fifodata_8; reg [15:0] fifodata_16; wire [11:0] rxfifolevel; wire rx_empty, rx_full; wire bypass_hb, want_q; wire [4:0] bitwidth; wire [3:0] bitshift; setting_reg #(`FR_RX_FORMAT) sr_rxformat(.clock(rxclk),.reset(reset_regs), .strobe(serial_strobe),.addr(serial_addr),.in(serial_data), .out({bypass_hb,want_q,bitwidth,bitshift})); // Receive FIFO (ADC --> USB) // 257 Bug Fix reg [8:0] read_count; always @(negedge usbclk) if(bus_reset) read_count <= #1 9'd0; else if(RD & ~read_count[8]) read_count <= #1 read_count + 9'd1; else read_count <= #1 RD ? read_count : 9'b0; // Detect overrun always @(posedge rxclk) if(reset) rx_overrun <= 1'b0; else if(rxstrobe & (store_next != 0)) rx_overrun <= 1'b1; else if(clear_status) rx_overrun <= 1'b0; reg [3:0] store_next; always @(posedge rxclk) if(reset) store_next <= #1 4'd0; else if(rxstrobe & (store_next == 0)) store_next <= #1 4'd1; else if(~rx_full & (store_next == channels)) store_next <= #1 4'd0; else if(~rx_full & (bitwidth == 5'd8) & (store_next == (channels>>1))) store_next <= #1 4'd0; else if(~rx_full & (store_next != 0)) store_next <= #1 store_next + 4'd1; assign fifodata = (bitwidth == 5'd8) ? fifodata_8 : fifodata_16; assign fifodata_8 = {round_8(top),round_8(bottom)}; reg [15:0] top,bottom; function [7:0] round_8; input [15:0] in_val; round_8 = in_val[15:8] + (in_val[15] & |in_val[7:0]); endfunction // round_8 always @* case(store_next) 4'd1 : begin bottom = ch_0; top = ch_1; end 4'd2 : begin bottom = ch_2; top = ch_3; end 4'd3 : begin bottom = ch_4; top = ch_5; end 4'd4 : begin bottom = ch_6; top = ch_7; end default : begin top = 16'hFFFF; bottom = 16'hFFFF; end endcase // case(store_next) always @* case(store_next) 4'd1 : fifodata_16 = ch_0; 4'd2 : fifodata_16 = ch_1; 4'd3 : fifodata_16 = ch_2; 4'd4 : fifodata_16 = ch_3; 4'd5 : fifodata_16 = ch_4; 4'd6 : fifodata_16 = ch_5; 4'd7 : fifodata_16 = ch_6; 4'd8 : fifodata_16 = ch_7; default : fifodata_16 = 16'hFFFF; endcase // case(store_next) fifo_4k rxfifo ( .data ( fifodata ), .wrreq (~rx_full & (store_next != 0)), .wrclk ( rxclk ), .q ( usbdata ), .rdreq ( RD & ~read_count[8] ), .rdclk ( ~usbclk ), .aclr ( reset ), // This one is asynchronous, so we can use either reset .rdempty ( rx_empty ), .rdusedw ( rxfifolevel ), .wrfull ( rx_full ), .wrusedw ( ) ); assign have_pkt_rdy = (rxfifolevel >= 256); // Debugging Aids assign debugbus[0] = RD; assign debugbus[1] = rx_overrun; assign debugbus[2] = read_count[8]; assign debugbus[3] = rx_full; assign debugbus[4] = rxstrobe; assign debugbus[5] = usbclk; assign debugbus[6] = have_pkt_rdy; assign debugbus[10:7] = store_next; //assign debugbus[15:11] = rxfifolevel[4:0]; assign debugbus[15:11] = bitwidth; endmodule // rx_buffer
// -*- verilog -*- // // USRP - Universal Software Radio Peripheral // // Copyright (C) 2003 Matt Ettus // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA // // Interface to Cypress FX2 bus // A packet is 512 Bytes. Each fifo line is 2 bytes // Fifo has 1024 or 2048 lines `include "../../firmware/include/fpga_regs_common.v" `include "../../firmware/include/fpga_regs_standard.v" module rx_buffer ( input usbclk, input bus_reset, // Not used in RX input reset, // DSP side reset (used here), do not reset registers input reset_regs, //Only reset registers output [15:0] usbdata, input RD, output wire have_pkt_rdy, output reg rx_overrun, input wire [3:0] channels, input wire [15:0] ch_0, input wire [15:0] ch_1, input wire [15:0] ch_2, input wire [15:0] ch_3, input wire [15:0] ch_4, input wire [15:0] ch_5, input wire [15:0] ch_6, input wire [15:0] ch_7, input rxclk, input rxstrobe, input clear_status, input [6:0] serial_addr, input [31:0] serial_data, input serial_strobe, output [15:0] debugbus ); wire [15:0] fifodata, fifodata_8; reg [15:0] fifodata_16; wire [11:0] rxfifolevel; wire rx_empty, rx_full; wire bypass_hb, want_q; wire [4:0] bitwidth; wire [3:0] bitshift; setting_reg #(`FR_RX_FORMAT) sr_rxformat(.clock(rxclk),.reset(reset_regs), .strobe(serial_strobe),.addr(serial_addr),.in(serial_data), .out({bypass_hb,want_q,bitwidth,bitshift})); // Receive FIFO (ADC --> USB) // 257 Bug Fix reg [8:0] read_count; always @(negedge usbclk) if(bus_reset) read_count <= #1 9'd0; else if(RD & ~read_count[8]) read_count <= #1 read_count + 9'd1; else read_count <= #1 RD ? read_count : 9'b0; // Detect overrun always @(posedge rxclk) if(reset) rx_overrun <= 1'b0; else if(rxstrobe & (store_next != 0)) rx_overrun <= 1'b1; else if(clear_status) rx_overrun <= 1'b0; reg [3:0] store_next; always @(posedge rxclk) if(reset) store_next <= #1 4'd0; else if(rxstrobe & (store_next == 0)) store_next <= #1 4'd1; else if(~rx_full & (store_next == channels)) store_next <= #1 4'd0; else if(~rx_full & (bitwidth == 5'd8) & (store_next == (channels>>1))) store_next <= #1 4'd0; else if(~rx_full & (store_next != 0)) store_next <= #1 store_next + 4'd1; assign fifodata = (bitwidth == 5'd8) ? fifodata_8 : fifodata_16; assign fifodata_8 = {round_8(top),round_8(bottom)}; reg [15:0] top,bottom; function [7:0] round_8; input [15:0] in_val; round_8 = in_val[15:8] + (in_val[15] & |in_val[7:0]); endfunction // round_8 always @* case(store_next) 4'd1 : begin bottom = ch_0; top = ch_1; end 4'd2 : begin bottom = ch_2; top = ch_3; end 4'd3 : begin bottom = ch_4; top = ch_5; end 4'd4 : begin bottom = ch_6; top = ch_7; end default : begin top = 16'hFFFF; bottom = 16'hFFFF; end endcase // case(store_next) always @* case(store_next) 4'd1 : fifodata_16 = ch_0; 4'd2 : fifodata_16 = ch_1; 4'd3 : fifodata_16 = ch_2; 4'd4 : fifodata_16 = ch_3; 4'd5 : fifodata_16 = ch_4; 4'd6 : fifodata_16 = ch_5; 4'd7 : fifodata_16 = ch_6; 4'd8 : fifodata_16 = ch_7; default : fifodata_16 = 16'hFFFF; endcase // case(store_next) fifo_4k rxfifo ( .data ( fifodata ), .wrreq (~rx_full & (store_next != 0)), .wrclk ( rxclk ), .q ( usbdata ), .rdreq ( RD & ~read_count[8] ), .rdclk ( ~usbclk ), .aclr ( reset ), // This one is asynchronous, so we can use either reset .rdempty ( rx_empty ), .rdusedw ( rxfifolevel ), .wrfull ( rx_full ), .wrusedw ( ) ); assign have_pkt_rdy = (rxfifolevel >= 256); // Debugging Aids assign debugbus[0] = RD; assign debugbus[1] = rx_overrun; assign debugbus[2] = read_count[8]; assign debugbus[3] = rx_full; assign debugbus[4] = rxstrobe; assign debugbus[5] = usbclk; assign debugbus[6] = have_pkt_rdy; assign debugbus[10:7] = store_next; //assign debugbus[15:11] = rxfifolevel[4:0]; assign debugbus[15:11] = bitwidth; endmodule // rx_buffer
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_fifo # ( parameter P_FIFO_WR_DATA_WIDTH = 128, parameter P_FIFO_RD_DATA_WIDTH = 64, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input wr_en, input [P_FIFO_DEPTH_WIDTH-1:0] wr_addr, input [P_FIFO_WR_DATA_WIDTH-1:0] wr_data, input [P_FIFO_DEPTH_WIDTH:0] rear_full_addr, input [P_FIFO_DEPTH_WIDTH:0] rear_addr, input [9:4] alloc_len, output full_n, input rd_clk, input rd_rst_n, input rd_en, output [P_FIFO_RD_DATA_WIDTH-1:0] rd_data, input free_en, input [9:4] free_len, output empty_n ); localparam P_FIFO_RD_DEPTH_WIDTH = P_FIFO_DEPTH_WIDTH + 1; localparam S_SYNC_STAGE0 = 3'b001; localparam S_SYNC_STAGE1 = 3'b010; localparam S_SYNC_STAGE2 = 3'b100; reg [2:0] cur_wr_state; reg [2:0] next_wr_state; reg [2:0] cur_rd_state; reg [2:0] next_rd_state; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync_en; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH:0] r_front_sync_addr; reg [P_FIFO_RD_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_RD_DEPTH_WIDTH:0] r_front_addr_p1; reg [P_FIFO_DEPTH_WIDTH:0] r_front_empty_addr; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync_en ; reg [P_FIFO_DEPTH_WIDTH:0] r_front_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH:0] r_rear_sync_addr; wire [(P_FIFO_RD_DATA_WIDTH*2)-1:0] w_bram_rd_data; wire [P_FIFO_RD_DATA_WIDTH-1:0] w_rd_data; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; wire [P_FIFO_DEPTH_WIDTH:0] w_valid_space; wire [P_FIFO_DEPTH_WIDTH:0] w_invalid_space; assign rd_data = w_rd_data; assign w_invalid_space = r_front_sync_addr - rear_full_addr; assign full_n = (w_invalid_space >= alloc_len); assign w_valid_space = r_rear_sync_addr - r_front_empty_addr; assign empty_n = (w_valid_space >= free_len); always @(posedge rd_clk or negedge rd_rst_n) begin if (rd_rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; r_front_empty_addr <= 0; end else begin if (rd_en == 1) begin r_front_addr <= r_front_addr_p1; r_front_addr_p1 <= r_front_addr_p1 + 1; end if (free_en == 1) r_front_empty_addr <= r_front_empty_addr + free_len; end end assign w_front_addr = (rd_en == 1) ? r_front_addr_p1[P_FIFO_RD_DEPTH_WIDTH-1:1] : r_front_addr[P_FIFO_RD_DEPTH_WIDTH-1:1]; assign w_rd_data = (r_front_addr[0] == 0) ? w_bram_rd_data[P_FIFO_RD_DATA_WIDTH-1:0] : w_bram_rd_data[(P_FIFO_RD_DATA_WIDTH*2)-1:P_FIFO_RD_DATA_WIDTH]; ///////////////////////////////////////////////////////////////////////////////////////////// always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_wr_state <= S_SYNC_STAGE0; else cur_wr_state <= next_wr_state; end always @(posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) r_rear_sync_en <= 0; else r_rear_sync_en <= r_rear_sync; end always @(posedge wr_clk) begin r_front_sync_en_d1 <= r_front_sync_en; r_front_sync_en_d2 <= r_front_sync_en_d1; end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin if(r_front_sync_en_d2 == 1) next_wr_state <= S_SYNC_STAGE1; else next_wr_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_wr_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_front_sync_en_d2 == 0) next_wr_state <= S_SYNC_STAGE0; else next_wr_state <= S_SYNC_STAGE2; end default: begin next_wr_state <= S_SYNC_STAGE0; end endcase end always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) begin r_rear_sync_data <= 0; r_front_sync_addr[P_FIFO_DEPTH_WIDTH] <= 1; r_front_sync_addr[P_FIFO_DEPTH_WIDTH-1:0] <= 0; end else begin case(cur_wr_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_rear_sync_data <= rear_addr; r_front_sync_addr <= r_front_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin r_rear_sync <= 0; end S_SYNC_STAGE1: begin r_rear_sync <= 0; end S_SYNC_STAGE2: begin r_rear_sync <= 1; end default: begin r_rear_sync <= 0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) cur_rd_state <= S_SYNC_STAGE0; else cur_rd_state <= next_rd_state; end always @(posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) r_front_sync_en <= 0; else r_front_sync_en <= r_front_sync; end always @(posedge rd_clk) begin r_rear_sync_en_d1 <= r_rear_sync_en; r_rear_sync_en_d2 <= r_rear_sync_en_d1; end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin if(r_rear_sync_en_d2 == 1) next_rd_state <= S_SYNC_STAGE1; else next_rd_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_rd_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_rear_sync_en_d2 == 0) next_rd_state <= S_SYNC_STAGE0; else next_rd_state <= S_SYNC_STAGE2; end default: begin next_rd_state <= S_SYNC_STAGE0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) begin r_front_sync_data[P_FIFO_DEPTH_WIDTH] <= 1; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= 0; r_rear_sync_addr <= 0; end else begin case(cur_rd_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_front_sync_data[P_FIFO_DEPTH_WIDTH] <= ~r_front_addr[P_FIFO_RD_DEPTH_WIDTH]; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= r_front_addr[P_FIFO_RD_DEPTH_WIDTH-1:1]; r_rear_sync_addr <= r_rear_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin r_front_sync <= 1; end S_SYNC_STAGE1: begin r_front_sync <= 1; end S_SYNC_STAGE2: begin r_front_sync <= 0; end default: begin r_front_sync <= 0; end endcase end ///////////////////////////////////////////////////////////////////////////////////////////// localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_RD_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_FIFO_WR_DATA_WIDTH/2; localparam LP_WRITE_MODE = "WRITE_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_FIFO_DEPTH_WIDTH; generate wire [LP_ADDR_TOTAL_WITDH-1:0] rdaddr; wire [LP_ADDR_TOTAL_WITDH-1:0] wraddr; wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; if(LP_ADDR_ZERO_PAD_WITDH == 0) begin : calc_addr assign rdaddr = w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; assign wraddr = wr_addr[P_FIFO_DEPTH_WIDTH-1:0]; end else begin assign rdaddr = {zero_padding[LP_ADDR_ZERO_PAD_WITDH-1:0], w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]}; assign wraddr = {zero_padding[LP_ADDR_ZERO_PAD_WITDH-1:0], wr_addr[P_FIFO_DEPTH_WIDTH-1:0]}; end endgenerate BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_0( .DO (w_bram_rd_data[LP_READ_WIDTH-1:0]), .DI (wr_data[LP_WRITE_WIDTH-1:0]), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (wr_en) ); BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_1( .DO (w_bram_rd_data[(P_FIFO_RD_DATA_WIDTH*2)-1:LP_READ_WIDTH]), .DI (wr_data[P_FIFO_WR_DATA_WIDTH-1:LP_WRITE_WIDTH]), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (wr_en) ); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_fifo # ( parameter P_FIFO_WR_DATA_WIDTH = 128, parameter P_FIFO_RD_DATA_WIDTH = 64, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input wr_en, input [P_FIFO_DEPTH_WIDTH-1:0] wr_addr, input [P_FIFO_WR_DATA_WIDTH-1:0] wr_data, input [P_FIFO_DEPTH_WIDTH:0] rear_full_addr, input [P_FIFO_DEPTH_WIDTH:0] rear_addr, input [9:4] alloc_len, output full_n, input rd_clk, input rd_rst_n, input rd_en, output [P_FIFO_RD_DATA_WIDTH-1:0] rd_data, input free_en, input [9:4] free_len, output empty_n ); localparam P_FIFO_RD_DEPTH_WIDTH = P_FIFO_DEPTH_WIDTH + 1; localparam S_SYNC_STAGE0 = 3'b001; localparam S_SYNC_STAGE1 = 3'b010; localparam S_SYNC_STAGE2 = 3'b100; reg [2:0] cur_wr_state; reg [2:0] next_wr_state; reg [2:0] cur_rd_state; reg [2:0] next_rd_state; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_rear_sync_en; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_front_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH:0] r_front_sync_addr; reg [P_FIFO_RD_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_RD_DEPTH_WIDTH:0] r_front_addr_p1; reg [P_FIFO_DEPTH_WIDTH:0] r_front_empty_addr; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync; (* KEEP = "TRUE", EQUIVALENT_REGISTER_REMOVAL = "NO" *) reg r_front_sync_en ; reg [P_FIFO_DEPTH_WIDTH:0] r_front_sync_data; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d1; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg r_rear_sync_en_d2; (* KEEP = "TRUE", SHIFT_EXTRACT = "NO" *) reg [P_FIFO_DEPTH_WIDTH:0] r_rear_sync_addr; wire [(P_FIFO_RD_DATA_WIDTH*2)-1:0] w_bram_rd_data; wire [P_FIFO_RD_DATA_WIDTH-1:0] w_rd_data; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; wire [P_FIFO_DEPTH_WIDTH:0] w_valid_space; wire [P_FIFO_DEPTH_WIDTH:0] w_invalid_space; assign rd_data = w_rd_data; assign w_invalid_space = r_front_sync_addr - rear_full_addr; assign full_n = (w_invalid_space >= alloc_len); assign w_valid_space = r_rear_sync_addr - r_front_empty_addr; assign empty_n = (w_valid_space >= free_len); always @(posedge rd_clk or negedge rd_rst_n) begin if (rd_rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; r_front_empty_addr <= 0; end else begin if (rd_en == 1) begin r_front_addr <= r_front_addr_p1; r_front_addr_p1 <= r_front_addr_p1 + 1; end if (free_en == 1) r_front_empty_addr <= r_front_empty_addr + free_len; end end assign w_front_addr = (rd_en == 1) ? r_front_addr_p1[P_FIFO_RD_DEPTH_WIDTH-1:1] : r_front_addr[P_FIFO_RD_DEPTH_WIDTH-1:1]; assign w_rd_data = (r_front_addr[0] == 0) ? w_bram_rd_data[P_FIFO_RD_DATA_WIDTH-1:0] : w_bram_rd_data[(P_FIFO_RD_DATA_WIDTH*2)-1:P_FIFO_RD_DATA_WIDTH]; ///////////////////////////////////////////////////////////////////////////////////////////// always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) cur_wr_state <= S_SYNC_STAGE0; else cur_wr_state <= next_wr_state; end always @(posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) r_rear_sync_en <= 0; else r_rear_sync_en <= r_rear_sync; end always @(posedge wr_clk) begin r_front_sync_en_d1 <= r_front_sync_en; r_front_sync_en_d2 <= r_front_sync_en_d1; end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin if(r_front_sync_en_d2 == 1) next_wr_state <= S_SYNC_STAGE1; else next_wr_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_wr_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_front_sync_en_d2 == 0) next_wr_state <= S_SYNC_STAGE0; else next_wr_state <= S_SYNC_STAGE2; end default: begin next_wr_state <= S_SYNC_STAGE0; end endcase end always @ (posedge wr_clk or negedge wr_rst_n) begin if(wr_rst_n == 0) begin r_rear_sync_data <= 0; r_front_sync_addr[P_FIFO_DEPTH_WIDTH] <= 1; r_front_sync_addr[P_FIFO_DEPTH_WIDTH-1:0] <= 0; end else begin case(cur_wr_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_rear_sync_data <= rear_addr; r_front_sync_addr <= r_front_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_wr_state) S_SYNC_STAGE0: begin r_rear_sync <= 0; end S_SYNC_STAGE1: begin r_rear_sync <= 0; end S_SYNC_STAGE2: begin r_rear_sync <= 1; end default: begin r_rear_sync <= 0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) cur_rd_state <= S_SYNC_STAGE0; else cur_rd_state <= next_rd_state; end always @(posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) r_front_sync_en <= 0; else r_front_sync_en <= r_front_sync; end always @(posedge rd_clk) begin r_rear_sync_en_d1 <= r_rear_sync_en; r_rear_sync_en_d2 <= r_rear_sync_en_d1; end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin if(r_rear_sync_en_d2 == 1) next_rd_state <= S_SYNC_STAGE1; else next_rd_state <= S_SYNC_STAGE0; end S_SYNC_STAGE1: begin next_rd_state <= S_SYNC_STAGE2; end S_SYNC_STAGE2: begin if(r_rear_sync_en_d2 == 0) next_rd_state <= S_SYNC_STAGE0; else next_rd_state <= S_SYNC_STAGE2; end default: begin next_rd_state <= S_SYNC_STAGE0; end endcase end always @ (posedge rd_clk or negedge rd_rst_n) begin if(rd_rst_n == 0) begin r_front_sync_data[P_FIFO_DEPTH_WIDTH] <= 1; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= 0; r_rear_sync_addr <= 0; end else begin case(cur_rd_state) S_SYNC_STAGE0: begin end S_SYNC_STAGE1: begin r_front_sync_data[P_FIFO_DEPTH_WIDTH] <= ~r_front_addr[P_FIFO_RD_DEPTH_WIDTH]; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= r_front_addr[P_FIFO_RD_DEPTH_WIDTH-1:1]; r_rear_sync_addr <= r_rear_sync_data; end S_SYNC_STAGE2: begin end default: begin end endcase end end always @ (*) begin case(cur_rd_state) S_SYNC_STAGE0: begin r_front_sync <= 1; end S_SYNC_STAGE1: begin r_front_sync <= 1; end S_SYNC_STAGE2: begin r_front_sync <= 0; end default: begin r_front_sync <= 0; end endcase end ///////////////////////////////////////////////////////////////////////////////////////////// localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_RD_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_FIFO_WR_DATA_WIDTH/2; localparam LP_WRITE_MODE = "WRITE_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_FIFO_DEPTH_WIDTH; generate wire [LP_ADDR_TOTAL_WITDH-1:0] rdaddr; wire [LP_ADDR_TOTAL_WITDH-1:0] wraddr; wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; if(LP_ADDR_ZERO_PAD_WITDH == 0) begin : calc_addr assign rdaddr = w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; assign wraddr = wr_addr[P_FIFO_DEPTH_WIDTH-1:0]; end else begin assign rdaddr = {zero_padding[LP_ADDR_ZERO_PAD_WITDH-1:0], w_front_addr[P_FIFO_DEPTH_WIDTH-1:0]}; assign wraddr = {zero_padding[LP_ADDR_ZERO_PAD_WITDH-1:0], wr_addr[P_FIFO_DEPTH_WIDTH-1:0]}; end endgenerate BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_0( .DO (w_bram_rd_data[LP_READ_WIDTH-1:0]), .DI (wr_data[LP_WRITE_WIDTH-1:0]), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (wr_en) ); BRAM_SDP_MACRO #( .DEVICE (LP_DEVICE), .BRAM_SIZE (LP_BRAM_SIZE), .DO_REG (LP_DOB_REG), .READ_WIDTH (LP_READ_WIDTH), .WRITE_WIDTH (LP_WRITE_WIDTH), .WRITE_MODE (LP_WRITE_MODE) ) ramb36sdp_1( .DO (w_bram_rd_data[(P_FIFO_RD_DATA_WIDTH*2)-1:LP_READ_WIDTH]), .DI (wr_data[P_FIFO_WR_DATA_WIDTH-1:LP_WRITE_WIDTH]), .RDADDR (rdaddr), .RDCLK (rd_clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (wr_clk), .WREN (wr_en) ); 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; integer p_i; reg [7*8:1] p_str; initial begin if ($test$plusargs("PLUS")!==1) $stop; if ($test$plusargs("PLUSNOT")!==0) $stop; if ($test$plusargs("PL")!==1) $stop; //if ($test$plusargs("")!==1) $stop; // Simulators differ in this answer if ($test$plusargs("NOTTHERE")!==0) $stop; p_i = 10; if ($value$plusargs("NOTTHERE%d", p_i)!==0) $stop; if (p_i !== 10) $stop; if ($value$plusargs("INT=%d", p_i)!==1) $stop; if (p_i !== 32'd1234) $stop; if ($value$plusargs("INT=%H", p_i)!==1) $stop; // tests uppercase % also if (p_i !== 32'h1234) $stop; if ($value$plusargs("INT=%o", p_i)!==1) $stop; if (p_i !== 32'o1234) $stop; if ($value$plusargs("IN%s", p_str)!==1) $stop; $display("str='%s'",p_str); if (p_str !== "T=1234") $stop; $write("*-* All Finished *-*\n"); $finish; end endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_dma # ( parameter P_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36, parameter C_M_AXI_DATA_WIDTH = 64 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_read_req_size, input pcie_rx_cmd_wr_en, input [33:0] pcie_rx_cmd_wr_data, output pcie_rx_cmd_full_n, output tx_dma_mrd_req, output [7:0] tx_dma_mrd_tag, output [11:2] tx_dma_mrd_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mrd_addr, input tx_dma_mrd_req_ack, input [7:0] cpld_dma_fifo_tag, input [P_PCIE_DATA_WIDTH-1:0] cpld_dma_fifo_wr_data, input cpld_dma_fifo_wr_en, input cpld_dma_fifo_tag_last, input dma_bus_clk, input dma_bus_rst_n, input pcie_rx_fifo_rd_en, output [C_M_AXI_DATA_WIDTH-1:0] pcie_rx_fifo_rd_data, input pcie_rx_fifo_free_en, input [9:4] pcie_rx_fifo_free_len, output pcie_rx_fifo_empty_n ); wire w_pcie_rx_cmd_rd_en; wire [33:0] w_pcie_rx_cmd_rd_data; wire w_pcie_rx_cmd_empty_n; wire w_pcie_tag_alloc; wire [7:0] w_pcie_alloc_tag; wire [9:4] w_pcie_tag_alloc_len; wire w_pcie_tag_full_n; wire w_pcie_rx_fifo_full_n; wire w_fifo_wr_en; wire [8:0] w_fifo_wr_addr; wire [127:0] w_fifo_wr_data; wire [9:0] w_rear_full_addr; wire [9:0] w_rear_addr; pcie_rx_cmd_fifo pcie_rx_cmd_fifo_inst0 ( .clk (pcie_user_clk), .rst_n (pcie_user_rst_n), .wr_en (pcie_rx_cmd_wr_en), .wr_data (pcie_rx_cmd_wr_data), .full_n (pcie_rx_cmd_full_n), .rd_en (w_pcie_rx_cmd_rd_en), .rd_data (w_pcie_rx_cmd_rd_data), .empty_n (w_pcie_rx_cmd_empty_n) ); pcie_rx_fifo pcie_rx_fifo_inst0 ( .wr_clk (pcie_user_clk), .wr_rst_n (pcie_user_rst_n), .wr_en (w_fifo_wr_en), .wr_addr (w_fifo_wr_addr), .wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr), .alloc_len (w_pcie_tag_alloc_len), .full_n (w_pcie_rx_fifo_full_n), .rd_clk (dma_bus_clk), .rd_rst_n (pcie_user_rst_n), .rd_en (pcie_rx_fifo_rd_en), .rd_data (pcie_rx_fifo_rd_data), .free_en (pcie_rx_fifo_free_en), .free_len (pcie_rx_fifo_free_len), .empty_n (pcie_rx_fifo_empty_n) ); pcie_rx_tag pcie_rx_tag_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .cpld_fifo_tag (cpld_dma_fifo_tag), .cpld_fifo_wr_data (cpld_dma_fifo_wr_data), .cpld_fifo_wr_en (cpld_dma_fifo_wr_en), .cpld_fifo_tag_last (cpld_dma_fifo_tag_last), .fifo_wr_en (w_fifo_wr_en), .fifo_wr_addr (w_fifo_wr_addr), .fifo_wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr) ); pcie_rx_req # ( .P_PCIE_DATA_WIDTH (P_PCIE_DATA_WIDTH), .C_PCIE_ADDR_WIDTH (C_PCIE_ADDR_WIDTH) ) pcie_rx_req_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_max_read_req_size (pcie_max_read_req_size), .pcie_rx_cmd_rd_en (w_pcie_rx_cmd_rd_en), .pcie_rx_cmd_rd_data (w_pcie_rx_cmd_rd_data), .pcie_rx_cmd_empty_n (w_pcie_rx_cmd_empty_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .pcie_rx_fifo_full_n (w_pcie_rx_fifo_full_n), .tx_dma_mrd_req (tx_dma_mrd_req), .tx_dma_mrd_tag (tx_dma_mrd_tag), .tx_dma_mrd_len (tx_dma_mrd_len), .tx_dma_mrd_addr (tx_dma_mrd_addr), .tx_dma_mrd_req_ack (tx_dma_mrd_req_ack) ); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_dma # ( parameter P_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36, parameter C_M_AXI_DATA_WIDTH = 64 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_read_req_size, input pcie_rx_cmd_wr_en, input [33:0] pcie_rx_cmd_wr_data, output pcie_rx_cmd_full_n, output tx_dma_mrd_req, output [7:0] tx_dma_mrd_tag, output [11:2] tx_dma_mrd_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mrd_addr, input tx_dma_mrd_req_ack, input [7:0] cpld_dma_fifo_tag, input [P_PCIE_DATA_WIDTH-1:0] cpld_dma_fifo_wr_data, input cpld_dma_fifo_wr_en, input cpld_dma_fifo_tag_last, input dma_bus_clk, input dma_bus_rst_n, input pcie_rx_fifo_rd_en, output [C_M_AXI_DATA_WIDTH-1:0] pcie_rx_fifo_rd_data, input pcie_rx_fifo_free_en, input [9:4] pcie_rx_fifo_free_len, output pcie_rx_fifo_empty_n ); wire w_pcie_rx_cmd_rd_en; wire [33:0] w_pcie_rx_cmd_rd_data; wire w_pcie_rx_cmd_empty_n; wire w_pcie_tag_alloc; wire [7:0] w_pcie_alloc_tag; wire [9:4] w_pcie_tag_alloc_len; wire w_pcie_tag_full_n; wire w_pcie_rx_fifo_full_n; wire w_fifo_wr_en; wire [8:0] w_fifo_wr_addr; wire [127:0] w_fifo_wr_data; wire [9:0] w_rear_full_addr; wire [9:0] w_rear_addr; pcie_rx_cmd_fifo pcie_rx_cmd_fifo_inst0 ( .clk (pcie_user_clk), .rst_n (pcie_user_rst_n), .wr_en (pcie_rx_cmd_wr_en), .wr_data (pcie_rx_cmd_wr_data), .full_n (pcie_rx_cmd_full_n), .rd_en (w_pcie_rx_cmd_rd_en), .rd_data (w_pcie_rx_cmd_rd_data), .empty_n (w_pcie_rx_cmd_empty_n) ); pcie_rx_fifo pcie_rx_fifo_inst0 ( .wr_clk (pcie_user_clk), .wr_rst_n (pcie_user_rst_n), .wr_en (w_fifo_wr_en), .wr_addr (w_fifo_wr_addr), .wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr), .alloc_len (w_pcie_tag_alloc_len), .full_n (w_pcie_rx_fifo_full_n), .rd_clk (dma_bus_clk), .rd_rst_n (pcie_user_rst_n), .rd_en (pcie_rx_fifo_rd_en), .rd_data (pcie_rx_fifo_rd_data), .free_en (pcie_rx_fifo_free_en), .free_len (pcie_rx_fifo_free_len), .empty_n (pcie_rx_fifo_empty_n) ); pcie_rx_tag pcie_rx_tag_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .cpld_fifo_tag (cpld_dma_fifo_tag), .cpld_fifo_wr_data (cpld_dma_fifo_wr_data), .cpld_fifo_wr_en (cpld_dma_fifo_wr_en), .cpld_fifo_tag_last (cpld_dma_fifo_tag_last), .fifo_wr_en (w_fifo_wr_en), .fifo_wr_addr (w_fifo_wr_addr), .fifo_wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr) ); pcie_rx_req # ( .P_PCIE_DATA_WIDTH (P_PCIE_DATA_WIDTH), .C_PCIE_ADDR_WIDTH (C_PCIE_ADDR_WIDTH) ) pcie_rx_req_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_max_read_req_size (pcie_max_read_req_size), .pcie_rx_cmd_rd_en (w_pcie_rx_cmd_rd_en), .pcie_rx_cmd_rd_data (w_pcie_rx_cmd_rd_data), .pcie_rx_cmd_empty_n (w_pcie_rx_cmd_empty_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .pcie_rx_fifo_full_n (w_pcie_rx_fifo_full_n), .tx_dma_mrd_req (tx_dma_mrd_req), .tx_dma_mrd_tag (tx_dma_mrd_tag), .tx_dma_mrd_len (tx_dma_mrd_len), .tx_dma_mrd_addr (tx_dma_mrd_addr), .tx_dma_mrd_req_ack (tx_dma_mrd_req_ack) ); endmodule
/* ---------------------------------------------------------------------------------- Copyright (c) 2013-2014 Embedded and Network Computing Lab. Open SSD Project Hanyang University All rights reserved. ---------------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this source code must display the following acknowledgement: This product includes source code developed by the Embedded and Network Computing Lab. and the Open SSD Project. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------------- http://enclab.hanyang.ac.kr/ http://www.openssd-project.org/ http://www.hanyang.ac.kr/ ---------------------------------------------------------------------------------- */ `timescale 1ns / 1ps module pcie_rx_dma # ( parameter P_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36, parameter C_M_AXI_DATA_WIDTH = 64 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_read_req_size, input pcie_rx_cmd_wr_en, input [33:0] pcie_rx_cmd_wr_data, output pcie_rx_cmd_full_n, output tx_dma_mrd_req, output [7:0] tx_dma_mrd_tag, output [11:2] tx_dma_mrd_len, output [C_PCIE_ADDR_WIDTH-1:2] tx_dma_mrd_addr, input tx_dma_mrd_req_ack, input [7:0] cpld_dma_fifo_tag, input [P_PCIE_DATA_WIDTH-1:0] cpld_dma_fifo_wr_data, input cpld_dma_fifo_wr_en, input cpld_dma_fifo_tag_last, input dma_bus_clk, input dma_bus_rst_n, input pcie_rx_fifo_rd_en, output [C_M_AXI_DATA_WIDTH-1:0] pcie_rx_fifo_rd_data, input pcie_rx_fifo_free_en, input [9:4] pcie_rx_fifo_free_len, output pcie_rx_fifo_empty_n ); wire w_pcie_rx_cmd_rd_en; wire [33:0] w_pcie_rx_cmd_rd_data; wire w_pcie_rx_cmd_empty_n; wire w_pcie_tag_alloc; wire [7:0] w_pcie_alloc_tag; wire [9:4] w_pcie_tag_alloc_len; wire w_pcie_tag_full_n; wire w_pcie_rx_fifo_full_n; wire w_fifo_wr_en; wire [8:0] w_fifo_wr_addr; wire [127:0] w_fifo_wr_data; wire [9:0] w_rear_full_addr; wire [9:0] w_rear_addr; pcie_rx_cmd_fifo pcie_rx_cmd_fifo_inst0 ( .clk (pcie_user_clk), .rst_n (pcie_user_rst_n), .wr_en (pcie_rx_cmd_wr_en), .wr_data (pcie_rx_cmd_wr_data), .full_n (pcie_rx_cmd_full_n), .rd_en (w_pcie_rx_cmd_rd_en), .rd_data (w_pcie_rx_cmd_rd_data), .empty_n (w_pcie_rx_cmd_empty_n) ); pcie_rx_fifo pcie_rx_fifo_inst0 ( .wr_clk (pcie_user_clk), .wr_rst_n (pcie_user_rst_n), .wr_en (w_fifo_wr_en), .wr_addr (w_fifo_wr_addr), .wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr), .alloc_len (w_pcie_tag_alloc_len), .full_n (w_pcie_rx_fifo_full_n), .rd_clk (dma_bus_clk), .rd_rst_n (pcie_user_rst_n), .rd_en (pcie_rx_fifo_rd_en), .rd_data (pcie_rx_fifo_rd_data), .free_en (pcie_rx_fifo_free_en), .free_len (pcie_rx_fifo_free_len), .empty_n (pcie_rx_fifo_empty_n) ); pcie_rx_tag pcie_rx_tag_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .cpld_fifo_tag (cpld_dma_fifo_tag), .cpld_fifo_wr_data (cpld_dma_fifo_wr_data), .cpld_fifo_wr_en (cpld_dma_fifo_wr_en), .cpld_fifo_tag_last (cpld_dma_fifo_tag_last), .fifo_wr_en (w_fifo_wr_en), .fifo_wr_addr (w_fifo_wr_addr), .fifo_wr_data (w_fifo_wr_data), .rear_full_addr (w_rear_full_addr), .rear_addr (w_rear_addr) ); pcie_rx_req # ( .P_PCIE_DATA_WIDTH (P_PCIE_DATA_WIDTH), .C_PCIE_ADDR_WIDTH (C_PCIE_ADDR_WIDTH) ) pcie_rx_req_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_max_read_req_size (pcie_max_read_req_size), .pcie_rx_cmd_rd_en (w_pcie_rx_cmd_rd_en), .pcie_rx_cmd_rd_data (w_pcie_rx_cmd_rd_data), .pcie_rx_cmd_empty_n (w_pcie_rx_cmd_empty_n), .pcie_tag_alloc (w_pcie_tag_alloc), .pcie_alloc_tag (w_pcie_alloc_tag), .pcie_tag_alloc_len (w_pcie_tag_alloc_len), .pcie_tag_full_n (w_pcie_tag_full_n), .pcie_rx_fifo_full_n (w_pcie_rx_fifo_full_n), .tx_dma_mrd_req (tx_dma_mrd_req), .tx_dma_mrd_tag (tx_dma_mrd_tag), .tx_dma_mrd_len (tx_dma_mrd_len), .tx_dma_mrd_addr (tx_dma_mrd_addr), .tx_dma_mrd_req_ack (tx_dma_mrd_req_ack) ); endmodule