text
stringlengths
938
1.05M
// 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
// 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
// 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. // 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
// (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
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: // Engineer: // // Create Date: 19:19:08 12/01/2010 // Design Name: // Module Name: sd_dma // Project Name: // Target Devices: // Tool versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // ////////////////////////////////////////////////////////////////////////////////// module sd_dma( input [3:0] SD_DAT, inout SD_CLK, input CLK, input SD_DMA_EN, output SD_DMA_STATUS, output SD_DMA_SRAM_WE, output SD_DMA_NEXTADDR, output [7:0] SD_DMA_SRAM_DATA, input SD_DMA_PARTIAL, input [10:0] SD_DMA_PARTIAL_START, input [10:0] SD_DMA_PARTIAL_END, input SD_DMA_START_MID_BLOCK, input SD_DMA_END_MID_BLOCK, output [10:0] DBG_cyclecnt, output [2:0] DBG_clkcnt ); reg [10:0] SD_DMA_STARTr; reg [10:0] SD_DMA_ENDr; reg SD_DMA_PARTIALr; always @(posedge CLK) SD_DMA_PARTIALr <= SD_DMA_PARTIAL; reg SD_DMA_DONEr; reg[1:0] SD_DMA_DONEr2; initial begin SD_DMA_DONEr2 = 2'b00; SD_DMA_DONEr = 1'b0; end always @(posedge CLK) SD_DMA_DONEr2 <= {SD_DMA_DONEr2[0], SD_DMA_DONEr}; wire SD_DMA_DONE_rising = (SD_DMA_DONEr2[1:0] == 2'b01); reg [1:0] SD_DMA_ENr; initial SD_DMA_ENr = 2'b00; always @(posedge CLK) SD_DMA_ENr <= {SD_DMA_ENr[0], SD_DMA_EN}; wire SD_DMA_EN_rising = (SD_DMA_ENr [1:0] == 2'b01); reg SD_DMA_STATUSr; assign SD_DMA_STATUS = SD_DMA_STATUSr; reg SD_DMA_CLKMASKr = 1'b1; // we need 1042 cycles (startbit + 1024 nibbles + 16 crc + stopbit) reg [10:0] cyclecnt; initial cyclecnt = 11'd0; reg SD_DMA_SRAM_WEr; initial SD_DMA_SRAM_WEr = 1'b1; assign SD_DMA_SRAM_WE = (cyclecnt < 1025 && SD_DMA_STATUSr) ? SD_DMA_SRAM_WEr : 1'b1; reg SD_DMA_NEXTADDRr; assign SD_DMA_NEXTADDR = (cyclecnt < 1025 && SD_DMA_STATUSr) ? SD_DMA_NEXTADDRr : 1'b0; reg[7:0] SD_DMA_SRAM_DATAr; assign SD_DMA_SRAM_DATA = SD_DMA_SRAM_DATAr; // we have 4 internal cycles per SD clock, 8 per RAM byte write reg [2:0] clkcnt; initial clkcnt = 3'b000; reg [1:0] SD_CLKr; initial SD_CLKr = 3'b111; always @(posedge CLK) if(SD_DMA_EN_rising) SD_CLKr <= 3'b111; else SD_CLKr <= {SD_CLKr[0], clkcnt[1]}; assign SD_CLK = SD_DMA_CLKMASKr ? 1'bZ : SD_CLKr[1]; always @(posedge CLK) begin if(SD_DMA_EN_rising) begin SD_DMA_STATUSr <= 1'b1; SD_DMA_STARTr <= (SD_DMA_PARTIALr ? SD_DMA_PARTIAL_START : 11'h0); SD_DMA_ENDr <= (SD_DMA_PARTIALr ? SD_DMA_PARTIAL_END : 11'd1024); end else if (SD_DMA_DONE_rising) SD_DMA_STATUSr <= 1'b0; end always @(posedge CLK) begin if(SD_DMA_EN_rising) begin SD_DMA_CLKMASKr <= 1'b0; end else if (SD_DMA_DONEr) begin SD_DMA_CLKMASKr <= 1'b1; end end always @(posedge CLK) begin if(cyclecnt == 1042 || ((SD_DMA_END_MID_BLOCK & SD_DMA_PARTIALr) && cyclecnt == SD_DMA_PARTIAL_END)) SD_DMA_DONEr <= 1; else SD_DMA_DONEr <= 0; end always @(posedge CLK) begin if(SD_DMA_EN_rising || !SD_DMA_STATUSr) begin clkcnt <= 0; end else begin if(SD_DMA_STATUSr) begin clkcnt <= clkcnt + 1; end end end always @(posedge CLK) begin if(SD_DMA_EN_rising) cyclecnt <= (SD_DMA_PARTIALr && SD_DMA_START_MID_BLOCK) ? SD_DMA_PARTIAL_START : 0; else if(!SD_DMA_STATUSr) cyclecnt <= 0; else if(clkcnt[1:0] == 2'b10) cyclecnt <= cyclecnt + 1; end // we have 8 clk cycles to complete one RAM write // (4 clk cycles per SD_CLK; 2 SD_CLK cycles per byte) always @(posedge CLK) begin if(SD_DMA_STATUSr) begin case(clkcnt[2:0]) 3'h0: begin SD_DMA_SRAM_DATAr[7:4] <= SD_DAT; if(cyclecnt>SD_DMA_STARTr && cyclecnt <= SD_DMA_ENDr) SD_DMA_NEXTADDRr <= 1'b1; end 3'h1: begin SD_DMA_NEXTADDRr <= 1'b0; end 3'h2: if(cyclecnt>=SD_DMA_STARTr && cyclecnt < SD_DMA_ENDr) SD_DMA_SRAM_WEr <= 1'b0; // 3'h3: 3'h4: SD_DMA_SRAM_DATAr[3:0] <= SD_DAT; // 3'h5: // 3'h6: 3'h7: SD_DMA_SRAM_WEr <= 1'b1; endcase end end endmodule
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: // Engineer: // // Create Date: 19:19:08 12/01/2010 // Design Name: // Module Name: sd_dma // Project Name: // Target Devices: // Tool versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // ////////////////////////////////////////////////////////////////////////////////// module sd_dma( input [3:0] SD_DAT, inout SD_CLK, input CLK, input SD_DMA_EN, output SD_DMA_STATUS, output SD_DMA_SRAM_WE, output SD_DMA_NEXTADDR, output [7:0] SD_DMA_SRAM_DATA, input SD_DMA_PARTIAL, input [10:0] SD_DMA_PARTIAL_START, input [10:0] SD_DMA_PARTIAL_END, input SD_DMA_START_MID_BLOCK, input SD_DMA_END_MID_BLOCK, output [10:0] DBG_cyclecnt, output [2:0] DBG_clkcnt ); reg [10:0] SD_DMA_STARTr; reg [10:0] SD_DMA_ENDr; reg SD_DMA_PARTIALr; always @(posedge CLK) SD_DMA_PARTIALr <= SD_DMA_PARTIAL; reg SD_DMA_DONEr; reg[1:0] SD_DMA_DONEr2; initial begin SD_DMA_DONEr2 = 2'b00; SD_DMA_DONEr = 1'b0; end always @(posedge CLK) SD_DMA_DONEr2 <= {SD_DMA_DONEr2[0], SD_DMA_DONEr}; wire SD_DMA_DONE_rising = (SD_DMA_DONEr2[1:0] == 2'b01); reg [1:0] SD_DMA_ENr; initial SD_DMA_ENr = 2'b00; always @(posedge CLK) SD_DMA_ENr <= {SD_DMA_ENr[0], SD_DMA_EN}; wire SD_DMA_EN_rising = (SD_DMA_ENr [1:0] == 2'b01); reg SD_DMA_STATUSr; assign SD_DMA_STATUS = SD_DMA_STATUSr; reg SD_DMA_CLKMASKr = 1'b1; // we need 1042 cycles (startbit + 1024 nibbles + 16 crc + stopbit) reg [10:0] cyclecnt; initial cyclecnt = 11'd0; reg SD_DMA_SRAM_WEr; initial SD_DMA_SRAM_WEr = 1'b1; assign SD_DMA_SRAM_WE = (cyclecnt < 1025 && SD_DMA_STATUSr) ? SD_DMA_SRAM_WEr : 1'b1; reg SD_DMA_NEXTADDRr; assign SD_DMA_NEXTADDR = (cyclecnt < 1025 && SD_DMA_STATUSr) ? SD_DMA_NEXTADDRr : 1'b0; reg[7:0] SD_DMA_SRAM_DATAr; assign SD_DMA_SRAM_DATA = SD_DMA_SRAM_DATAr; // we have 4 internal cycles per SD clock, 8 per RAM byte write reg [2:0] clkcnt; initial clkcnt = 3'b000; reg [1:0] SD_CLKr; initial SD_CLKr = 3'b111; always @(posedge CLK) if(SD_DMA_EN_rising) SD_CLKr <= 3'b111; else SD_CLKr <= {SD_CLKr[0], clkcnt[1]}; assign SD_CLK = SD_DMA_CLKMASKr ? 1'bZ : SD_CLKr[1]; always @(posedge CLK) begin if(SD_DMA_EN_rising) begin SD_DMA_STATUSr <= 1'b1; SD_DMA_STARTr <= (SD_DMA_PARTIALr ? SD_DMA_PARTIAL_START : 11'h0); SD_DMA_ENDr <= (SD_DMA_PARTIALr ? SD_DMA_PARTIAL_END : 11'd1024); end else if (SD_DMA_DONE_rising) SD_DMA_STATUSr <= 1'b0; end always @(posedge CLK) begin if(SD_DMA_EN_rising) begin SD_DMA_CLKMASKr <= 1'b0; end else if (SD_DMA_DONEr) begin SD_DMA_CLKMASKr <= 1'b1; end end always @(posedge CLK) begin if(cyclecnt == 1042 || ((SD_DMA_END_MID_BLOCK & SD_DMA_PARTIALr) && cyclecnt == SD_DMA_PARTIAL_END)) SD_DMA_DONEr <= 1; else SD_DMA_DONEr <= 0; end always @(posedge CLK) begin if(SD_DMA_EN_rising || !SD_DMA_STATUSr) begin clkcnt <= 0; end else begin if(SD_DMA_STATUSr) begin clkcnt <= clkcnt + 1; end end end always @(posedge CLK) begin if(SD_DMA_EN_rising) cyclecnt <= (SD_DMA_PARTIALr && SD_DMA_START_MID_BLOCK) ? SD_DMA_PARTIAL_START : 0; else if(!SD_DMA_STATUSr) cyclecnt <= 0; else if(clkcnt[1:0] == 2'b10) cyclecnt <= cyclecnt + 1; end // we have 8 clk cycles to complete one RAM write // (4 clk cycles per SD_CLK; 2 SD_CLK cycles per byte) always @(posedge CLK) begin if(SD_DMA_STATUSr) begin case(clkcnt[2:0]) 3'h0: begin SD_DMA_SRAM_DATAr[7:4] <= SD_DAT; if(cyclecnt>SD_DMA_STARTr && cyclecnt <= SD_DMA_ENDr) SD_DMA_NEXTADDRr <= 1'b1; end 3'h1: begin SD_DMA_NEXTADDRr <= 1'b0; end 3'h2: if(cyclecnt>=SD_DMA_STARTr && cyclecnt < SD_DMA_ENDr) SD_DMA_SRAM_WEr <= 1'b0; // 3'h3: 3'h4: SD_DMA_SRAM_DATAr[3:0] <= SD_DAT; // 3'h5: // 3'h6: 3'h7: SD_DMA_SRAM_WEr <= 1'b1; endcase end end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2011 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; reg [63:0] crc; reg [63:0] sum; wire [3:0] drv_a = crc[3:0]; wire [3:0] drv_b = crc[7:4]; wire [3:0] drv_e = crc[19:16]; /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [8:0] match1; // From test1 of Test1.v wire [8:0] match2; // From test2 of Test2.v // End of automatics Test1 test1 (/*AUTOINST*/ // Outputs .match1 (match1[8:0]), // Inputs .drv_a (drv_a[3:0]), .drv_e (drv_e[3:0])); Test2 test2 (/*AUTOINST*/ // Outputs .match2 (match2[8:0]), // Inputs .drv_a (drv_a[3:0]), .drv_e (drv_e[3:0])); // Aggregate outputs into a single result vector wire [63:0] result = {39'h0, match2, 7'h0, match1}; // Test loop always @ (posedge clk) begin `ifdef TEST_VERBOSE $write("[%0t] cyc==%0d crc=%x m1=%x m2=%x (%b??%b:%b)\n",$time, cyc, crc, match1, match2, drv_e,drv_a,drv_b); `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'hc0c4a2b9aea7c4b4 if (sum !== `EXPECTED_SUM) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module Test1 ( input wire [3:0] drv_a, input wire [3:0] drv_e, output wire [8:0] match1 ); wire [2:1] drv_all; bufif1 bufa [2:1] (drv_all, drv_a[2:1], drv_e[2:1]); `ifdef VERILATOR // At present Verilator only allows comparisons with Zs assign match1[0] = (drv_a[2:1]== 2'b00 && drv_e[2:1]==2'b11); assign match1[1] = (drv_a[2:1]== 2'b01 && drv_e[2:1]==2'b11); assign match1[2] = (drv_a[2:1]== 2'b10 && drv_e[2:1]==2'b11); assign match1[3] = (drv_a[2:1]== 2'b11 && drv_e[2:1]==2'b11); `else assign match1[0] = drv_all === 2'b00; assign match1[1] = drv_all === 2'b01; assign match1[2] = drv_all === 2'b10; assign match1[3] = drv_all === 2'b11; `endif assign match1[4] = drv_all === 2'bz0; assign match1[5] = drv_all === 2'bz1; assign match1[6] = drv_all === 2'bzz; assign match1[7] = drv_all === 2'b0z; assign match1[8] = drv_all === 2'b1z; endmodule module Test2 ( input wire [3:0] drv_a, input wire [3:0] drv_e, output wire [8:0] match2 ); wire [2:1] drv_all; bufif1 bufa [2:1] (drv_all, drv_a[2:1], drv_e[2:1]); `ifdef VERILATOR assign match2[0] = (drv_all !== 2'b00 || drv_e[2:1]!=2'b11); assign match2[1] = (drv_all !== 2'b01 || drv_e[2:1]!=2'b11); assign match2[2] = (drv_all !== 2'b10 || drv_e[2:1]!=2'b11); assign match2[3] = (drv_all !== 2'b11 || drv_e[2:1]!=2'b11); `else assign match2[0] = drv_all !== 2'b00; assign match2[1] = drv_all !== 2'b01; assign match2[2] = drv_all !== 2'b10; assign match2[3] = drv_all !== 2'b11; `endif assign match2[4] = drv_all !== 2'bz0; assign match2[5] = drv_all !== 2'bz1; assign match2[6] = drv_all !== 2'bzz; assign match2[7] = drv_all !== 2'b0z; assign match2[8] = drv_all !== 2'b1z; endmodule
/* Copyright (c) 2014-2017 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Language: Verilog-2001 `timescale 1 ns / 1 ps /* * Synchronizes switch and button inputs with a slow sampled shift register */ module debounce_switch #( parameter WIDTH=1, // width of the input and output signals parameter N=3, // length of shift register parameter RATE=125000 // clock division factor )( input wire clk, input wire rst, input wire [WIDTH-1:0] in, output wire [WIDTH-1:0] out ); reg [23:0] cnt_reg = 24'd0; reg [N-1:0] debounce_reg[WIDTH-1:0]; reg [WIDTH-1:0] state; /* * The synchronized output is the state register */ assign out = state; integer k; always @(posedge clk or posedge rst) begin if (rst) begin cnt_reg <= 0; state <= 0; for (k = 0; k < WIDTH; k = k + 1) begin debounce_reg[k] <= 0; end end else begin if (cnt_reg < RATE) begin cnt_reg <= cnt_reg + 24'd1; end else begin cnt_reg <= 24'd0; end if (cnt_reg == 24'd0) begin for (k = 0; k < WIDTH; k = k + 1) begin debounce_reg[k] <= {debounce_reg[k][N-2:0], in[k]}; end end for (k = 0; k < WIDTH; k = k + 1) begin if (|debounce_reg[k] == 0) begin state[k] <= 0; end else if (&debounce_reg[k] == 1) begin state[k] <= 1; end else begin state[k] <= state[k]; end end end end endmodule
/* Copyright (c) 2014-2017 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Language: Verilog-2001 `timescale 1 ns / 1 ps /* * Synchronizes switch and button inputs with a slow sampled shift register */ module debounce_switch #( parameter WIDTH=1, // width of the input and output signals parameter N=3, // length of shift register parameter RATE=125000 // clock division factor )( input wire clk, input wire rst, input wire [WIDTH-1:0] in, output wire [WIDTH-1:0] out ); reg [23:0] cnt_reg = 24'd0; reg [N-1:0] debounce_reg[WIDTH-1:0]; reg [WIDTH-1:0] state; /* * The synchronized output is the state register */ assign out = state; integer k; always @(posedge clk or posedge rst) begin if (rst) begin cnt_reg <= 0; state <= 0; for (k = 0; k < WIDTH; k = k + 1) begin debounce_reg[k] <= 0; end end else begin if (cnt_reg < RATE) begin cnt_reg <= cnt_reg + 24'd1; end else begin cnt_reg <= 24'd0; end if (cnt_reg == 24'd0) begin for (k = 0; k < WIDTH; k = k + 1) begin debounce_reg[k] <= {debounce_reg[k][N-2:0], in[k]}; end end for (k = 0; k < WIDTH; k = k + 1) begin if (|debounce_reg[k] == 0) begin state[k] <= 0; end else if (&debounce_reg[k] == 1) begin state[k] <= 1; end else begin state[k] <= state[k]; end end end 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; 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
(** * 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
// 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
// // (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. // Work-group limiter. This module has two interface points: the entry point // and the exit point. The purpose of the module is to ensure that there are // no more than WG_LIMIT work-groups in the pipeline between the entry and // exit points. The limiter also remaps the kernel-level work-group id into // a local work-group id; this is needed because in general the kernel-level // work-group id space is larger than the local work-group id space. It is // assumed that any work-item that passes through the entry point will pass // through the exit point at some point. // // The ordering of the work-groups affects the implementation. In particular, // if the work-group order is the same through the entry point and the exit // point, the implementation is simple. This is referred to as work-group FIFO // (first-in-first-out) order. It remains a TODO to support work-group // non-FIFO order (through the exit point). // // The work-group order does NOT matter if WG_LIMIT >= KERNEL_WG_LIMIT. // In this configuration, the real limiter is at the kernel-level and this // work-group limiter does not do anything useful. It does match the latency // specifiction though so that the latency and capacity of the core is the // same regardless of the configuration. // // Latency/capacity: // Through entry: 1 cycle // Through exit: 1 cycle module acl_work_group_limiter #( parameter unsigned WG_LIMIT = 1, // >0 parameter unsigned KERNEL_WG_LIMIT = 1, // >0 parameter unsigned MAX_WG_SIZE = 1, // >0 parameter unsigned WG_FIFO_ORDER = 1, // 0|1 parameter string IMPL = "local" // kernel|local ) ( clock, resetn, wg_size, // Limiter entry entry_valid_in, entry_k_wgid, entry_stall_out, entry_valid_out, entry_l_wgid, entry_stall_in, // Limiter exit exit_valid_in, exit_l_wgid, exit_stall_out, exit_valid_out, exit_stall_in ); input logic clock; input logic resetn; // check for overflow localparam MAX_WG_SIZE_WIDTH = $clog2({1'b0, MAX_WG_SIZE} + 1); input logic [MAX_WG_SIZE_WIDTH-1:0] wg_size; // Limiter entry input logic entry_valid_in; input logic [$clog2(KERNEL_WG_LIMIT)-1:0] entry_k_wgid; // not used if WG_FIFO_ORDER==1 output logic entry_stall_out; output logic entry_valid_out; output logic [$clog2(WG_LIMIT)-1:0] entry_l_wgid; input logic entry_stall_in; // Limiter exit input logic exit_valid_in; input logic [$clog2(WG_LIMIT)-1:0] exit_l_wgid; // never used output logic exit_stall_out; output logic exit_valid_out; input logic exit_stall_in; generate // WG_FIFO_ORDER needs to be handled first because the limiter always needs // to generate the work-group if( WG_FIFO_ORDER == 1 ) begin // IMPLEMENTATION ASSUMPTION: complete work-groups are assumed to // pass-through work-group and therefore it is sufficient to declare // a work-group as done when wg_size work-items have appeared at one point logic [MAX_WG_SIZE_WIDTH-1:0] wg_size_limit /* synthesis preserve */; always @(posedge clock) wg_size_limit <= wg_size - 'd1; // this is a constant throughout the execution of an kernel, but register to limit fanout of source // Number of active work-groups that have (partially) entered the limiter and have not // (completely) exited the limiter. Counts from 0 to WG_LIMIT. logic [$clog2(WG_LIMIT+1)-1:0] active_wg_count; logic incr_active_wg, decr_active_wg; logic active_wg_limit_reached; // Number of work-items seen in the currently-entering work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_entry_wg_wi_count; logic cur_entry_wg_wi_count_eq_zero; logic [$clog2(WG_LIMIT)-1:0] cur_entry_l_wgid; // Number of work-items seen in the currently-exiting work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_exit_wg_wi_count; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin active_wg_count <= '0; active_wg_limit_reached <= 1'b0; end else begin active_wg_count <= active_wg_count + incr_active_wg - decr_active_wg; if( (active_wg_count == WG_LIMIT - 1) & incr_active_wg & ~decr_active_wg ) active_wg_limit_reached <= 1'b1; else if( (active_wg_count == WG_LIMIT) & decr_active_wg ) active_wg_limit_reached <= 1'b0; end end // // Entry logic: latency = 1 // logic accept_entry; logic entry_output_stall_out; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; cur_entry_l_wgid <= '0; end else if( accept_entry ) begin if( cur_entry_wg_wi_count == wg_size_limit ) begin // The entering work-item is the last work-item of the current // work-group. Prepare for the next work-group. cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; if( cur_entry_l_wgid == WG_LIMIT - 1 ) cur_entry_l_wgid <= '0; else cur_entry_l_wgid <= cur_entry_l_wgid + 'd1; end else begin // Increment work-item counter. cur_entry_wg_wi_count <= cur_entry_wg_wi_count + 'd1; cur_entry_wg_wi_count_eq_zero <= 1'b0; end end end assign incr_active_wg = cur_entry_wg_wi_count_eq_zero & accept_entry; assign accept_entry = entry_valid_in & ~entry_output_stall_out & ~(active_wg_limit_reached & cur_entry_wg_wi_count_eq_zero); // Register entry output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_output_stall_out ) begin entry_valid_out <= accept_entry; entry_l_wgid <= cur_entry_l_wgid; end end assign entry_output_stall_out = entry_valid_out & entry_stall_in; assign entry_stall_out = entry_valid_in & ~accept_entry; // // Exit logic: latency = 1 // always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_exit_wg_wi_count <= '0; end else if( exit_valid_in & ~exit_stall_out ) begin if( cur_exit_wg_wi_count == wg_size_limit ) begin // The exiting work-item is the last work-item of the current // work-group. Entire work-group has cleared. cur_exit_wg_wi_count <= '0; end else begin // Increment work-item counter. cur_exit_wg_wi_count <= cur_exit_wg_wi_count + 'd1; end end end assign decr_active_wg = exit_valid_in & ~exit_stall_out & (cur_exit_wg_wi_count == wg_size_limit); // Register output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else if( IMPL == "local" && WG_LIMIT >= KERNEL_WG_LIMIT ) begin // In this scenario, this work-group limiter doesn't have to do anything // because the kernel-level limit is already sufficient. // // Simply use the kernel hwid as the local hwid. // // This particular implementation is suitable for any kind of // work-item ordering at entry and exit. Register to meet the latency // requirements. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_stall_out ) begin entry_valid_out <= entry_valid_in; entry_l_wgid <= entry_k_wgid; end end assign entry_stall_out = entry_valid_out & entry_stall_in; always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else begin // synthesis translate off initial $fatal("%m: unsupported configuration (WG_LIMIT < KERNEL_WG_LIMIT and WG_FIFO_ORDER != 1)"); // synthesis translate on 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. // Work-group limiter. This module has two interface points: the entry point // and the exit point. The purpose of the module is to ensure that there are // no more than WG_LIMIT work-groups in the pipeline between the entry and // exit points. The limiter also remaps the kernel-level work-group id into // a local work-group id; this is needed because in general the kernel-level // work-group id space is larger than the local work-group id space. It is // assumed that any work-item that passes through the entry point will pass // through the exit point at some point. // // The ordering of the work-groups affects the implementation. In particular, // if the work-group order is the same through the entry point and the exit // point, the implementation is simple. This is referred to as work-group FIFO // (first-in-first-out) order. It remains a TODO to support work-group // non-FIFO order (through the exit point). // // The work-group order does NOT matter if WG_LIMIT >= KERNEL_WG_LIMIT. // In this configuration, the real limiter is at the kernel-level and this // work-group limiter does not do anything useful. It does match the latency // specifiction though so that the latency and capacity of the core is the // same regardless of the configuration. // // Latency/capacity: // Through entry: 1 cycle // Through exit: 1 cycle module acl_work_group_limiter #( parameter unsigned WG_LIMIT = 1, // >0 parameter unsigned KERNEL_WG_LIMIT = 1, // >0 parameter unsigned MAX_WG_SIZE = 1, // >0 parameter unsigned WG_FIFO_ORDER = 1, // 0|1 parameter string IMPL = "local" // kernel|local ) ( clock, resetn, wg_size, // Limiter entry entry_valid_in, entry_k_wgid, entry_stall_out, entry_valid_out, entry_l_wgid, entry_stall_in, // Limiter exit exit_valid_in, exit_l_wgid, exit_stall_out, exit_valid_out, exit_stall_in ); input logic clock; input logic resetn; // check for overflow localparam MAX_WG_SIZE_WIDTH = $clog2({1'b0, MAX_WG_SIZE} + 1); input logic [MAX_WG_SIZE_WIDTH-1:0] wg_size; // Limiter entry input logic entry_valid_in; input logic [$clog2(KERNEL_WG_LIMIT)-1:0] entry_k_wgid; // not used if WG_FIFO_ORDER==1 output logic entry_stall_out; output logic entry_valid_out; output logic [$clog2(WG_LIMIT)-1:0] entry_l_wgid; input logic entry_stall_in; // Limiter exit input logic exit_valid_in; input logic [$clog2(WG_LIMIT)-1:0] exit_l_wgid; // never used output logic exit_stall_out; output logic exit_valid_out; input logic exit_stall_in; generate // WG_FIFO_ORDER needs to be handled first because the limiter always needs // to generate the work-group if( WG_FIFO_ORDER == 1 ) begin // IMPLEMENTATION ASSUMPTION: complete work-groups are assumed to // pass-through work-group and therefore it is sufficient to declare // a work-group as done when wg_size work-items have appeared at one point logic [MAX_WG_SIZE_WIDTH-1:0] wg_size_limit /* synthesis preserve */; always @(posedge clock) wg_size_limit <= wg_size - 'd1; // this is a constant throughout the execution of an kernel, but register to limit fanout of source // Number of active work-groups that have (partially) entered the limiter and have not // (completely) exited the limiter. Counts from 0 to WG_LIMIT. logic [$clog2(WG_LIMIT+1)-1:0] active_wg_count; logic incr_active_wg, decr_active_wg; logic active_wg_limit_reached; // Number of work-items seen in the currently-entering work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_entry_wg_wi_count; logic cur_entry_wg_wi_count_eq_zero; logic [$clog2(WG_LIMIT)-1:0] cur_entry_l_wgid; // Number of work-items seen in the currently-exiting work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_exit_wg_wi_count; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin active_wg_count <= '0; active_wg_limit_reached <= 1'b0; end else begin active_wg_count <= active_wg_count + incr_active_wg - decr_active_wg; if( (active_wg_count == WG_LIMIT - 1) & incr_active_wg & ~decr_active_wg ) active_wg_limit_reached <= 1'b1; else if( (active_wg_count == WG_LIMIT) & decr_active_wg ) active_wg_limit_reached <= 1'b0; end end // // Entry logic: latency = 1 // logic accept_entry; logic entry_output_stall_out; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; cur_entry_l_wgid <= '0; end else if( accept_entry ) begin if( cur_entry_wg_wi_count == wg_size_limit ) begin // The entering work-item is the last work-item of the current // work-group. Prepare for the next work-group. cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; if( cur_entry_l_wgid == WG_LIMIT - 1 ) cur_entry_l_wgid <= '0; else cur_entry_l_wgid <= cur_entry_l_wgid + 'd1; end else begin // Increment work-item counter. cur_entry_wg_wi_count <= cur_entry_wg_wi_count + 'd1; cur_entry_wg_wi_count_eq_zero <= 1'b0; end end end assign incr_active_wg = cur_entry_wg_wi_count_eq_zero & accept_entry; assign accept_entry = entry_valid_in & ~entry_output_stall_out & ~(active_wg_limit_reached & cur_entry_wg_wi_count_eq_zero); // Register entry output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_output_stall_out ) begin entry_valid_out <= accept_entry; entry_l_wgid <= cur_entry_l_wgid; end end assign entry_output_stall_out = entry_valid_out & entry_stall_in; assign entry_stall_out = entry_valid_in & ~accept_entry; // // Exit logic: latency = 1 // always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_exit_wg_wi_count <= '0; end else if( exit_valid_in & ~exit_stall_out ) begin if( cur_exit_wg_wi_count == wg_size_limit ) begin // The exiting work-item is the last work-item of the current // work-group. Entire work-group has cleared. cur_exit_wg_wi_count <= '0; end else begin // Increment work-item counter. cur_exit_wg_wi_count <= cur_exit_wg_wi_count + 'd1; end end end assign decr_active_wg = exit_valid_in & ~exit_stall_out & (cur_exit_wg_wi_count == wg_size_limit); // Register output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else if( IMPL == "local" && WG_LIMIT >= KERNEL_WG_LIMIT ) begin // In this scenario, this work-group limiter doesn't have to do anything // because the kernel-level limit is already sufficient. // // Simply use the kernel hwid as the local hwid. // // This particular implementation is suitable for any kind of // work-item ordering at entry and exit. Register to meet the latency // requirements. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_stall_out ) begin entry_valid_out <= entry_valid_in; entry_l_wgid <= entry_k_wgid; end end assign entry_stall_out = entry_valid_out & entry_stall_in; always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else begin // synthesis translate off initial $fatal("%m: unsupported configuration (WG_LIMIT < KERNEL_WG_LIMIT and WG_FIFO_ORDER != 1)"); // synthesis translate on 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. // Work-group limiter. This module has two interface points: the entry point // and the exit point. The purpose of the module is to ensure that there are // no more than WG_LIMIT work-groups in the pipeline between the entry and // exit points. The limiter also remaps the kernel-level work-group id into // a local work-group id; this is needed because in general the kernel-level // work-group id space is larger than the local work-group id space. It is // assumed that any work-item that passes through the entry point will pass // through the exit point at some point. // // The ordering of the work-groups affects the implementation. In particular, // if the work-group order is the same through the entry point and the exit // point, the implementation is simple. This is referred to as work-group FIFO // (first-in-first-out) order. It remains a TODO to support work-group // non-FIFO order (through the exit point). // // The work-group order does NOT matter if WG_LIMIT >= KERNEL_WG_LIMIT. // In this configuration, the real limiter is at the kernel-level and this // work-group limiter does not do anything useful. It does match the latency // specifiction though so that the latency and capacity of the core is the // same regardless of the configuration. // // Latency/capacity: // Through entry: 1 cycle // Through exit: 1 cycle module acl_work_group_limiter #( parameter unsigned WG_LIMIT = 1, // >0 parameter unsigned KERNEL_WG_LIMIT = 1, // >0 parameter unsigned MAX_WG_SIZE = 1, // >0 parameter unsigned WG_FIFO_ORDER = 1, // 0|1 parameter string IMPL = "local" // kernel|local ) ( clock, resetn, wg_size, // Limiter entry entry_valid_in, entry_k_wgid, entry_stall_out, entry_valid_out, entry_l_wgid, entry_stall_in, // Limiter exit exit_valid_in, exit_l_wgid, exit_stall_out, exit_valid_out, exit_stall_in ); input logic clock; input logic resetn; // check for overflow localparam MAX_WG_SIZE_WIDTH = $clog2({1'b0, MAX_WG_SIZE} + 1); input logic [MAX_WG_SIZE_WIDTH-1:0] wg_size; // Limiter entry input logic entry_valid_in; input logic [$clog2(KERNEL_WG_LIMIT)-1:0] entry_k_wgid; // not used if WG_FIFO_ORDER==1 output logic entry_stall_out; output logic entry_valid_out; output logic [$clog2(WG_LIMIT)-1:0] entry_l_wgid; input logic entry_stall_in; // Limiter exit input logic exit_valid_in; input logic [$clog2(WG_LIMIT)-1:0] exit_l_wgid; // never used output logic exit_stall_out; output logic exit_valid_out; input logic exit_stall_in; generate // WG_FIFO_ORDER needs to be handled first because the limiter always needs // to generate the work-group if( WG_FIFO_ORDER == 1 ) begin // IMPLEMENTATION ASSUMPTION: complete work-groups are assumed to // pass-through work-group and therefore it is sufficient to declare // a work-group as done when wg_size work-items have appeared at one point logic [MAX_WG_SIZE_WIDTH-1:0] wg_size_limit /* synthesis preserve */; always @(posedge clock) wg_size_limit <= wg_size - 'd1; // this is a constant throughout the execution of an kernel, but register to limit fanout of source // Number of active work-groups that have (partially) entered the limiter and have not // (completely) exited the limiter. Counts from 0 to WG_LIMIT. logic [$clog2(WG_LIMIT+1)-1:0] active_wg_count; logic incr_active_wg, decr_active_wg; logic active_wg_limit_reached; // Number of work-items seen in the currently-entering work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_entry_wg_wi_count; logic cur_entry_wg_wi_count_eq_zero; logic [$clog2(WG_LIMIT)-1:0] cur_entry_l_wgid; // Number of work-items seen in the currently-exiting work-group. // Counts from 0 to MAX_WG_SIZE-1. logic [$clog2(MAX_WG_SIZE)-1:0] cur_exit_wg_wi_count; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin active_wg_count <= '0; active_wg_limit_reached <= 1'b0; end else begin active_wg_count <= active_wg_count + incr_active_wg - decr_active_wg; if( (active_wg_count == WG_LIMIT - 1) & incr_active_wg & ~decr_active_wg ) active_wg_limit_reached <= 1'b1; else if( (active_wg_count == WG_LIMIT) & decr_active_wg ) active_wg_limit_reached <= 1'b0; end end // // Entry logic: latency = 1 // logic accept_entry; logic entry_output_stall_out; always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; cur_entry_l_wgid <= '0; end else if( accept_entry ) begin if( cur_entry_wg_wi_count == wg_size_limit ) begin // The entering work-item is the last work-item of the current // work-group. Prepare for the next work-group. cur_entry_wg_wi_count <= '0; cur_entry_wg_wi_count_eq_zero <= 1'b1; if( cur_entry_l_wgid == WG_LIMIT - 1 ) cur_entry_l_wgid <= '0; else cur_entry_l_wgid <= cur_entry_l_wgid + 'd1; end else begin // Increment work-item counter. cur_entry_wg_wi_count <= cur_entry_wg_wi_count + 'd1; cur_entry_wg_wi_count_eq_zero <= 1'b0; end end end assign incr_active_wg = cur_entry_wg_wi_count_eq_zero & accept_entry; assign accept_entry = entry_valid_in & ~entry_output_stall_out & ~(active_wg_limit_reached & cur_entry_wg_wi_count_eq_zero); // Register entry output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_output_stall_out ) begin entry_valid_out <= accept_entry; entry_l_wgid <= cur_entry_l_wgid; end end assign entry_output_stall_out = entry_valid_out & entry_stall_in; assign entry_stall_out = entry_valid_in & ~accept_entry; // // Exit logic: latency = 1 // always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin cur_exit_wg_wi_count <= '0; end else if( exit_valid_in & ~exit_stall_out ) begin if( cur_exit_wg_wi_count == wg_size_limit ) begin // The exiting work-item is the last work-item of the current // work-group. Entire work-group has cleared. cur_exit_wg_wi_count <= '0; end else begin // Increment work-item counter. cur_exit_wg_wi_count <= cur_exit_wg_wi_count + 'd1; end end end assign decr_active_wg = exit_valid_in & ~exit_stall_out & (cur_exit_wg_wi_count == wg_size_limit); // Register output. always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else if( IMPL == "local" && WG_LIMIT >= KERNEL_WG_LIMIT ) begin // In this scenario, this work-group limiter doesn't have to do anything // because the kernel-level limit is already sufficient. // // Simply use the kernel hwid as the local hwid. // // This particular implementation is suitable for any kind of // work-item ordering at entry and exit. Register to meet the latency // requirements. always @( posedge clock or negedge resetn ) begin if( ~resetn ) begin entry_valid_out <= 1'b0; entry_l_wgid <= 'x; end else if( ~entry_stall_out ) begin entry_valid_out <= entry_valid_in; entry_l_wgid <= entry_k_wgid; end end assign entry_stall_out = entry_valid_out & entry_stall_in; always @( posedge clock or negedge resetn ) begin if( ~resetn ) exit_valid_out <= 1'b0; else if( ~exit_stall_out ) exit_valid_out <= exit_valid_in; end assign exit_stall_out = exit_valid_out & exit_stall_in; end else begin // synthesis translate off initial $fatal("%m: unsupported configuration (WG_LIMIT < KERNEL_WG_LIMIT and WG_FIFO_ORDER != 1)"); // synthesis translate on end endgenerate endmodule
(** * UseAuto: Theory and Practice of Automation in Coq Proofs *) (* Chapter maintained by Arthur Chargueraud *) (** In a machine-checked proof, every single detail has to be justified. This can result in huge proof scripts. Fortunately, Coq comes with a proof-search mechanism and with several decision procedures that enable the system to automatically synthesize simple pieces of proof. Automation is very powerful when set up appropriately. The purpose of this chapter is to explain the basics of working of automation. The chapter is organized in two parts. The first part focuses on a general mechanism called "proof search." In short, proof search consists in naively trying to apply lemmas and assumptions in all possible ways. The second part describes "decision procedures", which are tactics that are very good at solving proof obligations that fall in some particular fragment of the logic of Coq. Many of the examples used in this chapter consist of small lemmas that have been made up to illustrate particular aspects of automation. These examples are completely independent from the rest of the Software Foundations course. This chapter also contains some bigger examples which are used to explain how to use automation in realistic proofs. These examples are taken from other chapters of the course (mostly from STLC), and the proofs that we present make use of the tactics from the library [LibTactics.v], which is presented in the chapter [UseTactics]. *) Require Import LibTactics. (* ####################################################### *) (** * Basic Features of Proof Search *) (** The idea of proof search is to replace a sequence of tactics applying lemmas and assumptions with a call to a single tactic, for example [auto]. This form of proof automation saves a lot of effort. It typically leads to much shorter proof scripts, and to scripts that are typically more robust to change. If one makes a little change to a definition, a proof that exploits automation probably won't need to be modified at all. Of course, using too much automation is a bad idea. When a proof script no longer records the main arguments of a proof, it becomes difficult to fix it when it gets broken after a change in a definition. Overall, a reasonable use of automation is generally a big win, as it saves a lot of time both in building proof scripts and in subsequently maintaining those proof scripts. *) (* ####################################################### *) (** ** Strength of Proof Search *) (** We are going to study four proof-search tactics: [auto], [eauto], [iauto] and [jauto]. The tactics [auto] and [eauto] are builtin in Coq. The tactic [iauto] is a shorthand for the builtin tactic [try solve [intuition eauto]]. The tactic [jauto] is defined in the library [LibTactics], and simply performs some preprocessing of the goal before calling [eauto]. The goal of this chapter is to explain the general principles of proof search and to give rule of thumbs for guessing which of the four tactics mentioned above is best suited for solving a given goal. Proof search is a compromise between efficiency and expressiveness, that is, a tradeoff between how complex goals the tactic can solve and how much time the tactic requires for terminating. The tactic [auto] builds proofs only by using the basic tactics [reflexivity], [assumption], and [apply]. The tactic [eauto] can also exploit [eapply]. The tactic [jauto] extends [eauto] by being able to open conjunctions and existentials that occur in the context. The tactic [iauto] is able to deal with conjunctions, disjunctions, and negation in a quite clever way; however it is not able to open existentials from the context. Also, [iauto] usually becomes very slow when the goal involves several disjunctions. Note that proof search tactics never perform any rewriting step (tactics [rewrite], [subst]), nor any case analysis on an arbitrary data structure or predicate (tactics [destruct] and [inversion]), nor any proof by induction (tactic [induction]). So, proof search is really intended to automate the final steps from the various branches of a proof. It is not able to discover the overall structure of a proof. *) (* ####################################################### *) (** ** Basics *) (** The tactic [auto] is able to solve a goal that can be proved using a sequence of [intros], [apply], [assumption], and [reflexivity]. Two examples follow. The first one shows the ability for [auto] to call [reflexivity] at any time. In fact, calling [reflexivity] is always the first thing that [auto] tries to do. *) Lemma solving_by_reflexivity : 2 + 3 = 5. Proof. auto. Qed. (** The second example illustrates a proof where a sequence of two calls to [apply] are needed. The goal is to prove that if [Q n] implies [P n] for any [n] and if [Q n] holds for any [n], then [P 2] holds. *) Lemma solving_by_apply : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. auto. Qed. (** We can ask [auto] to tell us what proof it came up with, by invoking [info_auto] in place of [auto]. *) Lemma solving_by_apply' : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. info_auto. Qed. (* The output is: [intro P; intro Q; intro H;] *) (* followed with [intro H0; simple apply H; simple apply H0]. *) (* i.e., the sequence [intros P Q H H0; apply H; apply H0]. *) (** The tactic [auto] can invoke [apply] but not [eapply]. So, [auto] cannot exploit lemmas whose instantiation cannot be directly deduced from the proof goal. To exploit such lemmas, one needs to invoke the tactic [eauto], which is able to call [eapply]. In the following example, the first hypothesis asserts that [P n] is true when [Q m] is true for some [m], and the goal is to prove that [Q 1] implies [P 2]. This implication follows direction from the hypothesis by instantiating [m] as the value [1]. The following proof script shows that [eauto] successfully solves the goal, whereas [auto] is not able to do so. *) Lemma solving_by_eapply : forall (P Q : nat->Prop), (forall n m, Q m -> P n) -> Q 1 -> P 2. Proof. auto. eauto. Qed. (** Remark: Again, we can use [info_eauto] to see what proof [eauto] comes up with. *) (* ####################################################### *) (** ** Conjunctions *) (** So far, we've seen that [eauto] is stronger than [auto] in the sense that it can deal with [eapply]. In the same way, we are going to see how [jauto] and [iauto] are stronger than [auto] and [eauto] in the sense that they provide better support for conjunctions. *) (** The tactics [auto] and [eauto] can prove a goal of the form [F /\ F'], where [F] and [F'] are two propositions, as soon as both [F] and [F'] can be proved in the current context. An example follows. *) Lemma solving_conj_goal : forall (P : nat->Prop) (F : Prop), (forall n, P n) -> F -> F /\ P 2. Proof. auto. Qed. (** However, when an assumption is a conjunction, [auto] and [eauto] are not able to exploit this conjunction. It can be quite surprising at first that [eauto] can prove very complex goals but that it fails to prove that [F /\ F'] implies [F]. The tactics [iauto] and [jauto] are able to decompose conjunctions from the context. Here is an example. *) Lemma solving_conj_hyp : forall (F F' : Prop), F /\ F' -> F. Proof. auto. eauto. jauto. (* or [iauto] *) Qed. (** The tactic [jauto] is implemented by first calling a pre-processing tactic called [jauto_set], and then calling [eauto]. So, to understand how [jauto] works, one can directly call the tactic [jauto_set]. *) Lemma solving_conj_hyp' : forall (F F' : Prop), F /\ F' -> F. Proof. intros. jauto_set. eauto. Qed. (** Next is a more involved goal that can be solved by [iauto] and [jauto]. *) Lemma solving_conj_more : forall (P Q R : nat->Prop) (F : Prop), (F /\ (forall n m, (Q m /\ R n) -> P n)) -> (F -> R 2) -> Q 1 -> P 2 /\ F. Proof. jauto. (* or [iauto] *) Qed. (** The strategy of [iauto] and [jauto] is to run a global analysis of the top-level conjunctions, and then call [eauto]. For this reason, those tactics are not good at dealing with conjunctions that occur as the conclusion of some universally quantified hypothesis. The following example illustrates a general weakness of Coq proof search mechanisms. *) Lemma solving_conj_hyp_forall : forall (P Q : nat->Prop), (forall n, P n /\ Q n) -> P 2. Proof. auto. eauto. iauto. jauto. (* Nothing works, so we have to do some of the work by hand *) intros. destruct (H 2). auto. Qed. (** This situation is slightly disappointing, since automation is able to prove the following goal, which is very similar. The only difference is that the universal quantification has been distributed over the conjunction. *) Lemma solved_by_jauto : forall (P Q : nat->Prop) (F : Prop), (forall n, P n) /\ (forall n, Q n) -> P 2. Proof. jauto. (* or [iauto] *) Qed. (* ####################################################### *) (** ** Disjunctions *) (** The tactics [auto] and [eauto] can handle disjunctions that occur in the goal. *) Lemma solving_disj_goal : forall (F F' : Prop), F -> F \/ F'. Proof. auto. Qed. (** However, only [iauto] is able to automate reasoning on the disjunctions that appear in the context. For example, [iauto] can prove that [F \/ F'] entails [F' \/ F]. *) Lemma solving_disj_hyp : forall (F F' : Prop), F \/ F' -> F' \/ F. Proof. auto. eauto. jauto. iauto. Qed. (** More generally, [iauto] can deal with complex combinations of conjunctions, disjunctions, and negations. Here is an example. *) Lemma solving_tauto : forall (F1 F2 F3 : Prop), ((~F1 /\ F3) \/ (F2 /\ ~F3)) -> (F2 -> F1) -> (F2 -> F3) -> ~F2. Proof. iauto. Qed. (** However, the ability of [iauto] to automatically perform a case analysis on disjunctions comes with a downside: [iauto] may be very slow. If the context involves several hypotheses with disjunctions, [iauto] typically generates an exponential number of subgoals on which [eauto] is called. One major advantage of [jauto] compared with [iauto] is that it never spends time performing this kind of case analyses. *) (* ####################################################### *) (** ** Existentials *) (** The tactics [eauto], [iauto], and [jauto] can prove goals whose conclusion is an existential. For example, if the goal is [exists x, f x], the tactic [eauto] introduces an existential variable, say [?25], in place of [x]. The remaining goal is [f ?25], and [eauto] tries to solve this goal, allowing itself to instantiate [?25] with any appropriate value. For example, if an assumption [f 2] is available, then the variable [?25] gets instantiated with [2] and the goal is solved, as shown below. *) Lemma solving_exists_goal : forall (f : nat->Prop), f 2 -> exists x, f x. Proof. auto. (* observe that [auto] does not deal with existentials, *) eauto. (* whereas [eauto], [iauto] and [jauto] solve the goal *) Qed. (** A major strength of [jauto] over the other proof search tactics is that it is able to exploit the existentially-quantified hypotheses, i.e., those of the form [exists x, P]. *) Lemma solving_exists_hyp : forall (f g : nat->Prop), (forall x, f x -> g x) -> (exists a, f a) -> (exists a, g a). Proof. auto. eauto. iauto. (* All of these tactics fail, *) jauto. (* whereas [jauto] succeeds. *) (* For the details, run [intros. jauto_set. eauto] *) Qed. (* ####################################################### *) (** ** Negation *) (** The tactics [auto] and [eauto] suffer from some limitations with respect to the manipulation of negations, mostly related to the fact that negation, written [~ P], is defined as [P -> False] but that the unfolding of this definition is not performed automatically. Consider the following example. *) Lemma negation_study_1 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. intros P H0 HX. eauto. (* It fails to see that [HX] applies *) unfold not in *. eauto. Qed. (** For this reason, the tactics [iauto] and [jauto] systematically invoke [unfold not in *] as part of their pre-processing. So, they are able to solve the previous goal right away. *) Lemma negation_study_2 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. jauto. (* or [iauto] *) Qed. (** We will come back later on to the behavior of proof search with respect to the unfolding of definitions. *) (* ####################################################### *) (** ** Equalities *) (** Coq's proof-search feature is not good at exploiting equalities. It can do very basic operations, like exploiting reflexivity and symmetry, but that's about it. Here is a simple example that [auto] can solve, by first calling [symmetry] and then applying the hypothesis. *) Lemma equality_by_auto : forall (f g : nat->Prop), (forall x, f x = g x) -> g 2 = f 2. Proof. auto. Qed. (** To automate more advanced reasoning on equalities, one should rather try to use the tactic [congruence], which is presented at the end of this chapter in the "Decision Procedures" section. *) (* ####################################################### *) (** * How Proof Search Works *) (* ####################################################### *) (** ** Search Depth *) (** The tactic [auto] works as follows. It first tries to call [reflexivity] and [assumption]. If one of these calls solves the goal, the job is done. Otherwise [auto] tries to apply the most recently introduced assumption that can be applied to the goal without producing and error. This application produces subgoals. There are two possible cases. If the sugboals produced can be solved by a recursive call to [auto], then the job is done. Otherwise, if this application produces at least one subgoal that [auto] cannot solve, then [auto] starts over by trying to apply the second most recently introduced assumption. It continues in a similar fashion until it finds a proof or until no assumption remains to be tried. It is very important to have a clear idea of the backtracking process involved in the execution of the [auto] tactic; otherwise its behavior can be quite puzzling. For example, [auto] is not able to solve the following triviality. *) Lemma search_depth_0 : True /\ True /\ True /\ True /\ True /\ True. Proof. auto. Abort. (** The reason [auto] fails to solve the goal is because there are too many conjunctions. If there had been only five of them, [auto] would have successfully solved the proof, but six is too many. The tactic [auto] limits the number of lemmas and hypotheses that can be applied in a proof, so as to ensure that the proof search eventually terminates. By default, the maximal number of steps is five. One can specify a different bound, writing for example [auto 6] to search for a proof involving at most six steps. For example, [auto 6] would solve the previous lemma. (Similarly, one can invoke [eauto 6] or [intuition eauto 6].) The argument [n] of [auto n] is called the "search depth." The tactic [auto] is simply defined as a shorthand for [auto 5]. The behavior of [auto n] can be summarized as follows. It first tries to solve the goal using [reflexivity] and [assumption]. If this fails, it tries to apply a hypothesis (or a lemma that has been registered in the hint database), and this application produces a number of sugoals. The tactic [auto (n-1)] is then called on each of those subgoals. If all the subgoals are solved, the job is completed, otherwise [auto n] tries to apply a different hypothesis. During the process, [auto n] calls [auto (n-1)], which in turn might call [auto (n-2)], and so on. The tactic [auto 0] only tries [reflexivity] and [assumption], and does not try to apply any lemma. Overall, this means that when the maximal number of steps allowed has been exceeded, the [auto] tactic stops searching and backtracks to try and investigate other paths. *) (** The following lemma admits a unique proof that involves exactly three steps. So, [auto n] proves this goal iff [n] is greater than three. *) Lemma search_depth_1 : forall (P : nat->Prop), P 0 -> (P 0 -> P 1) -> (P 1 -> P 2) -> (P 2). Proof. auto 0. (* does not find the proof *) auto 1. (* does not find the proof *) auto 2. (* does not find the proof *) auto 3. (* finds the proof *) (* more generally, [auto n] solves the goal if [n >= 3] *) Qed. (** We can generalize the example by introducing an assumption asserting that [P k] is derivable from [P (k-1)] for all [k], and keep the assumption [P 0]. The tactic [auto], which is the same as [auto 5], is able to derive [P k] for all values of [k] less than 5. For example, it can prove [P 4]. *) Lemma search_depth_3 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4). Proof. auto. Qed. (** However, to prove [P 5], one needs to call at least [auto 6]. *) Lemma search_depth_4 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 5). Proof. auto. auto 6. Qed. (** Because [auto] looks for proofs at a limited depth, there are cases where [auto] can prove a goal [F] and can prove a goal [F'] but cannot prove [F /\ F']. In the following example, [auto] can prove [P 4] but it is not able to prove [P 4 /\ P 4], because the splitting of the conjunction consumes one proof step. To prove the conjunction, one needs to increase the search depth, using at least [auto 6]. *) Lemma search_depth_5 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4 /\ P 4). Proof. auto. auto 6. Qed. (* ####################################################### *) (** ** Backtracking *) (** In the previous section, we have considered proofs where at each step there was a unique assumption that [auto] could apply. In general, [auto] can have several choices at every step. The strategy of [auto] consists of trying all of the possibilities (using a depth-first search exploration). To illustrate how automation works, we are going to extend the previous example with an additional assumption asserting that [P k] is also derivable from [P (k+1)]. Adding this hypothesis offers a new possibility that [auto] could consider at every step. There exists a special command that one can use for tracing all the steps that proof-search considers. To view such a trace, one should write [debug eauto]. (For some reason, the command [debug auto] does not exist, so we have to use the command [debug eauto] instead.) *) Lemma working_of_auto_1 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 2). (* Uncomment "debug" in the following line to see the debug trace: *) Proof. intros P H1 H2 H3. (* debug *) eauto. Qed. (** The output message produced by [debug eauto] is as follows. << depth=5 depth=4 apply H3 depth=3 apply H3 depth=3 exact H1 >> The depth indicates the value of [n] with which [eauto n] is called. The tactics shown in the message indicate that the first thing that [eauto] has tried to do is to apply [H3]. The effect of applying [H3] is to replace the goal [P 2] with the goal [P 1]. Then, again, [H3] has been applied, changing the goal [P 1] into [P 0]. At that point, the goal was exactly the hypothesis [H1]. It seems that [eauto] was quite lucky there, as it never even tried to use the hypothesis [H2] at any time. The reason is that [auto] always tries to use the most recently introduced hypothesis first, and [H3] is a more recent hypothesis than [H2] in the goal. So, let's permute the hypotheses [H2] and [H3] and see what happens. *) Lemma working_of_auto_2 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Goal: *) (P 2). Proof. intros P H1 H3 H2. (* debug *) eauto. Qed. (** This time, the output message suggests that the proof search investigates many possibilities. Replacing [debug eauto] with [info_eauto], we observe that the proof that [eauto] comes up with is actually not the simplest one. [apply H2; apply H3; apply H3; apply H3; exact H1] This proof goes through the proof obligation [P 3], even though it is not any useful. The following tree drawing describes all the goals that automation has been through. << |5||4||3||2||1||0| -- below, tabulation indicates the depth [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 6] -> [P 7] -> [P 5] -> [P 4] -> [P 5] -> [P 3] --> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 1] -> [P 2] -> [P 3] -> [P 1] -> [P 0] -> !! Done !! >> The first few lines read as follows. To prove [P 2], [eauto 5] has first tried to apply [H2], producing the subgoal [P 3]. To solve it, [eauto 4] has tried again to apply [H2], producing the goal [P 4]. Similarly, the search goes through [P 5], [P 6] and [P 7]. When reaching [P 7], the tactic [eauto 0] is called but as it is not allowed to try and apply any lemma, it fails. So, we come back to the goal [P 6], and try this time to apply hypothesis [H3], producing the subgoal [P 5]. Here again, [eauto 0] fails to solve this goal. The process goes on and on, until backtracking to [P 3] and trying to apply [H2] three times in a row, going through [P 2] and [P 1] and [P 0]. This search tree explains why [eauto] came up with a proof starting with [apply H2]. *) (* ####################################################### *) (** ** Adding Hints *) (** By default, [auto] (and [eauto]) only tries to apply the hypotheses that appear in the proof context. There are two possibilities for telling [auto] to exploit a lemma that have been proved previously: either adding the lemma as an assumption just before calling [auto], or adding the lemma as a hint, so that it can be used by every calls to [auto]. The first possibility is useful to have [auto] exploit a lemma that only serves at this particular point. To add the lemma as hypothesis, one can type [generalize mylemma; intros], or simply [lets: mylemma] (the latter requires [LibTactics.v]). The second possibility is useful for lemmas that need to be exploited several times. The syntax for adding a lemma as a hint is [Hint Resolve mylemma]. For example, the lemma asserting than any number is less than or equal to itself, [forall x, x <= x], called [Le.le_refl] in the Coq standard library, can be added as a hint as follows. *) Hint Resolve Le.le_refl. (** A convenient shorthand for adding all the constructors of an inductive datatype as hints is the command [Hint Constructors mydatatype]. Warning: some lemmas, such as transitivity results, should not be added as hints as they would very badly affect the performance of proof search. The description of this problem and the presentation of a general work-around for transitivity lemmas appear further on. *) (* ####################################################### *) (** ** Integration of Automation in Tactics *) (** The library "LibTactics" introduces a convenient feature for invoking automation after calling a tactic. In short, it suffices to add the symbol star ([*]) to the name of a tactic. For example, [apply* H] is equivalent to [apply H; auto_star], where [auto_star] is a tactic that can be defined as needed. The definition of [auto_star], which determines the meaning of the star symbol, can be modified whenever needed. Simply write: Ltac auto_star ::= a_new_definition. ]] Observe the use of [::=] instead of [:=], which indicates that the tactic is being rebound to a new definition. So, the default definition is as follows. *) Ltac auto_star ::= try solve [ jauto ]. (** Nearly all standard Coq tactics and all the tactics from "LibTactics" can be called with a star symbol. For example, one can invoke [subst*], [destruct* H], [inverts* H], [lets* I: H x], [specializes* H x], and so on... There are two notable exceptions. The tactic [auto*] is just another name for the tactic [auto_star]. And the tactic [apply* H] calls [eapply H] (or the more powerful [applys H] if needed), and then calls [auto_star]. Note that there is no [eapply* H] tactic, use [apply* H] instead. *) (** In large developments, it can be convenient to use two degrees of automation. Typically, one would use a fast tactic, like [auto], and a slower but more powerful tactic, like [jauto]. To allow for a smooth coexistence of the two form of automation, [LibTactics.v] also defines a "tilde" version of tactics, like [apply~ H], [destruct~ H], [subst~], [auto~] and so on. The meaning of the tilde symbol is described by the [auto_tilde] tactic, whose default implementation is [auto]. *) Ltac auto_tilde ::= auto. (** In the examples that follow, only [auto_star] is needed. *) (** An alternative, possibly more efficient version of auto_star is the following": Ltac auto_star ::= try solve [ eassumption | auto | jauto ]. With the above definition, [auto_star] first tries to solve the goal using the assumptions; if it fails, it tries using [auto], and if this still fails, then it calls [jauto]. Even though [jauto] is strictly stronger than [eassumption] and [auto], it makes sense to call these tactics first, because, when the succeed, they save a lot of time, and when they fail to prove the goal, they fail very quickly.". *) (* ####################################################### *) (** * Examples of Use of Automation *) (** Let's see how to use proof search in practice on the main theorems of the "Software Foundations" course, proving in particular results such as determinism, preservation and progress. *) (* ####################################################### *) (** ** Determinism *) Module DeterministicImp. Require Import Imp. (** Recall the original proof of the determinism lemma for the IMP language, shown below. *) Theorem ceval_deterministic: forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. intros c st st1 st2 E1 E2. generalize dependent st2. (ceval_cases (induction E1) Case); intros st2 E2; inversion E2; subst. Case "E_Skip". reflexivity. Case "E_Ass". reflexivity. Case "E_Seq". assert (st' = st'0) as EQ1. SCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Case "E_IfTrue". SCase "b1 evaluates to true". apply IHE1. assumption. SCase "b1 evaluates to false (contradiction)". rewrite H in H5. inversion H5. Case "E_IfFalse". SCase "b1 evaluates to true (contradiction)". rewrite H in H5. inversion H5. SCase "b1 evaluates to false". apply IHE1. assumption. Case "E_WhileEnd". SCase "b1 evaluates to true". reflexivity. SCase "b1 evaluates to false (contradiction)". rewrite H in H2. inversion H2. Case "E_WhileLoop". SCase "b1 evaluates to true (contradiction)". rewrite H in H4. inversion H4. SCase "b1 evaluates to false". assert (st' = st'0) as EQ1. SSCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Qed. (** Exercise: rewrite this proof using [auto] whenever possible. (The solution uses [auto] 9 times.) *) Theorem ceval_deterministic': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* FILL IN HERE *) admit. Qed. (** In fact, using automation is not just a matter of calling [auto] in place of one or two other tactics. Using automation is about rethinking the organization of sequences of tactics so as to minimize the effort involved in writing and maintaining the proof. This process is eased by the use of the tactics from [LibTactics.v]. So, before trying to optimize the way automation is used, let's first rewrite the proof of determinism: - use [introv H] instead of [intros x H], - use [gen x] instead of [generalize dependent x], - use [inverts H] instead of [inversion H; subst], - use [tryfalse] to handle contradictions, and get rid of the cases where [beval st b1 = true] and [beval st b1 = false] both appear in the context, - stop using [ceval_cases] to label subcases. *) Theorem ceval_deterministic'': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. assert (st' = st'0). auto. subst. auto. auto. auto. auto. assert (st' = st'0). auto. subst. auto. Qed. (** To obtain a nice clean proof script, we have to remove the calls [assert (st' = st'0)]. Such a tactic invokation is not nice because it refers to some variables whose name has been automatically generated. This kind of tactics tend to be very brittle. The tactic [assert (st' = st'0)] is used to assert the conclusion that we want to derive from the induction hypothesis. So, rather than stating this conclusion explicitly, we are going to ask Coq to instantiate the induction hypothesis, using automation to figure out how to instantiate it. The tactic [forwards], described in [LibTactics.v] precisely helps with instantiating a fact. So, let's see how it works out on our example. *) Theorem ceval_deterministic''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* Let's replay the proof up to the [assert] tactic. *) introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. (* We duplicate the goal for comparing different proofs. *) dup 4. (* The old proof: *) assert (st' = st'0). apply IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, without automation: *) forwards: IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, with automation: *) forwards: IHE1_1. eauto. (* produces [H: st' = st'0]. *) skip. (* The new proof, with integrated automation: *) forwards*: IHE1_1. (* produces [H: st' = st'0]. *) skip. Abort. (** To polish the proof script, it remains to factorize the calls to [auto], using the star symbol. The proof of determinism can then be rewritten in only four lines, including no more than 10 tactics. *) Theorem ceval_deterministic'''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts* E2; tryfalse. forwards*: IHE1_1. subst*. forwards*: IHE1_1. subst*. Qed. End DeterministicImp. (* ####################################################### *) (** ** Preservation for STLC *) Module PreservationProgressStlc. Require Import StlcProp. Import STLC. Import STLCProp. (** Consider the proof of perservation of STLC, shown below. This proof already uses [eauto] through the triple-dot mechanism. *) Theorem preservation : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof with eauto. remember (@empty ty) as Gamma. intros t t' T HT. generalize dependent t'. (has_type_cases (induction HT) Case); intros t' HE; subst Gamma. Case "T_Var". inversion HE. Case "T_Abs". inversion HE. Case "T_App". inversion HE; subst... (* (step_cases (inversion HE) SCase); subst...*) (* The ST_App1 and ST_App2 cases are immediate by induction, and auto takes care of them *) SCase "ST_AppAbs". apply substitution_preserves_typing with T11... inversion HT1... Case "T_True". inversion HE. Case "T_False". inversion HE. Case "T_If". inversion HE; subst... Qed. (** Exercise: rewrite this proof using tactics from [LibTactics] and calling automation using the star symbol rather than the triple-dot notation. More precisely, make use of the tactics [inverts*] and [applys*] to call [auto*] after a call to [inverts] or to [applys]. The solution is three lines long.*) Theorem preservation' : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof. (* FILL IN HERE *) admit. Qed. (* ####################################################### *) (** ** Progress for STLC *) (** Consider the proof of the progress theorem. *) Theorem progress : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof with eauto. intros t T Ht. remember (@empty ty) as Gamma. (has_type_cases (induction Ht) Case); subst Gamma... Case "T_Var". inversion H. Case "T_App". right. destruct IHHt1... SCase "t1 is a value". destruct IHHt2... SSCase "t2 is a value". inversion H; subst; try solve by inversion. exists ([x0:=t2]t)... SSCase "t2 steps". destruct H0 as [t2' Hstp]. exists (tapp t1 t2')... SCase "t1 steps". destruct H as [t1' Hstp]. exists (tapp t1' t2)... Case "T_If". right. destruct IHHt1... destruct t1; try solve by inversion... inversion H. exists (tif x0 t2 t3)... Qed. (** Exercise: optimize the above proof. Hint: make use of [destruct*] and [inverts*]. The solution consists of 10 short lines. *) Theorem progress' : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof. (* FILL IN HERE *) admit. Qed. End PreservationProgressStlc. (* ####################################################### *) (** ** BigStep and SmallStep *) Module Semantics. Require Import Smallstep. (** Consider the proof relating a small-step reduction judgment to a big-step reduction judgment. *) Theorem multistep__eval : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. intros t v Hnorm. unfold normal_form_of in Hnorm. inversion Hnorm as [Hs Hnf]; clear Hnorm. rewrite nf_same_as_value in Hnf. inversion Hnf. clear Hnf. exists n. split. reflexivity. multi_cases (induction Hs) Case; subst. Case "multi_refl". apply E_Const. Case "multi_step". eapply step__eval. eassumption. apply IHHs. reflexivity. Qed. (** Our goal is to optimize the above proof. It is generally easier to isolate inductions into separate lemmas. So, we are going to first prove an intermediate result that consists of the judgment over which the induction is being performed. *) (** Exercise: prove the following result, using tactics [introv], [induction] and [subst], and [apply*]. The solution is 3 lines long. *) Theorem multistep_eval_ind : forall t v, t ==>* v -> forall n, C n = v -> t || n. Proof. (* FILL IN HERE *) admit. Qed. (** Exercise: using the lemma above, simplify the proof of the result [multistep__eval]. You should use the tactics [introv], [inverts], [split*] and [apply*]. The solution is 2 lines long. *) Theorem multistep__eval' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. (** If we try to combine the two proofs into a single one, we will likely fail, because of a limitation of the [induction] tactic. Indeed, this tactic looses information when applied to a predicate whose arguments are not reduced to variables, such as [t ==>* (C n)]. You will thus need to use the more powerful tactic called [dependent induction]. This tactic is available only after importing the [Program] library, as shown below. *) Require Import Program. (** Exercise: prove the lemma [multistep__eval] without invoking the lemma [multistep_eval_ind], that is, by inlining the proof by induction involved in [multistep_eval_ind], using the tactic [dependent induction] instead of [induction]. The solution is 5 lines long. *) Theorem multistep__eval'' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. End Semantics. (* ####################################################### *) (** ** Preservation for STLCRef *) Module PreservationProgressReferences. Require Import References. Import STLCRef. Hint Resolve store_weakening extends_refl. (** The proof of preservation for [STLCRef] can be found in chapter [References]. It contains 58 lines (not counting the labelling of cases). The optimized proof script is more than twice shorter. The following material explains how to build the optimized proof script. The resulting optimized proof script for the preservation theorem appears afterwards. *) Theorem preservation : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. (* old: [Proof. with eauto using store_weakening, extends_refl.] new: [Proof.], and the two lemmas are registered as hints before the proof of the lemma, possibly inside a section in order to restrict the scope of the hints. *) remember (@empty ty) as Gamma. introv Ht. gen t'. (has_type_cases (induction Ht) Case); introv HST Hstep; (* old: [subst; try (solve by inversion); inversion Hstep; subst; try (eauto using store_weakening, extends_refl)] new: [subst Gamma; inverts Hstep; eauto.] We want to be more precise on what exactly we substitute, and we do not want to call [try (solve by inversion)] which is way to slow. *) subst Gamma; inverts Hstep; eauto. Case "T_App". SCase "ST_AppAbs". (* old: exists ST. inversion Ht1; subst. split; try split... eapply substitution_preserves_typing... *) (* new: we use [inverts] in place of [inversion] and [splits] to split the conjunction, and [applys*] in place of [eapply...] *) exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. SCase "ST_App1". (* old: eapply IHHt1 in H0... inversion H0 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: The tactic [eapply IHHt1 in H0...] applies [IHHt1] to [H0]. But [H0] is only thing that [IHHt1] could be applied to, so there [eauto] can figure this out on its own. The tactic [forwards] is used to instantiate all the arguments of [IHHt1], producing existential variables and subgoals when needed. *) forwards: IHHt1. eauto. eauto. eauto. (* At this point, we need to decompose the hypothesis [H] that has just been created by [forwards]. This is done by the first part of the preprocessing phase of [jauto]. *) jauto_set_hyps; intros. (* It remains to decompose the goal, which is done by the second part of the preprocessing phase of [jauto]. *) jauto_set_goal; intros. (* All the subgoals produced can then be solved by [eauto]. *) eauto. eauto. eauto. SCase "ST_App2". (* old: eapply IHHt2 in H5... inversion H5 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: this time, we need to call [forwards] on [IHHt2], and we call [jauto] right away, by writing [forwards*], proving the goal in a single tactic! *) forwards*: IHHt2. (* The same trick works for many of the other subgoals. *) forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. Case "T_Ref". SCase "ST_RefValue". (* old: 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. *) (* new: in this proof case, we need to perform an inversion without removing the hypothesis. The tactic [inverts keep] serves exactly this purpose. *) exists (snoc ST T1). inverts keep HST. splits. (* The proof of the first subgoal needs not be changed *) apply extends_snoc. (* For the second subgoal, we use the tactic [applys_eq] to avoid a manual [replace] before [T_loc] can be applied. *) applys_eq T_Loc 1. (* To justify the inequality, there is no need to call [rewrite <- H], because the tactic [omega] is able to exploit [H] on its own. So, only the rewriting of [lenght_snoc] and the call to the tactic [omega] remain. *) rewrite length_snoc. omega. (* The next proof case is hard to polish because it relies on the lemma [nth_eq_snoc] whose statement is not automation-friendly. We'll come back to this proof case further on. *) unfold store_Tlookup. rewrite <- H. rewrite* nth_eq_snoc. (* Last, we replace [apply ..; assumption] with [apply* ..] *) apply* store_well_typed_snoc. forwards*: IHHt. Case "T_Deref". SCase "ST_DerefLoc". (* old: exists ST. split; try split... destruct HST as [_ Hsty]. replace T11 with (store_Tlookup l ST). apply Hsty... inversion Ht; subst... *) (* new: we start by calling [exists ST] and [splits*]. *) exists ST. splits*. (* new: we replace [destruct HST as [_ Hsty]] by the following *) lets [_ Hsty]: HST. (* new: then we use the tactic [applys_eq] to avoid the need to perform a manual [replace] before applying [Hsty]. *) applys_eq* Hsty 1. (* new: we then can call [inverts] in place of [inversion;subst] *) inverts* Ht. forwards*: IHHt. Case "T_Assign". SCase "ST_Assign". (* old: exists ST. split; try split... eapply assign_pres_store_typing... inversion Ht1; subst... *) (* new: simply using nicer tactics *) exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (** Let's come back to the proof case that was hard to optimize. The difficulty comes from the statement of [nth_eq_snoc], which takes the form [nth (length l) (snoc l x) d = x]. This lemma is hard to exploit because its first argument, [length l], mentions a list [l] that has to be exactly the same as the [l] occuring in [snoc l x]. In practice, the first argument is often a natural number [n] that is provably equal to [length l] yet that is not syntactically equal to [length l]. There is a simple fix for making [nth_eq_snoc] easy to apply: introduce the intermediate variable [n] explicitly, so that the goal becomes [nth n (snoc l x) d = x], with a premise asserting [n = length l]. *) Lemma nth_eq_snoc' : forall (A : Type) (l : list A) (x d : A) (n : nat), n = length l -> nth n (snoc l x) d = x. Proof. intros. subst. apply nth_eq_snoc. Qed. (** The proof case for [ref] from the preservation theorem then becomes much easier to prove, because [rewrite nth_eq_snoc'] now succeeds. *) Lemma preservation_ref : forall (st:store) (ST : store_ty) T1, length ST = length st -> TRef T1 = TRef (store_Tlookup (length st) (snoc ST T1)). Proof. intros. dup. (* A first proof, with an explicit [unfold] *) unfold store_Tlookup. rewrite* nth_eq_snoc'. (* A second proof, with a call to [fequal] *) fequal. symmetry. apply* nth_eq_snoc'. Qed. (** The optimized proof of preservation is summarized next. *) Theorem preservation' : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. remember (@empty ty) as Gamma. introv Ht. gen t'. induction Ht; introv HST Hstep; subst Gamma; inverts Hstep; eauto. exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. exists (snoc ST T1). inverts keep HST. splits. apply extends_snoc. applys_eq T_Loc 1. rewrite length_snoc. omega. unfold store_Tlookup. rewrite* nth_eq_snoc'. apply* store_well_typed_snoc. forwards*: IHHt. exists ST. splits*. lets [_ Hsty]: HST. applys_eq* Hsty 1. inverts* Ht. forwards*: IHHt. exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (* ####################################################### *) (** ** Progress for STLCRef *) (** The proof of progress for [STLCRef] can be found in chapter [References]. It contains 53 lines and the optimized proof script is, here again, half the length. *) Theorem progress : forall ST t T st, has_type empty ST t T -> store_well_typed ST st -> (value t \/ exists t', exists st', t / st ==> t' / st'). Proof. introv Ht HST. remember (@empty ty) as Gamma. induction Ht; subst Gamma; tryfalse; try solve [left*]. right. destruct* IHHt1 as [K|]. inverts K; inverts Ht1. destruct* IHHt2. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* IHHt2 as [M|]. inverts M; try solve [inverts Ht2]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* n. right. destruct* IHHt. right. destruct* IHHt as [K|]. inverts K; inverts Ht as M. inverts HST as N. rewrite* N in M. right. destruct* IHHt1 as [K|]. destruct* IHHt2. inverts K; inverts Ht1 as M. inverts HST as N. rewrite* N in M. Qed. End PreservationProgressReferences. (* ####################################################### *) (** ** Subtyping *) Module SubtypingInversion. Require Import Sub. (** Consider the inversion lemma for typing judgment of abstractions in a type system with subtyping. *) Lemma abs_arrow : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof with eauto. intros x S1 s2 T1 T2 Hty. apply typing_inversion_abs in Hty. destruct Hty as [S2 [Hsub Hty]]. apply sub_inversion_arrow in Hsub. destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]]. inversion Heq; subst... Qed. (** Exercise: optimize the proof script, using [introv], [lets] and [inverts*]. In particular, you will find it useful to replace the pattern [apply K in H. destruct H as I] with [lets I: K H]. The solution is 4 lines. *) Lemma abs_arrow' : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof. (* FILL IN HERE *) admit. Qed. (** The lemma [substitution_preserves_typing] has already been used to illustrate the working of [lets] and [applys] in chapter [UseTactics]. Optimize further this proof using automation (with the star symbol), and using the tactic [cases_if']. The solution is 33 lines, including the [Case] instructions (21 lines without them). *) 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. (* FILL IN HERE *) admit. Qed. End SubtypingInversion. (* ####################################################### *) (** * Advanced Topics in Proof Search *) (* ####################################################### *) (** ** Stating Lemmas in the Right Way *) (** Due to its depth-first strategy, [eauto] can get exponentially slower as the depth search increases, even when a short proof exists. In general, to make proof search run reasonably fast, one should avoid using a depth search greater than 5 or 6. Moreover, one should try to minimize the number of applicable lemmas, and usually put first the hypotheses whose proof usefully instantiates the existential variables. In fact, the ability for [eauto] to solve certain goals actually depends on the order in which the hypotheses are stated. This point is illustrated through the following example, in which [P] is a predicate on natural numbers. This predicate is such that [P n] holds for any [n] as soon as [P m] holds for at least one [m] different from zero. The goal is to prove that [P 2] implies [P 1]. When the hypothesis about [P] is stated in the form [forall n m, P m -> m <> 0 -> P n], then [eauto] works. However, with [forall n m, m <> 0 -> P m -> P n], the tactic [eauto] fails. *) Lemma order_matters_1 : forall (P : nat->Prop), (forall n m, P m -> m <> 0 -> P n) -> P 2 -> P 1. Proof. eauto. (* Success *) (* The proof: [intros P H K. eapply H. apply K. auto.] *) Qed. Lemma order_matters_2 : forall (P : nat->Prop), (forall n m, m <> 0 -> P m -> P n) -> P 5 -> P 1. Proof. eauto. (* Failure *) (* To understand why, let us replay the previous proof *) intros P H K. eapply H. (* The application of [eapply] has left two subgoals, [?X <> 0] and [P ?X], where [?X] is an existential variable. *) (* Solving the first subgoal is easy for [eauto]: it suffices to instantiate [?X] as the value [1], which is the simplest value that satisfies [?X <> 0]. *) eauto. (* But then the second goal becomes [P 1], which is where we started from. So, [eauto] gets stuck at this point. *) Abort. (** It is very important to understand that the hypothesis [forall n m, P m -> m <> 0 -> P n] is eauto-friendly, whereas [forall n m, m <> 0 -> P m -> P n] really isn't. Guessing a value of [m] for which [P m] holds and then checking that [m <> 0] holds works well because there are few values of [m] for which [P m] holds. So, it is likely that [eauto] comes up with the right one. On the other hand, guessing a value of [m] for which [m <> 0] and then checking that [P m] holds does not work well, because there are many values of [m] that satisfy [m <> 0] but not [P m]. *) (* ####################################################### *) (** ** Unfolding of Definitions During Proof-Search *) (** The use of intermediate definitions is generally encouraged in a formal development as it usually leads to more concise and more readable statements. Yet, definitions can make it a little harder to automate proofs. The problem is that it is not obvious for a proof search mechanism to know when definitions need to be unfolded. Note that a naive strategy that consists in unfolding all definitions before calling proof search does not scale up to large proofs, so we avoid it. This section introduces a few techniques for avoiding to manually unfold definitions before calling proof search. *) (** To illustrate the treatment of definitions, let [P] be an abstract predicate on natural numbers, and let [myFact] be a definition denoting the proposition [P x] holds for any [x] less than or equal to 3. *) Axiom P : nat -> Prop. Definition myFact := forall x, x <= 3 -> P x. (** Proving that [myFact] under the assumption that [P x] holds for any [x] should be trivial. Yet, [auto] fails to prove it unless we unfold the definition of [myFact] explicitly. *) Lemma demo_hint_unfold_goal_1 : (forall x, P x) -> myFact. Proof. auto. (* Proof search doesn't know what to do, *) unfold myFact. auto. (* unless we unfold the definition. *) Qed. (** To automate the unfolding of definitions that appear as proof obligation, one can use the command [Hint Unfold myFact] to tell Coq that it should always try to unfold [myFact] when [myFact] appears in the goal. *) Hint Unfold myFact. (** This time, automation is able to see through the definition of [myFact]. *) Lemma demo_hint_unfold_goal_2 : (forall x, P x) -> myFact. Proof. auto. Qed. (** However, the [Hint Unfold] mechanism only works for unfolding definitions that appear in the goal. In general, proof search does not unfold definitions from the context. For example, assume we want to prove that [P 3] holds under the assumption that [True -> myFact]. *) Lemma demo_hint_unfold_context_1 : (True -> myFact) -> P 3. Proof. intros. auto. (* fails *) unfold myFact in *. auto. (* succeeds *) Qed. (** There is actually one exception to the previous rule: a constant occuring in an hypothesis is automatically unfolded if the hypothesis can be directly applied to the current goal. For example, [auto] can prove [myFact -> P 3], as illustrated below. *) Lemma demo_hint_unfold_context_2 : myFact -> P 3. Proof. auto. Qed. (* ####################################################### *) (** ** Automation for Proving Absurd Goals *) (** In this section, we'll see that lemmas concluding on a negation are generally not useful as hints, and that lemmas whose conclusion is [False] can be useful hints but having too many of them makes proof search inefficient. We'll also see a practical work-around to the efficiency issue. *) (** Consider the following lemma, which asserts that a number less than or equal to 3 is not greater than 3. *) Parameter le_not_gt : forall x, (x <= 3) -> ~ (x > 3). (** Equivalently, one could state that a number greater than three is not less than or equal to 3. *) Parameter gt_not_le : forall x, (x > 3) -> ~ (x <= 3). (** In fact, both statements are equivalent to a third one stating that [x <= 3] and [x > 3] are contradictory, in the sense that they imply [False]. *) Parameter le_gt_false : forall x, (x <= 3) -> (x > 3) -> False. (** The following investigation aim at figuring out which of the three statments is the most convenient with respect to proof automation. The following material is enclosed inside a [Section], so as to restrict the scope of the hints that we are adding. In other words, after the end of the section, the hints added within the section will no longer be active.*) Section DemoAbsurd1. (** Let's try to add the first lemma, [le_not_gt], as hint, and see whether we can prove that the proposition [exists x, x <= 3 /\ x > 3] is absurd. *) Hint Resolve le_not_gt. Lemma demo_auto_absurd_1 : (exists x, x <= 3 /\ x > 3) -> False. Proof. intros. jauto_set. (* decomposes the assumption *) (* debug *) eauto. (* does not see that [le_not_gt] could apply *) eapply le_not_gt. eauto. eauto. Qed. (** The lemma [gt_not_le] is symmetric to [le_not_gt], so it will not be any better. The third lemma, [le_gt_false], is a more useful hint, because it concludes on [False], so proof search will try to apply it when the current goal is [False]. *) Hint Resolve le_gt_false. Lemma demo_auto_absurd_2 : (exists x, x <= 3 /\ x > 3) -> False. Proof. dup. (* detailed version: *) intros. jauto_set. (* debug *) eauto. (* short version: *) jauto. Qed. (** In summary, a lemma of the form [H1 -> H2 -> False] is a much more effective hint than [H1 -> ~ H2], even though the two statments are equivalent up to the definition of the negation symbol [~]. *) (** That said, one should be careful with adding lemmas whose conclusion is [False] as hint. The reason is that whenever reaching the goal [False], the proof search mechanism will potentially try to apply all the hints whose conclusion is [False] before applying the appropriate one. *) End DemoAbsurd1. (** Adding lemmas whose conclusion is [False] as hint can be, locally, a very effective solution. However, this approach does not scale up for global hints. For most practical applications, it is reasonable to give the name of the lemmas to be exploited for deriving a contradiction. The tactic [false H], provided by [LibTactics] serves that purpose: [false H] replaces the goal with [False] and calls [eapply H]. Its behavior is described next. Observe that any of the three statements [le_not_gt], [gt_not_le] or [le_gt_false] can be used. *) Lemma demo_false : forall x, (x <= 3) -> (x > 3) -> 4 = 5. Proof. intros. dup 4. (* A failed proof: *) false. eapply le_gt_false. auto. (* here, [auto] does not prove [?x <= 3] by using [H] but by using the lemma [le_refl : forall x, x <= x]. *) (* The second subgoal becomes [3 > 3], which is not provable. *) skip. (* A correct proof: *) false. eapply le_gt_false. eauto. (* here, [eauto] uses [H], as expected, to prove [?x <= 3] *) eauto. (* so the second subgoal becomes [x > 3] *) (* The same proof using [false]: *) false le_gt_false. eauto. eauto. (* The lemmas [le_not_gt] and [gt_not_le] work as well *) false le_not_gt. eauto. eauto. Qed. (** In the above example, [false le_gt_false; eauto] proves the goal, but [false le_gt_false; auto] does not, because [auto] does not correctly instantiate the existential variable. Note that [false* le_gt_false] would not work either, because the star symbol tries to call [auto] first. So, there are two possibilities for completing the proof: either call [false le_gt_false; eauto], or call [false* (le_gt_false 3)]. *) (* ####################################################### *) (** ** Automation for Transitivity Lemmas *) (** Some lemmas should never be added as hints, because they would very badly slow down proof search. The typical example is that of transitivity results. This section describes the problem and presents a general workaround. Consider a subtyping relation, written [subtype S T], that relates two object [S] and [T] of type [typ]. Assume that this relation has been proved reflexive and transitive. The corresponding lemmas are named [subtype_refl] and [subtype_trans]. *) Parameter typ : Type. Parameter subtype : typ -> typ -> Prop. Parameter subtype_refl : forall T, subtype T T. Parameter subtype_trans : forall S T U, subtype S T -> subtype T U -> subtype S U. (** Adding reflexivity as hint is generally a good idea, so let's add reflexivity of subtyping as hint. *) Hint Resolve subtype_refl. (** Adding transitivity as hint is generally a bad idea. To understand why, let's add it as hint and see what happens. Because we cannot remove hints once we've added them, we are going to open a "Section," so as to restrict the scope of the transitivity hint to that section. *) Section HintsTransitivity. Hint Resolve subtype_trans. (** Now, consider the goal [forall S T, subtype S T], which clearly has no hope of being solved. Let's call [eauto] on this goal. *) Lemma transitivity_bad_hint_1 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 106 applications... *) Abort. (** Note that after closing the section, the hint [subtype_trans] is no longer active. *) End HintsTransitivity. (** In the previous example, the proof search has spent a lot of time trying to apply transitivity and reflexivity in every possible way. Its process can be summarized as follows. The first goal is [subtype S T]. Since reflexivity does not apply, [eauto] invokes transitivity, which produces two subgoals, [subtype S ?X] and [subtype ?X T]. Solving the first subgoal, [subtype S ?X], is straightforward, it suffices to apply reflexivity. This unifies [?X] with [S]. So, the second sugoal, [subtype ?X T], becomes [subtype S T], which is exactly what we started from... The problem with the transitivity lemma is that it is applicable to any goal concluding on a subtyping relation. Because of this, [eauto] keeps trying to apply it even though it most often doesn't help to solve the goal. So, one should never add a transitivity lemma as a hint for proof search. *) (** There is a general workaround for having automation to exploit transitivity lemmas without giving up on efficiency. This workaround relies on a powerful mechanism called "external hint." This mechanism allows to manually describe the condition under which a particular lemma should be tried out during proof search. For the case of transitivity of subtyping, we are going to tell Coq to try and apply the transitivity lemma on a goal of the form [subtype S U] only when the proof context already contains an assumption either of the form [subtype S T] or of the form [subtype T U]. In other words, we only apply the transitivity lemma when there is some evidence that this application might help. To set up this "external hint," one has to write the following. *) Hint Extern 1 (subtype ?S ?U) => match goal with | H: subtype S ?T |- _ => apply (@subtype_trans S T U) | H: subtype ?T U |- _ => apply (@subtype_trans S T U) end. (** This hint declaration can be understood as follows. - "Hint Extern" introduces the hint. - The number "1" corresponds to a priority for proof search. It doesn't matter so much what priority is used in practice. - The pattern [subtype ?S ?U] describes the kind of goal on which the pattern should apply. The question marks are used to indicate that the variables [?S] and [?U] should be bound to some value in the rest of the hint description. - The construction [match goal with ... end] tries to recognize patterns in the goal, or in the proof context, or both. - The first pattern is [H: subtype S ?T |- _]. It indices that the context should contain an hypothesis [H] of type [subtype S ?T], where [S] has to be the same as in the goal, and where [?T] can have any value. - The symbol [|- _] at the end of [H: subtype S ?T |- _] indicates that we do not impose further condition on how the proof obligation has to look like. - The branch [=> apply (@subtype_trans S T U)] that follows indicates that if the goal has the form [subtype S U] and if there exists an hypothesis of the form [subtype S T], then we should try and apply transitivity lemma instantiated on the arguments [S], [T] and [U]. (Note: the symbol [@] in front of [subtype_trans] is only actually needed when the "Implicit Arguments" feature is activated.) - The other branch, which corresponds to an hypothesis of the form [H: subtype ?T U] is symmetrical. Note: the same external hint can be reused for any other transitive relation, simply by renaming [subtype] into the name of that relation. *) (** Let us see an example illustrating how the hint works. *) Lemma transitivity_workaround_1 : forall T1 T2 T3 T4, subtype T1 T2 -> subtype T2 T3 -> subtype T3 T4 -> subtype T1 T4. Proof. intros. (* debug *) eauto. (* The trace shows the external hint being used *) Qed. (** We may also check that the new external hint does not suffer from the complexity blow up. *) Lemma transitivity_workaround_2 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 0 applications *) Abort. (* ####################################################### *) (** * Decision Procedures *) (** A decision procedure is able to solve proof obligations whose statement admits a particular form. This section describes three useful decision procedures. The tactic [omega] handles goals involving arithmetic and inequalities, but not general multiplications. The tactic [ring] handles goals involving arithmetic, including multiplications, but does not support inequalities. The tactic [congruence] is able to prove equalities and inequalities by exploiting equalities available in the proof context. *) (* ####################################################### *) (** ** Omega *) (** The tactic [omega] supports natural numbers (type [nat]) as well as integers (type [Z], available by including the module [ZArith]). It supports addition, substraction, equalities and inequalities. Before using [omega], one needs to import the module [Omega], as follows. *) Require Import Omega. (** Here is an example. Let [x] and [y] be two natural numbers (they cannot be negative). Assume [y] is less than 4, assume [x+x+1] is less than [y], and assume [x] is not zero. Then, it must be the case that [x] is equal to one. *) Lemma omega_demo_1 : forall (x y : nat), (y <= 4) -> (x + x + 1 <= y) -> (x <> 0) -> (x = 1). Proof. intros. omega. Qed. (** Another example: if [z] is the mean of [x] and [y], and if the difference between [x] and [y] is at most [4], then the difference between [x] and [z] is at most 2. *) Lemma omega_demo_2 : forall (x y z : nat), (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2). Proof. intros. omega. Qed. (** One can proof [False] using [omega] if the mathematical facts from the context are contradictory. In the following example, the constraints on the values [x] and [y] cannot be all satisfied in the same time. *) Lemma omega_demo_3 : forall (x y : nat), (x + 5 <= y) -> (y - x < 3) -> False. Proof. intros. omega. Qed. (** Note: [omega] can prove a goal by contradiction only if its conclusion is reduced [False]. The tactic [omega] always fails when the conclusion is an arbitrary proposition [P], even though [False] implies any proposition [P] (by [ex_falso_quodlibet]). *) Lemma omega_demo_4 : forall (x y : nat) (P : Prop), (x + 5 <= y) -> (y - x < 3) -> P. Proof. intros. (* Calling [omega] at this point fails with the message: "Omega: Can't solve a goal with proposition variables" *) (* So, one needs to replace the goal by [False] first. *) false. omega. Qed. (* ####################################################### *) (** ** Ring *) (** Compared with [omega], the tactic [ring] adds support for multiplications, however it gives up the ability to reason on inequations. Moreover, it supports only integers (type [Z]) and not natural numbers (type [nat]). Here is an example showing how to use [ring]. *) Module RingDemo. Require Import ZArith. Open Scope Z_scope. (* Arithmetic symbols are now interpreted in [Z] *) Lemma ring_demo : forall (x y z : Z), x * (y + z) - z * 3 * x = x * y - 2 * x * z. Proof. intros. ring. Qed. End RingDemo. (* ####################################################### *) (** ** Congruence *) (** The tactic [congruence] is able to exploit equalities from the proof context in order to automatically perform the rewriting operations necessary to establish a goal. It is slightly more powerful than the tactic [subst], which can only handle equalities of the form [x = e] where [x] is a variable and [e] an expression. *) Lemma congruence_demo_1 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), f (g x) (g y) = z -> 2 = g x -> g y = h z -> f 2 (h z) = z. Proof. intros. congruence. Qed. (** Moreover, [congruence] is able to exploit universally quantified equalities, for example [forall a, g a = h a]. *) Lemma congruence_demo_2 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), (forall a, g a = h a) -> f (g x) (g y) = z -> g x = 2 -> f 2 (h y) = z. Proof. congruence. Qed. (** Next is an example where [congruence] is very useful. *) Lemma congruence_demo_4 : forall (f g : nat->nat), (forall a, f a = g a) -> f (g (g 2)) = g (f (f 2)). Proof. congruence. Qed. (** The tactic [congruence] is able to prove a contradiction if the goal entails an equality that contradicts an inequality available in the proof context. *) Lemma congruence_demo_3 : forall (f g h : nat->nat) (x : nat), (forall a, f a = h a) -> g x = f x -> g x <> h x -> False. Proof. congruence. Qed. (** One of the strengths of [congruence] is that it is a very fast tactic. So, one should not hesitate to invoke it wherever it might help. *) (* ####################################################### *) (** * Summary *) (** Let us summarize the main automation tactics available. - [auto] automatically applies [reflexivity], [assumption], and [apply]. - [eauto] moreover tries [eapply], and in particular can instantiate existentials in the conclusion. - [iauto] extends [eauto] with support for negation, conjunctions, and disjunctions. However, its support for disjunction can make it exponentially slow. - [jauto] extends [eauto] with support for negation, conjunctions, and existential at the head of hypothesis. - [congruence] helps reasoning about equalities and inequalities. - [omega] proves arithmetic goals with equalities and inequalities, but it does not support multiplication. - [ring] proves arithmetic goals with multiplications, but does not support inequalities. In order to set up automation appropriately, keep in mind the following rule of thumbs: - automation is all about balance: not enough automation makes proofs not very robust on change, whereas too much automation makes proofs very hard to fix when they break. - if a lemma is not goal directed (i.e., some of its variables do not occur in its conclusion), then the premises need to be ordered in such a way that proving the first premises maximizes the chances of correctly instantiating the variables that do not occur in the conclusion. - a lemma whose conclusion is [False] should only be added as a local hint, i.e., as a hint within the current section. - a transitivity lemma should never be considered as hint; if automation of transitivity reasoning is really necessary, an [Extern Hint] needs to be set up. - a definition usually needs to be accompanied with a [Hint Unfold]. Becoming a master in the black art of automation certainly requires some investment, however this investment will pay off very quickly. *) (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * UseAuto: Theory and Practice of Automation in Coq Proofs *) (* Chapter maintained by Arthur Chargueraud *) (** In a machine-checked proof, every single detail has to be justified. This can result in huge proof scripts. Fortunately, Coq comes with a proof-search mechanism and with several decision procedures that enable the system to automatically synthesize simple pieces of proof. Automation is very powerful when set up appropriately. The purpose of this chapter is to explain the basics of working of automation. The chapter is organized in two parts. The first part focuses on a general mechanism called "proof search." In short, proof search consists in naively trying to apply lemmas and assumptions in all possible ways. The second part describes "decision procedures", which are tactics that are very good at solving proof obligations that fall in some particular fragment of the logic of Coq. Many of the examples used in this chapter consist of small lemmas that have been made up to illustrate particular aspects of automation. These examples are completely independent from the rest of the Software Foundations course. This chapter also contains some bigger examples which are used to explain how to use automation in realistic proofs. These examples are taken from other chapters of the course (mostly from STLC), and the proofs that we present make use of the tactics from the library [LibTactics.v], which is presented in the chapter [UseTactics]. *) Require Import LibTactics. (* ####################################################### *) (** * Basic Features of Proof Search *) (** The idea of proof search is to replace a sequence of tactics applying lemmas and assumptions with a call to a single tactic, for example [auto]. This form of proof automation saves a lot of effort. It typically leads to much shorter proof scripts, and to scripts that are typically more robust to change. If one makes a little change to a definition, a proof that exploits automation probably won't need to be modified at all. Of course, using too much automation is a bad idea. When a proof script no longer records the main arguments of a proof, it becomes difficult to fix it when it gets broken after a change in a definition. Overall, a reasonable use of automation is generally a big win, as it saves a lot of time both in building proof scripts and in subsequently maintaining those proof scripts. *) (* ####################################################### *) (** ** Strength of Proof Search *) (** We are going to study four proof-search tactics: [auto], [eauto], [iauto] and [jauto]. The tactics [auto] and [eauto] are builtin in Coq. The tactic [iauto] is a shorthand for the builtin tactic [try solve [intuition eauto]]. The tactic [jauto] is defined in the library [LibTactics], and simply performs some preprocessing of the goal before calling [eauto]. The goal of this chapter is to explain the general principles of proof search and to give rule of thumbs for guessing which of the four tactics mentioned above is best suited for solving a given goal. Proof search is a compromise between efficiency and expressiveness, that is, a tradeoff between how complex goals the tactic can solve and how much time the tactic requires for terminating. The tactic [auto] builds proofs only by using the basic tactics [reflexivity], [assumption], and [apply]. The tactic [eauto] can also exploit [eapply]. The tactic [jauto] extends [eauto] by being able to open conjunctions and existentials that occur in the context. The tactic [iauto] is able to deal with conjunctions, disjunctions, and negation in a quite clever way; however it is not able to open existentials from the context. Also, [iauto] usually becomes very slow when the goal involves several disjunctions. Note that proof search tactics never perform any rewriting step (tactics [rewrite], [subst]), nor any case analysis on an arbitrary data structure or predicate (tactics [destruct] and [inversion]), nor any proof by induction (tactic [induction]). So, proof search is really intended to automate the final steps from the various branches of a proof. It is not able to discover the overall structure of a proof. *) (* ####################################################### *) (** ** Basics *) (** The tactic [auto] is able to solve a goal that can be proved using a sequence of [intros], [apply], [assumption], and [reflexivity]. Two examples follow. The first one shows the ability for [auto] to call [reflexivity] at any time. In fact, calling [reflexivity] is always the first thing that [auto] tries to do. *) Lemma solving_by_reflexivity : 2 + 3 = 5. Proof. auto. Qed. (** The second example illustrates a proof where a sequence of two calls to [apply] are needed. The goal is to prove that if [Q n] implies [P n] for any [n] and if [Q n] holds for any [n], then [P 2] holds. *) Lemma solving_by_apply : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. auto. Qed. (** We can ask [auto] to tell us what proof it came up with, by invoking [info_auto] in place of [auto]. *) Lemma solving_by_apply' : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. info_auto. Qed. (* The output is: [intro P; intro Q; intro H;] *) (* followed with [intro H0; simple apply H; simple apply H0]. *) (* i.e., the sequence [intros P Q H H0; apply H; apply H0]. *) (** The tactic [auto] can invoke [apply] but not [eapply]. So, [auto] cannot exploit lemmas whose instantiation cannot be directly deduced from the proof goal. To exploit such lemmas, one needs to invoke the tactic [eauto], which is able to call [eapply]. In the following example, the first hypothesis asserts that [P n] is true when [Q m] is true for some [m], and the goal is to prove that [Q 1] implies [P 2]. This implication follows direction from the hypothesis by instantiating [m] as the value [1]. The following proof script shows that [eauto] successfully solves the goal, whereas [auto] is not able to do so. *) Lemma solving_by_eapply : forall (P Q : nat->Prop), (forall n m, Q m -> P n) -> Q 1 -> P 2. Proof. auto. eauto. Qed. (** Remark: Again, we can use [info_eauto] to see what proof [eauto] comes up with. *) (* ####################################################### *) (** ** Conjunctions *) (** So far, we've seen that [eauto] is stronger than [auto] in the sense that it can deal with [eapply]. In the same way, we are going to see how [jauto] and [iauto] are stronger than [auto] and [eauto] in the sense that they provide better support for conjunctions. *) (** The tactics [auto] and [eauto] can prove a goal of the form [F /\ F'], where [F] and [F'] are two propositions, as soon as both [F] and [F'] can be proved in the current context. An example follows. *) Lemma solving_conj_goal : forall (P : nat->Prop) (F : Prop), (forall n, P n) -> F -> F /\ P 2. Proof. auto. Qed. (** However, when an assumption is a conjunction, [auto] and [eauto] are not able to exploit this conjunction. It can be quite surprising at first that [eauto] can prove very complex goals but that it fails to prove that [F /\ F'] implies [F]. The tactics [iauto] and [jauto] are able to decompose conjunctions from the context. Here is an example. *) Lemma solving_conj_hyp : forall (F F' : Prop), F /\ F' -> F. Proof. auto. eauto. jauto. (* or [iauto] *) Qed. (** The tactic [jauto] is implemented by first calling a pre-processing tactic called [jauto_set], and then calling [eauto]. So, to understand how [jauto] works, one can directly call the tactic [jauto_set]. *) Lemma solving_conj_hyp' : forall (F F' : Prop), F /\ F' -> F. Proof. intros. jauto_set. eauto. Qed. (** Next is a more involved goal that can be solved by [iauto] and [jauto]. *) Lemma solving_conj_more : forall (P Q R : nat->Prop) (F : Prop), (F /\ (forall n m, (Q m /\ R n) -> P n)) -> (F -> R 2) -> Q 1 -> P 2 /\ F. Proof. jauto. (* or [iauto] *) Qed. (** The strategy of [iauto] and [jauto] is to run a global analysis of the top-level conjunctions, and then call [eauto]. For this reason, those tactics are not good at dealing with conjunctions that occur as the conclusion of some universally quantified hypothesis. The following example illustrates a general weakness of Coq proof search mechanisms. *) Lemma solving_conj_hyp_forall : forall (P Q : nat->Prop), (forall n, P n /\ Q n) -> P 2. Proof. auto. eauto. iauto. jauto. (* Nothing works, so we have to do some of the work by hand *) intros. destruct (H 2). auto. Qed. (** This situation is slightly disappointing, since automation is able to prove the following goal, which is very similar. The only difference is that the universal quantification has been distributed over the conjunction. *) Lemma solved_by_jauto : forall (P Q : nat->Prop) (F : Prop), (forall n, P n) /\ (forall n, Q n) -> P 2. Proof. jauto. (* or [iauto] *) Qed. (* ####################################################### *) (** ** Disjunctions *) (** The tactics [auto] and [eauto] can handle disjunctions that occur in the goal. *) Lemma solving_disj_goal : forall (F F' : Prop), F -> F \/ F'. Proof. auto. Qed. (** However, only [iauto] is able to automate reasoning on the disjunctions that appear in the context. For example, [iauto] can prove that [F \/ F'] entails [F' \/ F]. *) Lemma solving_disj_hyp : forall (F F' : Prop), F \/ F' -> F' \/ F. Proof. auto. eauto. jauto. iauto. Qed. (** More generally, [iauto] can deal with complex combinations of conjunctions, disjunctions, and negations. Here is an example. *) Lemma solving_tauto : forall (F1 F2 F3 : Prop), ((~F1 /\ F3) \/ (F2 /\ ~F3)) -> (F2 -> F1) -> (F2 -> F3) -> ~F2. Proof. iauto. Qed. (** However, the ability of [iauto] to automatically perform a case analysis on disjunctions comes with a downside: [iauto] may be very slow. If the context involves several hypotheses with disjunctions, [iauto] typically generates an exponential number of subgoals on which [eauto] is called. One major advantage of [jauto] compared with [iauto] is that it never spends time performing this kind of case analyses. *) (* ####################################################### *) (** ** Existentials *) (** The tactics [eauto], [iauto], and [jauto] can prove goals whose conclusion is an existential. For example, if the goal is [exists x, f x], the tactic [eauto] introduces an existential variable, say [?25], in place of [x]. The remaining goal is [f ?25], and [eauto] tries to solve this goal, allowing itself to instantiate [?25] with any appropriate value. For example, if an assumption [f 2] is available, then the variable [?25] gets instantiated with [2] and the goal is solved, as shown below. *) Lemma solving_exists_goal : forall (f : nat->Prop), f 2 -> exists x, f x. Proof. auto. (* observe that [auto] does not deal with existentials, *) eauto. (* whereas [eauto], [iauto] and [jauto] solve the goal *) Qed. (** A major strength of [jauto] over the other proof search tactics is that it is able to exploit the existentially-quantified hypotheses, i.e., those of the form [exists x, P]. *) Lemma solving_exists_hyp : forall (f g : nat->Prop), (forall x, f x -> g x) -> (exists a, f a) -> (exists a, g a). Proof. auto. eauto. iauto. (* All of these tactics fail, *) jauto. (* whereas [jauto] succeeds. *) (* For the details, run [intros. jauto_set. eauto] *) Qed. (* ####################################################### *) (** ** Negation *) (** The tactics [auto] and [eauto] suffer from some limitations with respect to the manipulation of negations, mostly related to the fact that negation, written [~ P], is defined as [P -> False] but that the unfolding of this definition is not performed automatically. Consider the following example. *) Lemma negation_study_1 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. intros P H0 HX. eauto. (* It fails to see that [HX] applies *) unfold not in *. eauto. Qed. (** For this reason, the tactics [iauto] and [jauto] systematically invoke [unfold not in *] as part of their pre-processing. So, they are able to solve the previous goal right away. *) Lemma negation_study_2 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. jauto. (* or [iauto] *) Qed. (** We will come back later on to the behavior of proof search with respect to the unfolding of definitions. *) (* ####################################################### *) (** ** Equalities *) (** Coq's proof-search feature is not good at exploiting equalities. It can do very basic operations, like exploiting reflexivity and symmetry, but that's about it. Here is a simple example that [auto] can solve, by first calling [symmetry] and then applying the hypothesis. *) Lemma equality_by_auto : forall (f g : nat->Prop), (forall x, f x = g x) -> g 2 = f 2. Proof. auto. Qed. (** To automate more advanced reasoning on equalities, one should rather try to use the tactic [congruence], which is presented at the end of this chapter in the "Decision Procedures" section. *) (* ####################################################### *) (** * How Proof Search Works *) (* ####################################################### *) (** ** Search Depth *) (** The tactic [auto] works as follows. It first tries to call [reflexivity] and [assumption]. If one of these calls solves the goal, the job is done. Otherwise [auto] tries to apply the most recently introduced assumption that can be applied to the goal without producing and error. This application produces subgoals. There are two possible cases. If the sugboals produced can be solved by a recursive call to [auto], then the job is done. Otherwise, if this application produces at least one subgoal that [auto] cannot solve, then [auto] starts over by trying to apply the second most recently introduced assumption. It continues in a similar fashion until it finds a proof or until no assumption remains to be tried. It is very important to have a clear idea of the backtracking process involved in the execution of the [auto] tactic; otherwise its behavior can be quite puzzling. For example, [auto] is not able to solve the following triviality. *) Lemma search_depth_0 : True /\ True /\ True /\ True /\ True /\ True. Proof. auto. Abort. (** The reason [auto] fails to solve the goal is because there are too many conjunctions. If there had been only five of them, [auto] would have successfully solved the proof, but six is too many. The tactic [auto] limits the number of lemmas and hypotheses that can be applied in a proof, so as to ensure that the proof search eventually terminates. By default, the maximal number of steps is five. One can specify a different bound, writing for example [auto 6] to search for a proof involving at most six steps. For example, [auto 6] would solve the previous lemma. (Similarly, one can invoke [eauto 6] or [intuition eauto 6].) The argument [n] of [auto n] is called the "search depth." The tactic [auto] is simply defined as a shorthand for [auto 5]. The behavior of [auto n] can be summarized as follows. It first tries to solve the goal using [reflexivity] and [assumption]. If this fails, it tries to apply a hypothesis (or a lemma that has been registered in the hint database), and this application produces a number of sugoals. The tactic [auto (n-1)] is then called on each of those subgoals. If all the subgoals are solved, the job is completed, otherwise [auto n] tries to apply a different hypothesis. During the process, [auto n] calls [auto (n-1)], which in turn might call [auto (n-2)], and so on. The tactic [auto 0] only tries [reflexivity] and [assumption], and does not try to apply any lemma. Overall, this means that when the maximal number of steps allowed has been exceeded, the [auto] tactic stops searching and backtracks to try and investigate other paths. *) (** The following lemma admits a unique proof that involves exactly three steps. So, [auto n] proves this goal iff [n] is greater than three. *) Lemma search_depth_1 : forall (P : nat->Prop), P 0 -> (P 0 -> P 1) -> (P 1 -> P 2) -> (P 2). Proof. auto 0. (* does not find the proof *) auto 1. (* does not find the proof *) auto 2. (* does not find the proof *) auto 3. (* finds the proof *) (* more generally, [auto n] solves the goal if [n >= 3] *) Qed. (** We can generalize the example by introducing an assumption asserting that [P k] is derivable from [P (k-1)] for all [k], and keep the assumption [P 0]. The tactic [auto], which is the same as [auto 5], is able to derive [P k] for all values of [k] less than 5. For example, it can prove [P 4]. *) Lemma search_depth_3 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4). Proof. auto. Qed. (** However, to prove [P 5], one needs to call at least [auto 6]. *) Lemma search_depth_4 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 5). Proof. auto. auto 6. Qed. (** Because [auto] looks for proofs at a limited depth, there are cases where [auto] can prove a goal [F] and can prove a goal [F'] but cannot prove [F /\ F']. In the following example, [auto] can prove [P 4] but it is not able to prove [P 4 /\ P 4], because the splitting of the conjunction consumes one proof step. To prove the conjunction, one needs to increase the search depth, using at least [auto 6]. *) Lemma search_depth_5 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4 /\ P 4). Proof. auto. auto 6. Qed. (* ####################################################### *) (** ** Backtracking *) (** In the previous section, we have considered proofs where at each step there was a unique assumption that [auto] could apply. In general, [auto] can have several choices at every step. The strategy of [auto] consists of trying all of the possibilities (using a depth-first search exploration). To illustrate how automation works, we are going to extend the previous example with an additional assumption asserting that [P k] is also derivable from [P (k+1)]. Adding this hypothesis offers a new possibility that [auto] could consider at every step. There exists a special command that one can use for tracing all the steps that proof-search considers. To view such a trace, one should write [debug eauto]. (For some reason, the command [debug auto] does not exist, so we have to use the command [debug eauto] instead.) *) Lemma working_of_auto_1 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 2). (* Uncomment "debug" in the following line to see the debug trace: *) Proof. intros P H1 H2 H3. (* debug *) eauto. Qed. (** The output message produced by [debug eauto] is as follows. << depth=5 depth=4 apply H3 depth=3 apply H3 depth=3 exact H1 >> The depth indicates the value of [n] with which [eauto n] is called. The tactics shown in the message indicate that the first thing that [eauto] has tried to do is to apply [H3]. The effect of applying [H3] is to replace the goal [P 2] with the goal [P 1]. Then, again, [H3] has been applied, changing the goal [P 1] into [P 0]. At that point, the goal was exactly the hypothesis [H1]. It seems that [eauto] was quite lucky there, as it never even tried to use the hypothesis [H2] at any time. The reason is that [auto] always tries to use the most recently introduced hypothesis first, and [H3] is a more recent hypothesis than [H2] in the goal. So, let's permute the hypotheses [H2] and [H3] and see what happens. *) Lemma working_of_auto_2 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Goal: *) (P 2). Proof. intros P H1 H3 H2. (* debug *) eauto. Qed. (** This time, the output message suggests that the proof search investigates many possibilities. Replacing [debug eauto] with [info_eauto], we observe that the proof that [eauto] comes up with is actually not the simplest one. [apply H2; apply H3; apply H3; apply H3; exact H1] This proof goes through the proof obligation [P 3], even though it is not any useful. The following tree drawing describes all the goals that automation has been through. << |5||4||3||2||1||0| -- below, tabulation indicates the depth [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 6] -> [P 7] -> [P 5] -> [P 4] -> [P 5] -> [P 3] --> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 1] -> [P 2] -> [P 3] -> [P 1] -> [P 0] -> !! Done !! >> The first few lines read as follows. To prove [P 2], [eauto 5] has first tried to apply [H2], producing the subgoal [P 3]. To solve it, [eauto 4] has tried again to apply [H2], producing the goal [P 4]. Similarly, the search goes through [P 5], [P 6] and [P 7]. When reaching [P 7], the tactic [eauto 0] is called but as it is not allowed to try and apply any lemma, it fails. So, we come back to the goal [P 6], and try this time to apply hypothesis [H3], producing the subgoal [P 5]. Here again, [eauto 0] fails to solve this goal. The process goes on and on, until backtracking to [P 3] and trying to apply [H2] three times in a row, going through [P 2] and [P 1] and [P 0]. This search tree explains why [eauto] came up with a proof starting with [apply H2]. *) (* ####################################################### *) (** ** Adding Hints *) (** By default, [auto] (and [eauto]) only tries to apply the hypotheses that appear in the proof context. There are two possibilities for telling [auto] to exploit a lemma that have been proved previously: either adding the lemma as an assumption just before calling [auto], or adding the lemma as a hint, so that it can be used by every calls to [auto]. The first possibility is useful to have [auto] exploit a lemma that only serves at this particular point. To add the lemma as hypothesis, one can type [generalize mylemma; intros], or simply [lets: mylemma] (the latter requires [LibTactics.v]). The second possibility is useful for lemmas that need to be exploited several times. The syntax for adding a lemma as a hint is [Hint Resolve mylemma]. For example, the lemma asserting than any number is less than or equal to itself, [forall x, x <= x], called [Le.le_refl] in the Coq standard library, can be added as a hint as follows. *) Hint Resolve Le.le_refl. (** A convenient shorthand for adding all the constructors of an inductive datatype as hints is the command [Hint Constructors mydatatype]. Warning: some lemmas, such as transitivity results, should not be added as hints as they would very badly affect the performance of proof search. The description of this problem and the presentation of a general work-around for transitivity lemmas appear further on. *) (* ####################################################### *) (** ** Integration of Automation in Tactics *) (** The library "LibTactics" introduces a convenient feature for invoking automation after calling a tactic. In short, it suffices to add the symbol star ([*]) to the name of a tactic. For example, [apply* H] is equivalent to [apply H; auto_star], where [auto_star] is a tactic that can be defined as needed. The definition of [auto_star], which determines the meaning of the star symbol, can be modified whenever needed. Simply write: Ltac auto_star ::= a_new_definition. ]] Observe the use of [::=] instead of [:=], which indicates that the tactic is being rebound to a new definition. So, the default definition is as follows. *) Ltac auto_star ::= try solve [ jauto ]. (** Nearly all standard Coq tactics and all the tactics from "LibTactics" can be called with a star symbol. For example, one can invoke [subst*], [destruct* H], [inverts* H], [lets* I: H x], [specializes* H x], and so on... There are two notable exceptions. The tactic [auto*] is just another name for the tactic [auto_star]. And the tactic [apply* H] calls [eapply H] (or the more powerful [applys H] if needed), and then calls [auto_star]. Note that there is no [eapply* H] tactic, use [apply* H] instead. *) (** In large developments, it can be convenient to use two degrees of automation. Typically, one would use a fast tactic, like [auto], and a slower but more powerful tactic, like [jauto]. To allow for a smooth coexistence of the two form of automation, [LibTactics.v] also defines a "tilde" version of tactics, like [apply~ H], [destruct~ H], [subst~], [auto~] and so on. The meaning of the tilde symbol is described by the [auto_tilde] tactic, whose default implementation is [auto]. *) Ltac auto_tilde ::= auto. (** In the examples that follow, only [auto_star] is needed. *) (** An alternative, possibly more efficient version of auto_star is the following": Ltac auto_star ::= try solve [ eassumption | auto | jauto ]. With the above definition, [auto_star] first tries to solve the goal using the assumptions; if it fails, it tries using [auto], and if this still fails, then it calls [jauto]. Even though [jauto] is strictly stronger than [eassumption] and [auto], it makes sense to call these tactics first, because, when the succeed, they save a lot of time, and when they fail to prove the goal, they fail very quickly.". *) (* ####################################################### *) (** * Examples of Use of Automation *) (** Let's see how to use proof search in practice on the main theorems of the "Software Foundations" course, proving in particular results such as determinism, preservation and progress. *) (* ####################################################### *) (** ** Determinism *) Module DeterministicImp. Require Import Imp. (** Recall the original proof of the determinism lemma for the IMP language, shown below. *) Theorem ceval_deterministic: forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. intros c st st1 st2 E1 E2. generalize dependent st2. (ceval_cases (induction E1) Case); intros st2 E2; inversion E2; subst. Case "E_Skip". reflexivity. Case "E_Ass". reflexivity. Case "E_Seq". assert (st' = st'0) as EQ1. SCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Case "E_IfTrue". SCase "b1 evaluates to true". apply IHE1. assumption. SCase "b1 evaluates to false (contradiction)". rewrite H in H5. inversion H5. Case "E_IfFalse". SCase "b1 evaluates to true (contradiction)". rewrite H in H5. inversion H5. SCase "b1 evaluates to false". apply IHE1. assumption. Case "E_WhileEnd". SCase "b1 evaluates to true". reflexivity. SCase "b1 evaluates to false (contradiction)". rewrite H in H2. inversion H2. Case "E_WhileLoop". SCase "b1 evaluates to true (contradiction)". rewrite H in H4. inversion H4. SCase "b1 evaluates to false". assert (st' = st'0) as EQ1. SSCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Qed. (** Exercise: rewrite this proof using [auto] whenever possible. (The solution uses [auto] 9 times.) *) Theorem ceval_deterministic': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* FILL IN HERE *) admit. Qed. (** In fact, using automation is not just a matter of calling [auto] in place of one or two other tactics. Using automation is about rethinking the organization of sequences of tactics so as to minimize the effort involved in writing and maintaining the proof. This process is eased by the use of the tactics from [LibTactics.v]. So, before trying to optimize the way automation is used, let's first rewrite the proof of determinism: - use [introv H] instead of [intros x H], - use [gen x] instead of [generalize dependent x], - use [inverts H] instead of [inversion H; subst], - use [tryfalse] to handle contradictions, and get rid of the cases where [beval st b1 = true] and [beval st b1 = false] both appear in the context, - stop using [ceval_cases] to label subcases. *) Theorem ceval_deterministic'': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. assert (st' = st'0). auto. subst. auto. auto. auto. auto. assert (st' = st'0). auto. subst. auto. Qed. (** To obtain a nice clean proof script, we have to remove the calls [assert (st' = st'0)]. Such a tactic invokation is not nice because it refers to some variables whose name has been automatically generated. This kind of tactics tend to be very brittle. The tactic [assert (st' = st'0)] is used to assert the conclusion that we want to derive from the induction hypothesis. So, rather than stating this conclusion explicitly, we are going to ask Coq to instantiate the induction hypothesis, using automation to figure out how to instantiate it. The tactic [forwards], described in [LibTactics.v] precisely helps with instantiating a fact. So, let's see how it works out on our example. *) Theorem ceval_deterministic''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* Let's replay the proof up to the [assert] tactic. *) introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. (* We duplicate the goal for comparing different proofs. *) dup 4. (* The old proof: *) assert (st' = st'0). apply IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, without automation: *) forwards: IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, with automation: *) forwards: IHE1_1. eauto. (* produces [H: st' = st'0]. *) skip. (* The new proof, with integrated automation: *) forwards*: IHE1_1. (* produces [H: st' = st'0]. *) skip. Abort. (** To polish the proof script, it remains to factorize the calls to [auto], using the star symbol. The proof of determinism can then be rewritten in only four lines, including no more than 10 tactics. *) Theorem ceval_deterministic'''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts* E2; tryfalse. forwards*: IHE1_1. subst*. forwards*: IHE1_1. subst*. Qed. End DeterministicImp. (* ####################################################### *) (** ** Preservation for STLC *) Module PreservationProgressStlc. Require Import StlcProp. Import STLC. Import STLCProp. (** Consider the proof of perservation of STLC, shown below. This proof already uses [eauto] through the triple-dot mechanism. *) Theorem preservation : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof with eauto. remember (@empty ty) as Gamma. intros t t' T HT. generalize dependent t'. (has_type_cases (induction HT) Case); intros t' HE; subst Gamma. Case "T_Var". inversion HE. Case "T_Abs". inversion HE. Case "T_App". inversion HE; subst... (* (step_cases (inversion HE) SCase); subst...*) (* The ST_App1 and ST_App2 cases are immediate by induction, and auto takes care of them *) SCase "ST_AppAbs". apply substitution_preserves_typing with T11... inversion HT1... Case "T_True". inversion HE. Case "T_False". inversion HE. Case "T_If". inversion HE; subst... Qed. (** Exercise: rewrite this proof using tactics from [LibTactics] and calling automation using the star symbol rather than the triple-dot notation. More precisely, make use of the tactics [inverts*] and [applys*] to call [auto*] after a call to [inverts] or to [applys]. The solution is three lines long.*) Theorem preservation' : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof. (* FILL IN HERE *) admit. Qed. (* ####################################################### *) (** ** Progress for STLC *) (** Consider the proof of the progress theorem. *) Theorem progress : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof with eauto. intros t T Ht. remember (@empty ty) as Gamma. (has_type_cases (induction Ht) Case); subst Gamma... Case "T_Var". inversion H. Case "T_App". right. destruct IHHt1... SCase "t1 is a value". destruct IHHt2... SSCase "t2 is a value". inversion H; subst; try solve by inversion. exists ([x0:=t2]t)... SSCase "t2 steps". destruct H0 as [t2' Hstp]. exists (tapp t1 t2')... SCase "t1 steps". destruct H as [t1' Hstp]. exists (tapp t1' t2)... Case "T_If". right. destruct IHHt1... destruct t1; try solve by inversion... inversion H. exists (tif x0 t2 t3)... Qed. (** Exercise: optimize the above proof. Hint: make use of [destruct*] and [inverts*]. The solution consists of 10 short lines. *) Theorem progress' : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof. (* FILL IN HERE *) admit. Qed. End PreservationProgressStlc. (* ####################################################### *) (** ** BigStep and SmallStep *) Module Semantics. Require Import Smallstep. (** Consider the proof relating a small-step reduction judgment to a big-step reduction judgment. *) Theorem multistep__eval : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. intros t v Hnorm. unfold normal_form_of in Hnorm. inversion Hnorm as [Hs Hnf]; clear Hnorm. rewrite nf_same_as_value in Hnf. inversion Hnf. clear Hnf. exists n. split. reflexivity. multi_cases (induction Hs) Case; subst. Case "multi_refl". apply E_Const. Case "multi_step". eapply step__eval. eassumption. apply IHHs. reflexivity. Qed. (** Our goal is to optimize the above proof. It is generally easier to isolate inductions into separate lemmas. So, we are going to first prove an intermediate result that consists of the judgment over which the induction is being performed. *) (** Exercise: prove the following result, using tactics [introv], [induction] and [subst], and [apply*]. The solution is 3 lines long. *) Theorem multistep_eval_ind : forall t v, t ==>* v -> forall n, C n = v -> t || n. Proof. (* FILL IN HERE *) admit. Qed. (** Exercise: using the lemma above, simplify the proof of the result [multistep__eval]. You should use the tactics [introv], [inverts], [split*] and [apply*]. The solution is 2 lines long. *) Theorem multistep__eval' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. (** If we try to combine the two proofs into a single one, we will likely fail, because of a limitation of the [induction] tactic. Indeed, this tactic looses information when applied to a predicate whose arguments are not reduced to variables, such as [t ==>* (C n)]. You will thus need to use the more powerful tactic called [dependent induction]. This tactic is available only after importing the [Program] library, as shown below. *) Require Import Program. (** Exercise: prove the lemma [multistep__eval] without invoking the lemma [multistep_eval_ind], that is, by inlining the proof by induction involved in [multistep_eval_ind], using the tactic [dependent induction] instead of [induction]. The solution is 5 lines long. *) Theorem multistep__eval'' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. End Semantics. (* ####################################################### *) (** ** Preservation for STLCRef *) Module PreservationProgressReferences. Require Import References. Import STLCRef. Hint Resolve store_weakening extends_refl. (** The proof of preservation for [STLCRef] can be found in chapter [References]. It contains 58 lines (not counting the labelling of cases). The optimized proof script is more than twice shorter. The following material explains how to build the optimized proof script. The resulting optimized proof script for the preservation theorem appears afterwards. *) Theorem preservation : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. (* old: [Proof. with eauto using store_weakening, extends_refl.] new: [Proof.], and the two lemmas are registered as hints before the proof of the lemma, possibly inside a section in order to restrict the scope of the hints. *) remember (@empty ty) as Gamma. introv Ht. gen t'. (has_type_cases (induction Ht) Case); introv HST Hstep; (* old: [subst; try (solve by inversion); inversion Hstep; subst; try (eauto using store_weakening, extends_refl)] new: [subst Gamma; inverts Hstep; eauto.] We want to be more precise on what exactly we substitute, and we do not want to call [try (solve by inversion)] which is way to slow. *) subst Gamma; inverts Hstep; eauto. Case "T_App". SCase "ST_AppAbs". (* old: exists ST. inversion Ht1; subst. split; try split... eapply substitution_preserves_typing... *) (* new: we use [inverts] in place of [inversion] and [splits] to split the conjunction, and [applys*] in place of [eapply...] *) exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. SCase "ST_App1". (* old: eapply IHHt1 in H0... inversion H0 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: The tactic [eapply IHHt1 in H0...] applies [IHHt1] to [H0]. But [H0] is only thing that [IHHt1] could be applied to, so there [eauto] can figure this out on its own. The tactic [forwards] is used to instantiate all the arguments of [IHHt1], producing existential variables and subgoals when needed. *) forwards: IHHt1. eauto. eauto. eauto. (* At this point, we need to decompose the hypothesis [H] that has just been created by [forwards]. This is done by the first part of the preprocessing phase of [jauto]. *) jauto_set_hyps; intros. (* It remains to decompose the goal, which is done by the second part of the preprocessing phase of [jauto]. *) jauto_set_goal; intros. (* All the subgoals produced can then be solved by [eauto]. *) eauto. eauto. eauto. SCase "ST_App2". (* old: eapply IHHt2 in H5... inversion H5 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: this time, we need to call [forwards] on [IHHt2], and we call [jauto] right away, by writing [forwards*], proving the goal in a single tactic! *) forwards*: IHHt2. (* The same trick works for many of the other subgoals. *) forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. Case "T_Ref". SCase "ST_RefValue". (* old: 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. *) (* new: in this proof case, we need to perform an inversion without removing the hypothesis. The tactic [inverts keep] serves exactly this purpose. *) exists (snoc ST T1). inverts keep HST. splits. (* The proof of the first subgoal needs not be changed *) apply extends_snoc. (* For the second subgoal, we use the tactic [applys_eq] to avoid a manual [replace] before [T_loc] can be applied. *) applys_eq T_Loc 1. (* To justify the inequality, there is no need to call [rewrite <- H], because the tactic [omega] is able to exploit [H] on its own. So, only the rewriting of [lenght_snoc] and the call to the tactic [omega] remain. *) rewrite length_snoc. omega. (* The next proof case is hard to polish because it relies on the lemma [nth_eq_snoc] whose statement is not automation-friendly. We'll come back to this proof case further on. *) unfold store_Tlookup. rewrite <- H. rewrite* nth_eq_snoc. (* Last, we replace [apply ..; assumption] with [apply* ..] *) apply* store_well_typed_snoc. forwards*: IHHt. Case "T_Deref". SCase "ST_DerefLoc". (* old: exists ST. split; try split... destruct HST as [_ Hsty]. replace T11 with (store_Tlookup l ST). apply Hsty... inversion Ht; subst... *) (* new: we start by calling [exists ST] and [splits*]. *) exists ST. splits*. (* new: we replace [destruct HST as [_ Hsty]] by the following *) lets [_ Hsty]: HST. (* new: then we use the tactic [applys_eq] to avoid the need to perform a manual [replace] before applying [Hsty]. *) applys_eq* Hsty 1. (* new: we then can call [inverts] in place of [inversion;subst] *) inverts* Ht. forwards*: IHHt. Case "T_Assign". SCase "ST_Assign". (* old: exists ST. split; try split... eapply assign_pres_store_typing... inversion Ht1; subst... *) (* new: simply using nicer tactics *) exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (** Let's come back to the proof case that was hard to optimize. The difficulty comes from the statement of [nth_eq_snoc], which takes the form [nth (length l) (snoc l x) d = x]. This lemma is hard to exploit because its first argument, [length l], mentions a list [l] that has to be exactly the same as the [l] occuring in [snoc l x]. In practice, the first argument is often a natural number [n] that is provably equal to [length l] yet that is not syntactically equal to [length l]. There is a simple fix for making [nth_eq_snoc] easy to apply: introduce the intermediate variable [n] explicitly, so that the goal becomes [nth n (snoc l x) d = x], with a premise asserting [n = length l]. *) Lemma nth_eq_snoc' : forall (A : Type) (l : list A) (x d : A) (n : nat), n = length l -> nth n (snoc l x) d = x. Proof. intros. subst. apply nth_eq_snoc. Qed. (** The proof case for [ref] from the preservation theorem then becomes much easier to prove, because [rewrite nth_eq_snoc'] now succeeds. *) Lemma preservation_ref : forall (st:store) (ST : store_ty) T1, length ST = length st -> TRef T1 = TRef (store_Tlookup (length st) (snoc ST T1)). Proof. intros. dup. (* A first proof, with an explicit [unfold] *) unfold store_Tlookup. rewrite* nth_eq_snoc'. (* A second proof, with a call to [fequal] *) fequal. symmetry. apply* nth_eq_snoc'. Qed. (** The optimized proof of preservation is summarized next. *) Theorem preservation' : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. remember (@empty ty) as Gamma. introv Ht. gen t'. induction Ht; introv HST Hstep; subst Gamma; inverts Hstep; eauto. exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. exists (snoc ST T1). inverts keep HST. splits. apply extends_snoc. applys_eq T_Loc 1. rewrite length_snoc. omega. unfold store_Tlookup. rewrite* nth_eq_snoc'. apply* store_well_typed_snoc. forwards*: IHHt. exists ST. splits*. lets [_ Hsty]: HST. applys_eq* Hsty 1. inverts* Ht. forwards*: IHHt. exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (* ####################################################### *) (** ** Progress for STLCRef *) (** The proof of progress for [STLCRef] can be found in chapter [References]. It contains 53 lines and the optimized proof script is, here again, half the length. *) Theorem progress : forall ST t T st, has_type empty ST t T -> store_well_typed ST st -> (value t \/ exists t', exists st', t / st ==> t' / st'). Proof. introv Ht HST. remember (@empty ty) as Gamma. induction Ht; subst Gamma; tryfalse; try solve [left*]. right. destruct* IHHt1 as [K|]. inverts K; inverts Ht1. destruct* IHHt2. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* IHHt2 as [M|]. inverts M; try solve [inverts Ht2]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* n. right. destruct* IHHt. right. destruct* IHHt as [K|]. inverts K; inverts Ht as M. inverts HST as N. rewrite* N in M. right. destruct* IHHt1 as [K|]. destruct* IHHt2. inverts K; inverts Ht1 as M. inverts HST as N. rewrite* N in M. Qed. End PreservationProgressReferences. (* ####################################################### *) (** ** Subtyping *) Module SubtypingInversion. Require Import Sub. (** Consider the inversion lemma for typing judgment of abstractions in a type system with subtyping. *) Lemma abs_arrow : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof with eauto. intros x S1 s2 T1 T2 Hty. apply typing_inversion_abs in Hty. destruct Hty as [S2 [Hsub Hty]]. apply sub_inversion_arrow in Hsub. destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]]. inversion Heq; subst... Qed. (** Exercise: optimize the proof script, using [introv], [lets] and [inverts*]. In particular, you will find it useful to replace the pattern [apply K in H. destruct H as I] with [lets I: K H]. The solution is 4 lines. *) Lemma abs_arrow' : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof. (* FILL IN HERE *) admit. Qed. (** The lemma [substitution_preserves_typing] has already been used to illustrate the working of [lets] and [applys] in chapter [UseTactics]. Optimize further this proof using automation (with the star symbol), and using the tactic [cases_if']. The solution is 33 lines, including the [Case] instructions (21 lines without them). *) 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. (* FILL IN HERE *) admit. Qed. End SubtypingInversion. (* ####################################################### *) (** * Advanced Topics in Proof Search *) (* ####################################################### *) (** ** Stating Lemmas in the Right Way *) (** Due to its depth-first strategy, [eauto] can get exponentially slower as the depth search increases, even when a short proof exists. In general, to make proof search run reasonably fast, one should avoid using a depth search greater than 5 or 6. Moreover, one should try to minimize the number of applicable lemmas, and usually put first the hypotheses whose proof usefully instantiates the existential variables. In fact, the ability for [eauto] to solve certain goals actually depends on the order in which the hypotheses are stated. This point is illustrated through the following example, in which [P] is a predicate on natural numbers. This predicate is such that [P n] holds for any [n] as soon as [P m] holds for at least one [m] different from zero. The goal is to prove that [P 2] implies [P 1]. When the hypothesis about [P] is stated in the form [forall n m, P m -> m <> 0 -> P n], then [eauto] works. However, with [forall n m, m <> 0 -> P m -> P n], the tactic [eauto] fails. *) Lemma order_matters_1 : forall (P : nat->Prop), (forall n m, P m -> m <> 0 -> P n) -> P 2 -> P 1. Proof. eauto. (* Success *) (* The proof: [intros P H K. eapply H. apply K. auto.] *) Qed. Lemma order_matters_2 : forall (P : nat->Prop), (forall n m, m <> 0 -> P m -> P n) -> P 5 -> P 1. Proof. eauto. (* Failure *) (* To understand why, let us replay the previous proof *) intros P H K. eapply H. (* The application of [eapply] has left two subgoals, [?X <> 0] and [P ?X], where [?X] is an existential variable. *) (* Solving the first subgoal is easy for [eauto]: it suffices to instantiate [?X] as the value [1], which is the simplest value that satisfies [?X <> 0]. *) eauto. (* But then the second goal becomes [P 1], which is where we started from. So, [eauto] gets stuck at this point. *) Abort. (** It is very important to understand that the hypothesis [forall n m, P m -> m <> 0 -> P n] is eauto-friendly, whereas [forall n m, m <> 0 -> P m -> P n] really isn't. Guessing a value of [m] for which [P m] holds and then checking that [m <> 0] holds works well because there are few values of [m] for which [P m] holds. So, it is likely that [eauto] comes up with the right one. On the other hand, guessing a value of [m] for which [m <> 0] and then checking that [P m] holds does not work well, because there are many values of [m] that satisfy [m <> 0] but not [P m]. *) (* ####################################################### *) (** ** Unfolding of Definitions During Proof-Search *) (** The use of intermediate definitions is generally encouraged in a formal development as it usually leads to more concise and more readable statements. Yet, definitions can make it a little harder to automate proofs. The problem is that it is not obvious for a proof search mechanism to know when definitions need to be unfolded. Note that a naive strategy that consists in unfolding all definitions before calling proof search does not scale up to large proofs, so we avoid it. This section introduces a few techniques for avoiding to manually unfold definitions before calling proof search. *) (** To illustrate the treatment of definitions, let [P] be an abstract predicate on natural numbers, and let [myFact] be a definition denoting the proposition [P x] holds for any [x] less than or equal to 3. *) Axiom P : nat -> Prop. Definition myFact := forall x, x <= 3 -> P x. (** Proving that [myFact] under the assumption that [P x] holds for any [x] should be trivial. Yet, [auto] fails to prove it unless we unfold the definition of [myFact] explicitly. *) Lemma demo_hint_unfold_goal_1 : (forall x, P x) -> myFact. Proof. auto. (* Proof search doesn't know what to do, *) unfold myFact. auto. (* unless we unfold the definition. *) Qed. (** To automate the unfolding of definitions that appear as proof obligation, one can use the command [Hint Unfold myFact] to tell Coq that it should always try to unfold [myFact] when [myFact] appears in the goal. *) Hint Unfold myFact. (** This time, automation is able to see through the definition of [myFact]. *) Lemma demo_hint_unfold_goal_2 : (forall x, P x) -> myFact. Proof. auto. Qed. (** However, the [Hint Unfold] mechanism only works for unfolding definitions that appear in the goal. In general, proof search does not unfold definitions from the context. For example, assume we want to prove that [P 3] holds under the assumption that [True -> myFact]. *) Lemma demo_hint_unfold_context_1 : (True -> myFact) -> P 3. Proof. intros. auto. (* fails *) unfold myFact in *. auto. (* succeeds *) Qed. (** There is actually one exception to the previous rule: a constant occuring in an hypothesis is automatically unfolded if the hypothesis can be directly applied to the current goal. For example, [auto] can prove [myFact -> P 3], as illustrated below. *) Lemma demo_hint_unfold_context_2 : myFact -> P 3. Proof. auto. Qed. (* ####################################################### *) (** ** Automation for Proving Absurd Goals *) (** In this section, we'll see that lemmas concluding on a negation are generally not useful as hints, and that lemmas whose conclusion is [False] can be useful hints but having too many of them makes proof search inefficient. We'll also see a practical work-around to the efficiency issue. *) (** Consider the following lemma, which asserts that a number less than or equal to 3 is not greater than 3. *) Parameter le_not_gt : forall x, (x <= 3) -> ~ (x > 3). (** Equivalently, one could state that a number greater than three is not less than or equal to 3. *) Parameter gt_not_le : forall x, (x > 3) -> ~ (x <= 3). (** In fact, both statements are equivalent to a third one stating that [x <= 3] and [x > 3] are contradictory, in the sense that they imply [False]. *) Parameter le_gt_false : forall x, (x <= 3) -> (x > 3) -> False. (** The following investigation aim at figuring out which of the three statments is the most convenient with respect to proof automation. The following material is enclosed inside a [Section], so as to restrict the scope of the hints that we are adding. In other words, after the end of the section, the hints added within the section will no longer be active.*) Section DemoAbsurd1. (** Let's try to add the first lemma, [le_not_gt], as hint, and see whether we can prove that the proposition [exists x, x <= 3 /\ x > 3] is absurd. *) Hint Resolve le_not_gt. Lemma demo_auto_absurd_1 : (exists x, x <= 3 /\ x > 3) -> False. Proof. intros. jauto_set. (* decomposes the assumption *) (* debug *) eauto. (* does not see that [le_not_gt] could apply *) eapply le_not_gt. eauto. eauto. Qed. (** The lemma [gt_not_le] is symmetric to [le_not_gt], so it will not be any better. The third lemma, [le_gt_false], is a more useful hint, because it concludes on [False], so proof search will try to apply it when the current goal is [False]. *) Hint Resolve le_gt_false. Lemma demo_auto_absurd_2 : (exists x, x <= 3 /\ x > 3) -> False. Proof. dup. (* detailed version: *) intros. jauto_set. (* debug *) eauto. (* short version: *) jauto. Qed. (** In summary, a lemma of the form [H1 -> H2 -> False] is a much more effective hint than [H1 -> ~ H2], even though the two statments are equivalent up to the definition of the negation symbol [~]. *) (** That said, one should be careful with adding lemmas whose conclusion is [False] as hint. The reason is that whenever reaching the goal [False], the proof search mechanism will potentially try to apply all the hints whose conclusion is [False] before applying the appropriate one. *) End DemoAbsurd1. (** Adding lemmas whose conclusion is [False] as hint can be, locally, a very effective solution. However, this approach does not scale up for global hints. For most practical applications, it is reasonable to give the name of the lemmas to be exploited for deriving a contradiction. The tactic [false H], provided by [LibTactics] serves that purpose: [false H] replaces the goal with [False] and calls [eapply H]. Its behavior is described next. Observe that any of the three statements [le_not_gt], [gt_not_le] or [le_gt_false] can be used. *) Lemma demo_false : forall x, (x <= 3) -> (x > 3) -> 4 = 5. Proof. intros. dup 4. (* A failed proof: *) false. eapply le_gt_false. auto. (* here, [auto] does not prove [?x <= 3] by using [H] but by using the lemma [le_refl : forall x, x <= x]. *) (* The second subgoal becomes [3 > 3], which is not provable. *) skip. (* A correct proof: *) false. eapply le_gt_false. eauto. (* here, [eauto] uses [H], as expected, to prove [?x <= 3] *) eauto. (* so the second subgoal becomes [x > 3] *) (* The same proof using [false]: *) false le_gt_false. eauto. eauto. (* The lemmas [le_not_gt] and [gt_not_le] work as well *) false le_not_gt. eauto. eauto. Qed. (** In the above example, [false le_gt_false; eauto] proves the goal, but [false le_gt_false; auto] does not, because [auto] does not correctly instantiate the existential variable. Note that [false* le_gt_false] would not work either, because the star symbol tries to call [auto] first. So, there are two possibilities for completing the proof: either call [false le_gt_false; eauto], or call [false* (le_gt_false 3)]. *) (* ####################################################### *) (** ** Automation for Transitivity Lemmas *) (** Some lemmas should never be added as hints, because they would very badly slow down proof search. The typical example is that of transitivity results. This section describes the problem and presents a general workaround. Consider a subtyping relation, written [subtype S T], that relates two object [S] and [T] of type [typ]. Assume that this relation has been proved reflexive and transitive. The corresponding lemmas are named [subtype_refl] and [subtype_trans]. *) Parameter typ : Type. Parameter subtype : typ -> typ -> Prop. Parameter subtype_refl : forall T, subtype T T. Parameter subtype_trans : forall S T U, subtype S T -> subtype T U -> subtype S U. (** Adding reflexivity as hint is generally a good idea, so let's add reflexivity of subtyping as hint. *) Hint Resolve subtype_refl. (** Adding transitivity as hint is generally a bad idea. To understand why, let's add it as hint and see what happens. Because we cannot remove hints once we've added them, we are going to open a "Section," so as to restrict the scope of the transitivity hint to that section. *) Section HintsTransitivity. Hint Resolve subtype_trans. (** Now, consider the goal [forall S T, subtype S T], which clearly has no hope of being solved. Let's call [eauto] on this goal. *) Lemma transitivity_bad_hint_1 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 106 applications... *) Abort. (** Note that after closing the section, the hint [subtype_trans] is no longer active. *) End HintsTransitivity. (** In the previous example, the proof search has spent a lot of time trying to apply transitivity and reflexivity in every possible way. Its process can be summarized as follows. The first goal is [subtype S T]. Since reflexivity does not apply, [eauto] invokes transitivity, which produces two subgoals, [subtype S ?X] and [subtype ?X T]. Solving the first subgoal, [subtype S ?X], is straightforward, it suffices to apply reflexivity. This unifies [?X] with [S]. So, the second sugoal, [subtype ?X T], becomes [subtype S T], which is exactly what we started from... The problem with the transitivity lemma is that it is applicable to any goal concluding on a subtyping relation. Because of this, [eauto] keeps trying to apply it even though it most often doesn't help to solve the goal. So, one should never add a transitivity lemma as a hint for proof search. *) (** There is a general workaround for having automation to exploit transitivity lemmas without giving up on efficiency. This workaround relies on a powerful mechanism called "external hint." This mechanism allows to manually describe the condition under which a particular lemma should be tried out during proof search. For the case of transitivity of subtyping, we are going to tell Coq to try and apply the transitivity lemma on a goal of the form [subtype S U] only when the proof context already contains an assumption either of the form [subtype S T] or of the form [subtype T U]. In other words, we only apply the transitivity lemma when there is some evidence that this application might help. To set up this "external hint," one has to write the following. *) Hint Extern 1 (subtype ?S ?U) => match goal with | H: subtype S ?T |- _ => apply (@subtype_trans S T U) | H: subtype ?T U |- _ => apply (@subtype_trans S T U) end. (** This hint declaration can be understood as follows. - "Hint Extern" introduces the hint. - The number "1" corresponds to a priority for proof search. It doesn't matter so much what priority is used in practice. - The pattern [subtype ?S ?U] describes the kind of goal on which the pattern should apply. The question marks are used to indicate that the variables [?S] and [?U] should be bound to some value in the rest of the hint description. - The construction [match goal with ... end] tries to recognize patterns in the goal, or in the proof context, or both. - The first pattern is [H: subtype S ?T |- _]. It indices that the context should contain an hypothesis [H] of type [subtype S ?T], where [S] has to be the same as in the goal, and where [?T] can have any value. - The symbol [|- _] at the end of [H: subtype S ?T |- _] indicates that we do not impose further condition on how the proof obligation has to look like. - The branch [=> apply (@subtype_trans S T U)] that follows indicates that if the goal has the form [subtype S U] and if there exists an hypothesis of the form [subtype S T], then we should try and apply transitivity lemma instantiated on the arguments [S], [T] and [U]. (Note: the symbol [@] in front of [subtype_trans] is only actually needed when the "Implicit Arguments" feature is activated.) - The other branch, which corresponds to an hypothesis of the form [H: subtype ?T U] is symmetrical. Note: the same external hint can be reused for any other transitive relation, simply by renaming [subtype] into the name of that relation. *) (** Let us see an example illustrating how the hint works. *) Lemma transitivity_workaround_1 : forall T1 T2 T3 T4, subtype T1 T2 -> subtype T2 T3 -> subtype T3 T4 -> subtype T1 T4. Proof. intros. (* debug *) eauto. (* The trace shows the external hint being used *) Qed. (** We may also check that the new external hint does not suffer from the complexity blow up. *) Lemma transitivity_workaround_2 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 0 applications *) Abort. (* ####################################################### *) (** * Decision Procedures *) (** A decision procedure is able to solve proof obligations whose statement admits a particular form. This section describes three useful decision procedures. The tactic [omega] handles goals involving arithmetic and inequalities, but not general multiplications. The tactic [ring] handles goals involving arithmetic, including multiplications, but does not support inequalities. The tactic [congruence] is able to prove equalities and inequalities by exploiting equalities available in the proof context. *) (* ####################################################### *) (** ** Omega *) (** The tactic [omega] supports natural numbers (type [nat]) as well as integers (type [Z], available by including the module [ZArith]). It supports addition, substraction, equalities and inequalities. Before using [omega], one needs to import the module [Omega], as follows. *) Require Import Omega. (** Here is an example. Let [x] and [y] be two natural numbers (they cannot be negative). Assume [y] is less than 4, assume [x+x+1] is less than [y], and assume [x] is not zero. Then, it must be the case that [x] is equal to one. *) Lemma omega_demo_1 : forall (x y : nat), (y <= 4) -> (x + x + 1 <= y) -> (x <> 0) -> (x = 1). Proof. intros. omega. Qed. (** Another example: if [z] is the mean of [x] and [y], and if the difference between [x] and [y] is at most [4], then the difference between [x] and [z] is at most 2. *) Lemma omega_demo_2 : forall (x y z : nat), (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2). Proof. intros. omega. Qed. (** One can proof [False] using [omega] if the mathematical facts from the context are contradictory. In the following example, the constraints on the values [x] and [y] cannot be all satisfied in the same time. *) Lemma omega_demo_3 : forall (x y : nat), (x + 5 <= y) -> (y - x < 3) -> False. Proof. intros. omega. Qed. (** Note: [omega] can prove a goal by contradiction only if its conclusion is reduced [False]. The tactic [omega] always fails when the conclusion is an arbitrary proposition [P], even though [False] implies any proposition [P] (by [ex_falso_quodlibet]). *) Lemma omega_demo_4 : forall (x y : nat) (P : Prop), (x + 5 <= y) -> (y - x < 3) -> P. Proof. intros. (* Calling [omega] at this point fails with the message: "Omega: Can't solve a goal with proposition variables" *) (* So, one needs to replace the goal by [False] first. *) false. omega. Qed. (* ####################################################### *) (** ** Ring *) (** Compared with [omega], the tactic [ring] adds support for multiplications, however it gives up the ability to reason on inequations. Moreover, it supports only integers (type [Z]) and not natural numbers (type [nat]). Here is an example showing how to use [ring]. *) Module RingDemo. Require Import ZArith. Open Scope Z_scope. (* Arithmetic symbols are now interpreted in [Z] *) Lemma ring_demo : forall (x y z : Z), x * (y + z) - z * 3 * x = x * y - 2 * x * z. Proof. intros. ring. Qed. End RingDemo. (* ####################################################### *) (** ** Congruence *) (** The tactic [congruence] is able to exploit equalities from the proof context in order to automatically perform the rewriting operations necessary to establish a goal. It is slightly more powerful than the tactic [subst], which can only handle equalities of the form [x = e] where [x] is a variable and [e] an expression. *) Lemma congruence_demo_1 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), f (g x) (g y) = z -> 2 = g x -> g y = h z -> f 2 (h z) = z. Proof. intros. congruence. Qed. (** Moreover, [congruence] is able to exploit universally quantified equalities, for example [forall a, g a = h a]. *) Lemma congruence_demo_2 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), (forall a, g a = h a) -> f (g x) (g y) = z -> g x = 2 -> f 2 (h y) = z. Proof. congruence. Qed. (** Next is an example where [congruence] is very useful. *) Lemma congruence_demo_4 : forall (f g : nat->nat), (forall a, f a = g a) -> f (g (g 2)) = g (f (f 2)). Proof. congruence. Qed. (** The tactic [congruence] is able to prove a contradiction if the goal entails an equality that contradicts an inequality available in the proof context. *) Lemma congruence_demo_3 : forall (f g h : nat->nat) (x : nat), (forall a, f a = h a) -> g x = f x -> g x <> h x -> False. Proof. congruence. Qed. (** One of the strengths of [congruence] is that it is a very fast tactic. So, one should not hesitate to invoke it wherever it might help. *) (* ####################################################### *) (** * Summary *) (** Let us summarize the main automation tactics available. - [auto] automatically applies [reflexivity], [assumption], and [apply]. - [eauto] moreover tries [eapply], and in particular can instantiate existentials in the conclusion. - [iauto] extends [eauto] with support for negation, conjunctions, and disjunctions. However, its support for disjunction can make it exponentially slow. - [jauto] extends [eauto] with support for negation, conjunctions, and existential at the head of hypothesis. - [congruence] helps reasoning about equalities and inequalities. - [omega] proves arithmetic goals with equalities and inequalities, but it does not support multiplication. - [ring] proves arithmetic goals with multiplications, but does not support inequalities. In order to set up automation appropriately, keep in mind the following rule of thumbs: - automation is all about balance: not enough automation makes proofs not very robust on change, whereas too much automation makes proofs very hard to fix when they break. - if a lemma is not goal directed (i.e., some of its variables do not occur in its conclusion), then the premises need to be ordered in such a way that proving the first premises maximizes the chances of correctly instantiating the variables that do not occur in the conclusion. - a lemma whose conclusion is [False] should only be added as a local hint, i.e., as a hint within the current section. - a transitivity lemma should never be considered as hint; if automation of transitivity reasoning is really necessary, an [Extern Hint] needs to be set up. - a definition usually needs to be accompanied with a [Hint Unfold]. Becoming a master in the black art of automation certainly requires some investment, however this investment will pay off very quickly. *) (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * UseAuto: Theory and Practice of Automation in Coq Proofs *) (* Chapter maintained by Arthur Chargueraud *) (** In a machine-checked proof, every single detail has to be justified. This can result in huge proof scripts. Fortunately, Coq comes with a proof-search mechanism and with several decision procedures that enable the system to automatically synthesize simple pieces of proof. Automation is very powerful when set up appropriately. The purpose of this chapter is to explain the basics of working of automation. The chapter is organized in two parts. The first part focuses on a general mechanism called "proof search." In short, proof search consists in naively trying to apply lemmas and assumptions in all possible ways. The second part describes "decision procedures", which are tactics that are very good at solving proof obligations that fall in some particular fragment of the logic of Coq. Many of the examples used in this chapter consist of small lemmas that have been made up to illustrate particular aspects of automation. These examples are completely independent from the rest of the Software Foundations course. This chapter also contains some bigger examples which are used to explain how to use automation in realistic proofs. These examples are taken from other chapters of the course (mostly from STLC), and the proofs that we present make use of the tactics from the library [LibTactics.v], which is presented in the chapter [UseTactics]. *) Require Import LibTactics. (* ####################################################### *) (** * Basic Features of Proof Search *) (** The idea of proof search is to replace a sequence of tactics applying lemmas and assumptions with a call to a single tactic, for example [auto]. This form of proof automation saves a lot of effort. It typically leads to much shorter proof scripts, and to scripts that are typically more robust to change. If one makes a little change to a definition, a proof that exploits automation probably won't need to be modified at all. Of course, using too much automation is a bad idea. When a proof script no longer records the main arguments of a proof, it becomes difficult to fix it when it gets broken after a change in a definition. Overall, a reasonable use of automation is generally a big win, as it saves a lot of time both in building proof scripts and in subsequently maintaining those proof scripts. *) (* ####################################################### *) (** ** Strength of Proof Search *) (** We are going to study four proof-search tactics: [auto], [eauto], [iauto] and [jauto]. The tactics [auto] and [eauto] are builtin in Coq. The tactic [iauto] is a shorthand for the builtin tactic [try solve [intuition eauto]]. The tactic [jauto] is defined in the library [LibTactics], and simply performs some preprocessing of the goal before calling [eauto]. The goal of this chapter is to explain the general principles of proof search and to give rule of thumbs for guessing which of the four tactics mentioned above is best suited for solving a given goal. Proof search is a compromise between efficiency and expressiveness, that is, a tradeoff between how complex goals the tactic can solve and how much time the tactic requires for terminating. The tactic [auto] builds proofs only by using the basic tactics [reflexivity], [assumption], and [apply]. The tactic [eauto] can also exploit [eapply]. The tactic [jauto] extends [eauto] by being able to open conjunctions and existentials that occur in the context. The tactic [iauto] is able to deal with conjunctions, disjunctions, and negation in a quite clever way; however it is not able to open existentials from the context. Also, [iauto] usually becomes very slow when the goal involves several disjunctions. Note that proof search tactics never perform any rewriting step (tactics [rewrite], [subst]), nor any case analysis on an arbitrary data structure or predicate (tactics [destruct] and [inversion]), nor any proof by induction (tactic [induction]). So, proof search is really intended to automate the final steps from the various branches of a proof. It is not able to discover the overall structure of a proof. *) (* ####################################################### *) (** ** Basics *) (** The tactic [auto] is able to solve a goal that can be proved using a sequence of [intros], [apply], [assumption], and [reflexivity]. Two examples follow. The first one shows the ability for [auto] to call [reflexivity] at any time. In fact, calling [reflexivity] is always the first thing that [auto] tries to do. *) Lemma solving_by_reflexivity : 2 + 3 = 5. Proof. auto. Qed. (** The second example illustrates a proof where a sequence of two calls to [apply] are needed. The goal is to prove that if [Q n] implies [P n] for any [n] and if [Q n] holds for any [n], then [P 2] holds. *) Lemma solving_by_apply : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. auto. Qed. (** We can ask [auto] to tell us what proof it came up with, by invoking [info_auto] in place of [auto]. *) Lemma solving_by_apply' : forall (P Q : nat->Prop), (forall n, Q n -> P n) -> (forall n, Q n) -> P 2. Proof. info_auto. Qed. (* The output is: [intro P; intro Q; intro H;] *) (* followed with [intro H0; simple apply H; simple apply H0]. *) (* i.e., the sequence [intros P Q H H0; apply H; apply H0]. *) (** The tactic [auto] can invoke [apply] but not [eapply]. So, [auto] cannot exploit lemmas whose instantiation cannot be directly deduced from the proof goal. To exploit such lemmas, one needs to invoke the tactic [eauto], which is able to call [eapply]. In the following example, the first hypothesis asserts that [P n] is true when [Q m] is true for some [m], and the goal is to prove that [Q 1] implies [P 2]. This implication follows direction from the hypothesis by instantiating [m] as the value [1]. The following proof script shows that [eauto] successfully solves the goal, whereas [auto] is not able to do so. *) Lemma solving_by_eapply : forall (P Q : nat->Prop), (forall n m, Q m -> P n) -> Q 1 -> P 2. Proof. auto. eauto. Qed. (** Remark: Again, we can use [info_eauto] to see what proof [eauto] comes up with. *) (* ####################################################### *) (** ** Conjunctions *) (** So far, we've seen that [eauto] is stronger than [auto] in the sense that it can deal with [eapply]. In the same way, we are going to see how [jauto] and [iauto] are stronger than [auto] and [eauto] in the sense that they provide better support for conjunctions. *) (** The tactics [auto] and [eauto] can prove a goal of the form [F /\ F'], where [F] and [F'] are two propositions, as soon as both [F] and [F'] can be proved in the current context. An example follows. *) Lemma solving_conj_goal : forall (P : nat->Prop) (F : Prop), (forall n, P n) -> F -> F /\ P 2. Proof. auto. Qed. (** However, when an assumption is a conjunction, [auto] and [eauto] are not able to exploit this conjunction. It can be quite surprising at first that [eauto] can prove very complex goals but that it fails to prove that [F /\ F'] implies [F]. The tactics [iauto] and [jauto] are able to decompose conjunctions from the context. Here is an example. *) Lemma solving_conj_hyp : forall (F F' : Prop), F /\ F' -> F. Proof. auto. eauto. jauto. (* or [iauto] *) Qed. (** The tactic [jauto] is implemented by first calling a pre-processing tactic called [jauto_set], and then calling [eauto]. So, to understand how [jauto] works, one can directly call the tactic [jauto_set]. *) Lemma solving_conj_hyp' : forall (F F' : Prop), F /\ F' -> F. Proof. intros. jauto_set. eauto. Qed. (** Next is a more involved goal that can be solved by [iauto] and [jauto]. *) Lemma solving_conj_more : forall (P Q R : nat->Prop) (F : Prop), (F /\ (forall n m, (Q m /\ R n) -> P n)) -> (F -> R 2) -> Q 1 -> P 2 /\ F. Proof. jauto. (* or [iauto] *) Qed. (** The strategy of [iauto] and [jauto] is to run a global analysis of the top-level conjunctions, and then call [eauto]. For this reason, those tactics are not good at dealing with conjunctions that occur as the conclusion of some universally quantified hypothesis. The following example illustrates a general weakness of Coq proof search mechanisms. *) Lemma solving_conj_hyp_forall : forall (P Q : nat->Prop), (forall n, P n /\ Q n) -> P 2. Proof. auto. eauto. iauto. jauto. (* Nothing works, so we have to do some of the work by hand *) intros. destruct (H 2). auto. Qed. (** This situation is slightly disappointing, since automation is able to prove the following goal, which is very similar. The only difference is that the universal quantification has been distributed over the conjunction. *) Lemma solved_by_jauto : forall (P Q : nat->Prop) (F : Prop), (forall n, P n) /\ (forall n, Q n) -> P 2. Proof. jauto. (* or [iauto] *) Qed. (* ####################################################### *) (** ** Disjunctions *) (** The tactics [auto] and [eauto] can handle disjunctions that occur in the goal. *) Lemma solving_disj_goal : forall (F F' : Prop), F -> F \/ F'. Proof. auto. Qed. (** However, only [iauto] is able to automate reasoning on the disjunctions that appear in the context. For example, [iauto] can prove that [F \/ F'] entails [F' \/ F]. *) Lemma solving_disj_hyp : forall (F F' : Prop), F \/ F' -> F' \/ F. Proof. auto. eauto. jauto. iauto. Qed. (** More generally, [iauto] can deal with complex combinations of conjunctions, disjunctions, and negations. Here is an example. *) Lemma solving_tauto : forall (F1 F2 F3 : Prop), ((~F1 /\ F3) \/ (F2 /\ ~F3)) -> (F2 -> F1) -> (F2 -> F3) -> ~F2. Proof. iauto. Qed. (** However, the ability of [iauto] to automatically perform a case analysis on disjunctions comes with a downside: [iauto] may be very slow. If the context involves several hypotheses with disjunctions, [iauto] typically generates an exponential number of subgoals on which [eauto] is called. One major advantage of [jauto] compared with [iauto] is that it never spends time performing this kind of case analyses. *) (* ####################################################### *) (** ** Existentials *) (** The tactics [eauto], [iauto], and [jauto] can prove goals whose conclusion is an existential. For example, if the goal is [exists x, f x], the tactic [eauto] introduces an existential variable, say [?25], in place of [x]. The remaining goal is [f ?25], and [eauto] tries to solve this goal, allowing itself to instantiate [?25] with any appropriate value. For example, if an assumption [f 2] is available, then the variable [?25] gets instantiated with [2] and the goal is solved, as shown below. *) Lemma solving_exists_goal : forall (f : nat->Prop), f 2 -> exists x, f x. Proof. auto. (* observe that [auto] does not deal with existentials, *) eauto. (* whereas [eauto], [iauto] and [jauto] solve the goal *) Qed. (** A major strength of [jauto] over the other proof search tactics is that it is able to exploit the existentially-quantified hypotheses, i.e., those of the form [exists x, P]. *) Lemma solving_exists_hyp : forall (f g : nat->Prop), (forall x, f x -> g x) -> (exists a, f a) -> (exists a, g a). Proof. auto. eauto. iauto. (* All of these tactics fail, *) jauto. (* whereas [jauto] succeeds. *) (* For the details, run [intros. jauto_set. eauto] *) Qed. (* ####################################################### *) (** ** Negation *) (** The tactics [auto] and [eauto] suffer from some limitations with respect to the manipulation of negations, mostly related to the fact that negation, written [~ P], is defined as [P -> False] but that the unfolding of this definition is not performed automatically. Consider the following example. *) Lemma negation_study_1 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. intros P H0 HX. eauto. (* It fails to see that [HX] applies *) unfold not in *. eauto. Qed. (** For this reason, the tactics [iauto] and [jauto] systematically invoke [unfold not in *] as part of their pre-processing. So, they are able to solve the previous goal right away. *) Lemma negation_study_2 : forall (P : nat->Prop), P 0 -> (forall x, ~ P x) -> False. Proof. jauto. (* or [iauto] *) Qed. (** We will come back later on to the behavior of proof search with respect to the unfolding of definitions. *) (* ####################################################### *) (** ** Equalities *) (** Coq's proof-search feature is not good at exploiting equalities. It can do very basic operations, like exploiting reflexivity and symmetry, but that's about it. Here is a simple example that [auto] can solve, by first calling [symmetry] and then applying the hypothesis. *) Lemma equality_by_auto : forall (f g : nat->Prop), (forall x, f x = g x) -> g 2 = f 2. Proof. auto. Qed. (** To automate more advanced reasoning on equalities, one should rather try to use the tactic [congruence], which is presented at the end of this chapter in the "Decision Procedures" section. *) (* ####################################################### *) (** * How Proof Search Works *) (* ####################################################### *) (** ** Search Depth *) (** The tactic [auto] works as follows. It first tries to call [reflexivity] and [assumption]. If one of these calls solves the goal, the job is done. Otherwise [auto] tries to apply the most recently introduced assumption that can be applied to the goal without producing and error. This application produces subgoals. There are two possible cases. If the sugboals produced can be solved by a recursive call to [auto], then the job is done. Otherwise, if this application produces at least one subgoal that [auto] cannot solve, then [auto] starts over by trying to apply the second most recently introduced assumption. It continues in a similar fashion until it finds a proof or until no assumption remains to be tried. It is very important to have a clear idea of the backtracking process involved in the execution of the [auto] tactic; otherwise its behavior can be quite puzzling. For example, [auto] is not able to solve the following triviality. *) Lemma search_depth_0 : True /\ True /\ True /\ True /\ True /\ True. Proof. auto. Abort. (** The reason [auto] fails to solve the goal is because there are too many conjunctions. If there had been only five of them, [auto] would have successfully solved the proof, but six is too many. The tactic [auto] limits the number of lemmas and hypotheses that can be applied in a proof, so as to ensure that the proof search eventually terminates. By default, the maximal number of steps is five. One can specify a different bound, writing for example [auto 6] to search for a proof involving at most six steps. For example, [auto 6] would solve the previous lemma. (Similarly, one can invoke [eauto 6] or [intuition eauto 6].) The argument [n] of [auto n] is called the "search depth." The tactic [auto] is simply defined as a shorthand for [auto 5]. The behavior of [auto n] can be summarized as follows. It first tries to solve the goal using [reflexivity] and [assumption]. If this fails, it tries to apply a hypothesis (or a lemma that has been registered in the hint database), and this application produces a number of sugoals. The tactic [auto (n-1)] is then called on each of those subgoals. If all the subgoals are solved, the job is completed, otherwise [auto n] tries to apply a different hypothesis. During the process, [auto n] calls [auto (n-1)], which in turn might call [auto (n-2)], and so on. The tactic [auto 0] only tries [reflexivity] and [assumption], and does not try to apply any lemma. Overall, this means that when the maximal number of steps allowed has been exceeded, the [auto] tactic stops searching and backtracks to try and investigate other paths. *) (** The following lemma admits a unique proof that involves exactly three steps. So, [auto n] proves this goal iff [n] is greater than three. *) Lemma search_depth_1 : forall (P : nat->Prop), P 0 -> (P 0 -> P 1) -> (P 1 -> P 2) -> (P 2). Proof. auto 0. (* does not find the proof *) auto 1. (* does not find the proof *) auto 2. (* does not find the proof *) auto 3. (* finds the proof *) (* more generally, [auto n] solves the goal if [n >= 3] *) Qed. (** We can generalize the example by introducing an assumption asserting that [P k] is derivable from [P (k-1)] for all [k], and keep the assumption [P 0]. The tactic [auto], which is the same as [auto 5], is able to derive [P k] for all values of [k] less than 5. For example, it can prove [P 4]. *) Lemma search_depth_3 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4). Proof. auto. Qed. (** However, to prove [P 5], one needs to call at least [auto 6]. *) Lemma search_depth_4 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 5). Proof. auto. auto 6. Qed. (** Because [auto] looks for proofs at a limited depth, there are cases where [auto] can prove a goal [F] and can prove a goal [F'] but cannot prove [F /\ F']. In the following example, [auto] can prove [P 4] but it is not able to prove [P 4 /\ P 4], because the splitting of the conjunction consumes one proof step. To prove the conjunction, one needs to increase the search depth, using at least [auto 6]. *) Lemma search_depth_5 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 4 /\ P 4). Proof. auto. auto 6. Qed. (* ####################################################### *) (** ** Backtracking *) (** In the previous section, we have considered proofs where at each step there was a unique assumption that [auto] could apply. In general, [auto] can have several choices at every step. The strategy of [auto] consists of trying all of the possibilities (using a depth-first search exploration). To illustrate how automation works, we are going to extend the previous example with an additional assumption asserting that [P k] is also derivable from [P (k+1)]. Adding this hypothesis offers a new possibility that [auto] could consider at every step. There exists a special command that one can use for tracing all the steps that proof-search considers. To view such a trace, one should write [debug eauto]. (For some reason, the command [debug auto] does not exist, so we have to use the command [debug eauto] instead.) *) Lemma working_of_auto_1 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Goal: *) (P 2). (* Uncomment "debug" in the following line to see the debug trace: *) Proof. intros P H1 H2 H3. (* debug *) eauto. Qed. (** The output message produced by [debug eauto] is as follows. << depth=5 depth=4 apply H3 depth=3 apply H3 depth=3 exact H1 >> The depth indicates the value of [n] with which [eauto n] is called. The tactics shown in the message indicate that the first thing that [eauto] has tried to do is to apply [H3]. The effect of applying [H3] is to replace the goal [P 2] with the goal [P 1]. Then, again, [H3] has been applied, changing the goal [P 1] into [P 0]. At that point, the goal was exactly the hypothesis [H1]. It seems that [eauto] was quite lucky there, as it never even tried to use the hypothesis [H2] at any time. The reason is that [auto] always tries to use the most recently introduced hypothesis first, and [H3] is a more recent hypothesis than [H2] in the goal. So, let's permute the hypotheses [H2] and [H3] and see what happens. *) Lemma working_of_auto_2 : forall (P : nat->Prop), (* Hypothesis H1: *) (P 0) -> (* Hypothesis H3: *) (forall k, P (k-1) -> P k) -> (* Hypothesis H2: *) (forall k, P (k+1) -> P k) -> (* Goal: *) (P 2). Proof. intros P H1 H3 H2. (* debug *) eauto. Qed. (** This time, the output message suggests that the proof search investigates many possibilities. Replacing [debug eauto] with [info_eauto], we observe that the proof that [eauto] comes up with is actually not the simplest one. [apply H2; apply H3; apply H3; apply H3; exact H1] This proof goes through the proof obligation [P 3], even though it is not any useful. The following tree drawing describes all the goals that automation has been through. << |5||4||3||2||1||0| -- below, tabulation indicates the depth [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 6] -> [P 7] -> [P 5] -> [P 4] -> [P 5] -> [P 3] --> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 2] -> [P 3] -> [P 4] -> [P 5] -> [P 3] -> [P 2] -> [P 3] -> [P 1] -> [P 1] -> [P 2] -> [P 3] -> [P 1] -> [P 0] -> !! Done !! >> The first few lines read as follows. To prove [P 2], [eauto 5] has first tried to apply [H2], producing the subgoal [P 3]. To solve it, [eauto 4] has tried again to apply [H2], producing the goal [P 4]. Similarly, the search goes through [P 5], [P 6] and [P 7]. When reaching [P 7], the tactic [eauto 0] is called but as it is not allowed to try and apply any lemma, it fails. So, we come back to the goal [P 6], and try this time to apply hypothesis [H3], producing the subgoal [P 5]. Here again, [eauto 0] fails to solve this goal. The process goes on and on, until backtracking to [P 3] and trying to apply [H2] three times in a row, going through [P 2] and [P 1] and [P 0]. This search tree explains why [eauto] came up with a proof starting with [apply H2]. *) (* ####################################################### *) (** ** Adding Hints *) (** By default, [auto] (and [eauto]) only tries to apply the hypotheses that appear in the proof context. There are two possibilities for telling [auto] to exploit a lemma that have been proved previously: either adding the lemma as an assumption just before calling [auto], or adding the lemma as a hint, so that it can be used by every calls to [auto]. The first possibility is useful to have [auto] exploit a lemma that only serves at this particular point. To add the lemma as hypothesis, one can type [generalize mylemma; intros], or simply [lets: mylemma] (the latter requires [LibTactics.v]). The second possibility is useful for lemmas that need to be exploited several times. The syntax for adding a lemma as a hint is [Hint Resolve mylemma]. For example, the lemma asserting than any number is less than or equal to itself, [forall x, x <= x], called [Le.le_refl] in the Coq standard library, can be added as a hint as follows. *) Hint Resolve Le.le_refl. (** A convenient shorthand for adding all the constructors of an inductive datatype as hints is the command [Hint Constructors mydatatype]. Warning: some lemmas, such as transitivity results, should not be added as hints as they would very badly affect the performance of proof search. The description of this problem and the presentation of a general work-around for transitivity lemmas appear further on. *) (* ####################################################### *) (** ** Integration of Automation in Tactics *) (** The library "LibTactics" introduces a convenient feature for invoking automation after calling a tactic. In short, it suffices to add the symbol star ([*]) to the name of a tactic. For example, [apply* H] is equivalent to [apply H; auto_star], where [auto_star] is a tactic that can be defined as needed. The definition of [auto_star], which determines the meaning of the star symbol, can be modified whenever needed. Simply write: Ltac auto_star ::= a_new_definition. ]] Observe the use of [::=] instead of [:=], which indicates that the tactic is being rebound to a new definition. So, the default definition is as follows. *) Ltac auto_star ::= try solve [ jauto ]. (** Nearly all standard Coq tactics and all the tactics from "LibTactics" can be called with a star symbol. For example, one can invoke [subst*], [destruct* H], [inverts* H], [lets* I: H x], [specializes* H x], and so on... There are two notable exceptions. The tactic [auto*] is just another name for the tactic [auto_star]. And the tactic [apply* H] calls [eapply H] (or the more powerful [applys H] if needed), and then calls [auto_star]. Note that there is no [eapply* H] tactic, use [apply* H] instead. *) (** In large developments, it can be convenient to use two degrees of automation. Typically, one would use a fast tactic, like [auto], and a slower but more powerful tactic, like [jauto]. To allow for a smooth coexistence of the two form of automation, [LibTactics.v] also defines a "tilde" version of tactics, like [apply~ H], [destruct~ H], [subst~], [auto~] and so on. The meaning of the tilde symbol is described by the [auto_tilde] tactic, whose default implementation is [auto]. *) Ltac auto_tilde ::= auto. (** In the examples that follow, only [auto_star] is needed. *) (** An alternative, possibly more efficient version of auto_star is the following": Ltac auto_star ::= try solve [ eassumption | auto | jauto ]. With the above definition, [auto_star] first tries to solve the goal using the assumptions; if it fails, it tries using [auto], and if this still fails, then it calls [jauto]. Even though [jauto] is strictly stronger than [eassumption] and [auto], it makes sense to call these tactics first, because, when the succeed, they save a lot of time, and when they fail to prove the goal, they fail very quickly.". *) (* ####################################################### *) (** * Examples of Use of Automation *) (** Let's see how to use proof search in practice on the main theorems of the "Software Foundations" course, proving in particular results such as determinism, preservation and progress. *) (* ####################################################### *) (** ** Determinism *) Module DeterministicImp. Require Import Imp. (** Recall the original proof of the determinism lemma for the IMP language, shown below. *) Theorem ceval_deterministic: forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. intros c st st1 st2 E1 E2. generalize dependent st2. (ceval_cases (induction E1) Case); intros st2 E2; inversion E2; subst. Case "E_Skip". reflexivity. Case "E_Ass". reflexivity. Case "E_Seq". assert (st' = st'0) as EQ1. SCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Case "E_IfTrue". SCase "b1 evaluates to true". apply IHE1. assumption. SCase "b1 evaluates to false (contradiction)". rewrite H in H5. inversion H5. Case "E_IfFalse". SCase "b1 evaluates to true (contradiction)". rewrite H in H5. inversion H5. SCase "b1 evaluates to false". apply IHE1. assumption. Case "E_WhileEnd". SCase "b1 evaluates to true". reflexivity. SCase "b1 evaluates to false (contradiction)". rewrite H in H2. inversion H2. Case "E_WhileLoop". SCase "b1 evaluates to true (contradiction)". rewrite H in H4. inversion H4. SCase "b1 evaluates to false". assert (st' = st'0) as EQ1. SSCase "Proof of assertion". apply IHE1_1; assumption. subst st'0. apply IHE1_2. assumption. Qed. (** Exercise: rewrite this proof using [auto] whenever possible. (The solution uses [auto] 9 times.) *) Theorem ceval_deterministic': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* FILL IN HERE *) admit. Qed. (** In fact, using automation is not just a matter of calling [auto] in place of one or two other tactics. Using automation is about rethinking the organization of sequences of tactics so as to minimize the effort involved in writing and maintaining the proof. This process is eased by the use of the tactics from [LibTactics.v]. So, before trying to optimize the way automation is used, let's first rewrite the proof of determinism: - use [introv H] instead of [intros x H], - use [gen x] instead of [generalize dependent x], - use [inverts H] instead of [inversion H; subst], - use [tryfalse] to handle contradictions, and get rid of the cases where [beval st b1 = true] and [beval st b1 = false] both appear in the context, - stop using [ceval_cases] to label subcases. *) Theorem ceval_deterministic'': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. assert (st' = st'0). auto. subst. auto. auto. auto. auto. assert (st' = st'0). auto. subst. auto. Qed. (** To obtain a nice clean proof script, we have to remove the calls [assert (st' = st'0)]. Such a tactic invokation is not nice because it refers to some variables whose name has been automatically generated. This kind of tactics tend to be very brittle. The tactic [assert (st' = st'0)] is used to assert the conclusion that we want to derive from the induction hypothesis. So, rather than stating this conclusion explicitly, we are going to ask Coq to instantiate the induction hypothesis, using automation to figure out how to instantiate it. The tactic [forwards], described in [LibTactics.v] precisely helps with instantiating a fact. So, let's see how it works out on our example. *) Theorem ceval_deterministic''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. (* Let's replay the proof up to the [assert] tactic. *) introv E1 E2. gen st2. induction E1; intros; inverts E2; tryfalse. auto. auto. (* We duplicate the goal for comparing different proofs. *) dup 4. (* The old proof: *) assert (st' = st'0). apply IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, without automation: *) forwards: IHE1_1. apply H1. (* produces [H: st' = st'0]. *) skip. (* The new proof, with automation: *) forwards: IHE1_1. eauto. (* produces [H: st' = st'0]. *) skip. (* The new proof, with integrated automation: *) forwards*: IHE1_1. (* produces [H: st' = st'0]. *) skip. Abort. (** To polish the proof script, it remains to factorize the calls to [auto], using the star symbol. The proof of determinism can then be rewritten in only four lines, including no more than 10 tactics. *) Theorem ceval_deterministic'''': forall c st st1 st2, c / st || st1 -> c / st || st2 -> st1 = st2. Proof. introv E1 E2. gen st2. induction E1; intros; inverts* E2; tryfalse. forwards*: IHE1_1. subst*. forwards*: IHE1_1. subst*. Qed. End DeterministicImp. (* ####################################################### *) (** ** Preservation for STLC *) Module PreservationProgressStlc. Require Import StlcProp. Import STLC. Import STLCProp. (** Consider the proof of perservation of STLC, shown below. This proof already uses [eauto] through the triple-dot mechanism. *) Theorem preservation : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof with eauto. remember (@empty ty) as Gamma. intros t t' T HT. generalize dependent t'. (has_type_cases (induction HT) Case); intros t' HE; subst Gamma. Case "T_Var". inversion HE. Case "T_Abs". inversion HE. Case "T_App". inversion HE; subst... (* (step_cases (inversion HE) SCase); subst...*) (* The ST_App1 and ST_App2 cases are immediate by induction, and auto takes care of them *) SCase "ST_AppAbs". apply substitution_preserves_typing with T11... inversion HT1... Case "T_True". inversion HE. Case "T_False". inversion HE. Case "T_If". inversion HE; subst... Qed. (** Exercise: rewrite this proof using tactics from [LibTactics] and calling automation using the star symbol rather than the triple-dot notation. More precisely, make use of the tactics [inverts*] and [applys*] to call [auto*] after a call to [inverts] or to [applys]. The solution is three lines long.*) Theorem preservation' : forall t t' T, has_type empty t T -> t ==> t' -> has_type empty t' T. Proof. (* FILL IN HERE *) admit. Qed. (* ####################################################### *) (** ** Progress for STLC *) (** Consider the proof of the progress theorem. *) Theorem progress : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof with eauto. intros t T Ht. remember (@empty ty) as Gamma. (has_type_cases (induction Ht) Case); subst Gamma... Case "T_Var". inversion H. Case "T_App". right. destruct IHHt1... SCase "t1 is a value". destruct IHHt2... SSCase "t2 is a value". inversion H; subst; try solve by inversion. exists ([x0:=t2]t)... SSCase "t2 steps". destruct H0 as [t2' Hstp]. exists (tapp t1 t2')... SCase "t1 steps". destruct H as [t1' Hstp]. exists (tapp t1' t2)... Case "T_If". right. destruct IHHt1... destruct t1; try solve by inversion... inversion H. exists (tif x0 t2 t3)... Qed. (** Exercise: optimize the above proof. Hint: make use of [destruct*] and [inverts*]. The solution consists of 10 short lines. *) Theorem progress' : forall t T, has_type empty t T -> value t \/ exists t', t ==> t'. Proof. (* FILL IN HERE *) admit. Qed. End PreservationProgressStlc. (* ####################################################### *) (** ** BigStep and SmallStep *) Module Semantics. Require Import Smallstep. (** Consider the proof relating a small-step reduction judgment to a big-step reduction judgment. *) Theorem multistep__eval : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. intros t v Hnorm. unfold normal_form_of in Hnorm. inversion Hnorm as [Hs Hnf]; clear Hnorm. rewrite nf_same_as_value in Hnf. inversion Hnf. clear Hnf. exists n. split. reflexivity. multi_cases (induction Hs) Case; subst. Case "multi_refl". apply E_Const. Case "multi_step". eapply step__eval. eassumption. apply IHHs. reflexivity. Qed. (** Our goal is to optimize the above proof. It is generally easier to isolate inductions into separate lemmas. So, we are going to first prove an intermediate result that consists of the judgment over which the induction is being performed. *) (** Exercise: prove the following result, using tactics [introv], [induction] and [subst], and [apply*]. The solution is 3 lines long. *) Theorem multistep_eval_ind : forall t v, t ==>* v -> forall n, C n = v -> t || n. Proof. (* FILL IN HERE *) admit. Qed. (** Exercise: using the lemma above, simplify the proof of the result [multistep__eval]. You should use the tactics [introv], [inverts], [split*] and [apply*]. The solution is 2 lines long. *) Theorem multistep__eval' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. (** If we try to combine the two proofs into a single one, we will likely fail, because of a limitation of the [induction] tactic. Indeed, this tactic looses information when applied to a predicate whose arguments are not reduced to variables, such as [t ==>* (C n)]. You will thus need to use the more powerful tactic called [dependent induction]. This tactic is available only after importing the [Program] library, as shown below. *) Require Import Program. (** Exercise: prove the lemma [multistep__eval] without invoking the lemma [multistep_eval_ind], that is, by inlining the proof by induction involved in [multistep_eval_ind], using the tactic [dependent induction] instead of [induction]. The solution is 5 lines long. *) Theorem multistep__eval'' : forall t v, normal_form_of t v -> exists n, v = C n /\ t || n. Proof. (* FILL IN HERE *) admit. Qed. End Semantics. (* ####################################################### *) (** ** Preservation for STLCRef *) Module PreservationProgressReferences. Require Import References. Import STLCRef. Hint Resolve store_weakening extends_refl. (** The proof of preservation for [STLCRef] can be found in chapter [References]. It contains 58 lines (not counting the labelling of cases). The optimized proof script is more than twice shorter. The following material explains how to build the optimized proof script. The resulting optimized proof script for the preservation theorem appears afterwards. *) Theorem preservation : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. (* old: [Proof. with eauto using store_weakening, extends_refl.] new: [Proof.], and the two lemmas are registered as hints before the proof of the lemma, possibly inside a section in order to restrict the scope of the hints. *) remember (@empty ty) as Gamma. introv Ht. gen t'. (has_type_cases (induction Ht) Case); introv HST Hstep; (* old: [subst; try (solve by inversion); inversion Hstep; subst; try (eauto using store_weakening, extends_refl)] new: [subst Gamma; inverts Hstep; eauto.] We want to be more precise on what exactly we substitute, and we do not want to call [try (solve by inversion)] which is way to slow. *) subst Gamma; inverts Hstep; eauto. Case "T_App". SCase "ST_AppAbs". (* old: exists ST. inversion Ht1; subst. split; try split... eapply substitution_preserves_typing... *) (* new: we use [inverts] in place of [inversion] and [splits] to split the conjunction, and [applys*] in place of [eapply...] *) exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. SCase "ST_App1". (* old: eapply IHHt1 in H0... inversion H0 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: The tactic [eapply IHHt1 in H0...] applies [IHHt1] to [H0]. But [H0] is only thing that [IHHt1] could be applied to, so there [eauto] can figure this out on its own. The tactic [forwards] is used to instantiate all the arguments of [IHHt1], producing existential variables and subgoals when needed. *) forwards: IHHt1. eauto. eauto. eauto. (* At this point, we need to decompose the hypothesis [H] that has just been created by [forwards]. This is done by the first part of the preprocessing phase of [jauto]. *) jauto_set_hyps; intros. (* It remains to decompose the goal, which is done by the second part of the preprocessing phase of [jauto]. *) jauto_set_goal; intros. (* All the subgoals produced can then be solved by [eauto]. *) eauto. eauto. eauto. SCase "ST_App2". (* old: eapply IHHt2 in H5... inversion H5 as [ST' [Hext [Hty Hsty]]]. exists ST'... *) (* new: this time, we need to call [forwards] on [IHHt2], and we call [jauto] right away, by writing [forwards*], proving the goal in a single tactic! *) forwards*: IHHt2. (* The same trick works for many of the other subgoals. *) forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. Case "T_Ref". SCase "ST_RefValue". (* old: 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. *) (* new: in this proof case, we need to perform an inversion without removing the hypothesis. The tactic [inverts keep] serves exactly this purpose. *) exists (snoc ST T1). inverts keep HST. splits. (* The proof of the first subgoal needs not be changed *) apply extends_snoc. (* For the second subgoal, we use the tactic [applys_eq] to avoid a manual [replace] before [T_loc] can be applied. *) applys_eq T_Loc 1. (* To justify the inequality, there is no need to call [rewrite <- H], because the tactic [omega] is able to exploit [H] on its own. So, only the rewriting of [lenght_snoc] and the call to the tactic [omega] remain. *) rewrite length_snoc. omega. (* The next proof case is hard to polish because it relies on the lemma [nth_eq_snoc] whose statement is not automation-friendly. We'll come back to this proof case further on. *) unfold store_Tlookup. rewrite <- H. rewrite* nth_eq_snoc. (* Last, we replace [apply ..; assumption] with [apply* ..] *) apply* store_well_typed_snoc. forwards*: IHHt. Case "T_Deref". SCase "ST_DerefLoc". (* old: exists ST. split; try split... destruct HST as [_ Hsty]. replace T11 with (store_Tlookup l ST). apply Hsty... inversion Ht; subst... *) (* new: we start by calling [exists ST] and [splits*]. *) exists ST. splits*. (* new: we replace [destruct HST as [_ Hsty]] by the following *) lets [_ Hsty]: HST. (* new: then we use the tactic [applys_eq] to avoid the need to perform a manual [replace] before applying [Hsty]. *) applys_eq* Hsty 1. (* new: we then can call [inverts] in place of [inversion;subst] *) inverts* Ht. forwards*: IHHt. Case "T_Assign". SCase "ST_Assign". (* old: exists ST. split; try split... eapply assign_pres_store_typing... inversion Ht1; subst... *) (* new: simply using nicer tactics *) exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (** Let's come back to the proof case that was hard to optimize. The difficulty comes from the statement of [nth_eq_snoc], which takes the form [nth (length l) (snoc l x) d = x]. This lemma is hard to exploit because its first argument, [length l], mentions a list [l] that has to be exactly the same as the [l] occuring in [snoc l x]. In practice, the first argument is often a natural number [n] that is provably equal to [length l] yet that is not syntactically equal to [length l]. There is a simple fix for making [nth_eq_snoc] easy to apply: introduce the intermediate variable [n] explicitly, so that the goal becomes [nth n (snoc l x) d = x], with a premise asserting [n = length l]. *) Lemma nth_eq_snoc' : forall (A : Type) (l : list A) (x d : A) (n : nat), n = length l -> nth n (snoc l x) d = x. Proof. intros. subst. apply nth_eq_snoc. Qed. (** The proof case for [ref] from the preservation theorem then becomes much easier to prove, because [rewrite nth_eq_snoc'] now succeeds. *) Lemma preservation_ref : forall (st:store) (ST : store_ty) T1, length ST = length st -> TRef T1 = TRef (store_Tlookup (length st) (snoc ST T1)). Proof. intros. dup. (* A first proof, with an explicit [unfold] *) unfold store_Tlookup. rewrite* nth_eq_snoc'. (* A second proof, with a call to [fequal] *) fequal. symmetry. apply* nth_eq_snoc'. Qed. (** The optimized proof of preservation is summarized next. *) Theorem preservation' : forall ST t t' T st st', has_type empty ST t T -> store_well_typed ST st -> t / st ==> t' / st' -> exists ST', (extends ST' ST /\ has_type empty ST' t' T /\ store_well_typed ST' st'). Proof. remember (@empty ty) as Gamma. introv Ht. gen t'. induction Ht; introv HST Hstep; subst Gamma; inverts Hstep; eauto. exists ST. inverts Ht1. splits*. applys* substitution_preserves_typing. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt. forwards*: IHHt. forwards*: IHHt1. forwards*: IHHt2. forwards*: IHHt1. exists (snoc ST T1). inverts keep HST. splits. apply extends_snoc. applys_eq T_Loc 1. rewrite length_snoc. omega. unfold store_Tlookup. rewrite* nth_eq_snoc'. apply* store_well_typed_snoc. forwards*: IHHt. exists ST. splits*. lets [_ Hsty]: HST. applys_eq* Hsty 1. inverts* Ht. forwards*: IHHt. exists ST. splits*. applys* assign_pres_store_typing. inverts* Ht1. forwards*: IHHt1. forwards*: IHHt2. Qed. (* ####################################################### *) (** ** Progress for STLCRef *) (** The proof of progress for [STLCRef] can be found in chapter [References]. It contains 53 lines and the optimized proof script is, here again, half the length. *) Theorem progress : forall ST t T st, has_type empty ST t T -> store_well_typed ST st -> (value t \/ exists t', exists st', t / st ==> t' / st'). Proof. introv Ht HST. remember (@empty ty) as Gamma. induction Ht; subst Gamma; tryfalse; try solve [left*]. right. destruct* IHHt1 as [K|]. inverts K; inverts Ht1. destruct* IHHt2. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt as [K|]. inverts K; try solve [inverts Ht]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* IHHt2 as [M|]. inverts M; try solve [inverts Ht2]. eauto. right. destruct* IHHt1 as [K|]. inverts K; try solve [inverts Ht1]. destruct* n. right. destruct* IHHt. right. destruct* IHHt as [K|]. inverts K; inverts Ht as M. inverts HST as N. rewrite* N in M. right. destruct* IHHt1 as [K|]. destruct* IHHt2. inverts K; inverts Ht1 as M. inverts HST as N. rewrite* N in M. Qed. End PreservationProgressReferences. (* ####################################################### *) (** ** Subtyping *) Module SubtypingInversion. Require Import Sub. (** Consider the inversion lemma for typing judgment of abstractions in a type system with subtyping. *) Lemma abs_arrow : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof with eauto. intros x S1 s2 T1 T2 Hty. apply typing_inversion_abs in Hty. destruct Hty as [S2 [Hsub Hty]]. apply sub_inversion_arrow in Hsub. destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]]. inversion Heq; subst... Qed. (** Exercise: optimize the proof script, using [introv], [lets] and [inverts*]. In particular, you will find it useful to replace the pattern [apply K in H. destruct H as I] with [lets I: K H]. The solution is 4 lines. *) Lemma abs_arrow' : forall x S1 s2 T1 T2, has_type empty (tabs x S1 s2) (TArrow T1 T2) -> subtype T1 S1 /\ has_type (extend empty x S1) s2 T2. Proof. (* FILL IN HERE *) admit. Qed. (** The lemma [substitution_preserves_typing] has already been used to illustrate the working of [lets] and [applys] in chapter [UseTactics]. Optimize further this proof using automation (with the star symbol), and using the tactic [cases_if']. The solution is 33 lines, including the [Case] instructions (21 lines without them). *) 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. (* FILL IN HERE *) admit. Qed. End SubtypingInversion. (* ####################################################### *) (** * Advanced Topics in Proof Search *) (* ####################################################### *) (** ** Stating Lemmas in the Right Way *) (** Due to its depth-first strategy, [eauto] can get exponentially slower as the depth search increases, even when a short proof exists. In general, to make proof search run reasonably fast, one should avoid using a depth search greater than 5 or 6. Moreover, one should try to minimize the number of applicable lemmas, and usually put first the hypotheses whose proof usefully instantiates the existential variables. In fact, the ability for [eauto] to solve certain goals actually depends on the order in which the hypotheses are stated. This point is illustrated through the following example, in which [P] is a predicate on natural numbers. This predicate is such that [P n] holds for any [n] as soon as [P m] holds for at least one [m] different from zero. The goal is to prove that [P 2] implies [P 1]. When the hypothesis about [P] is stated in the form [forall n m, P m -> m <> 0 -> P n], then [eauto] works. However, with [forall n m, m <> 0 -> P m -> P n], the tactic [eauto] fails. *) Lemma order_matters_1 : forall (P : nat->Prop), (forall n m, P m -> m <> 0 -> P n) -> P 2 -> P 1. Proof. eauto. (* Success *) (* The proof: [intros P H K. eapply H. apply K. auto.] *) Qed. Lemma order_matters_2 : forall (P : nat->Prop), (forall n m, m <> 0 -> P m -> P n) -> P 5 -> P 1. Proof. eauto. (* Failure *) (* To understand why, let us replay the previous proof *) intros P H K. eapply H. (* The application of [eapply] has left two subgoals, [?X <> 0] and [P ?X], where [?X] is an existential variable. *) (* Solving the first subgoal is easy for [eauto]: it suffices to instantiate [?X] as the value [1], which is the simplest value that satisfies [?X <> 0]. *) eauto. (* But then the second goal becomes [P 1], which is where we started from. So, [eauto] gets stuck at this point. *) Abort. (** It is very important to understand that the hypothesis [forall n m, P m -> m <> 0 -> P n] is eauto-friendly, whereas [forall n m, m <> 0 -> P m -> P n] really isn't. Guessing a value of [m] for which [P m] holds and then checking that [m <> 0] holds works well because there are few values of [m] for which [P m] holds. So, it is likely that [eauto] comes up with the right one. On the other hand, guessing a value of [m] for which [m <> 0] and then checking that [P m] holds does not work well, because there are many values of [m] that satisfy [m <> 0] but not [P m]. *) (* ####################################################### *) (** ** Unfolding of Definitions During Proof-Search *) (** The use of intermediate definitions is generally encouraged in a formal development as it usually leads to more concise and more readable statements. Yet, definitions can make it a little harder to automate proofs. The problem is that it is not obvious for a proof search mechanism to know when definitions need to be unfolded. Note that a naive strategy that consists in unfolding all definitions before calling proof search does not scale up to large proofs, so we avoid it. This section introduces a few techniques for avoiding to manually unfold definitions before calling proof search. *) (** To illustrate the treatment of definitions, let [P] be an abstract predicate on natural numbers, and let [myFact] be a definition denoting the proposition [P x] holds for any [x] less than or equal to 3. *) Axiom P : nat -> Prop. Definition myFact := forall x, x <= 3 -> P x. (** Proving that [myFact] under the assumption that [P x] holds for any [x] should be trivial. Yet, [auto] fails to prove it unless we unfold the definition of [myFact] explicitly. *) Lemma demo_hint_unfold_goal_1 : (forall x, P x) -> myFact. Proof. auto. (* Proof search doesn't know what to do, *) unfold myFact. auto. (* unless we unfold the definition. *) Qed. (** To automate the unfolding of definitions that appear as proof obligation, one can use the command [Hint Unfold myFact] to tell Coq that it should always try to unfold [myFact] when [myFact] appears in the goal. *) Hint Unfold myFact. (** This time, automation is able to see through the definition of [myFact]. *) Lemma demo_hint_unfold_goal_2 : (forall x, P x) -> myFact. Proof. auto. Qed. (** However, the [Hint Unfold] mechanism only works for unfolding definitions that appear in the goal. In general, proof search does not unfold definitions from the context. For example, assume we want to prove that [P 3] holds under the assumption that [True -> myFact]. *) Lemma demo_hint_unfold_context_1 : (True -> myFact) -> P 3. Proof. intros. auto. (* fails *) unfold myFact in *. auto. (* succeeds *) Qed. (** There is actually one exception to the previous rule: a constant occuring in an hypothesis is automatically unfolded if the hypothesis can be directly applied to the current goal. For example, [auto] can prove [myFact -> P 3], as illustrated below. *) Lemma demo_hint_unfold_context_2 : myFact -> P 3. Proof. auto. Qed. (* ####################################################### *) (** ** Automation for Proving Absurd Goals *) (** In this section, we'll see that lemmas concluding on a negation are generally not useful as hints, and that lemmas whose conclusion is [False] can be useful hints but having too many of them makes proof search inefficient. We'll also see a practical work-around to the efficiency issue. *) (** Consider the following lemma, which asserts that a number less than or equal to 3 is not greater than 3. *) Parameter le_not_gt : forall x, (x <= 3) -> ~ (x > 3). (** Equivalently, one could state that a number greater than three is not less than or equal to 3. *) Parameter gt_not_le : forall x, (x > 3) -> ~ (x <= 3). (** In fact, both statements are equivalent to a third one stating that [x <= 3] and [x > 3] are contradictory, in the sense that they imply [False]. *) Parameter le_gt_false : forall x, (x <= 3) -> (x > 3) -> False. (** The following investigation aim at figuring out which of the three statments is the most convenient with respect to proof automation. The following material is enclosed inside a [Section], so as to restrict the scope of the hints that we are adding. In other words, after the end of the section, the hints added within the section will no longer be active.*) Section DemoAbsurd1. (** Let's try to add the first lemma, [le_not_gt], as hint, and see whether we can prove that the proposition [exists x, x <= 3 /\ x > 3] is absurd. *) Hint Resolve le_not_gt. Lemma demo_auto_absurd_1 : (exists x, x <= 3 /\ x > 3) -> False. Proof. intros. jauto_set. (* decomposes the assumption *) (* debug *) eauto. (* does not see that [le_not_gt] could apply *) eapply le_not_gt. eauto. eauto. Qed. (** The lemma [gt_not_le] is symmetric to [le_not_gt], so it will not be any better. The third lemma, [le_gt_false], is a more useful hint, because it concludes on [False], so proof search will try to apply it when the current goal is [False]. *) Hint Resolve le_gt_false. Lemma demo_auto_absurd_2 : (exists x, x <= 3 /\ x > 3) -> False. Proof. dup. (* detailed version: *) intros. jauto_set. (* debug *) eauto. (* short version: *) jauto. Qed. (** In summary, a lemma of the form [H1 -> H2 -> False] is a much more effective hint than [H1 -> ~ H2], even though the two statments are equivalent up to the definition of the negation symbol [~]. *) (** That said, one should be careful with adding lemmas whose conclusion is [False] as hint. The reason is that whenever reaching the goal [False], the proof search mechanism will potentially try to apply all the hints whose conclusion is [False] before applying the appropriate one. *) End DemoAbsurd1. (** Adding lemmas whose conclusion is [False] as hint can be, locally, a very effective solution. However, this approach does not scale up for global hints. For most practical applications, it is reasonable to give the name of the lemmas to be exploited for deriving a contradiction. The tactic [false H], provided by [LibTactics] serves that purpose: [false H] replaces the goal with [False] and calls [eapply H]. Its behavior is described next. Observe that any of the three statements [le_not_gt], [gt_not_le] or [le_gt_false] can be used. *) Lemma demo_false : forall x, (x <= 3) -> (x > 3) -> 4 = 5. Proof. intros. dup 4. (* A failed proof: *) false. eapply le_gt_false. auto. (* here, [auto] does not prove [?x <= 3] by using [H] but by using the lemma [le_refl : forall x, x <= x]. *) (* The second subgoal becomes [3 > 3], which is not provable. *) skip. (* A correct proof: *) false. eapply le_gt_false. eauto. (* here, [eauto] uses [H], as expected, to prove [?x <= 3] *) eauto. (* so the second subgoal becomes [x > 3] *) (* The same proof using [false]: *) false le_gt_false. eauto. eauto. (* The lemmas [le_not_gt] and [gt_not_le] work as well *) false le_not_gt. eauto. eauto. Qed. (** In the above example, [false le_gt_false; eauto] proves the goal, but [false le_gt_false; auto] does not, because [auto] does not correctly instantiate the existential variable. Note that [false* le_gt_false] would not work either, because the star symbol tries to call [auto] first. So, there are two possibilities for completing the proof: either call [false le_gt_false; eauto], or call [false* (le_gt_false 3)]. *) (* ####################################################### *) (** ** Automation for Transitivity Lemmas *) (** Some lemmas should never be added as hints, because they would very badly slow down proof search. The typical example is that of transitivity results. This section describes the problem and presents a general workaround. Consider a subtyping relation, written [subtype S T], that relates two object [S] and [T] of type [typ]. Assume that this relation has been proved reflexive and transitive. The corresponding lemmas are named [subtype_refl] and [subtype_trans]. *) Parameter typ : Type. Parameter subtype : typ -> typ -> Prop. Parameter subtype_refl : forall T, subtype T T. Parameter subtype_trans : forall S T U, subtype S T -> subtype T U -> subtype S U. (** Adding reflexivity as hint is generally a good idea, so let's add reflexivity of subtyping as hint. *) Hint Resolve subtype_refl. (** Adding transitivity as hint is generally a bad idea. To understand why, let's add it as hint and see what happens. Because we cannot remove hints once we've added them, we are going to open a "Section," so as to restrict the scope of the transitivity hint to that section. *) Section HintsTransitivity. Hint Resolve subtype_trans. (** Now, consider the goal [forall S T, subtype S T], which clearly has no hope of being solved. Let's call [eauto] on this goal. *) Lemma transitivity_bad_hint_1 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 106 applications... *) Abort. (** Note that after closing the section, the hint [subtype_trans] is no longer active. *) End HintsTransitivity. (** In the previous example, the proof search has spent a lot of time trying to apply transitivity and reflexivity in every possible way. Its process can be summarized as follows. The first goal is [subtype S T]. Since reflexivity does not apply, [eauto] invokes transitivity, which produces two subgoals, [subtype S ?X] and [subtype ?X T]. Solving the first subgoal, [subtype S ?X], is straightforward, it suffices to apply reflexivity. This unifies [?X] with [S]. So, the second sugoal, [subtype ?X T], becomes [subtype S T], which is exactly what we started from... The problem with the transitivity lemma is that it is applicable to any goal concluding on a subtyping relation. Because of this, [eauto] keeps trying to apply it even though it most often doesn't help to solve the goal. So, one should never add a transitivity lemma as a hint for proof search. *) (** There is a general workaround for having automation to exploit transitivity lemmas without giving up on efficiency. This workaround relies on a powerful mechanism called "external hint." This mechanism allows to manually describe the condition under which a particular lemma should be tried out during proof search. For the case of transitivity of subtyping, we are going to tell Coq to try and apply the transitivity lemma on a goal of the form [subtype S U] only when the proof context already contains an assumption either of the form [subtype S T] or of the form [subtype T U]. In other words, we only apply the transitivity lemma when there is some evidence that this application might help. To set up this "external hint," one has to write the following. *) Hint Extern 1 (subtype ?S ?U) => match goal with | H: subtype S ?T |- _ => apply (@subtype_trans S T U) | H: subtype ?T U |- _ => apply (@subtype_trans S T U) end. (** This hint declaration can be understood as follows. - "Hint Extern" introduces the hint. - The number "1" corresponds to a priority for proof search. It doesn't matter so much what priority is used in practice. - The pattern [subtype ?S ?U] describes the kind of goal on which the pattern should apply. The question marks are used to indicate that the variables [?S] and [?U] should be bound to some value in the rest of the hint description. - The construction [match goal with ... end] tries to recognize patterns in the goal, or in the proof context, or both. - The first pattern is [H: subtype S ?T |- _]. It indices that the context should contain an hypothesis [H] of type [subtype S ?T], where [S] has to be the same as in the goal, and where [?T] can have any value. - The symbol [|- _] at the end of [H: subtype S ?T |- _] indicates that we do not impose further condition on how the proof obligation has to look like. - The branch [=> apply (@subtype_trans S T U)] that follows indicates that if the goal has the form [subtype S U] and if there exists an hypothesis of the form [subtype S T], then we should try and apply transitivity lemma instantiated on the arguments [S], [T] and [U]. (Note: the symbol [@] in front of [subtype_trans] is only actually needed when the "Implicit Arguments" feature is activated.) - The other branch, which corresponds to an hypothesis of the form [H: subtype ?T U] is symmetrical. Note: the same external hint can be reused for any other transitive relation, simply by renaming [subtype] into the name of that relation. *) (** Let us see an example illustrating how the hint works. *) Lemma transitivity_workaround_1 : forall T1 T2 T3 T4, subtype T1 T2 -> subtype T2 T3 -> subtype T3 T4 -> subtype T1 T4. Proof. intros. (* debug *) eauto. (* The trace shows the external hint being used *) Qed. (** We may also check that the new external hint does not suffer from the complexity blow up. *) Lemma transitivity_workaround_2 : forall S T, subtype S T. Proof. intros. (* debug *) eauto. (* Investigates 0 applications *) Abort. (* ####################################################### *) (** * Decision Procedures *) (** A decision procedure is able to solve proof obligations whose statement admits a particular form. This section describes three useful decision procedures. The tactic [omega] handles goals involving arithmetic and inequalities, but not general multiplications. The tactic [ring] handles goals involving arithmetic, including multiplications, but does not support inequalities. The tactic [congruence] is able to prove equalities and inequalities by exploiting equalities available in the proof context. *) (* ####################################################### *) (** ** Omega *) (** The tactic [omega] supports natural numbers (type [nat]) as well as integers (type [Z], available by including the module [ZArith]). It supports addition, substraction, equalities and inequalities. Before using [omega], one needs to import the module [Omega], as follows. *) Require Import Omega. (** Here is an example. Let [x] and [y] be two natural numbers (they cannot be negative). Assume [y] is less than 4, assume [x+x+1] is less than [y], and assume [x] is not zero. Then, it must be the case that [x] is equal to one. *) Lemma omega_demo_1 : forall (x y : nat), (y <= 4) -> (x + x + 1 <= y) -> (x <> 0) -> (x = 1). Proof. intros. omega. Qed. (** Another example: if [z] is the mean of [x] and [y], and if the difference between [x] and [y] is at most [4], then the difference between [x] and [z] is at most 2. *) Lemma omega_demo_2 : forall (x y z : nat), (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2). Proof. intros. omega. Qed. (** One can proof [False] using [omega] if the mathematical facts from the context are contradictory. In the following example, the constraints on the values [x] and [y] cannot be all satisfied in the same time. *) Lemma omega_demo_3 : forall (x y : nat), (x + 5 <= y) -> (y - x < 3) -> False. Proof. intros. omega. Qed. (** Note: [omega] can prove a goal by contradiction only if its conclusion is reduced [False]. The tactic [omega] always fails when the conclusion is an arbitrary proposition [P], even though [False] implies any proposition [P] (by [ex_falso_quodlibet]). *) Lemma omega_demo_4 : forall (x y : nat) (P : Prop), (x + 5 <= y) -> (y - x < 3) -> P. Proof. intros. (* Calling [omega] at this point fails with the message: "Omega: Can't solve a goal with proposition variables" *) (* So, one needs to replace the goal by [False] first. *) false. omega. Qed. (* ####################################################### *) (** ** Ring *) (** Compared with [omega], the tactic [ring] adds support for multiplications, however it gives up the ability to reason on inequations. Moreover, it supports only integers (type [Z]) and not natural numbers (type [nat]). Here is an example showing how to use [ring]. *) Module RingDemo. Require Import ZArith. Open Scope Z_scope. (* Arithmetic symbols are now interpreted in [Z] *) Lemma ring_demo : forall (x y z : Z), x * (y + z) - z * 3 * x = x * y - 2 * x * z. Proof. intros. ring. Qed. End RingDemo. (* ####################################################### *) (** ** Congruence *) (** The tactic [congruence] is able to exploit equalities from the proof context in order to automatically perform the rewriting operations necessary to establish a goal. It is slightly more powerful than the tactic [subst], which can only handle equalities of the form [x = e] where [x] is a variable and [e] an expression. *) Lemma congruence_demo_1 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), f (g x) (g y) = z -> 2 = g x -> g y = h z -> f 2 (h z) = z. Proof. intros. congruence. Qed. (** Moreover, [congruence] is able to exploit universally quantified equalities, for example [forall a, g a = h a]. *) Lemma congruence_demo_2 : forall (f : nat->nat->nat) (g h : nat->nat) (x y z : nat), (forall a, g a = h a) -> f (g x) (g y) = z -> g x = 2 -> f 2 (h y) = z. Proof. congruence. Qed. (** Next is an example where [congruence] is very useful. *) Lemma congruence_demo_4 : forall (f g : nat->nat), (forall a, f a = g a) -> f (g (g 2)) = g (f (f 2)). Proof. congruence. Qed. (** The tactic [congruence] is able to prove a contradiction if the goal entails an equality that contradicts an inequality available in the proof context. *) Lemma congruence_demo_3 : forall (f g h : nat->nat) (x : nat), (forall a, f a = h a) -> g x = f x -> g x <> h x -> False. Proof. congruence. Qed. (** One of the strengths of [congruence] is that it is a very fast tactic. So, one should not hesitate to invoke it wherever it might help. *) (* ####################################################### *) (** * Summary *) (** Let us summarize the main automation tactics available. - [auto] automatically applies [reflexivity], [assumption], and [apply]. - [eauto] moreover tries [eapply], and in particular can instantiate existentials in the conclusion. - [iauto] extends [eauto] with support for negation, conjunctions, and disjunctions. However, its support for disjunction can make it exponentially slow. - [jauto] extends [eauto] with support for negation, conjunctions, and existential at the head of hypothesis. - [congruence] helps reasoning about equalities and inequalities. - [omega] proves arithmetic goals with equalities and inequalities, but it does not support multiplication. - [ring] proves arithmetic goals with multiplications, but does not support inequalities. In order to set up automation appropriately, keep in mind the following rule of thumbs: - automation is all about balance: not enough automation makes proofs not very robust on change, whereas too much automation makes proofs very hard to fix when they break. - if a lemma is not goal directed (i.e., some of its variables do not occur in its conclusion), then the premises need to be ordered in such a way that proving the first premises maximizes the chances of correctly instantiating the variables that do not occur in the conclusion. - a lemma whose conclusion is [False] should only be added as a local hint, i.e., as a hint within the current section. - a transitivity lemma should never be considered as hint; if automation of transitivity reasoning is really necessary, an [Extern Hint] needs to be set up. - a definition usually needs to be accompanied with a [Hint Unfold]. Becoming a master in the black art of automation certainly requires some investment, however this investment will pay off very quickly. *) (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
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
// (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
// (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
/* ******************************************************************************* * * FIFO Generator - Verilog Behavioral Model * ******************************************************************************* * * (c) Copyright 1995 - 2009 Xilinx, Inc. All rights reserved. * * This file contains confidential and proprietary information * of Xilinx, Inc. and is protected under U.S. and * international copyright and other intellectual property * laws. * * DISCLAIMER * This disclaimer is not a license and does not grant any * rights to the materials distributed herewith. Except as * otherwise provided in a valid license issued to you by * Xilinx, and to the maximum extent permitted by applicable * law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND * WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES * AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING * BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- * INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and * (2) Xilinx shall not be liable (whether in contract or tort, * including negligence, or under any other theory of * liability) for any loss or damage of any kind or nature * related to, arising under or in connection with these * materials, including for any direct, or any indirect, * special, incidental, or consequential loss or damage * (including loss of data, profits, goodwill, or any type of * loss or damage suffered as a result of any action brought * by a third party) even if such damage or loss was * reasonably foreseeable or Xilinx had been advised of the * possibility of the same. * * CRITICAL APPLICATIONS * Xilinx products are not designed or intended to be fail- * safe, or for use in any application requiring fail-safe * performance, such as life-support or safety devices or * systems, Class III medical devices, nuclear facilities, * applications related to the deployment of airbags, or any * other applications that could lead to death, personal * injury, or severe property or environmental damage * (individually and collectively, "Critical * Applications"). Customer assumes the sole risk and * liability of any use of Xilinx products in Critical * Applications, subject only to applicable laws and * regulations governing limitations on product liability. * * THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS * PART OF THIS FILE AT ALL TIMES. * ******************************************************************************* ******************************************************************************* * * Filename: fifo_generator_vlog_beh.v * * Author : Xilinx * ******************************************************************************* * Structure: * * fifo_generator_vlog_beh.v * | * +-fifo_generator_v13_1_1_bhv_ver_as * | * +-fifo_generator_v13_1_1_bhv_ver_ss * | * +-fifo_generator_v13_1_1_bhv_ver_preload0 * ******************************************************************************* * Description: * * The Verilog behavioral model for the FIFO Generator. * * The behavioral model has three parts: * - The behavioral model for independent clocks FIFOs (_as) * - The behavioral model for common clock FIFOs (_ss) * - The "preload logic" block which implements First-word Fall-through * ******************************************************************************* * Description: * The verilog behavioral model for the FIFO generator core. * ******************************************************************************* */ `timescale 1ps/1ps `ifndef TCQ `define TCQ 100 `endif /******************************************************************************* * Declaration of top-level module ******************************************************************************/ module fifo_generator_vlog_beh #( //----------------------------------------------------------------------- // Generic Declarations //----------------------------------------------------------------------- parameter C_COMMON_CLOCK = 0, parameter C_COUNT_TYPE = 0, parameter C_DATA_COUNT_WIDTH = 2, parameter C_DEFAULT_VALUE = "", parameter C_DIN_WIDTH = 8, parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_ENABLE_RLOCS = 0, parameter C_FAMILY = "", parameter C_FULL_FLAGS_RST_VAL = 1, parameter C_HAS_ALMOST_EMPTY = 0, parameter C_HAS_ALMOST_FULL = 0, parameter C_HAS_BACKUP = 0, parameter C_HAS_DATA_COUNT = 0, parameter C_HAS_INT_CLK = 0, parameter C_HAS_MEMINIT_FILE = 0, parameter C_HAS_OVERFLOW = 0, parameter C_HAS_RD_DATA_COUNT = 0, parameter C_HAS_RD_RST = 0, parameter C_HAS_RST = 1, parameter C_HAS_SRST = 0, parameter C_HAS_UNDERFLOW = 0, parameter C_HAS_VALID = 0, parameter C_HAS_WR_ACK = 0, parameter C_HAS_WR_DATA_COUNT = 0, parameter C_HAS_WR_RST = 0, parameter C_IMPLEMENTATION_TYPE = 0, parameter C_INIT_WR_PNTR_VAL = 0, parameter C_MEMORY_TYPE = 1, parameter C_MIF_FILE_NAME = "", parameter C_OPTIMIZATION_MODE = 0, parameter C_OVERFLOW_LOW = 0, parameter C_EN_SAFETY_CKT = 0, parameter C_PRELOAD_LATENCY = 1, parameter C_PRELOAD_REGS = 0, parameter C_PRIM_FIFO_TYPE = "4kx4", parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0, parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0, parameter C_PROG_EMPTY_TYPE = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0, parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0, parameter C_PROG_FULL_TYPE = 0, parameter C_RD_DATA_COUNT_WIDTH = 2, parameter C_RD_DEPTH = 256, parameter C_RD_FREQ = 1, parameter C_RD_PNTR_WIDTH = 8, parameter C_UNDERFLOW_LOW = 0, parameter C_USE_DOUT_RST = 0, parameter C_USE_ECC = 0, parameter C_USE_EMBEDDED_REG = 0, parameter C_USE_PIPELINE_REG = 0, parameter C_POWER_SAVING_MODE = 0, parameter C_USE_FIFO16_FLAGS = 0, parameter C_USE_FWFT_DATA_COUNT = 0, parameter C_VALID_LOW = 0, parameter C_WR_ACK_LOW = 0, parameter C_WR_DATA_COUNT_WIDTH = 2, parameter C_WR_DEPTH = 256, parameter C_WR_FREQ = 1, parameter C_WR_PNTR_WIDTH = 8, parameter C_WR_RESPONSE_LATENCY = 1, parameter C_MSGON_VAL = 1, parameter C_ENABLE_RST_SYNC = 1, parameter C_ERROR_INJECTION_TYPE = 0, parameter C_SYNCHRONIZER_STAGE = 2, // AXI Interface related parameters start here parameter C_INTERFACE_TYPE = 0, // 0: Native Interface, 1: AXI4 Stream, 2: AXI4/AXI3 parameter C_AXI_TYPE = 0, // 1: AXI4, 2: AXI4 Lite, 3: AXI3 parameter C_HAS_AXI_WR_CHANNEL = 0, parameter C_HAS_AXI_RD_CHANNEL = 0, parameter C_HAS_SLAVE_CE = 0, parameter C_HAS_MASTER_CE = 0, parameter C_ADD_NGC_CONSTRAINT = 0, parameter C_USE_COMMON_UNDERFLOW = 0, parameter C_USE_COMMON_OVERFLOW = 0, parameter C_USE_DEFAULT_SETTINGS = 0, // AXI Full/Lite parameter C_AXI_ID_WIDTH = 0, parameter C_AXI_ADDR_WIDTH = 0, parameter C_AXI_DATA_WIDTH = 0, parameter C_AXI_LEN_WIDTH = 8, parameter C_AXI_LOCK_WIDTH = 2, parameter C_HAS_AXI_ID = 0, parameter C_HAS_AXI_AWUSER = 0, parameter C_HAS_AXI_WUSER = 0, parameter C_HAS_AXI_BUSER = 0, parameter C_HAS_AXI_ARUSER = 0, parameter C_HAS_AXI_RUSER = 0, parameter C_AXI_ARUSER_WIDTH = 0, parameter C_AXI_AWUSER_WIDTH = 0, parameter C_AXI_WUSER_WIDTH = 0, parameter C_AXI_BUSER_WIDTH = 0, parameter C_AXI_RUSER_WIDTH = 0, // AXI Streaming parameter C_HAS_AXIS_TDATA = 0, parameter C_HAS_AXIS_TID = 0, parameter C_HAS_AXIS_TDEST = 0, parameter C_HAS_AXIS_TUSER = 0, parameter C_HAS_AXIS_TREADY = 0, parameter C_HAS_AXIS_TLAST = 0, parameter C_HAS_AXIS_TSTRB = 0, parameter C_HAS_AXIS_TKEEP = 0, parameter C_AXIS_TDATA_WIDTH = 1, parameter C_AXIS_TID_WIDTH = 1, parameter C_AXIS_TDEST_WIDTH = 1, parameter C_AXIS_TUSER_WIDTH = 1, parameter C_AXIS_TSTRB_WIDTH = 1, parameter C_AXIS_TKEEP_WIDTH = 1, // AXI Channel Type // WACH --> Write Address Channel // WDCH --> Write Data Channel // WRCH --> Write Response Channel // RACH --> Read Address Channel // RDCH --> Read Data Channel // AXIS --> AXI Streaming parameter C_WACH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logic parameter C_WDCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie parameter C_WRCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie parameter C_RACH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie parameter C_RDCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie parameter C_AXIS_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie // AXI Implementation Type // 1 = Common Clock Block RAM FIFO // 2 = Common Clock Distributed RAM FIFO // 11 = Independent Clock Block RAM FIFO // 12 = Independent Clock Distributed RAM FIFO parameter C_IMPLEMENTATION_TYPE_WACH = 0, parameter C_IMPLEMENTATION_TYPE_WDCH = 0, parameter C_IMPLEMENTATION_TYPE_WRCH = 0, parameter C_IMPLEMENTATION_TYPE_RACH = 0, parameter C_IMPLEMENTATION_TYPE_RDCH = 0, parameter C_IMPLEMENTATION_TYPE_AXIS = 0, // AXI FIFO Type // 0 = Data FIFO // 1 = Packet FIFO // 2 = Low Latency Sync FIFO // 3 = Low Latency Async FIFO parameter C_APPLICATION_TYPE_WACH = 0, parameter C_APPLICATION_TYPE_WDCH = 0, parameter C_APPLICATION_TYPE_WRCH = 0, parameter C_APPLICATION_TYPE_RACH = 0, parameter C_APPLICATION_TYPE_RDCH = 0, parameter C_APPLICATION_TYPE_AXIS = 0, // AXI Built-in FIFO Primitive Type // 512x36, 1kx18, 2kx9, 4kx4, etc parameter C_PRIM_FIFO_TYPE_WACH = "512x36", parameter C_PRIM_FIFO_TYPE_WDCH = "512x36", parameter C_PRIM_FIFO_TYPE_WRCH = "512x36", parameter C_PRIM_FIFO_TYPE_RACH = "512x36", parameter C_PRIM_FIFO_TYPE_RDCH = "512x36", parameter C_PRIM_FIFO_TYPE_AXIS = "512x36", // Enable ECC // 0 = ECC disabled // 1 = ECC enabled parameter C_USE_ECC_WACH = 0, parameter C_USE_ECC_WDCH = 0, parameter C_USE_ECC_WRCH = 0, parameter C_USE_ECC_RACH = 0, parameter C_USE_ECC_RDCH = 0, parameter C_USE_ECC_AXIS = 0, // ECC Error Injection Type // 0 = No Error Injection // 1 = Single Bit Error Injection // 2 = Double Bit Error Injection // 3 = Single Bit and Double Bit Error Injection parameter C_ERROR_INJECTION_TYPE_WACH = 0, parameter C_ERROR_INJECTION_TYPE_WDCH = 0, parameter C_ERROR_INJECTION_TYPE_WRCH = 0, parameter C_ERROR_INJECTION_TYPE_RACH = 0, parameter C_ERROR_INJECTION_TYPE_RDCH = 0, parameter C_ERROR_INJECTION_TYPE_AXIS = 0, // Input Data Width // Accumulation of all AXI input signal's width parameter C_DIN_WIDTH_WACH = 1, parameter C_DIN_WIDTH_WDCH = 1, parameter C_DIN_WIDTH_WRCH = 1, parameter C_DIN_WIDTH_RACH = 1, parameter C_DIN_WIDTH_RDCH = 1, parameter C_DIN_WIDTH_AXIS = 1, parameter C_WR_DEPTH_WACH = 16, parameter C_WR_DEPTH_WDCH = 16, parameter C_WR_DEPTH_WRCH = 16, parameter C_WR_DEPTH_RACH = 16, parameter C_WR_DEPTH_RDCH = 16, parameter C_WR_DEPTH_AXIS = 16, parameter C_WR_PNTR_WIDTH_WACH = 4, parameter C_WR_PNTR_WIDTH_WDCH = 4, parameter C_WR_PNTR_WIDTH_WRCH = 4, parameter C_WR_PNTR_WIDTH_RACH = 4, parameter C_WR_PNTR_WIDTH_RDCH = 4, parameter C_WR_PNTR_WIDTH_AXIS = 4, parameter C_HAS_DATA_COUNTS_WACH = 0, parameter C_HAS_DATA_COUNTS_WDCH = 0, parameter C_HAS_DATA_COUNTS_WRCH = 0, parameter C_HAS_DATA_COUNTS_RACH = 0, parameter C_HAS_DATA_COUNTS_RDCH = 0, parameter C_HAS_DATA_COUNTS_AXIS = 0, parameter C_HAS_PROG_FLAGS_WACH = 0, parameter C_HAS_PROG_FLAGS_WDCH = 0, parameter C_HAS_PROG_FLAGS_WRCH = 0, parameter C_HAS_PROG_FLAGS_RACH = 0, parameter C_HAS_PROG_FLAGS_RDCH = 0, parameter C_HAS_PROG_FLAGS_AXIS = 0, parameter C_PROG_FULL_TYPE_WACH = 0, parameter C_PROG_FULL_TYPE_WDCH = 0, parameter C_PROG_FULL_TYPE_WRCH = 0, parameter C_PROG_FULL_TYPE_RACH = 0, parameter C_PROG_FULL_TYPE_RDCH = 0, parameter C_PROG_FULL_TYPE_AXIS = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_WACH = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_WDCH = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_WRCH = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_RACH = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_RDCH = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL_AXIS = 0, parameter C_PROG_EMPTY_TYPE_WACH = 0, parameter C_PROG_EMPTY_TYPE_WDCH = 0, parameter C_PROG_EMPTY_TYPE_WRCH = 0, parameter C_PROG_EMPTY_TYPE_RACH = 0, parameter C_PROG_EMPTY_TYPE_RDCH = 0, parameter C_PROG_EMPTY_TYPE_AXIS = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WACH = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WDCH = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WRCH = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_RACH = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_RDCH = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_AXIS = 0, parameter C_REG_SLICE_MODE_WACH = 0, parameter C_REG_SLICE_MODE_WDCH = 0, parameter C_REG_SLICE_MODE_WRCH = 0, parameter C_REG_SLICE_MODE_RACH = 0, parameter C_REG_SLICE_MODE_RDCH = 0, parameter C_REG_SLICE_MODE_AXIS = 0 ) ( //------------------------------------------------------------------------------ // Input and Output Declarations //------------------------------------------------------------------------------ // Conventional FIFO Interface Signals input backup, input backup_marker, input clk, input rst, input srst, input wr_clk, input wr_rst, input rd_clk, input rd_rst, input [C_DIN_WIDTH-1:0] din, input wr_en, input rd_en, // Optional inputs input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh, input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_assert, input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_negate, input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh, input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_assert, input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_negate, input int_clk, input injectdbiterr, input injectsbiterr, input sleep, output [C_DOUT_WIDTH-1:0] dout, output full, output almost_full, output wr_ack, output overflow, output empty, output almost_empty, output valid, output underflow, output [C_DATA_COUNT_WIDTH-1:0] data_count, output [C_RD_DATA_COUNT_WIDTH-1:0] rd_data_count, output [C_WR_DATA_COUNT_WIDTH-1:0] wr_data_count, output prog_full, output prog_empty, output sbiterr, output dbiterr, output wr_rst_busy, output rd_rst_busy, // AXI Global Signal input m_aclk, input s_aclk, input s_aresetn, input s_aclk_en, input m_aclk_en, // AXI Full/Lite Slave Write Channel (write side) input [C_AXI_ID_WIDTH-1:0] s_axi_awid, input [C_AXI_ADDR_WIDTH-1:0] s_axi_awaddr, input [C_AXI_LEN_WIDTH-1:0] s_axi_awlen, input [3-1:0] s_axi_awsize, input [2-1:0] s_axi_awburst, input [C_AXI_LOCK_WIDTH-1:0] s_axi_awlock, input [4-1:0] s_axi_awcache, input [3-1:0] s_axi_awprot, input [4-1:0] s_axi_awqos, input [4-1:0] s_axi_awregion, input [C_AXI_AWUSER_WIDTH-1:0] s_axi_awuser, input s_axi_awvalid, output s_axi_awready, input [C_AXI_ID_WIDTH-1:0] s_axi_wid, input [C_AXI_DATA_WIDTH-1:0] s_axi_wdata, input [C_AXI_DATA_WIDTH/8-1:0] s_axi_wstrb, input s_axi_wlast, input [C_AXI_WUSER_WIDTH-1:0] s_axi_wuser, input s_axi_wvalid, output s_axi_wready, output [C_AXI_ID_WIDTH-1:0] s_axi_bid, output [2-1:0] s_axi_bresp, output [C_AXI_BUSER_WIDTH-1:0] s_axi_buser, output s_axi_bvalid, input s_axi_bready, // AXI Full/Lite Master Write Channel (read side) output [C_AXI_ID_WIDTH-1:0] m_axi_awid, output [C_AXI_ADDR_WIDTH-1:0] m_axi_awaddr, output [C_AXI_LEN_WIDTH-1:0] m_axi_awlen, output [3-1:0] m_axi_awsize, output [2-1:0] m_axi_awburst, output [C_AXI_LOCK_WIDTH-1:0] m_axi_awlock, output [4-1:0] m_axi_awcache, output [3-1:0] m_axi_awprot, output [4-1:0] m_axi_awqos, output [4-1:0] m_axi_awregion, output [C_AXI_AWUSER_WIDTH-1:0] m_axi_awuser, output m_axi_awvalid, input m_axi_awready, output [C_AXI_ID_WIDTH-1:0] m_axi_wid, output [C_AXI_DATA_WIDTH-1:0] m_axi_wdata, output [C_AXI_DATA_WIDTH/8-1:0] m_axi_wstrb, output m_axi_wlast, output [C_AXI_WUSER_WIDTH-1:0] m_axi_wuser, output m_axi_wvalid, input m_axi_wready, input [C_AXI_ID_WIDTH-1:0] m_axi_bid, input [2-1:0] m_axi_bresp, input [C_AXI_BUSER_WIDTH-1:0] m_axi_buser, input m_axi_bvalid, output m_axi_bready, // AXI Full/Lite Slave Read Channel (write side) input [C_AXI_ID_WIDTH-1:0] s_axi_arid, input [C_AXI_ADDR_WIDTH-1:0] s_axi_araddr, input [C_AXI_LEN_WIDTH-1:0] s_axi_arlen, input [3-1:0] s_axi_arsize, input [2-1:0] s_axi_arburst, input [C_AXI_LOCK_WIDTH-1:0] s_axi_arlock, input [4-1:0] s_axi_arcache, input [3-1:0] s_axi_arprot, input [4-1:0] s_axi_arqos, input [4-1:0] s_axi_arregion, input [C_AXI_ARUSER_WIDTH-1:0] s_axi_aruser, input s_axi_arvalid, output s_axi_arready, output [C_AXI_ID_WIDTH-1:0] s_axi_rid, output [C_AXI_DATA_WIDTH-1:0] s_axi_rdata, output [2-1:0] s_axi_rresp, output s_axi_rlast, output [C_AXI_RUSER_WIDTH-1:0] s_axi_ruser, output s_axi_rvalid, input s_axi_rready, // AXI Full/Lite Master Read Channel (read side) output [C_AXI_ID_WIDTH-1:0] m_axi_arid, output [C_AXI_ADDR_WIDTH-1:0] m_axi_araddr, output [C_AXI_LEN_WIDTH-1:0] m_axi_arlen, output [3-1:0] m_axi_arsize, output [2-1:0] m_axi_arburst, output [C_AXI_LOCK_WIDTH-1:0] m_axi_arlock, output [4-1:0] m_axi_arcache, output [3-1:0] m_axi_arprot, output [4-1:0] m_axi_arqos, output [4-1:0] m_axi_arregion, output [C_AXI_ARUSER_WIDTH-1:0] m_axi_aruser, output m_axi_arvalid, input m_axi_arready, input [C_AXI_ID_WIDTH-1:0] m_axi_rid, input [C_AXI_DATA_WIDTH-1:0] m_axi_rdata, input [2-1:0] m_axi_rresp, input m_axi_rlast, input [C_AXI_RUSER_WIDTH-1:0] m_axi_ruser, input m_axi_rvalid, output m_axi_rready, // AXI Streaming Slave Signals (Write side) input s_axis_tvalid, output s_axis_tready, input [C_AXIS_TDATA_WIDTH-1:0] s_axis_tdata, input [C_AXIS_TSTRB_WIDTH-1:0] s_axis_tstrb, input [C_AXIS_TKEEP_WIDTH-1:0] s_axis_tkeep, input s_axis_tlast, input [C_AXIS_TID_WIDTH-1:0] s_axis_tid, input [C_AXIS_TDEST_WIDTH-1:0] s_axis_tdest, input [C_AXIS_TUSER_WIDTH-1:0] s_axis_tuser, // AXI Streaming Master Signals (Read side) output m_axis_tvalid, input m_axis_tready, output [C_AXIS_TDATA_WIDTH-1:0] m_axis_tdata, output [C_AXIS_TSTRB_WIDTH-1:0] m_axis_tstrb, output [C_AXIS_TKEEP_WIDTH-1:0] m_axis_tkeep, output m_axis_tlast, output [C_AXIS_TID_WIDTH-1:0] m_axis_tid, output [C_AXIS_TDEST_WIDTH-1:0] m_axis_tdest, output [C_AXIS_TUSER_WIDTH-1:0] m_axis_tuser, // AXI Full/Lite Write Address Channel signals input axi_aw_injectsbiterr, input axi_aw_injectdbiterr, input [C_WR_PNTR_WIDTH_WACH-1:0] axi_aw_prog_full_thresh, input [C_WR_PNTR_WIDTH_WACH-1:0] axi_aw_prog_empty_thresh, output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_data_count, output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_wr_data_count, output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_rd_data_count, output axi_aw_sbiterr, output axi_aw_dbiterr, output axi_aw_overflow, output axi_aw_underflow, output axi_aw_prog_full, output axi_aw_prog_empty, // AXI Full/Lite Write Data Channel signals input axi_w_injectsbiterr, input axi_w_injectdbiterr, input [C_WR_PNTR_WIDTH_WDCH-1:0] axi_w_prog_full_thresh, input [C_WR_PNTR_WIDTH_WDCH-1:0] axi_w_prog_empty_thresh, output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_data_count, output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_wr_data_count, output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_rd_data_count, output axi_w_sbiterr, output axi_w_dbiterr, output axi_w_overflow, output axi_w_underflow, output axi_w_prog_full, output axi_w_prog_empty, // AXI Full/Lite Write Response Channel signals input axi_b_injectsbiterr, input axi_b_injectdbiterr, input [C_WR_PNTR_WIDTH_WRCH-1:0] axi_b_prog_full_thresh, input [C_WR_PNTR_WIDTH_WRCH-1:0] axi_b_prog_empty_thresh, output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_data_count, output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_wr_data_count, output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_rd_data_count, output axi_b_sbiterr, output axi_b_dbiterr, output axi_b_overflow, output axi_b_underflow, output axi_b_prog_full, output axi_b_prog_empty, // AXI Full/Lite Read Address Channel signals input axi_ar_injectsbiterr, input axi_ar_injectdbiterr, input [C_WR_PNTR_WIDTH_RACH-1:0] axi_ar_prog_full_thresh, input [C_WR_PNTR_WIDTH_RACH-1:0] axi_ar_prog_empty_thresh, output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_data_count, output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_wr_data_count, output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_rd_data_count, output axi_ar_sbiterr, output axi_ar_dbiterr, output axi_ar_overflow, output axi_ar_underflow, output axi_ar_prog_full, output axi_ar_prog_empty, // AXI Full/Lite Read Data Channel Signals input axi_r_injectsbiterr, input axi_r_injectdbiterr, input [C_WR_PNTR_WIDTH_RDCH-1:0] axi_r_prog_full_thresh, input [C_WR_PNTR_WIDTH_RDCH-1:0] axi_r_prog_empty_thresh, output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_data_count, output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_wr_data_count, output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_rd_data_count, output axi_r_sbiterr, output axi_r_dbiterr, output axi_r_overflow, output axi_r_underflow, output axi_r_prog_full, output axi_r_prog_empty, // AXI Streaming FIFO Related Signals input axis_injectsbiterr, input axis_injectdbiterr, input [C_WR_PNTR_WIDTH_AXIS-1:0] axis_prog_full_thresh, input [C_WR_PNTR_WIDTH_AXIS-1:0] axis_prog_empty_thresh, output [C_WR_PNTR_WIDTH_AXIS:0] axis_data_count, output [C_WR_PNTR_WIDTH_AXIS:0] axis_wr_data_count, output [C_WR_PNTR_WIDTH_AXIS:0] axis_rd_data_count, output axis_sbiterr, output axis_dbiterr, output axis_overflow, output axis_underflow, output axis_prog_full, output axis_prog_empty ); wire BACKUP; wire BACKUP_MARKER; wire CLK; wire RST; wire SRST; wire WR_CLK; wire WR_RST; wire RD_CLK; wire RD_RST; wire [C_DIN_WIDTH-1:0] DIN; wire WR_EN; wire RD_EN; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE; wire INT_CLK; wire INJECTDBITERR; wire INJECTSBITERR; wire SLEEP; wire [C_DOUT_WIDTH-1:0] DOUT; wire FULL; wire ALMOST_FULL; wire WR_ACK; wire OVERFLOW; wire EMPTY; wire ALMOST_EMPTY; wire VALID; wire UNDERFLOW; wire [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT; wire [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT; wire [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT; wire PROG_FULL; wire PROG_EMPTY; wire SBITERR; wire DBITERR; wire WR_RST_BUSY; wire RD_RST_BUSY; wire M_ACLK; wire S_ACLK; wire S_ARESETN; wire S_ACLK_EN; wire M_ACLK_EN; wire [C_AXI_ID_WIDTH-1:0] S_AXI_AWID; wire [C_AXI_ADDR_WIDTH-1:0] S_AXI_AWADDR; wire [C_AXI_LEN_WIDTH-1:0] S_AXI_AWLEN; wire [3-1:0] S_AXI_AWSIZE; wire [2-1:0] S_AXI_AWBURST; wire [C_AXI_LOCK_WIDTH-1:0] S_AXI_AWLOCK; wire [4-1:0] S_AXI_AWCACHE; wire [3-1:0] S_AXI_AWPROT; wire [4-1:0] S_AXI_AWQOS; wire [4-1:0] S_AXI_AWREGION; wire [C_AXI_AWUSER_WIDTH-1:0] S_AXI_AWUSER; wire S_AXI_AWVALID; wire S_AXI_AWREADY; wire [C_AXI_ID_WIDTH-1:0] S_AXI_WID; wire [C_AXI_DATA_WIDTH-1:0] S_AXI_WDATA; wire [C_AXI_DATA_WIDTH/8-1:0] S_AXI_WSTRB; wire S_AXI_WLAST; wire [C_AXI_WUSER_WIDTH-1:0] S_AXI_WUSER; wire S_AXI_WVALID; wire S_AXI_WREADY; wire [C_AXI_ID_WIDTH-1:0] S_AXI_BID; wire [2-1:0] S_AXI_BRESP; wire [C_AXI_BUSER_WIDTH-1:0] S_AXI_BUSER; wire S_AXI_BVALID; wire S_AXI_BREADY; wire [C_AXI_ID_WIDTH-1:0] M_AXI_AWID; wire [C_AXI_ADDR_WIDTH-1:0] M_AXI_AWADDR; wire [C_AXI_LEN_WIDTH-1:0] M_AXI_AWLEN; wire [3-1:0] M_AXI_AWSIZE; wire [2-1:0] M_AXI_AWBURST; wire [C_AXI_LOCK_WIDTH-1:0] M_AXI_AWLOCK; wire [4-1:0] M_AXI_AWCACHE; wire [3-1:0] M_AXI_AWPROT; wire [4-1:0] M_AXI_AWQOS; wire [4-1:0] M_AXI_AWREGION; wire [C_AXI_AWUSER_WIDTH-1:0] M_AXI_AWUSER; wire M_AXI_AWVALID; wire M_AXI_AWREADY; wire [C_AXI_ID_WIDTH-1:0] M_AXI_WID; wire [C_AXI_DATA_WIDTH-1:0] M_AXI_WDATA; wire [C_AXI_DATA_WIDTH/8-1:0] M_AXI_WSTRB; wire M_AXI_WLAST; wire [C_AXI_WUSER_WIDTH-1:0] M_AXI_WUSER; wire M_AXI_WVALID; wire M_AXI_WREADY; wire [C_AXI_ID_WIDTH-1:0] M_AXI_BID; wire [2-1:0] M_AXI_BRESP; wire [C_AXI_BUSER_WIDTH-1:0] M_AXI_BUSER; wire M_AXI_BVALID; wire M_AXI_BREADY; wire [C_AXI_ID_WIDTH-1:0] S_AXI_ARID; wire [C_AXI_ADDR_WIDTH-1:0] S_AXI_ARADDR; wire [C_AXI_LEN_WIDTH-1:0] S_AXI_ARLEN; wire [3-1:0] S_AXI_ARSIZE; wire [2-1:0] S_AXI_ARBURST; wire [C_AXI_LOCK_WIDTH-1:0] S_AXI_ARLOCK; wire [4-1:0] S_AXI_ARCACHE; wire [3-1:0] S_AXI_ARPROT; wire [4-1:0] S_AXI_ARQOS; wire [4-1:0] S_AXI_ARREGION; wire [C_AXI_ARUSER_WIDTH-1:0] S_AXI_ARUSER; wire S_AXI_ARVALID; wire S_AXI_ARREADY; wire [C_AXI_ID_WIDTH-1:0] S_AXI_RID; wire [C_AXI_DATA_WIDTH-1:0] S_AXI_RDATA; wire [2-1:0] S_AXI_RRESP; wire S_AXI_RLAST; wire [C_AXI_RUSER_WIDTH-1:0] S_AXI_RUSER; wire S_AXI_RVALID; wire S_AXI_RREADY; wire [C_AXI_ID_WIDTH-1:0] M_AXI_ARID; wire [C_AXI_ADDR_WIDTH-1:0] M_AXI_ARADDR; wire [C_AXI_LEN_WIDTH-1:0] M_AXI_ARLEN; wire [3-1:0] M_AXI_ARSIZE; wire [2-1:0] M_AXI_ARBURST; wire [C_AXI_LOCK_WIDTH-1:0] M_AXI_ARLOCK; wire [4-1:0] M_AXI_ARCACHE; wire [3-1:0] M_AXI_ARPROT; wire [4-1:0] M_AXI_ARQOS; wire [4-1:0] M_AXI_ARREGION; wire [C_AXI_ARUSER_WIDTH-1:0] M_AXI_ARUSER; wire M_AXI_ARVALID; wire M_AXI_ARREADY; wire [C_AXI_ID_WIDTH-1:0] M_AXI_RID; wire [C_AXI_DATA_WIDTH-1:0] M_AXI_RDATA; wire [2-1:0] M_AXI_RRESP; wire M_AXI_RLAST; wire [C_AXI_RUSER_WIDTH-1:0] M_AXI_RUSER; wire M_AXI_RVALID; wire M_AXI_RREADY; wire S_AXIS_TVALID; wire S_AXIS_TREADY; wire [C_AXIS_TDATA_WIDTH-1:0] S_AXIS_TDATA; wire [C_AXIS_TSTRB_WIDTH-1:0] S_AXIS_TSTRB; wire [C_AXIS_TKEEP_WIDTH-1:0] S_AXIS_TKEEP; wire S_AXIS_TLAST; wire [C_AXIS_TID_WIDTH-1:0] S_AXIS_TID; wire [C_AXIS_TDEST_WIDTH-1:0] S_AXIS_TDEST; wire [C_AXIS_TUSER_WIDTH-1:0] S_AXIS_TUSER; wire M_AXIS_TVALID; wire M_AXIS_TREADY; wire [C_AXIS_TDATA_WIDTH-1:0] M_AXIS_TDATA; wire [C_AXIS_TSTRB_WIDTH-1:0] M_AXIS_TSTRB; wire [C_AXIS_TKEEP_WIDTH-1:0] M_AXIS_TKEEP; wire M_AXIS_TLAST; wire [C_AXIS_TID_WIDTH-1:0] M_AXIS_TID; wire [C_AXIS_TDEST_WIDTH-1:0] M_AXIS_TDEST; wire [C_AXIS_TUSER_WIDTH-1:0] M_AXIS_TUSER; wire AXI_AW_INJECTSBITERR; wire AXI_AW_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_WACH-1:0] AXI_AW_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_WACH-1:0] AXI_AW_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_RD_DATA_COUNT; wire AXI_AW_SBITERR; wire AXI_AW_DBITERR; wire AXI_AW_OVERFLOW; wire AXI_AW_UNDERFLOW; wire AXI_AW_PROG_FULL; wire AXI_AW_PROG_EMPTY; wire AXI_W_INJECTSBITERR; wire AXI_W_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_WDCH-1:0] AXI_W_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_WDCH-1:0] AXI_W_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_RD_DATA_COUNT; wire AXI_W_SBITERR; wire AXI_W_DBITERR; wire AXI_W_OVERFLOW; wire AXI_W_UNDERFLOW; wire AXI_W_PROG_FULL; wire AXI_W_PROG_EMPTY; wire AXI_B_INJECTSBITERR; wire AXI_B_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_WRCH-1:0] AXI_B_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_WRCH-1:0] AXI_B_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_RD_DATA_COUNT; wire AXI_B_SBITERR; wire AXI_B_DBITERR; wire AXI_B_OVERFLOW; wire AXI_B_UNDERFLOW; wire AXI_B_PROG_FULL; wire AXI_B_PROG_EMPTY; wire AXI_AR_INJECTSBITERR; wire AXI_AR_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_RACH-1:0] AXI_AR_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_RACH-1:0] AXI_AR_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_RD_DATA_COUNT; wire AXI_AR_SBITERR; wire AXI_AR_DBITERR; wire AXI_AR_OVERFLOW; wire AXI_AR_UNDERFLOW; wire AXI_AR_PROG_FULL; wire AXI_AR_PROG_EMPTY; wire AXI_R_INJECTSBITERR; wire AXI_R_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_RDCH-1:0] AXI_R_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_RDCH-1:0] AXI_R_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_DATA_COUNT; wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_RD_DATA_COUNT; wire AXI_R_SBITERR; wire AXI_R_DBITERR; wire AXI_R_OVERFLOW; wire AXI_R_UNDERFLOW; wire AXI_R_PROG_FULL; wire AXI_R_PROG_EMPTY; wire AXIS_INJECTSBITERR; wire AXIS_INJECTDBITERR; wire [C_WR_PNTR_WIDTH_AXIS-1:0] AXIS_PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH_AXIS-1:0] AXIS_PROG_EMPTY_THRESH; wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_DATA_COUNT; wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_WR_DATA_COUNT; wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_RD_DATA_COUNT; wire AXIS_SBITERR; wire AXIS_DBITERR; wire AXIS_OVERFLOW; wire AXIS_UNDERFLOW; wire AXIS_PROG_FULL; wire AXIS_PROG_EMPTY; wire [C_WR_DATA_COUNT_WIDTH-1:0] wr_data_count_in; wire wr_rst_int; wire rd_rst_int; function integer find_log2; input integer int_val; integer i,j; begin i = 1; j = 0; for (i = 1; i < int_val; i = i*2) begin j = j + 1; end find_log2 = j; end endfunction // Conventional FIFO Interface Signals assign BACKUP = backup; assign BACKUP_MARKER = backup_marker; assign CLK = clk; assign RST = rst; assign SRST = srst; assign WR_CLK = wr_clk; assign WR_RST = wr_rst; assign RD_CLK = rd_clk; assign RD_RST = rd_rst; assign WR_EN = wr_en; assign RD_EN = rd_en; assign INT_CLK = int_clk; assign INJECTDBITERR = injectdbiterr; assign INJECTSBITERR = injectsbiterr; assign SLEEP = sleep; assign full = FULL; assign almost_full = ALMOST_FULL; assign wr_ack = WR_ACK; assign overflow = OVERFLOW; assign empty = EMPTY; assign almost_empty = ALMOST_EMPTY; assign valid = VALID; assign underflow = UNDERFLOW; assign prog_full = PROG_FULL; assign prog_empty = PROG_EMPTY; assign sbiterr = SBITERR; assign dbiterr = DBITERR; assign wr_rst_busy = WR_RST_BUSY; assign rd_rst_busy = RD_RST_BUSY; assign M_ACLK = m_aclk; assign S_ACLK = s_aclk; assign S_ARESETN = s_aresetn; assign S_ACLK_EN = s_aclk_en; assign M_ACLK_EN = m_aclk_en; assign S_AXI_AWVALID = s_axi_awvalid; assign s_axi_awready = S_AXI_AWREADY; assign S_AXI_WLAST = s_axi_wlast; assign S_AXI_WVALID = s_axi_wvalid; assign s_axi_wready = S_AXI_WREADY; assign s_axi_bvalid = S_AXI_BVALID; assign S_AXI_BREADY = s_axi_bready; assign m_axi_awvalid = M_AXI_AWVALID; assign M_AXI_AWREADY = m_axi_awready; assign m_axi_wlast = M_AXI_WLAST; assign m_axi_wvalid = M_AXI_WVALID; assign M_AXI_WREADY = m_axi_wready; assign M_AXI_BVALID = m_axi_bvalid; assign m_axi_bready = M_AXI_BREADY; assign S_AXI_ARVALID = s_axi_arvalid; assign s_axi_arready = S_AXI_ARREADY; assign s_axi_rlast = S_AXI_RLAST; assign s_axi_rvalid = S_AXI_RVALID; assign S_AXI_RREADY = s_axi_rready; assign m_axi_arvalid = M_AXI_ARVALID; assign M_AXI_ARREADY = m_axi_arready; assign M_AXI_RLAST = m_axi_rlast; assign M_AXI_RVALID = m_axi_rvalid; assign m_axi_rready = M_AXI_RREADY; assign S_AXIS_TVALID = s_axis_tvalid; assign s_axis_tready = S_AXIS_TREADY; assign S_AXIS_TLAST = s_axis_tlast; assign m_axis_tvalid = M_AXIS_TVALID; assign M_AXIS_TREADY = m_axis_tready; assign m_axis_tlast = M_AXIS_TLAST; assign AXI_AW_INJECTSBITERR = axi_aw_injectsbiterr; assign AXI_AW_INJECTDBITERR = axi_aw_injectdbiterr; assign axi_aw_sbiterr = AXI_AW_SBITERR; assign axi_aw_dbiterr = AXI_AW_DBITERR; assign axi_aw_overflow = AXI_AW_OVERFLOW; assign axi_aw_underflow = AXI_AW_UNDERFLOW; assign axi_aw_prog_full = AXI_AW_PROG_FULL; assign axi_aw_prog_empty = AXI_AW_PROG_EMPTY; assign AXI_W_INJECTSBITERR = axi_w_injectsbiterr; assign AXI_W_INJECTDBITERR = axi_w_injectdbiterr; assign axi_w_sbiterr = AXI_W_SBITERR; assign axi_w_dbiterr = AXI_W_DBITERR; assign axi_w_overflow = AXI_W_OVERFLOW; assign axi_w_underflow = AXI_W_UNDERFLOW; assign axi_w_prog_full = AXI_W_PROG_FULL; assign axi_w_prog_empty = AXI_W_PROG_EMPTY; assign AXI_B_INJECTSBITERR = axi_b_injectsbiterr; assign AXI_B_INJECTDBITERR = axi_b_injectdbiterr; assign axi_b_sbiterr = AXI_B_SBITERR; assign axi_b_dbiterr = AXI_B_DBITERR; assign axi_b_overflow = AXI_B_OVERFLOW; assign axi_b_underflow = AXI_B_UNDERFLOW; assign axi_b_prog_full = AXI_B_PROG_FULL; assign axi_b_prog_empty = AXI_B_PROG_EMPTY; assign AXI_AR_INJECTSBITERR = axi_ar_injectsbiterr; assign AXI_AR_INJECTDBITERR = axi_ar_injectdbiterr; assign axi_ar_sbiterr = AXI_AR_SBITERR; assign axi_ar_dbiterr = AXI_AR_DBITERR; assign axi_ar_overflow = AXI_AR_OVERFLOW; assign axi_ar_underflow = AXI_AR_UNDERFLOW; assign axi_ar_prog_full = AXI_AR_PROG_FULL; assign axi_ar_prog_empty = AXI_AR_PROG_EMPTY; assign AXI_R_INJECTSBITERR = axi_r_injectsbiterr; assign AXI_R_INJECTDBITERR = axi_r_injectdbiterr; assign axi_r_sbiterr = AXI_R_SBITERR; assign axi_r_dbiterr = AXI_R_DBITERR; assign axi_r_overflow = AXI_R_OVERFLOW; assign axi_r_underflow = AXI_R_UNDERFLOW; assign axi_r_prog_full = AXI_R_PROG_FULL; assign axi_r_prog_empty = AXI_R_PROG_EMPTY; assign AXIS_INJECTSBITERR = axis_injectsbiterr; assign AXIS_INJECTDBITERR = axis_injectdbiterr; assign axis_sbiterr = AXIS_SBITERR; assign axis_dbiterr = AXIS_DBITERR; assign axis_overflow = AXIS_OVERFLOW; assign axis_underflow = AXIS_UNDERFLOW; assign axis_prog_full = AXIS_PROG_FULL; assign axis_prog_empty = AXIS_PROG_EMPTY; assign DIN = din; assign PROG_EMPTY_THRESH = prog_empty_thresh; assign PROG_EMPTY_THRESH_ASSERT = prog_empty_thresh_assert; assign PROG_EMPTY_THRESH_NEGATE = prog_empty_thresh_negate; assign PROG_FULL_THRESH = prog_full_thresh; assign PROG_FULL_THRESH_ASSERT = prog_full_thresh_assert; assign PROG_FULL_THRESH_NEGATE = prog_full_thresh_negate; assign dout = DOUT; assign data_count = DATA_COUNT; assign rd_data_count = RD_DATA_COUNT; assign wr_data_count = WR_DATA_COUNT; assign S_AXI_AWID = s_axi_awid; assign S_AXI_AWADDR = s_axi_awaddr; assign S_AXI_AWLEN = s_axi_awlen; assign S_AXI_AWSIZE = s_axi_awsize; assign S_AXI_AWBURST = s_axi_awburst; assign S_AXI_AWLOCK = s_axi_awlock; assign S_AXI_AWCACHE = s_axi_awcache; assign S_AXI_AWPROT = s_axi_awprot; assign S_AXI_AWQOS = s_axi_awqos; assign S_AXI_AWREGION = s_axi_awregion; assign S_AXI_AWUSER = s_axi_awuser; assign S_AXI_WID = s_axi_wid; assign S_AXI_WDATA = s_axi_wdata; assign S_AXI_WSTRB = s_axi_wstrb; assign S_AXI_WUSER = s_axi_wuser; assign s_axi_bid = S_AXI_BID; assign s_axi_bresp = S_AXI_BRESP; assign s_axi_buser = S_AXI_BUSER; assign m_axi_awid = M_AXI_AWID; assign m_axi_awaddr = M_AXI_AWADDR; assign m_axi_awlen = M_AXI_AWLEN; assign m_axi_awsize = M_AXI_AWSIZE; assign m_axi_awburst = M_AXI_AWBURST; assign m_axi_awlock = M_AXI_AWLOCK; assign m_axi_awcache = M_AXI_AWCACHE; assign m_axi_awprot = M_AXI_AWPROT; assign m_axi_awqos = M_AXI_AWQOS; assign m_axi_awregion = M_AXI_AWREGION; assign m_axi_awuser = M_AXI_AWUSER; assign m_axi_wid = M_AXI_WID; assign m_axi_wdata = M_AXI_WDATA; assign m_axi_wstrb = M_AXI_WSTRB; assign m_axi_wuser = M_AXI_WUSER; assign M_AXI_BID = m_axi_bid; assign M_AXI_BRESP = m_axi_bresp; assign M_AXI_BUSER = m_axi_buser; assign S_AXI_ARID = s_axi_arid; assign S_AXI_ARADDR = s_axi_araddr; assign S_AXI_ARLEN = s_axi_arlen; assign S_AXI_ARSIZE = s_axi_arsize; assign S_AXI_ARBURST = s_axi_arburst; assign S_AXI_ARLOCK = s_axi_arlock; assign S_AXI_ARCACHE = s_axi_arcache; assign S_AXI_ARPROT = s_axi_arprot; assign S_AXI_ARQOS = s_axi_arqos; assign S_AXI_ARREGION = s_axi_arregion; assign S_AXI_ARUSER = s_axi_aruser; assign s_axi_rid = S_AXI_RID; assign s_axi_rdata = S_AXI_RDATA; assign s_axi_rresp = S_AXI_RRESP; assign s_axi_ruser = S_AXI_RUSER; assign m_axi_arid = M_AXI_ARID; assign m_axi_araddr = M_AXI_ARADDR; assign m_axi_arlen = M_AXI_ARLEN; assign m_axi_arsize = M_AXI_ARSIZE; assign m_axi_arburst = M_AXI_ARBURST; assign m_axi_arlock = M_AXI_ARLOCK; assign m_axi_arcache = M_AXI_ARCACHE; assign m_axi_arprot = M_AXI_ARPROT; assign m_axi_arqos = M_AXI_ARQOS; assign m_axi_arregion = M_AXI_ARREGION; assign m_axi_aruser = M_AXI_ARUSER; assign M_AXI_RID = m_axi_rid; assign M_AXI_RDATA = m_axi_rdata; assign M_AXI_RRESP = m_axi_rresp; assign M_AXI_RUSER = m_axi_ruser; assign S_AXIS_TDATA = s_axis_tdata; assign S_AXIS_TSTRB = s_axis_tstrb; assign S_AXIS_TKEEP = s_axis_tkeep; assign S_AXIS_TID = s_axis_tid; assign S_AXIS_TDEST = s_axis_tdest; assign S_AXIS_TUSER = s_axis_tuser; assign m_axis_tdata = M_AXIS_TDATA; assign m_axis_tstrb = M_AXIS_TSTRB; assign m_axis_tkeep = M_AXIS_TKEEP; assign m_axis_tid = M_AXIS_TID; assign m_axis_tdest = M_AXIS_TDEST; assign m_axis_tuser = M_AXIS_TUSER; assign AXI_AW_PROG_FULL_THRESH = axi_aw_prog_full_thresh; assign AXI_AW_PROG_EMPTY_THRESH = axi_aw_prog_empty_thresh; assign axi_aw_data_count = AXI_AW_DATA_COUNT; assign axi_aw_wr_data_count = AXI_AW_WR_DATA_COUNT; assign axi_aw_rd_data_count = AXI_AW_RD_DATA_COUNT; assign AXI_W_PROG_FULL_THRESH = axi_w_prog_full_thresh; assign AXI_W_PROG_EMPTY_THRESH = axi_w_prog_empty_thresh; assign axi_w_data_count = AXI_W_DATA_COUNT; assign axi_w_wr_data_count = AXI_W_WR_DATA_COUNT; assign axi_w_rd_data_count = AXI_W_RD_DATA_COUNT; assign AXI_B_PROG_FULL_THRESH = axi_b_prog_full_thresh; assign AXI_B_PROG_EMPTY_THRESH = axi_b_prog_empty_thresh; assign axi_b_data_count = AXI_B_DATA_COUNT; assign axi_b_wr_data_count = AXI_B_WR_DATA_COUNT; assign axi_b_rd_data_count = AXI_B_RD_DATA_COUNT; assign AXI_AR_PROG_FULL_THRESH = axi_ar_prog_full_thresh; assign AXI_AR_PROG_EMPTY_THRESH = axi_ar_prog_empty_thresh; assign axi_ar_data_count = AXI_AR_DATA_COUNT; assign axi_ar_wr_data_count = AXI_AR_WR_DATA_COUNT; assign axi_ar_rd_data_count = AXI_AR_RD_DATA_COUNT; assign AXI_R_PROG_FULL_THRESH = axi_r_prog_full_thresh; assign AXI_R_PROG_EMPTY_THRESH = axi_r_prog_empty_thresh; assign axi_r_data_count = AXI_R_DATA_COUNT; assign axi_r_wr_data_count = AXI_R_WR_DATA_COUNT; assign axi_r_rd_data_count = AXI_R_RD_DATA_COUNT; assign AXIS_PROG_FULL_THRESH = axis_prog_full_thresh; assign AXIS_PROG_EMPTY_THRESH = axis_prog_empty_thresh; assign axis_data_count = AXIS_DATA_COUNT; assign axis_wr_data_count = AXIS_WR_DATA_COUNT; assign axis_rd_data_count = AXIS_RD_DATA_COUNT; generate if (C_INTERFACE_TYPE == 0) begin : conv_fifo fifo_generator_v13_1_1_CONV_VER #( .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_DIN_WIDTH (C_DIN_WIDTH), .C_DOUT_RST_VAL (C_USE_DOUT_RST == 1 ? C_DOUT_RST_VAL : 0), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_FAMILY (C_FAMILY), .C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL), .C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY), .C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_DATA_COUNT (C_HAS_DATA_COUNT), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT), .C_HAS_RD_RST (C_HAS_RD_RST), .C_HAS_RST (C_HAS_RST), .C_HAS_SRST (C_HAS_SRST), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_HAS_VALID (C_HAS_VALID), .C_HAS_WR_ACK (C_HAS_WR_ACK), .C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT), .C_HAS_WR_RST (C_HAS_WR_RST), .C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_PRELOAD_LATENCY (C_PRELOAD_LATENCY), .C_PRELOAD_REGS (C_PRELOAD_REGS), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL), .C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL), .C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE), .C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH), .C_RD_DEPTH (C_RD_DEPTH), .C_RD_FREQ (C_RD_FREQ), .C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_ECC (C_USE_ECC), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT), .C_VALID_LOW (C_VALID_LOW), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH), .C_WR_DEPTH (C_WR_DEPTH), .C_WR_FREQ (C_WR_FREQ), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE), .C_AXI_TYPE (C_AXI_TYPE), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE) ) fifo_generator_v13_1_1_conv_dut ( .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .CLK (CLK), .RST (RST), .SRST (SRST), .WR_CLK (WR_CLK), .WR_RST (WR_RST), .RD_CLK (RD_CLK), .RD_RST (RD_RST), .DIN (DIN), .WR_EN (WR_EN), .RD_EN (RD_EN), .PROG_EMPTY_THRESH (PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT (PROG_EMPTY_THRESH_ASSERT), .PROG_EMPTY_THRESH_NEGATE (PROG_EMPTY_THRESH_NEGATE), .PROG_FULL_THRESH (PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT (PROG_FULL_THRESH_ASSERT), .PROG_FULL_THRESH_NEGATE (PROG_FULL_THRESH_NEGATE), .INT_CLK (INT_CLK), .INJECTDBITERR (INJECTDBITERR), .INJECTSBITERR (INJECTSBITERR), .DOUT (DOUT), .FULL (FULL), .ALMOST_FULL (ALMOST_FULL), .WR_ACK (WR_ACK), .OVERFLOW (OVERFLOW), .EMPTY (EMPTY), .ALMOST_EMPTY (ALMOST_EMPTY), .VALID (VALID), .UNDERFLOW (UNDERFLOW), .DATA_COUNT (DATA_COUNT), .RD_DATA_COUNT (RD_DATA_COUNT), .WR_DATA_COUNT (wr_data_count_in), .PROG_FULL (PROG_FULL), .PROG_EMPTY (PROG_EMPTY), .SBITERR (SBITERR), .DBITERR (DBITERR), .wr_rst_busy (wr_rst_busy), .rd_rst_busy (rd_rst_busy), .wr_rst_i_out (wr_rst_int), .rd_rst_i_out (rd_rst_int) ); end endgenerate localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexuplus" || C_FAMILY == "zynquplus" || C_FAMILY == "kintexuplus") ? 1 : 0; localparam C_AXI_SIZE_WIDTH = 3; localparam C_AXI_BURST_WIDTH = 2; localparam C_AXI_CACHE_WIDTH = 4; localparam C_AXI_PROT_WIDTH = 3; localparam C_AXI_QOS_WIDTH = 4; localparam C_AXI_REGION_WIDTH = 4; localparam C_AXI_BRESP_WIDTH = 2; localparam C_AXI_RRESP_WIDTH = 2; localparam IS_AXI_STREAMING = C_INTERFACE_TYPE == 1 ? 1 : 0; localparam TDATA_OFFSET = C_HAS_AXIS_TDATA == 1 ? C_DIN_WIDTH_AXIS-C_AXIS_TDATA_WIDTH : C_DIN_WIDTH_AXIS; localparam TSTRB_OFFSET = C_HAS_AXIS_TSTRB == 1 ? TDATA_OFFSET-C_AXIS_TSTRB_WIDTH : TDATA_OFFSET; localparam TKEEP_OFFSET = C_HAS_AXIS_TKEEP == 1 ? TSTRB_OFFSET-C_AXIS_TKEEP_WIDTH : TSTRB_OFFSET; localparam TID_OFFSET = C_HAS_AXIS_TID == 1 ? TKEEP_OFFSET-C_AXIS_TID_WIDTH : TKEEP_OFFSET; localparam TDEST_OFFSET = C_HAS_AXIS_TDEST == 1 ? TID_OFFSET-C_AXIS_TDEST_WIDTH : TID_OFFSET; localparam TUSER_OFFSET = C_HAS_AXIS_TUSER == 1 ? TDEST_OFFSET-C_AXIS_TUSER_WIDTH : TDEST_OFFSET; localparam LOG_DEPTH_AXIS = find_log2(C_WR_DEPTH_AXIS); localparam LOG_WR_DEPTH = find_log2(C_WR_DEPTH); function [LOG_DEPTH_AXIS-1:0] bin2gray; input [LOG_DEPTH_AXIS-1:0] x; begin bin2gray = x ^ (x>>1); end endfunction function [LOG_DEPTH_AXIS-1:0] gray2bin; input [LOG_DEPTH_AXIS-1:0] x; integer i; begin gray2bin[LOG_DEPTH_AXIS-1] = x[LOG_DEPTH_AXIS-1]; for(i=LOG_DEPTH_AXIS-2; i>=0; i=i-1) begin gray2bin[i] = gray2bin[i+1] ^ x[i]; end end endfunction wire [(LOG_WR_DEPTH)-1 : 0] w_cnt_gc_asreg_last; wire [LOG_WR_DEPTH-1 : 0] w_q [0:C_SYNCHRONIZER_STAGE] ; wire [LOG_WR_DEPTH-1 : 0] w_q_temp [1:C_SYNCHRONIZER_STAGE] ; reg [LOG_WR_DEPTH-1 : 0] w_cnt_rd = 0; reg [LOG_WR_DEPTH-1 : 0] w_cnt = 0; reg [LOG_WR_DEPTH-1 : 0] w_cnt_gc = 0; reg [LOG_WR_DEPTH-1 : 0] r_cnt = 0; wire [LOG_WR_DEPTH : 0] adj_w_cnt_rd_pad; wire [LOG_WR_DEPTH : 0] r_inv_pad; wire [LOG_WR_DEPTH-1 : 0] d_cnt; reg [LOG_WR_DEPTH : 0] d_cnt_pad = 0; reg adj_w_cnt_rd_pad_0 = 0; reg r_inv_pad_0 = 0; genvar l; generate for (l = 1; ((l <= C_SYNCHRONIZER_STAGE) && (C_HAS_DATA_COUNTS_AXIS == 3 && C_INTERFACE_TYPE == 0) ); l = l + 1) begin : g_cnt_sync_stage fifo_generator_v13_1_1_sync_stage #( .C_WIDTH (LOG_WR_DEPTH) ) rd_stg_inst ( .RST (rd_rst_int), .CLK (RD_CLK), .DIN (w_q[l-1]), .DOUT (w_q[l]) ); end endgenerate // gpkt_cnt_sync_stage generate if (C_INTERFACE_TYPE == 0 && C_HAS_DATA_COUNTS_AXIS == 3) begin : fifo_ic_adapter assign wr_eop_ad = WR_EN & !(FULL); assign rd_eop_ad = RD_EN & !(EMPTY); always @ (posedge wr_rst_int or posedge WR_CLK) begin if (wr_rst_int) w_cnt <= 1'b0; else if (wr_eop_ad) w_cnt <= w_cnt + 1; end always @ (posedge wr_rst_int or posedge WR_CLK) begin if (wr_rst_int) w_cnt_gc <= 1'b0; else w_cnt_gc <= bin2gray(w_cnt); end assign w_q[0] = w_cnt_gc; assign w_cnt_gc_asreg_last = w_q[C_SYNCHRONIZER_STAGE]; always @ (posedge rd_rst_int or posedge RD_CLK) begin if (rd_rst_int) w_cnt_rd <= 1'b0; else w_cnt_rd <= gray2bin(w_cnt_gc_asreg_last); end always @ (posedge rd_rst_int or posedge RD_CLK) begin if (rd_rst_int) r_cnt <= 1'b0; else if (rd_eop_ad) r_cnt <= r_cnt + 1; end // Take the difference of write and read packet count // Logic is similar to rd_pe_as assign adj_w_cnt_rd_pad[LOG_WR_DEPTH : 1] = w_cnt_rd; assign r_inv_pad[LOG_WR_DEPTH : 1] = ~r_cnt; assign adj_w_cnt_rd_pad[0] = adj_w_cnt_rd_pad_0; assign r_inv_pad[0] = r_inv_pad_0; always @ ( rd_eop_ad ) begin if (!rd_eop_ad) begin adj_w_cnt_rd_pad_0 <= 1'b1; r_inv_pad_0 <= 1'b1; end else begin adj_w_cnt_rd_pad_0 <= 1'b0; r_inv_pad_0 <= 1'b0; end end always @ (posedge rd_rst_int or posedge RD_CLK) begin if (rd_rst_int) d_cnt_pad <= 1'b0; else d_cnt_pad <= adj_w_cnt_rd_pad + r_inv_pad ; end assign d_cnt = d_cnt_pad [LOG_WR_DEPTH : 1] ; assign WR_DATA_COUNT = d_cnt; end endgenerate // fifo_ic_adapter generate if (C_INTERFACE_TYPE == 0 && C_HAS_DATA_COUNTS_AXIS != 3) begin : fifo_icn_adapter assign WR_DATA_COUNT = wr_data_count_in; end endgenerate // fifo_icn_adapter wire inverted_reset = ~S_ARESETN; wire axi_rs_rst; reg rst_d1 = 0 ; reg rst_d2 = 0 ; wire [C_DIN_WIDTH_AXIS-1:0] axis_din ; wire [C_DIN_WIDTH_AXIS-1:0] axis_dout ; wire axis_full ; wire axis_almost_full ; wire axis_empty ; wire axis_s_axis_tready; wire axis_m_axis_tvalid; wire axis_wr_en ; wire axis_rd_en ; wire axis_we ; wire axis_re ; wire [C_WR_PNTR_WIDTH_AXIS:0] axis_dc; reg axis_pkt_read = 1'b0; wire axis_rd_rst; wire axis_wr_rst; generate if (C_INTERFACE_TYPE > 0 && (C_AXIS_TYPE == 1 || C_WACH_TYPE == 1 || C_WDCH_TYPE == 1 || C_WRCH_TYPE == 1 || C_RACH_TYPE == 1 || C_RDCH_TYPE == 1)) begin : gaxi_rs_rst always @ (posedge inverted_reset or posedge S_ACLK) begin if (inverted_reset) begin rst_d1 <= 1'b1; rst_d2 <= 1'b1; end else begin rst_d1 <= #`TCQ 1'b0; rst_d2 <= #`TCQ rst_d1; end end assign axi_rs_rst = rst_d2; end endgenerate // gaxi_rs_rst generate if (IS_AXI_STREAMING == 1 && C_AXIS_TYPE == 0) begin : axi_streaming // Write protection when almost full or prog_full is high assign axis_we = (C_PROG_FULL_TYPE_AXIS != 0) ? axis_s_axis_tready & S_AXIS_TVALID : (C_APPLICATION_TYPE_AXIS == 1) ? axis_s_axis_tready & S_AXIS_TVALID : S_AXIS_TVALID; // Read protection when almost empty or prog_empty is high assign axis_re = (C_PROG_EMPTY_TYPE_AXIS != 0) ? axis_m_axis_tvalid & M_AXIS_TREADY : (C_APPLICATION_TYPE_AXIS == 1) ? axis_m_axis_tvalid & M_AXIS_TREADY : M_AXIS_TREADY; assign axis_wr_en = (C_HAS_SLAVE_CE == 1) ? axis_we & S_ACLK_EN : axis_we; assign axis_rd_en = (C_HAS_MASTER_CE == 1) ? axis_re & M_ACLK_EN : axis_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_AXIS == 1 || C_IMPLEMENTATION_TYPE_AXIS == 11) ? 1 : (C_IMPLEMENTATION_TYPE_AXIS == 2 || C_IMPLEMENTATION_TYPE_AXIS == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_AXIS == 1 || C_IMPLEMENTATION_TYPE_AXIS == 2) ? 0 : (C_IMPLEMENTATION_TYPE_AXIS == 11 || C_IMPLEMENTATION_TYPE_AXIS == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_AXIS), .C_WR_DEPTH (C_WR_DEPTH_AXIS), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_AXIS), .C_DOUT_WIDTH (C_DIN_WIDTH_AXIS), .C_RD_DEPTH (C_WR_DEPTH_AXIS), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_AXIS), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_AXIS), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_AXIS), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_AXIS), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_AXIS), .C_USE_ECC (C_USE_ECC_AXIS), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_AXIS), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (C_APPLICATION_TYPE_AXIS == 1 ? 1: 0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), //.C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_FIFO_TYPE (C_APPLICATION_TYPE_AXIS == 1 ? 0: C_APPLICATION_TYPE_AXIS), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), .C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_axis_dut ( .CLK (S_ACLK), .WR_CLK (S_ACLK), .RD_CLK (M_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (axis_wr_en), .RD_EN (axis_rd_en), .PROG_FULL_THRESH (AXIS_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_AXIS{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_AXIS{1'b0}}), .PROG_EMPTY_THRESH (AXIS_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_AXIS{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_AXIS{1'b0}}), .INJECTDBITERR (AXIS_INJECTDBITERR), .INJECTSBITERR (AXIS_INJECTSBITERR), .DIN (axis_din), .DOUT (axis_dout), .FULL (axis_full), .EMPTY (axis_empty), .ALMOST_FULL (axis_almost_full), .PROG_FULL (AXIS_PROG_FULL), .ALMOST_EMPTY (), .PROG_EMPTY (AXIS_PROG_EMPTY), .WR_ACK (), .OVERFLOW (AXIS_OVERFLOW), .VALID (), .UNDERFLOW (AXIS_UNDERFLOW), .DATA_COUNT (axis_dc), .RD_DATA_COUNT (AXIS_RD_DATA_COUNT), .WR_DATA_COUNT (AXIS_WR_DATA_COUNT), .SBITERR (AXIS_SBITERR), .DBITERR (AXIS_DBITERR), .wr_rst_busy (wr_rst_busy_axis), .rd_rst_busy (rd_rst_busy_axis), .wr_rst_i_out (axis_wr_rst), .rd_rst_i_out (axis_rd_rst), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign axis_s_axis_tready = (IS_8SERIES == 0) ? ~axis_full : (C_IMPLEMENTATION_TYPE_AXIS == 5 || C_IMPLEMENTATION_TYPE_AXIS == 13) ? ~(axis_full | wr_rst_busy_axis) : ~axis_full; assign axis_m_axis_tvalid = (C_APPLICATION_TYPE_AXIS != 1) ? ~axis_empty : ~axis_empty & axis_pkt_read; assign S_AXIS_TREADY = axis_s_axis_tready; assign M_AXIS_TVALID = axis_m_axis_tvalid; end endgenerate // axi_streaming wire axis_wr_eop; reg axis_wr_eop_d1 = 1'b0; wire axis_rd_eop; integer axis_pkt_cnt; generate if (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 1) begin : gaxis_pkt_fifo_cc assign axis_wr_eop = axis_wr_en & S_AXIS_TLAST; assign axis_rd_eop = axis_rd_en & axis_dout[0]; always @ (posedge inverted_reset or posedge S_ACLK) begin if (inverted_reset) axis_pkt_read <= 1'b0; else if (axis_rd_eop && (axis_pkt_cnt == 1) && ~axis_wr_eop_d1) axis_pkt_read <= 1'b0; else if ((axis_pkt_cnt > 0) || (axis_almost_full && ~axis_empty)) axis_pkt_read <= 1'b1; end always @ (posedge inverted_reset or posedge S_ACLK) begin if (inverted_reset) axis_wr_eop_d1 <= 1'b0; else axis_wr_eop_d1 <= axis_wr_eop; end always @ (posedge inverted_reset or posedge S_ACLK) begin if (inverted_reset) axis_pkt_cnt <= 0; else if (axis_wr_eop_d1 && ~axis_rd_eop) axis_pkt_cnt <= axis_pkt_cnt + 1; else if (axis_rd_eop && ~axis_wr_eop_d1) axis_pkt_cnt <= axis_pkt_cnt - 1; end end endgenerate // gaxis_pkt_fifo_cc reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt_gc = 0; wire [(LOG_DEPTH_AXIS)-1 : 0] axis_wpkt_cnt_gc_asreg_last; wire axis_rd_has_rst; wire [0:C_SYNCHRONIZER_STAGE] axis_af_q ; wire [LOG_DEPTH_AXIS-1 : 0] wpkt_q [0:C_SYNCHRONIZER_STAGE] ; wire [1:C_SYNCHRONIZER_STAGE] axis_af_q_temp = 0; wire [LOG_DEPTH_AXIS-1 : 0] wpkt_q_temp [1:C_SYNCHRONIZER_STAGE] ; reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt_rd = 0; reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt = 0; reg [LOG_DEPTH_AXIS-1 : 0] axis_rpkt_cnt = 0; wire [LOG_DEPTH_AXIS : 0] adj_axis_wpkt_cnt_rd_pad; wire [LOG_DEPTH_AXIS : 0] rpkt_inv_pad; wire [LOG_DEPTH_AXIS-1 : 0] diff_pkt_cnt; reg [LOG_DEPTH_AXIS : 0] diff_pkt_cnt_pad = 0; reg adj_axis_wpkt_cnt_rd_pad_0 = 0; reg rpkt_inv_pad_0 = 0; wire axis_af_rd ; generate if (C_HAS_RST == 1) begin : rst_blk_has assign axis_rd_has_rst = axis_rd_rst; end endgenerate //rst_blk_has generate if (C_HAS_RST == 0) begin :rst_blk_no assign axis_rd_has_rst = 1'b0; end endgenerate //rst_blk_no genvar i; generate for (i = 1; ((i <= C_SYNCHRONIZER_STAGE) && (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 0) ); i = i + 1) begin : gpkt_cnt_sync_stage fifo_generator_v13_1_1_sync_stage #( .C_WIDTH (LOG_DEPTH_AXIS) ) rd_stg_inst ( .RST (axis_rd_has_rst), .CLK (M_ACLK), .DIN (wpkt_q[i-1]), .DOUT (wpkt_q[i]) ); fifo_generator_v13_1_1_sync_stage #( .C_WIDTH (1) ) wr_stg_inst ( .RST (axis_rd_has_rst), .CLK (M_ACLK), .DIN (axis_af_q[i-1]), .DOUT (axis_af_q[i]) ); end endgenerate // gpkt_cnt_sync_stage generate if (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 0) begin : gaxis_pkt_fifo_ic assign axis_wr_eop = axis_wr_en & S_AXIS_TLAST; assign axis_rd_eop = axis_rd_en & axis_dout[0]; always @ (posedge axis_rd_has_rst or posedge M_ACLK) begin if (axis_rd_has_rst) axis_pkt_read <= 1'b0; else if (axis_rd_eop && (diff_pkt_cnt == 1)) axis_pkt_read <= 1'b0; else if ((diff_pkt_cnt > 0) || (axis_af_rd && ~axis_empty)) axis_pkt_read <= 1'b1; end always @ (posedge axis_wr_rst or posedge S_ACLK) begin if (axis_wr_rst) axis_wpkt_cnt <= 1'b0; else if (axis_wr_eop) axis_wpkt_cnt <= axis_wpkt_cnt + 1; end always @ (posedge axis_wr_rst or posedge S_ACLK) begin if (axis_wr_rst) axis_wpkt_cnt_gc <= 1'b0; else axis_wpkt_cnt_gc <= bin2gray(axis_wpkt_cnt); end assign wpkt_q[0] = axis_wpkt_cnt_gc; assign axis_wpkt_cnt_gc_asreg_last = wpkt_q[C_SYNCHRONIZER_STAGE]; assign axis_af_q[0] = axis_almost_full; //assign axis_af_q[1:C_SYNCHRONIZER_STAGE] = axis_af_q_temp[1:C_SYNCHRONIZER_STAGE]; assign axis_af_rd = axis_af_q[C_SYNCHRONIZER_STAGE]; always @ (posedge axis_rd_has_rst or posedge M_ACLK) begin if (axis_rd_has_rst) axis_wpkt_cnt_rd <= 1'b0; else axis_wpkt_cnt_rd <= gray2bin(axis_wpkt_cnt_gc_asreg_last); end always @ (posedge axis_rd_rst or posedge M_ACLK) begin if (axis_rd_has_rst) axis_rpkt_cnt <= 1'b0; else if (axis_rd_eop) axis_rpkt_cnt <= axis_rpkt_cnt + 1; end // Take the difference of write and read packet count // Logic is similar to rd_pe_as assign adj_axis_wpkt_cnt_rd_pad[LOG_DEPTH_AXIS : 1] = axis_wpkt_cnt_rd; assign rpkt_inv_pad[LOG_DEPTH_AXIS : 1] = ~axis_rpkt_cnt; assign adj_axis_wpkt_cnt_rd_pad[0] = adj_axis_wpkt_cnt_rd_pad_0; assign rpkt_inv_pad[0] = rpkt_inv_pad_0; always @ ( axis_rd_eop ) begin if (!axis_rd_eop) begin adj_axis_wpkt_cnt_rd_pad_0 <= 1'b1; rpkt_inv_pad_0 <= 1'b1; end else begin adj_axis_wpkt_cnt_rd_pad_0 <= 1'b0; rpkt_inv_pad_0 <= 1'b0; end end always @ (posedge axis_rd_rst or posedge M_ACLK) begin if (axis_rd_has_rst) diff_pkt_cnt_pad <= 1'b0; else diff_pkt_cnt_pad <= adj_axis_wpkt_cnt_rd_pad + rpkt_inv_pad ; end assign diff_pkt_cnt = diff_pkt_cnt_pad [LOG_DEPTH_AXIS : 1] ; end endgenerate // gaxis_pkt_fifo_ic // Generate the accurate data count for axi stream packet fifo configuration reg [C_WR_PNTR_WIDTH_AXIS:0] axis_dc_pkt_fifo = 0; generate if (IS_AXI_STREAMING == 1 && C_HAS_DATA_COUNTS_AXIS == 1 && C_APPLICATION_TYPE_AXIS == 1) begin : gdc_pkt always @ (posedge inverted_reset or posedge S_ACLK) begin if (inverted_reset) axis_dc_pkt_fifo <= 0; else if (axis_wr_en && (~axis_rd_en)) axis_dc_pkt_fifo <= #`TCQ axis_dc_pkt_fifo + 1; else if (~axis_wr_en && axis_rd_en) axis_dc_pkt_fifo <= #`TCQ axis_dc_pkt_fifo - 1; end assign AXIS_DATA_COUNT = axis_dc_pkt_fifo; end endgenerate // gdc_pkt generate if (IS_AXI_STREAMING == 1 && C_HAS_DATA_COUNTS_AXIS == 0 && C_APPLICATION_TYPE_AXIS == 1) begin : gndc_pkt assign AXIS_DATA_COUNT = 0; end endgenerate // gndc_pkt generate if (IS_AXI_STREAMING == 1 && C_APPLICATION_TYPE_AXIS != 1) begin : gdc assign AXIS_DATA_COUNT = axis_dc; end endgenerate // gdc // Register Slice for Write Address Channel generate if (C_AXIS_TYPE == 1) begin : gaxis_reg_slice assign axis_wr_en = (C_HAS_SLAVE_CE == 1) ? S_AXIS_TVALID & S_ACLK_EN : S_AXIS_TVALID; assign axis_rd_en = (C_HAS_MASTER_CE == 1) ? M_AXIS_TREADY & M_ACLK_EN : M_AXIS_TREADY; fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_AXIS), .C_REG_CONFIG (C_REG_SLICE_MODE_AXIS) ) axis_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (axis_din), .S_VALID (axis_wr_en), .S_READY (S_AXIS_TREADY), // Master side .M_PAYLOAD_DATA (axis_dout), .M_VALID (M_AXIS_TVALID), .M_READY (axis_rd_en) ); end endgenerate // gaxis_reg_slice generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TDATA == 1) begin : tdata assign axis_din[C_DIN_WIDTH_AXIS-1:TDATA_OFFSET] = S_AXIS_TDATA; assign M_AXIS_TDATA = axis_dout[C_DIN_WIDTH_AXIS-1:TDATA_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TSTRB == 1) begin : tstrb assign axis_din[TDATA_OFFSET-1:TSTRB_OFFSET] = S_AXIS_TSTRB; assign M_AXIS_TSTRB = axis_dout[TDATA_OFFSET-1:TSTRB_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TKEEP == 1) begin : tkeep assign axis_din[TSTRB_OFFSET-1:TKEEP_OFFSET] = S_AXIS_TKEEP; assign M_AXIS_TKEEP = axis_dout[TSTRB_OFFSET-1:TKEEP_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TID == 1) begin : tid assign axis_din[TKEEP_OFFSET-1:TID_OFFSET] = S_AXIS_TID; assign M_AXIS_TID = axis_dout[TKEEP_OFFSET-1:TID_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TDEST == 1) begin : tdest assign axis_din[TID_OFFSET-1:TDEST_OFFSET] = S_AXIS_TDEST; assign M_AXIS_TDEST = axis_dout[TID_OFFSET-1:TDEST_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TUSER == 1) begin : tuser assign axis_din[TDEST_OFFSET-1:TUSER_OFFSET] = S_AXIS_TUSER; assign M_AXIS_TUSER = axis_dout[TDEST_OFFSET-1:TUSER_OFFSET]; end endgenerate generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TLAST == 1) begin : tlast assign axis_din[0] = S_AXIS_TLAST; assign M_AXIS_TLAST = axis_dout[0]; end endgenerate //########################################################################### // AXI FULL Write Channel (axi_write_channel) //########################################################################### localparam IS_AXI_FULL = ((C_INTERFACE_TYPE == 2) && (C_AXI_TYPE != 2)) ? 1 : 0; localparam IS_AXI_LITE = ((C_INTERFACE_TYPE == 2) && (C_AXI_TYPE == 2)) ? 1 : 0; localparam IS_AXI_FULL_WACH = ((IS_AXI_FULL == 1) && (C_WACH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_FULL_WDCH = ((IS_AXI_FULL == 1) && (C_WDCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_FULL_WRCH = ((IS_AXI_FULL == 1) && (C_WRCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_FULL_RACH = ((IS_AXI_FULL == 1) && (C_RACH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_FULL_RDCH = ((IS_AXI_FULL == 1) && (C_RDCH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_LITE_WACH = ((IS_AXI_LITE == 1) && (C_WACH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_LITE_WDCH = ((IS_AXI_LITE == 1) && (C_WDCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_LITE_WRCH = ((IS_AXI_LITE == 1) && (C_WRCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_LITE_RACH = ((IS_AXI_LITE == 1) && (C_RACH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0; localparam IS_AXI_LITE_RDCH = ((IS_AXI_LITE == 1) && (C_RDCH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0; localparam IS_WR_ADDR_CH = ((IS_AXI_FULL_WACH == 1) || (IS_AXI_LITE_WACH == 1)) ? 1 : 0; localparam IS_WR_DATA_CH = ((IS_AXI_FULL_WDCH == 1) || (IS_AXI_LITE_WDCH == 1)) ? 1 : 0; localparam IS_WR_RESP_CH = ((IS_AXI_FULL_WRCH == 1) || (IS_AXI_LITE_WRCH == 1)) ? 1 : 0; localparam IS_RD_ADDR_CH = ((IS_AXI_FULL_RACH == 1) || (IS_AXI_LITE_RACH == 1)) ? 1 : 0; localparam IS_RD_DATA_CH = ((IS_AXI_FULL_RDCH == 1) || (IS_AXI_LITE_RDCH == 1)) ? 1 : 0; localparam AWID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WACH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WACH; localparam AWADDR_OFFSET = AWID_OFFSET - C_AXI_ADDR_WIDTH; localparam AWLEN_OFFSET = C_AXI_TYPE != 2 ? AWADDR_OFFSET - C_AXI_LEN_WIDTH : AWADDR_OFFSET; localparam AWSIZE_OFFSET = C_AXI_TYPE != 2 ? AWLEN_OFFSET - C_AXI_SIZE_WIDTH : AWLEN_OFFSET; localparam AWBURST_OFFSET = C_AXI_TYPE != 2 ? AWSIZE_OFFSET - C_AXI_BURST_WIDTH : AWSIZE_OFFSET; localparam AWLOCK_OFFSET = C_AXI_TYPE != 2 ? AWBURST_OFFSET - C_AXI_LOCK_WIDTH : AWBURST_OFFSET; localparam AWCACHE_OFFSET = C_AXI_TYPE != 2 ? AWLOCK_OFFSET - C_AXI_CACHE_WIDTH : AWLOCK_OFFSET; localparam AWPROT_OFFSET = AWCACHE_OFFSET - C_AXI_PROT_WIDTH; localparam AWQOS_OFFSET = AWPROT_OFFSET - C_AXI_QOS_WIDTH; localparam AWREGION_OFFSET = C_AXI_TYPE == 1 ? AWQOS_OFFSET - C_AXI_REGION_WIDTH : AWQOS_OFFSET; localparam AWUSER_OFFSET = C_HAS_AXI_AWUSER == 1 ? AWREGION_OFFSET-C_AXI_AWUSER_WIDTH : AWREGION_OFFSET; localparam WID_OFFSET = (C_AXI_TYPE == 3 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WDCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WDCH; localparam WDATA_OFFSET = WID_OFFSET - C_AXI_DATA_WIDTH; localparam WSTRB_OFFSET = WDATA_OFFSET - C_AXI_DATA_WIDTH/8; localparam WUSER_OFFSET = C_HAS_AXI_WUSER == 1 ? WSTRB_OFFSET-C_AXI_WUSER_WIDTH : WSTRB_OFFSET; localparam BID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WRCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WRCH; localparam BRESP_OFFSET = BID_OFFSET - C_AXI_BRESP_WIDTH; localparam BUSER_OFFSET = C_HAS_AXI_BUSER == 1 ? BRESP_OFFSET-C_AXI_BUSER_WIDTH : BRESP_OFFSET; wire [C_DIN_WIDTH_WACH-1:0] wach_din ; wire [C_DIN_WIDTH_WACH-1:0] wach_dout ; wire [C_DIN_WIDTH_WACH-1:0] wach_dout_pkt ; wire wach_full ; wire wach_almost_full ; wire wach_prog_full ; wire wach_empty ; wire wach_almost_empty ; wire wach_prog_empty ; wire [C_DIN_WIDTH_WDCH-1:0] wdch_din ; wire [C_DIN_WIDTH_WDCH-1:0] wdch_dout ; wire wdch_full ; wire wdch_almost_full ; wire wdch_prog_full ; wire wdch_empty ; wire wdch_almost_empty ; wire wdch_prog_empty ; wire [C_DIN_WIDTH_WRCH-1:0] wrch_din ; wire [C_DIN_WIDTH_WRCH-1:0] wrch_dout ; wire wrch_full ; wire wrch_almost_full ; wire wrch_prog_full ; wire wrch_empty ; wire wrch_almost_empty ; wire wrch_prog_empty ; wire axi_aw_underflow_i; wire axi_w_underflow_i ; wire axi_b_underflow_i ; wire axi_aw_overflow_i ; wire axi_w_overflow_i ; wire axi_b_overflow_i ; wire axi_wr_underflow_i; wire axi_wr_overflow_i ; wire wach_s_axi_awready; wire wach_m_axi_awvalid; wire wach_wr_en ; wire wach_rd_en ; wire wdch_s_axi_wready ; wire wdch_m_axi_wvalid ; wire wdch_wr_en ; wire wdch_rd_en ; wire wrch_s_axi_bvalid ; wire wrch_m_axi_bready ; wire wrch_wr_en ; wire wrch_rd_en ; wire txn_count_up ; wire txn_count_down ; wire awvalid_en ; wire awvalid_pkt ; wire awready_pkt ; integer wr_pkt_count ; wire wach_we ; wire wach_re ; wire wdch_we ; wire wdch_re ; wire wrch_we ; wire wrch_re ; generate if (IS_WR_ADDR_CH == 1) begin : axi_write_address_channel // Write protection when almost full or prog_full is high assign wach_we = (C_PROG_FULL_TYPE_WACH != 0) ? wach_s_axi_awready & S_AXI_AWVALID : S_AXI_AWVALID; // Read protection when almost empty or prog_empty is high assign wach_re = (C_PROG_EMPTY_TYPE_WACH != 0 && C_APPLICATION_TYPE_WACH == 1) ? wach_m_axi_awvalid & awready_pkt & awvalid_en : (C_PROG_EMPTY_TYPE_WACH != 0 && C_APPLICATION_TYPE_WACH != 1) ? M_AXI_AWREADY && wach_m_axi_awvalid : (C_PROG_EMPTY_TYPE_WACH == 0 && C_APPLICATION_TYPE_WACH == 1) ? awready_pkt & awvalid_en : (C_PROG_EMPTY_TYPE_WACH == 0 && C_APPLICATION_TYPE_WACH != 1) ? M_AXI_AWREADY : 1'b0; assign wach_wr_en = (C_HAS_SLAVE_CE == 1) ? wach_we & S_ACLK_EN : wach_we; assign wach_rd_en = (C_HAS_MASTER_CE == 1) ? wach_re & M_ACLK_EN : wach_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WACH == 1 || C_IMPLEMENTATION_TYPE_WACH == 11) ? 1 : (C_IMPLEMENTATION_TYPE_WACH == 2 || C_IMPLEMENTATION_TYPE_WACH == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WACH == 1 || C_IMPLEMENTATION_TYPE_WACH == 2) ? 0 : (C_IMPLEMENTATION_TYPE_WACH == 11 || C_IMPLEMENTATION_TYPE_WACH == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_WACH), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_WR_DEPTH (C_WR_DEPTH_WACH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WACH), .C_DOUT_WIDTH (C_DIN_WIDTH_WACH), .C_RD_DEPTH (C_WR_DEPTH_WACH), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WACH), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WACH), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WACH), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WACH), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WACH), .C_USE_ECC (C_USE_ECC_WACH), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WACH), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_FIFO_TYPE ((C_APPLICATION_TYPE_WACH == 1)?0:C_APPLICATION_TYPE_WACH), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_EN_SAFETY_CKT (1), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_EMBEDDED_REG (0), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), //.C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_wach_dut ( .CLK (S_ACLK), .WR_CLK (S_ACLK), .RD_CLK (M_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (wach_wr_en), .RD_EN (wach_rd_en), .PROG_FULL_THRESH (AXI_AW_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WACH{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WACH{1'b0}}), .PROG_EMPTY_THRESH (AXI_AW_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WACH{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WACH{1'b0}}), .INJECTDBITERR (AXI_AW_INJECTDBITERR), .INJECTSBITERR (AXI_AW_INJECTSBITERR), .DIN (wach_din), .DOUT (wach_dout_pkt), .FULL (wach_full), .EMPTY (wach_empty), .ALMOST_FULL (), .PROG_FULL (AXI_AW_PROG_FULL), .ALMOST_EMPTY (), .PROG_EMPTY (AXI_AW_PROG_EMPTY), .WR_ACK (), .OVERFLOW (axi_aw_overflow_i), .VALID (), .UNDERFLOW (axi_aw_underflow_i), .DATA_COUNT (AXI_AW_DATA_COUNT), .RD_DATA_COUNT (AXI_AW_RD_DATA_COUNT), .WR_DATA_COUNT (AXI_AW_WR_DATA_COUNT), .SBITERR (AXI_AW_SBITERR), .DBITERR (AXI_AW_DBITERR), .wr_rst_busy (wr_rst_busy_wach), .rd_rst_busy (rd_rst_busy_wach), .wr_rst_i_out (), .rd_rst_i_out (), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign wach_s_axi_awready = (IS_8SERIES == 0) ? ~wach_full : (C_IMPLEMENTATION_TYPE_WACH == 5 || C_IMPLEMENTATION_TYPE_WACH == 13) ? ~(wach_full | wr_rst_busy_wach) : ~wach_full; assign wach_m_axi_awvalid = ~wach_empty; assign S_AXI_AWREADY = wach_s_axi_awready; assign AXI_AW_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_aw_underflow_i : 0; assign AXI_AW_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_aw_overflow_i : 0; end endgenerate // axi_write_address_channel // Register Slice for Write Address Channel generate if (C_WACH_TYPE == 1) begin : gwach_reg_slice fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_WACH), .C_REG_CONFIG (C_REG_SLICE_MODE_WACH) ) wach_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (wach_din), .S_VALID (S_AXI_AWVALID), .S_READY (S_AXI_AWREADY), // Master side .M_PAYLOAD_DATA (wach_dout), .M_VALID (M_AXI_AWVALID), .M_READY (M_AXI_AWREADY) ); end endgenerate // gwach_reg_slice generate if (C_APPLICATION_TYPE_WACH == 1 && C_HAS_AXI_WR_CHANNEL == 1) begin : axi_mm_pkt_fifo_wr fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_WACH), .C_REG_CONFIG (1) ) wach_pkt_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (inverted_reset), // Slave side .S_PAYLOAD_DATA (wach_dout_pkt), .S_VALID (awvalid_pkt), .S_READY (awready_pkt), // Master side .M_PAYLOAD_DATA (wach_dout), .M_VALID (M_AXI_AWVALID), .M_READY (M_AXI_AWREADY) ); assign awvalid_pkt = wach_m_axi_awvalid && awvalid_en; assign txn_count_up = wdch_s_axi_wready && wdch_wr_en && wdch_din[0]; assign txn_count_down = wach_m_axi_awvalid && awready_pkt && awvalid_en; always@(posedge S_ACLK or posedge inverted_reset) begin if(inverted_reset == 1) begin wr_pkt_count <= 0; end else begin if(txn_count_up == 1 && txn_count_down == 0) begin wr_pkt_count <= wr_pkt_count + 1; end else if(txn_count_up == 0 && txn_count_down == 1) begin wr_pkt_count <= wr_pkt_count - 1; end end end //Always end assign awvalid_en = (wr_pkt_count > 0)?1:0; end endgenerate generate if (C_APPLICATION_TYPE_WACH != 1) begin : axi_mm_fifo_wr assign awvalid_en = 1; assign wach_dout = wach_dout_pkt; assign M_AXI_AWVALID = wach_m_axi_awvalid; end endgenerate generate if (IS_WR_DATA_CH == 1) begin : axi_write_data_channel // Write protection when almost full or prog_full is high assign wdch_we = (C_PROG_FULL_TYPE_WDCH != 0) ? wdch_s_axi_wready & S_AXI_WVALID : S_AXI_WVALID; // Read protection when almost empty or prog_empty is high assign wdch_re = (C_PROG_EMPTY_TYPE_WDCH != 0) ? wdch_m_axi_wvalid & M_AXI_WREADY : M_AXI_WREADY; assign wdch_wr_en = (C_HAS_SLAVE_CE == 1) ? wdch_we & S_ACLK_EN : wdch_we; assign wdch_rd_en = (C_HAS_MASTER_CE == 1) ? wdch_re & M_ACLK_EN : wdch_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WDCH == 1 || C_IMPLEMENTATION_TYPE_WDCH == 11) ? 1 : (C_IMPLEMENTATION_TYPE_WDCH == 2 || C_IMPLEMENTATION_TYPE_WDCH == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WDCH == 1 || C_IMPLEMENTATION_TYPE_WDCH == 2) ? 0 : (C_IMPLEMENTATION_TYPE_WDCH == 11 || C_IMPLEMENTATION_TYPE_WDCH == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_WDCH), .C_WR_DEPTH (C_WR_DEPTH_WDCH), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WDCH), .C_DOUT_WIDTH (C_DIN_WIDTH_WDCH), .C_RD_DEPTH (C_WR_DEPTH_WDCH), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WDCH), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WDCH), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WDCH), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WDCH), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WDCH), .C_USE_ECC (C_USE_ECC_WDCH), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WDCH), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_FIFO_TYPE (C_APPLICATION_TYPE_WDCH), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_EMBEDDED_REG (0), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), .C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_wdch_dut ( .CLK (S_ACLK), .WR_CLK (S_ACLK), .RD_CLK (M_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (wdch_wr_en), .RD_EN (wdch_rd_en), .PROG_FULL_THRESH (AXI_W_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WDCH{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WDCH{1'b0}}), .PROG_EMPTY_THRESH (AXI_W_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WDCH{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WDCH{1'b0}}), .INJECTDBITERR (AXI_W_INJECTDBITERR), .INJECTSBITERR (AXI_W_INJECTSBITERR), .DIN (wdch_din), .DOUT (wdch_dout), .FULL (wdch_full), .EMPTY (wdch_empty), .ALMOST_FULL (), .PROG_FULL (AXI_W_PROG_FULL), .ALMOST_EMPTY (), .PROG_EMPTY (AXI_W_PROG_EMPTY), .WR_ACK (), .OVERFLOW (axi_w_overflow_i), .VALID (), .UNDERFLOW (axi_w_underflow_i), .DATA_COUNT (AXI_W_DATA_COUNT), .RD_DATA_COUNT (AXI_W_RD_DATA_COUNT), .WR_DATA_COUNT (AXI_W_WR_DATA_COUNT), .SBITERR (AXI_W_SBITERR), .DBITERR (AXI_W_DBITERR), .wr_rst_busy (wr_rst_busy_wdch), .rd_rst_busy (rd_rst_busy_wdch), .wr_rst_i_out (), .rd_rst_i_out (), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign wdch_s_axi_wready = (IS_8SERIES == 0) ? ~wdch_full : (C_IMPLEMENTATION_TYPE_WDCH == 5 || C_IMPLEMENTATION_TYPE_WDCH == 13) ? ~(wdch_full | wr_rst_busy_wdch) : ~wdch_full; assign wdch_m_axi_wvalid = ~wdch_empty; assign S_AXI_WREADY = wdch_s_axi_wready; assign M_AXI_WVALID = wdch_m_axi_wvalid; assign AXI_W_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_w_underflow_i : 0; assign AXI_W_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_w_overflow_i : 0; end endgenerate // axi_write_data_channel // Register Slice for Write Data Channel generate if (C_WDCH_TYPE == 1) begin : gwdch_reg_slice fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_WDCH), .C_REG_CONFIG (C_REG_SLICE_MODE_WDCH) ) wdch_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (wdch_din), .S_VALID (S_AXI_WVALID), .S_READY (S_AXI_WREADY), // Master side .M_PAYLOAD_DATA (wdch_dout), .M_VALID (M_AXI_WVALID), .M_READY (M_AXI_WREADY) ); end endgenerate // gwdch_reg_slice generate if (IS_WR_RESP_CH == 1) begin : axi_write_resp_channel // Write protection when almost full or prog_full is high assign wrch_we = (C_PROG_FULL_TYPE_WRCH != 0) ? wrch_m_axi_bready & M_AXI_BVALID : M_AXI_BVALID; // Read protection when almost empty or prog_empty is high assign wrch_re = (C_PROG_EMPTY_TYPE_WRCH != 0) ? wrch_s_axi_bvalid & S_AXI_BREADY : S_AXI_BREADY; assign wrch_wr_en = (C_HAS_MASTER_CE == 1) ? wrch_we & M_ACLK_EN : wrch_we; assign wrch_rd_en = (C_HAS_SLAVE_CE == 1) ? wrch_re & S_ACLK_EN : wrch_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WRCH == 1 || C_IMPLEMENTATION_TYPE_WRCH == 11) ? 1 : (C_IMPLEMENTATION_TYPE_WRCH == 2 || C_IMPLEMENTATION_TYPE_WRCH == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WRCH == 1 || C_IMPLEMENTATION_TYPE_WRCH == 2) ? 0 : (C_IMPLEMENTATION_TYPE_WRCH == 11 || C_IMPLEMENTATION_TYPE_WRCH == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_WRCH), .C_WR_DEPTH (C_WR_DEPTH_WRCH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WRCH), .C_DOUT_WIDTH (C_DIN_WIDTH_WRCH), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_RD_DEPTH (C_WR_DEPTH_WRCH), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WRCH), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WRCH), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WRCH), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WRCH), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WRCH), .C_USE_ECC (C_USE_ECC_WRCH), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WRCH), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_FIFO_TYPE (C_APPLICATION_TYPE_WRCH), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_EMBEDDED_REG (0), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), .C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_wrch_dut ( .CLK (S_ACLK), .WR_CLK (M_ACLK), .RD_CLK (S_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (wrch_wr_en), .RD_EN (wrch_rd_en), .PROG_FULL_THRESH (AXI_B_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WRCH{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WRCH{1'b0}}), .PROG_EMPTY_THRESH (AXI_B_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WRCH{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WRCH{1'b0}}), .INJECTDBITERR (AXI_B_INJECTDBITERR), .INJECTSBITERR (AXI_B_INJECTSBITERR), .DIN (wrch_din), .DOUT (wrch_dout), .FULL (wrch_full), .EMPTY (wrch_empty), .ALMOST_FULL (), .ALMOST_EMPTY (), .PROG_FULL (AXI_B_PROG_FULL), .PROG_EMPTY (AXI_B_PROG_EMPTY), .WR_ACK (), .OVERFLOW (axi_b_overflow_i), .VALID (), .UNDERFLOW (axi_b_underflow_i), .DATA_COUNT (AXI_B_DATA_COUNT), .RD_DATA_COUNT (AXI_B_RD_DATA_COUNT), .WR_DATA_COUNT (AXI_B_WR_DATA_COUNT), .SBITERR (AXI_B_SBITERR), .DBITERR (AXI_B_DBITERR), .wr_rst_busy (wr_rst_busy_wrch), .rd_rst_busy (rd_rst_busy_wrch), .wr_rst_i_out (), .rd_rst_i_out (), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign wrch_s_axi_bvalid = ~wrch_empty; assign wrch_m_axi_bready = (IS_8SERIES == 0) ? ~wrch_full : (C_IMPLEMENTATION_TYPE_WRCH == 5 || C_IMPLEMENTATION_TYPE_WRCH == 13) ? ~(wrch_full | wr_rst_busy_wrch) : ~wrch_full; assign S_AXI_BVALID = wrch_s_axi_bvalid; assign M_AXI_BREADY = wrch_m_axi_bready; assign AXI_B_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_b_underflow_i : 0; assign AXI_B_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_b_overflow_i : 0; end endgenerate // axi_write_resp_channel // Register Slice for Write Response Channel generate if (C_WRCH_TYPE == 1) begin : gwrch_reg_slice fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_WRCH), .C_REG_CONFIG (C_REG_SLICE_MODE_WRCH) ) wrch_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (wrch_din), .S_VALID (M_AXI_BVALID), .S_READY (M_AXI_BREADY), // Master side .M_PAYLOAD_DATA (wrch_dout), .M_VALID (S_AXI_BVALID), .M_READY (S_AXI_BREADY) ); end endgenerate // gwrch_reg_slice assign axi_wr_underflow_i = C_USE_COMMON_UNDERFLOW == 1 ? (axi_aw_underflow_i || axi_w_underflow_i || axi_b_underflow_i) : 0; assign axi_wr_overflow_i = C_USE_COMMON_OVERFLOW == 1 ? (axi_aw_overflow_i || axi_w_overflow_i || axi_b_overflow_i) : 0; generate if (IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) begin : axi_wach_output assign M_AXI_AWADDR = wach_dout[AWID_OFFSET-1:AWADDR_OFFSET]; assign M_AXI_AWLEN = wach_dout[AWADDR_OFFSET-1:AWLEN_OFFSET]; assign M_AXI_AWSIZE = wach_dout[AWLEN_OFFSET-1:AWSIZE_OFFSET]; assign M_AXI_AWBURST = wach_dout[AWSIZE_OFFSET-1:AWBURST_OFFSET]; assign M_AXI_AWLOCK = wach_dout[AWBURST_OFFSET-1:AWLOCK_OFFSET]; assign M_AXI_AWCACHE = wach_dout[AWLOCK_OFFSET-1:AWCACHE_OFFSET]; assign M_AXI_AWPROT = wach_dout[AWCACHE_OFFSET-1:AWPROT_OFFSET]; assign M_AXI_AWQOS = wach_dout[AWPROT_OFFSET-1:AWQOS_OFFSET]; assign wach_din[AWID_OFFSET-1:AWADDR_OFFSET] = S_AXI_AWADDR; assign wach_din[AWADDR_OFFSET-1:AWLEN_OFFSET] = S_AXI_AWLEN; assign wach_din[AWLEN_OFFSET-1:AWSIZE_OFFSET] = S_AXI_AWSIZE; assign wach_din[AWSIZE_OFFSET-1:AWBURST_OFFSET] = S_AXI_AWBURST; assign wach_din[AWBURST_OFFSET-1:AWLOCK_OFFSET] = S_AXI_AWLOCK; assign wach_din[AWLOCK_OFFSET-1:AWCACHE_OFFSET] = S_AXI_AWCACHE; assign wach_din[AWCACHE_OFFSET-1:AWPROT_OFFSET] = S_AXI_AWPROT; assign wach_din[AWPROT_OFFSET-1:AWQOS_OFFSET] = S_AXI_AWQOS; end endgenerate // axi_wach_output generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : axi_awregion assign M_AXI_AWREGION = wach_dout[AWQOS_OFFSET-1:AWREGION_OFFSET]; end endgenerate // axi_awregion generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE != 1) begin : naxi_awregion assign M_AXI_AWREGION = 0; end endgenerate // naxi_awregion generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 1) begin : axi_awuser assign M_AXI_AWUSER = wach_dout[AWREGION_OFFSET-1:AWUSER_OFFSET]; end endgenerate // axi_awuser generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 0) begin : naxi_awuser assign M_AXI_AWUSER = 0; end endgenerate // naxi_awuser generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_awid assign M_AXI_AWID = wach_dout[C_DIN_WIDTH_WACH-1:AWID_OFFSET]; end endgenerate //axi_awid generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_awid assign M_AXI_AWID = 0; end endgenerate //naxi_awid generate if (IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) begin : axi_wdch_output assign M_AXI_WDATA = wdch_dout[WID_OFFSET-1:WDATA_OFFSET]; assign M_AXI_WSTRB = wdch_dout[WDATA_OFFSET-1:WSTRB_OFFSET]; assign M_AXI_WLAST = wdch_dout[0]; assign wdch_din[WID_OFFSET-1:WDATA_OFFSET] = S_AXI_WDATA; assign wdch_din[WDATA_OFFSET-1:WSTRB_OFFSET] = S_AXI_WSTRB; assign wdch_din[0] = S_AXI_WLAST; end endgenerate // axi_wdch_output generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_ID == 1 && C_AXI_TYPE == 3) begin assign M_AXI_WID = wdch_dout[C_DIN_WIDTH_WDCH-1:WID_OFFSET]; end endgenerate generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && (C_HAS_AXI_ID == 0 || C_AXI_TYPE != 3)) begin assign M_AXI_WID = 0; end endgenerate generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_WUSER == 1 ) begin assign M_AXI_WUSER = wdch_dout[WSTRB_OFFSET-1:WUSER_OFFSET]; end endgenerate generate if (C_HAS_AXI_WUSER == 0) begin assign M_AXI_WUSER = 0; end endgenerate generate if (IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) begin : axi_wrch_output assign S_AXI_BRESP = wrch_dout[BID_OFFSET-1:BRESP_OFFSET]; assign wrch_din[BID_OFFSET-1:BRESP_OFFSET] = M_AXI_BRESP; end endgenerate // axi_wrch_output generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 1) begin : axi_buser assign S_AXI_BUSER = wrch_dout[BRESP_OFFSET-1:BUSER_OFFSET]; end endgenerate // axi_buser generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 0) begin : naxi_buser assign S_AXI_BUSER = 0; end endgenerate // naxi_buser generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_bid assign S_AXI_BID = wrch_dout[C_DIN_WIDTH_WRCH-1:BID_OFFSET]; end endgenerate // axi_bid generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_bid assign S_AXI_BID = 0 ; end endgenerate // naxi_bid generate if (IS_AXI_LITE_WACH == 1 || (IS_AXI_LITE == 1 && C_WACH_TYPE == 1)) begin : axi_wach_output1 assign wach_din = {S_AXI_AWADDR, S_AXI_AWPROT}; assign M_AXI_AWADDR = wach_dout[C_DIN_WIDTH_WACH-1:AWADDR_OFFSET]; assign M_AXI_AWPROT = wach_dout[AWADDR_OFFSET-1:AWPROT_OFFSET]; end endgenerate // axi_wach_output1 generate if (IS_AXI_LITE_WDCH == 1 || (IS_AXI_LITE == 1 && C_WDCH_TYPE == 1)) begin : axi_wdch_output1 assign wdch_din = {S_AXI_WDATA, S_AXI_WSTRB}; assign M_AXI_WDATA = wdch_dout[C_DIN_WIDTH_WDCH-1:WDATA_OFFSET]; assign M_AXI_WSTRB = wdch_dout[WDATA_OFFSET-1:WSTRB_OFFSET]; end endgenerate // axi_wdch_output1 generate if (IS_AXI_LITE_WRCH == 1 || (IS_AXI_LITE == 1 && C_WRCH_TYPE == 1)) begin : axi_wrch_output1 assign wrch_din = M_AXI_BRESP; assign S_AXI_BRESP = wrch_dout[C_DIN_WIDTH_WRCH-1:BRESP_OFFSET]; end endgenerate // axi_wrch_output1 generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 1) begin : gwach_din1 assign wach_din[AWREGION_OFFSET-1:AWUSER_OFFSET] = S_AXI_AWUSER; end endgenerate // gwach_din1 generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : gwach_din2 assign wach_din[C_DIN_WIDTH_WACH-1:AWID_OFFSET] = S_AXI_AWID; end endgenerate // gwach_din2 generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : gwach_din3 assign wach_din[AWQOS_OFFSET-1:AWREGION_OFFSET] = S_AXI_AWREGION; end endgenerate // gwach_din3 generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_WUSER == 1) begin : gwdch_din1 assign wdch_din[WSTRB_OFFSET-1:WUSER_OFFSET] = S_AXI_WUSER; end endgenerate // gwdch_din1 generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_ID == 1 && C_AXI_TYPE == 3) begin : gwdch_din2 assign wdch_din[C_DIN_WIDTH_WDCH-1:WID_OFFSET] = S_AXI_WID; end endgenerate // gwdch_din2 generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 1) begin : gwrch_din1 assign wrch_din[BRESP_OFFSET-1:BUSER_OFFSET] = M_AXI_BUSER; end endgenerate // gwrch_din1 generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : gwrch_din2 assign wrch_din[C_DIN_WIDTH_WRCH-1:BID_OFFSET] = M_AXI_BID; end endgenerate // gwrch_din2 //end of axi_write_channel //########################################################################### // AXI FULL Read Channel (axi_read_channel) //########################################################################### wire [C_DIN_WIDTH_RACH-1:0] rach_din ; wire [C_DIN_WIDTH_RACH-1:0] rach_dout ; wire [C_DIN_WIDTH_RACH-1:0] rach_dout_pkt ; wire rach_full ; wire rach_almost_full ; wire rach_prog_full ; wire rach_empty ; wire rach_almost_empty ; wire rach_prog_empty ; wire [C_DIN_WIDTH_RDCH-1:0] rdch_din ; wire [C_DIN_WIDTH_RDCH-1:0] rdch_dout ; wire rdch_full ; wire rdch_almost_full ; wire rdch_prog_full ; wire rdch_empty ; wire rdch_almost_empty ; wire rdch_prog_empty ; wire axi_ar_underflow_i ; wire axi_r_underflow_i ; wire axi_ar_overflow_i ; wire axi_r_overflow_i ; wire axi_rd_underflow_i ; wire axi_rd_overflow_i ; wire rach_s_axi_arready ; wire rach_m_axi_arvalid ; wire rach_wr_en ; wire rach_rd_en ; wire rdch_m_axi_rready ; wire rdch_s_axi_rvalid ; wire rdch_wr_en ; wire rdch_rd_en ; wire arvalid_pkt ; wire arready_pkt ; wire arvalid_en ; wire rdch_rd_ok ; wire accept_next_pkt ; integer rdch_free_space ; integer rdch_commited_space ; wire rach_we ; wire rach_re ; wire rdch_we ; wire rdch_re ; localparam ARID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_RACH - C_AXI_ID_WIDTH : C_DIN_WIDTH_RACH; localparam ARADDR_OFFSET = ARID_OFFSET - C_AXI_ADDR_WIDTH; localparam ARLEN_OFFSET = C_AXI_TYPE != 2 ? ARADDR_OFFSET - C_AXI_LEN_WIDTH : ARADDR_OFFSET; localparam ARSIZE_OFFSET = C_AXI_TYPE != 2 ? ARLEN_OFFSET - C_AXI_SIZE_WIDTH : ARLEN_OFFSET; localparam ARBURST_OFFSET = C_AXI_TYPE != 2 ? ARSIZE_OFFSET - C_AXI_BURST_WIDTH : ARSIZE_OFFSET; localparam ARLOCK_OFFSET = C_AXI_TYPE != 2 ? ARBURST_OFFSET - C_AXI_LOCK_WIDTH : ARBURST_OFFSET; localparam ARCACHE_OFFSET = C_AXI_TYPE != 2 ? ARLOCK_OFFSET - C_AXI_CACHE_WIDTH : ARLOCK_OFFSET; localparam ARPROT_OFFSET = ARCACHE_OFFSET - C_AXI_PROT_WIDTH; localparam ARQOS_OFFSET = ARPROT_OFFSET - C_AXI_QOS_WIDTH; localparam ARREGION_OFFSET = C_AXI_TYPE == 1 ? ARQOS_OFFSET - C_AXI_REGION_WIDTH : ARQOS_OFFSET; localparam ARUSER_OFFSET = C_HAS_AXI_ARUSER == 1 ? ARREGION_OFFSET-C_AXI_ARUSER_WIDTH : ARREGION_OFFSET; localparam RID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_RDCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_RDCH; localparam RDATA_OFFSET = RID_OFFSET - C_AXI_DATA_WIDTH; localparam RRESP_OFFSET = RDATA_OFFSET - C_AXI_RRESP_WIDTH; localparam RUSER_OFFSET = C_HAS_AXI_RUSER == 1 ? RRESP_OFFSET-C_AXI_RUSER_WIDTH : RRESP_OFFSET; generate if (IS_RD_ADDR_CH == 1) begin : axi_read_addr_channel // Write protection when almost full or prog_full is high assign rach_we = (C_PROG_FULL_TYPE_RACH != 0) ? rach_s_axi_arready & S_AXI_ARVALID : S_AXI_ARVALID; // Read protection when almost empty or prog_empty is high // assign rach_rd_en = (C_PROG_EMPTY_TYPE_RACH != 5) ? rach_m_axi_arvalid & M_AXI_ARREADY : M_AXI_ARREADY && arvalid_en; assign rach_re = (C_PROG_EMPTY_TYPE_RACH != 0 && C_APPLICATION_TYPE_RACH == 1) ? rach_m_axi_arvalid & arready_pkt & arvalid_en : (C_PROG_EMPTY_TYPE_RACH != 0 && C_APPLICATION_TYPE_RACH != 1) ? M_AXI_ARREADY && rach_m_axi_arvalid : (C_PROG_EMPTY_TYPE_RACH == 0 && C_APPLICATION_TYPE_RACH == 1) ? arready_pkt & arvalid_en : (C_PROG_EMPTY_TYPE_RACH == 0 && C_APPLICATION_TYPE_RACH != 1) ? M_AXI_ARREADY : 1'b0; assign rach_wr_en = (C_HAS_SLAVE_CE == 1) ? rach_we & S_ACLK_EN : rach_we; assign rach_rd_en = (C_HAS_MASTER_CE == 1) ? rach_re & M_ACLK_EN : rach_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_RACH == 1 || C_IMPLEMENTATION_TYPE_RACH == 11) ? 1 : (C_IMPLEMENTATION_TYPE_RACH == 2 || C_IMPLEMENTATION_TYPE_RACH == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_RACH == 1 || C_IMPLEMENTATION_TYPE_RACH == 2) ? 0 : (C_IMPLEMENTATION_TYPE_RACH == 11 || C_IMPLEMENTATION_TYPE_RACH == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_RACH), .C_WR_DEPTH (C_WR_DEPTH_RACH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_RACH), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_DOUT_WIDTH (C_DIN_WIDTH_RACH), .C_RD_DEPTH (C_WR_DEPTH_RACH), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_RACH), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_RACH), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_RACH), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_RACH), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_RACH), .C_USE_ECC (C_USE_ECC_RACH), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_RACH), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_FIFO_TYPE ((C_APPLICATION_TYPE_RACH == 1)?0:C_APPLICATION_TYPE_RACH), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_EMBEDDED_REG (0), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), .C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_rach_dut ( .CLK (S_ACLK), .WR_CLK (S_ACLK), .RD_CLK (M_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (rach_wr_en), .RD_EN (rach_rd_en), .PROG_FULL_THRESH (AXI_AR_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RACH{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RACH{1'b0}}), .PROG_EMPTY_THRESH (AXI_AR_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RACH{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RACH{1'b0}}), .INJECTDBITERR (AXI_AR_INJECTDBITERR), .INJECTSBITERR (AXI_AR_INJECTSBITERR), .DIN (rach_din), .DOUT (rach_dout_pkt), .FULL (rach_full), .EMPTY (rach_empty), .ALMOST_FULL (), .ALMOST_EMPTY (), .PROG_FULL (AXI_AR_PROG_FULL), .PROG_EMPTY (AXI_AR_PROG_EMPTY), .WR_ACK (), .OVERFLOW (axi_ar_overflow_i), .VALID (), .UNDERFLOW (axi_ar_underflow_i), .DATA_COUNT (AXI_AR_DATA_COUNT), .RD_DATA_COUNT (AXI_AR_RD_DATA_COUNT), .WR_DATA_COUNT (AXI_AR_WR_DATA_COUNT), .SBITERR (AXI_AR_SBITERR), .DBITERR (AXI_AR_DBITERR), .wr_rst_busy (wr_rst_busy_rach), .rd_rst_busy (rd_rst_busy_rach), .wr_rst_i_out (), .rd_rst_i_out (), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign rach_s_axi_arready = (IS_8SERIES == 0) ? ~rach_full : (C_IMPLEMENTATION_TYPE_RACH == 5 || C_IMPLEMENTATION_TYPE_RACH == 13) ? ~(rach_full | wr_rst_busy_rach) : ~rach_full; assign rach_m_axi_arvalid = ~rach_empty; assign S_AXI_ARREADY = rach_s_axi_arready; assign AXI_AR_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_ar_underflow_i : 0; assign AXI_AR_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_ar_overflow_i : 0; end endgenerate // axi_read_addr_channel // Register Slice for Read Address Channel generate if (C_RACH_TYPE == 1) begin : grach_reg_slice fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_RACH), .C_REG_CONFIG (C_REG_SLICE_MODE_RACH) ) rach_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (rach_din), .S_VALID (S_AXI_ARVALID), .S_READY (S_AXI_ARREADY), // Master side .M_PAYLOAD_DATA (rach_dout), .M_VALID (M_AXI_ARVALID), .M_READY (M_AXI_ARREADY) ); end endgenerate // grach_reg_slice // Register Slice for Read Address Channel for MM Packet FIFO generate if (C_RACH_TYPE == 0 && C_APPLICATION_TYPE_RACH == 1) begin : grach_reg_slice_mm_pkt_fifo fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_RACH), .C_REG_CONFIG (1) ) reg_slice_mm_pkt_fifo_inst ( // System Signals .ACLK (S_ACLK), .ARESET (inverted_reset), // Slave side .S_PAYLOAD_DATA (rach_dout_pkt), .S_VALID (arvalid_pkt), .S_READY (arready_pkt), // Master side .M_PAYLOAD_DATA (rach_dout), .M_VALID (M_AXI_ARVALID), .M_READY (M_AXI_ARREADY) ); end endgenerate // grach_reg_slice_mm_pkt_fifo generate if (C_RACH_TYPE == 0 && C_APPLICATION_TYPE_RACH != 1) begin : grach_m_axi_arvalid assign M_AXI_ARVALID = rach_m_axi_arvalid; assign rach_dout = rach_dout_pkt; end endgenerate // grach_m_axi_arvalid generate if (C_APPLICATION_TYPE_RACH == 1 && C_HAS_AXI_RD_CHANNEL == 1) begin : axi_mm_pkt_fifo_rd assign rdch_rd_ok = rdch_s_axi_rvalid && rdch_rd_en; assign arvalid_pkt = rach_m_axi_arvalid && arvalid_en; assign accept_next_pkt = rach_m_axi_arvalid && arready_pkt && arvalid_en; always@(posedge S_ACLK or posedge inverted_reset) begin if(inverted_reset) begin rdch_commited_space <= 0; end else begin if(rdch_rd_ok && !accept_next_pkt) begin rdch_commited_space <= rdch_commited_space-1; end else if(!rdch_rd_ok && accept_next_pkt) begin rdch_commited_space <= rdch_commited_space+(rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]+1); end else if(rdch_rd_ok && accept_next_pkt) begin rdch_commited_space <= rdch_commited_space+(rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]); end end end //Always end always@(*) begin rdch_free_space <= (C_WR_DEPTH_RDCH-(rdch_commited_space+rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]+1)); end assign arvalid_en = (rdch_free_space >= 0)?1:0; end endgenerate generate if (C_APPLICATION_TYPE_RACH != 1) begin : axi_mm_fifo_rd assign arvalid_en = 1; end endgenerate generate if (IS_RD_DATA_CH == 1) begin : axi_read_data_channel // Write protection when almost full or prog_full is high assign rdch_we = (C_PROG_FULL_TYPE_RDCH != 0) ? rdch_m_axi_rready & M_AXI_RVALID : M_AXI_RVALID; // Read protection when almost empty or prog_empty is high assign rdch_re = (C_PROG_EMPTY_TYPE_RDCH != 0) ? rdch_s_axi_rvalid & S_AXI_RREADY : S_AXI_RREADY; assign rdch_wr_en = (C_HAS_MASTER_CE == 1) ? rdch_we & M_ACLK_EN : rdch_we; assign rdch_rd_en = (C_HAS_SLAVE_CE == 1) ? rdch_re & S_ACLK_EN : rdch_re; fifo_generator_v13_1_1_CONV_VER #( .C_FAMILY (C_FAMILY), .C_COMMON_CLOCK (C_COMMON_CLOCK), .C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_RDCH == 1 || C_IMPLEMENTATION_TYPE_RDCH == 11) ? 1 : (C_IMPLEMENTATION_TYPE_RDCH == 2 || C_IMPLEMENTATION_TYPE_RDCH == 12) ? 2 : 4), .C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_RDCH == 1 || C_IMPLEMENTATION_TYPE_RDCH == 2) ? 0 : (C_IMPLEMENTATION_TYPE_RDCH == 11 || C_IMPLEMENTATION_TYPE_RDCH == 12) ? 2 : 6), .C_PRELOAD_REGS (1), // always FWFT for AXI .C_PRELOAD_LATENCY (0), // always FWFT for AXI .C_DIN_WIDTH (C_DIN_WIDTH_RDCH), .C_WR_DEPTH (C_WR_DEPTH_RDCH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_RDCH), .C_DOUT_WIDTH (C_DIN_WIDTH_RDCH), .C_RD_DEPTH (C_WR_DEPTH_RDCH), .C_INTERFACE_TYPE (C_INTERFACE_TYPE), .C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_RDCH), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_RDCH), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_RDCH), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_RDCH), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_RDCH), .C_USE_ECC (C_USE_ECC_RDCH), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_RDCH), .C_HAS_ALMOST_EMPTY (0), .C_HAS_ALMOST_FULL (0), .C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE), .C_FIFO_TYPE (C_APPLICATION_TYPE_RDCH), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_HAS_WR_RST (0), .C_HAS_RD_RST (0), .C_HAS_RST (1), .C_HAS_SRST (0), .C_DOUT_RST_VAL (0), .C_HAS_VALID (0), .C_VALID_LOW (C_VALID_LOW), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_HAS_WR_ACK (0), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0), .C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1), .C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0), .C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1), .C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true .C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0), .C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1), .C_FULL_FLAGS_RST_VAL (1), .C_USE_EMBEDDED_REG (0), .C_USE_DOUT_RST (0), .C_MSGON_VAL (C_MSGON_VAL), .C_ENABLE_RST_SYNC (1), .C_EN_SAFETY_CKT (1), .C_COUNT_TYPE (C_COUNT_TYPE), .C_DEFAULT_VALUE (C_DEFAULT_VALUE), .C_ENABLE_RLOCS (C_ENABLE_RLOCS), .C_HAS_BACKUP (C_HAS_BACKUP), .C_HAS_INT_CLK (C_HAS_INT_CLK), .C_MIF_FILE_NAME (C_MIF_FILE_NAME), .C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE), .C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL), .C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE), .C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE), .C_RD_FREQ (C_RD_FREQ), .C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS), .C_WR_FREQ (C_WR_FREQ), .C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY) ) fifo_generator_v13_1_1_rdch_dut ( .CLK (S_ACLK), .WR_CLK (M_ACLK), .RD_CLK (S_ACLK), .RST (inverted_reset), .SRST (1'b0), .WR_RST (inverted_reset), .RD_RST (inverted_reset), .WR_EN (rdch_wr_en), .RD_EN (rdch_rd_en), .PROG_FULL_THRESH (AXI_R_PROG_FULL_THRESH), .PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RDCH{1'b0}}), .PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RDCH{1'b0}}), .PROG_EMPTY_THRESH (AXI_R_PROG_EMPTY_THRESH), .PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RDCH{1'b0}}), .PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RDCH{1'b0}}), .INJECTDBITERR (AXI_R_INJECTDBITERR), .INJECTSBITERR (AXI_R_INJECTSBITERR), .DIN (rdch_din), .DOUT (rdch_dout), .FULL (rdch_full), .EMPTY (rdch_empty), .ALMOST_FULL (), .ALMOST_EMPTY (), .PROG_FULL (AXI_R_PROG_FULL), .PROG_EMPTY (AXI_R_PROG_EMPTY), .WR_ACK (), .OVERFLOW (axi_r_overflow_i), .VALID (), .UNDERFLOW (axi_r_underflow_i), .DATA_COUNT (AXI_R_DATA_COUNT), .RD_DATA_COUNT (AXI_R_RD_DATA_COUNT), .WR_DATA_COUNT (AXI_R_WR_DATA_COUNT), .SBITERR (AXI_R_SBITERR), .DBITERR (AXI_R_DBITERR), .wr_rst_busy (wr_rst_busy_rdch), .rd_rst_busy (rd_rst_busy_rdch), .wr_rst_i_out (), .rd_rst_i_out (), .BACKUP (BACKUP), .BACKUP_MARKER (BACKUP_MARKER), .INT_CLK (INT_CLK) ); assign rdch_s_axi_rvalid = ~rdch_empty; assign rdch_m_axi_rready = (IS_8SERIES == 0) ? ~rdch_full : (C_IMPLEMENTATION_TYPE_RDCH == 5 || C_IMPLEMENTATION_TYPE_RDCH == 13) ? ~(rdch_full | wr_rst_busy_rdch) : ~rdch_full; assign S_AXI_RVALID = rdch_s_axi_rvalid; assign M_AXI_RREADY = rdch_m_axi_rready; assign AXI_R_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_r_underflow_i : 0; assign AXI_R_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_r_overflow_i : 0; end endgenerate //axi_read_data_channel // Register Slice for read Data Channel generate if (C_RDCH_TYPE == 1) begin : grdch_reg_slice fifo_generator_v13_1_1_axic_reg_slice #( .C_FAMILY (C_FAMILY), .C_DATA_WIDTH (C_DIN_WIDTH_RDCH), .C_REG_CONFIG (C_REG_SLICE_MODE_RDCH) ) rdch_reg_slice_inst ( // System Signals .ACLK (S_ACLK), .ARESET (axi_rs_rst), // Slave side .S_PAYLOAD_DATA (rdch_din), .S_VALID (M_AXI_RVALID), .S_READY (M_AXI_RREADY), // Master side .M_PAYLOAD_DATA (rdch_dout), .M_VALID (S_AXI_RVALID), .M_READY (S_AXI_RREADY) ); end endgenerate // grdch_reg_slice assign axi_rd_underflow_i = C_USE_COMMON_UNDERFLOW == 1 ? (axi_ar_underflow_i || axi_r_underflow_i) : 0; assign axi_rd_overflow_i = C_USE_COMMON_OVERFLOW == 1 ? (axi_ar_overflow_i || axi_r_overflow_i) : 0; generate if (IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) begin : axi_full_rach_output assign M_AXI_ARADDR = rach_dout[ARID_OFFSET-1:ARADDR_OFFSET]; assign M_AXI_ARLEN = rach_dout[ARADDR_OFFSET-1:ARLEN_OFFSET]; assign M_AXI_ARSIZE = rach_dout[ARLEN_OFFSET-1:ARSIZE_OFFSET]; assign M_AXI_ARBURST = rach_dout[ARSIZE_OFFSET-1:ARBURST_OFFSET]; assign M_AXI_ARLOCK = rach_dout[ARBURST_OFFSET-1:ARLOCK_OFFSET]; assign M_AXI_ARCACHE = rach_dout[ARLOCK_OFFSET-1:ARCACHE_OFFSET]; assign M_AXI_ARPROT = rach_dout[ARCACHE_OFFSET-1:ARPROT_OFFSET]; assign M_AXI_ARQOS = rach_dout[ARPROT_OFFSET-1:ARQOS_OFFSET]; assign rach_din[ARID_OFFSET-1:ARADDR_OFFSET] = S_AXI_ARADDR; assign rach_din[ARADDR_OFFSET-1:ARLEN_OFFSET] = S_AXI_ARLEN; assign rach_din[ARLEN_OFFSET-1:ARSIZE_OFFSET] = S_AXI_ARSIZE; assign rach_din[ARSIZE_OFFSET-1:ARBURST_OFFSET] = S_AXI_ARBURST; assign rach_din[ARBURST_OFFSET-1:ARLOCK_OFFSET] = S_AXI_ARLOCK; assign rach_din[ARLOCK_OFFSET-1:ARCACHE_OFFSET] = S_AXI_ARCACHE; assign rach_din[ARCACHE_OFFSET-1:ARPROT_OFFSET] = S_AXI_ARPROT; assign rach_din[ARPROT_OFFSET-1:ARQOS_OFFSET] = S_AXI_ARQOS; end endgenerate // axi_full_rach_output generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : axi_arregion assign M_AXI_ARREGION = rach_dout[ARQOS_OFFSET-1:ARREGION_OFFSET]; end endgenerate // axi_arregion generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE != 1) begin : naxi_arregion assign M_AXI_ARREGION = 0; end endgenerate // naxi_arregion generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 1) begin : axi_aruser assign M_AXI_ARUSER = rach_dout[ARREGION_OFFSET-1:ARUSER_OFFSET]; end endgenerate // axi_aruser generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 0) begin : naxi_aruser assign M_AXI_ARUSER = 0; end endgenerate // naxi_aruser generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_arid assign M_AXI_ARID = rach_dout[C_DIN_WIDTH_RACH-1:ARID_OFFSET]; end endgenerate // axi_arid generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_arid assign M_AXI_ARID = 0; end endgenerate // naxi_arid generate if (IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) begin : axi_full_rdch_output assign S_AXI_RDATA = rdch_dout[RID_OFFSET-1:RDATA_OFFSET]; assign S_AXI_RRESP = rdch_dout[RDATA_OFFSET-1:RRESP_OFFSET]; assign S_AXI_RLAST = rdch_dout[0]; assign rdch_din[RID_OFFSET-1:RDATA_OFFSET] = M_AXI_RDATA; assign rdch_din[RDATA_OFFSET-1:RRESP_OFFSET] = M_AXI_RRESP; assign rdch_din[0] = M_AXI_RLAST; end endgenerate // axi_full_rdch_output generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 1) begin : axi_full_ruser_output assign S_AXI_RUSER = rdch_dout[RRESP_OFFSET-1:RUSER_OFFSET]; end endgenerate // axi_full_ruser_output generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 0) begin : axi_full_nruser_output assign S_AXI_RUSER = 0; end endgenerate // axi_full_nruser_output generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_rid assign S_AXI_RID = rdch_dout[C_DIN_WIDTH_RDCH-1:RID_OFFSET]; end endgenerate // axi_rid generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_rid assign S_AXI_RID = 0; end endgenerate // naxi_rid generate if (IS_AXI_LITE_RACH == 1 || (IS_AXI_LITE == 1 && C_RACH_TYPE == 1)) begin : axi_lite_rach_output1 assign rach_din = {S_AXI_ARADDR, S_AXI_ARPROT}; assign M_AXI_ARADDR = rach_dout[C_DIN_WIDTH_RACH-1:ARADDR_OFFSET]; assign M_AXI_ARPROT = rach_dout[ARADDR_OFFSET-1:ARPROT_OFFSET]; end endgenerate // axi_lite_rach_output generate if (IS_AXI_LITE_RDCH == 1 || (IS_AXI_LITE == 1 && C_RDCH_TYPE == 1)) begin : axi_lite_rdch_output1 assign rdch_din = {M_AXI_RDATA, M_AXI_RRESP}; assign S_AXI_RDATA = rdch_dout[C_DIN_WIDTH_RDCH-1:RDATA_OFFSET]; assign S_AXI_RRESP = rdch_dout[RDATA_OFFSET-1:RRESP_OFFSET]; end endgenerate // axi_lite_rdch_output generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 1) begin : grach_din1 assign rach_din[ARREGION_OFFSET-1:ARUSER_OFFSET] = S_AXI_ARUSER; end endgenerate // grach_din1 generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : grach_din2 assign rach_din[C_DIN_WIDTH_RACH-1:ARID_OFFSET] = S_AXI_ARID; end endgenerate // grach_din2 generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE == 1) begin assign rach_din[ARQOS_OFFSET-1:ARREGION_OFFSET] = S_AXI_ARREGION; end endgenerate generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 1) begin : grdch_din1 assign rdch_din[RRESP_OFFSET-1:RUSER_OFFSET] = M_AXI_RUSER; end endgenerate // grdch_din1 generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : grdch_din2 assign rdch_din[C_DIN_WIDTH_RDCH-1:RID_OFFSET] = M_AXI_RID; end endgenerate // grdch_din2 //end of axi_read_channel generate if (C_INTERFACE_TYPE == 1 && C_USE_COMMON_UNDERFLOW == 1) begin : gaxi_comm_uf assign UNDERFLOW = (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 1) ? (axi_wr_underflow_i || axi_rd_underflow_i) : (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 0) ? axi_wr_underflow_i : (C_HAS_AXI_WR_CHANNEL == 0 && C_HAS_AXI_RD_CHANNEL == 1) ? axi_rd_underflow_i : 0; end endgenerate // gaxi_comm_uf generate if (C_INTERFACE_TYPE == 1 && C_USE_COMMON_OVERFLOW == 1) begin : gaxi_comm_of assign OVERFLOW = (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 1) ? (axi_wr_overflow_i || axi_rd_overflow_i) : (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 0) ? axi_wr_overflow_i : (C_HAS_AXI_WR_CHANNEL == 0 && C_HAS_AXI_RD_CHANNEL == 1) ? axi_rd_overflow_i : 0; end endgenerate // gaxi_comm_of //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Pass Through Logic or Wiring Logic //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Pass Through Logic for Read Channel //------------------------------------------------------------------------- // Wiring logic for Write Address Channel generate if (C_WACH_TYPE == 2) begin : gwach_pass_through assign M_AXI_AWID = S_AXI_AWID; assign M_AXI_AWADDR = S_AXI_AWADDR; assign M_AXI_AWLEN = S_AXI_AWLEN; assign M_AXI_AWSIZE = S_AXI_AWSIZE; assign M_AXI_AWBURST = S_AXI_AWBURST; assign M_AXI_AWLOCK = S_AXI_AWLOCK; assign M_AXI_AWCACHE = S_AXI_AWCACHE; assign M_AXI_AWPROT = S_AXI_AWPROT; assign M_AXI_AWQOS = S_AXI_AWQOS; assign M_AXI_AWREGION = S_AXI_AWREGION; assign M_AXI_AWUSER = S_AXI_AWUSER; assign S_AXI_AWREADY = M_AXI_AWREADY; assign M_AXI_AWVALID = S_AXI_AWVALID; end endgenerate // gwach_pass_through; // Wiring logic for Write Data Channel generate if (C_WDCH_TYPE == 2) begin : gwdch_pass_through assign M_AXI_WID = S_AXI_WID; assign M_AXI_WDATA = S_AXI_WDATA; assign M_AXI_WSTRB = S_AXI_WSTRB; assign M_AXI_WLAST = S_AXI_WLAST; assign M_AXI_WUSER = S_AXI_WUSER; assign S_AXI_WREADY = M_AXI_WREADY; assign M_AXI_WVALID = S_AXI_WVALID; end endgenerate // gwdch_pass_through; // Wiring logic for Write Response Channel generate if (C_WRCH_TYPE == 2) begin : gwrch_pass_through assign S_AXI_BID = M_AXI_BID; assign S_AXI_BRESP = M_AXI_BRESP; assign S_AXI_BUSER = M_AXI_BUSER; assign M_AXI_BREADY = S_AXI_BREADY; assign S_AXI_BVALID = M_AXI_BVALID; end endgenerate // gwrch_pass_through; //------------------------------------------------------------------------- // Pass Through Logic for Read Channel //------------------------------------------------------------------------- // Wiring logic for Read Address Channel generate if (C_RACH_TYPE == 2) begin : grach_pass_through assign M_AXI_ARID = S_AXI_ARID; assign M_AXI_ARADDR = S_AXI_ARADDR; assign M_AXI_ARLEN = S_AXI_ARLEN; assign M_AXI_ARSIZE = S_AXI_ARSIZE; assign M_AXI_ARBURST = S_AXI_ARBURST; assign M_AXI_ARLOCK = S_AXI_ARLOCK; assign M_AXI_ARCACHE = S_AXI_ARCACHE; assign M_AXI_ARPROT = S_AXI_ARPROT; assign M_AXI_ARQOS = S_AXI_ARQOS; assign M_AXI_ARREGION = S_AXI_ARREGION; assign M_AXI_ARUSER = S_AXI_ARUSER; assign S_AXI_ARREADY = M_AXI_ARREADY; assign M_AXI_ARVALID = S_AXI_ARVALID; end endgenerate // grach_pass_through; // Wiring logic for Read Data Channel generate if (C_RDCH_TYPE == 2) begin : grdch_pass_through assign S_AXI_RID = M_AXI_RID; assign S_AXI_RLAST = M_AXI_RLAST; assign S_AXI_RUSER = M_AXI_RUSER; assign S_AXI_RDATA = M_AXI_RDATA; assign S_AXI_RRESP = M_AXI_RRESP; assign S_AXI_RVALID = M_AXI_RVALID; assign M_AXI_RREADY = S_AXI_RREADY; end endgenerate // grdch_pass_through; // Wiring logic for AXI Streaming generate if (C_AXIS_TYPE == 2) begin : gaxis_pass_through assign M_AXIS_TDATA = S_AXIS_TDATA; assign M_AXIS_TSTRB = S_AXIS_TSTRB; assign M_AXIS_TKEEP = S_AXIS_TKEEP; assign M_AXIS_TID = S_AXIS_TID; assign M_AXIS_TDEST = S_AXIS_TDEST; assign M_AXIS_TUSER = S_AXIS_TUSER; assign M_AXIS_TLAST = S_AXIS_TLAST; assign S_AXIS_TREADY = M_AXIS_TREADY; assign M_AXIS_TVALID = S_AXIS_TVALID; end endgenerate // gaxis_pass_through; endmodule //fifo_generator_v13_1_1 /******************************************************************************* * Declaration of top-level module for Conventional FIFO ******************************************************************************/ module fifo_generator_v13_1_1_CONV_VER #( parameter C_COMMON_CLOCK = 0, parameter C_INTERFACE_TYPE = 0, parameter C_EN_SAFETY_CKT = 0, parameter C_COUNT_TYPE = 0, parameter C_DATA_COUNT_WIDTH = 2, parameter C_DEFAULT_VALUE = "", parameter C_DIN_WIDTH = 8, parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_ENABLE_RLOCS = 0, parameter C_FAMILY = "virtex7", //Not allowed in Verilog model parameter C_FULL_FLAGS_RST_VAL = 1, parameter C_HAS_ALMOST_EMPTY = 0, parameter C_HAS_ALMOST_FULL = 0, parameter C_HAS_BACKUP = 0, parameter C_HAS_DATA_COUNT = 0, parameter C_HAS_INT_CLK = 0, parameter C_HAS_MEMINIT_FILE = 0, parameter C_HAS_OVERFLOW = 0, parameter C_HAS_RD_DATA_COUNT = 0, parameter C_HAS_RD_RST = 0, parameter C_HAS_RST = 0, parameter C_HAS_SRST = 0, parameter C_HAS_UNDERFLOW = 0, parameter C_HAS_VALID = 0, parameter C_HAS_WR_ACK = 0, parameter C_HAS_WR_DATA_COUNT = 0, parameter C_HAS_WR_RST = 0, parameter C_IMPLEMENTATION_TYPE = 0, parameter C_INIT_WR_PNTR_VAL = 0, parameter C_MEMORY_TYPE = 1, parameter C_MIF_FILE_NAME = "", parameter C_OPTIMIZATION_MODE = 0, parameter C_OVERFLOW_LOW = 0, parameter C_PRELOAD_LATENCY = 1, parameter C_PRELOAD_REGS = 0, parameter C_PRIM_FIFO_TYPE = "", parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0, parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0, parameter C_PROG_EMPTY_TYPE = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0, parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0, parameter C_PROG_FULL_TYPE = 0, parameter C_RD_DATA_COUNT_WIDTH = 2, parameter C_RD_DEPTH = 256, parameter C_RD_FREQ = 1, parameter C_RD_PNTR_WIDTH = 8, parameter C_UNDERFLOW_LOW = 0, parameter C_USE_DOUT_RST = 0, parameter C_USE_ECC = 0, parameter C_USE_EMBEDDED_REG = 0, parameter C_USE_FIFO16_FLAGS = 0, parameter C_USE_FWFT_DATA_COUNT = 0, parameter C_VALID_LOW = 0, parameter C_WR_ACK_LOW = 0, parameter C_WR_DATA_COUNT_WIDTH = 2, parameter C_WR_DEPTH = 256, parameter C_WR_FREQ = 1, parameter C_WR_PNTR_WIDTH = 8, parameter C_WR_RESPONSE_LATENCY = 1, parameter C_MSGON_VAL = 1, parameter C_ENABLE_RST_SYNC = 1, parameter C_ERROR_INJECTION_TYPE = 0, parameter C_FIFO_TYPE = 0, parameter C_SYNCHRONIZER_STAGE = 2, parameter C_AXI_TYPE = 0 ) ( input BACKUP, input BACKUP_MARKER, input CLK, input RST, input SRST, input WR_CLK, input WR_RST, input RD_CLK, input RD_RST, input [C_DIN_WIDTH-1:0] DIN, input WR_EN, input RD_EN, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE, input INT_CLK, input INJECTDBITERR, input INJECTSBITERR, output [C_DOUT_WIDTH-1:0] DOUT, output FULL, output ALMOST_FULL, output WR_ACK, output OVERFLOW, output EMPTY, output ALMOST_EMPTY, output VALID, output UNDERFLOW, output [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT, output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT, output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT, output PROG_FULL, output PROG_EMPTY, output SBITERR, output DBITERR, output wr_rst_busy, output rd_rst_busy, output wr_rst_i_out, output rd_rst_i_out ); /* ****************************************************************************** * Definition of Parameters ****************************************************************************** * C_COMMON_CLOCK : Common Clock (1), Independent Clocks (0) * C_COUNT_TYPE : *not used * C_DATA_COUNT_WIDTH : Width of DATA_COUNT bus * C_DEFAULT_VALUE : *not used * C_DIN_WIDTH : Width of DIN bus * C_DOUT_RST_VAL : Reset value of DOUT * C_DOUT_WIDTH : Width of DOUT bus * C_ENABLE_RLOCS : *not used * C_FAMILY : not used in bhv model * C_FULL_FLAGS_RST_VAL : Full flags rst val (0 or 1) * C_HAS_ALMOST_EMPTY : 1=Core has ALMOST_EMPTY flag * C_HAS_ALMOST_FULL : 1=Core has ALMOST_FULL flag * C_HAS_BACKUP : *not used * C_HAS_DATA_COUNT : 1=Core has DATA_COUNT bus * C_HAS_INT_CLK : not used in bhv model * C_HAS_MEMINIT_FILE : *not used * C_HAS_OVERFLOW : 1=Core has OVERFLOW flag * C_HAS_RD_DATA_COUNT : 1=Core has RD_DATA_COUNT bus * C_HAS_RD_RST : *not used * C_HAS_RST : 1=Core has Async Rst * C_HAS_SRST : 1=Core has Sync Rst * C_HAS_UNDERFLOW : 1=Core has UNDERFLOW flag * C_HAS_VALID : 1=Core has VALID flag * C_HAS_WR_ACK : 1=Core has WR_ACK flag * C_HAS_WR_DATA_COUNT : 1=Core has WR_DATA_COUNT bus * C_HAS_WR_RST : *not used * C_IMPLEMENTATION_TYPE : 0=Common-Clock Bram/Dram * 1=Common-Clock ShiftRam * 2=Indep. Clocks Bram/Dram * 3=Virtex-4 Built-in * 4=Virtex-5 Built-in * C_INIT_WR_PNTR_VAL : *not used * C_MEMORY_TYPE : 1=Block RAM * 2=Distributed RAM * 3=Shift RAM * 4=Built-in FIFO * C_MIF_FILE_NAME : *not used * C_OPTIMIZATION_MODE : *not used * C_OVERFLOW_LOW : 1=OVERFLOW active low * C_PRELOAD_LATENCY : Latency of read: 0, 1, 2 * C_PRELOAD_REGS : 1=Use output registers * C_PRIM_FIFO_TYPE : not used in bhv model * C_PROG_EMPTY_THRESH_ASSERT_VAL: PROG_EMPTY assert threshold * C_PROG_EMPTY_THRESH_NEGATE_VAL: PROG_EMPTY negate threshold * C_PROG_EMPTY_TYPE : 0=No programmable empty * 1=Single prog empty thresh constant * 2=Multiple prog empty thresh constants * 3=Single prog empty thresh input * 4=Multiple prog empty thresh inputs * C_PROG_FULL_THRESH_ASSERT_VAL : PROG_FULL assert threshold * C_PROG_FULL_THRESH_NEGATE_VAL : PROG_FULL negate threshold * C_PROG_FULL_TYPE : 0=No prog full * 1=Single prog full thresh constant * 2=Multiple prog full thresh constants * 3=Single prog full thresh input * 4=Multiple prog full thresh inputs * C_RD_DATA_COUNT_WIDTH : Width of RD_DATA_COUNT bus * C_RD_DEPTH : Depth of read interface (2^N) * C_RD_FREQ : not used in bhv model * C_RD_PNTR_WIDTH : always log2(C_RD_DEPTH) * C_UNDERFLOW_LOW : 1=UNDERFLOW active low * C_USE_DOUT_RST : 1=Resets DOUT on RST * C_USE_ECC : Used for error injection purpose * C_USE_EMBEDDED_REG : 1=Use BRAM embedded output register * C_USE_FIFO16_FLAGS : not used in bhv model * C_USE_FWFT_DATA_COUNT : 1=Use extra logic for FWFT data count * C_VALID_LOW : 1=VALID active low * C_WR_ACK_LOW : 1=WR_ACK active low * C_WR_DATA_COUNT_WIDTH : Width of WR_DATA_COUNT bus * C_WR_DEPTH : Depth of write interface (2^N) * C_WR_FREQ : not used in bhv model * C_WR_PNTR_WIDTH : always log2(C_WR_DEPTH) * C_WR_RESPONSE_LATENCY : *not used * C_MSGON_VAL : *not used by bhv model * C_ENABLE_RST_SYNC : 0 = Use WR_RST & RD_RST * 1 = Use RST * C_ERROR_INJECTION_TYPE : 0 = No error injection * 1 = Single bit error injection only * 2 = Double bit error injection only * 3 = Single and double bit error injection ****************************************************************************** * Definition of Ports ****************************************************************************** * BACKUP : Not used * BACKUP_MARKER: Not used * CLK : Clock * DIN : Input data bus * PROG_EMPTY_THRESH : Threshold for Programmable Empty Flag * PROG_EMPTY_THRESH_ASSERT: Threshold for Programmable Empty Flag * PROG_EMPTY_THRESH_NEGATE: Threshold for Programmable Empty Flag * PROG_FULL_THRESH : Threshold for Programmable Full Flag * PROG_FULL_THRESH_ASSERT : Threshold for Programmable Full Flag * PROG_FULL_THRESH_NEGATE : Threshold for Programmable Full Flag * RD_CLK : Read Domain Clock * RD_EN : Read enable * RD_RST : Read Reset * RST : Asynchronous Reset * SRST : Synchronous Reset * WR_CLK : Write Domain Clock * WR_EN : Write enable * WR_RST : Write Reset * INT_CLK : Internal Clock * INJECTSBITERR: Inject Signle bit error * INJECTDBITERR: Inject Double bit error * ALMOST_EMPTY : One word remaining in FIFO * ALMOST_FULL : One empty space remaining in FIFO * DATA_COUNT : Number of data words in fifo( synchronous to CLK) * DOUT : Output data bus * EMPTY : Empty flag * FULL : Full flag * OVERFLOW : Last write rejected * PROG_EMPTY : Programmable Empty Flag * PROG_FULL : Programmable Full Flag * RD_DATA_COUNT: Number of data words in fifo (synchronous to RD_CLK) * UNDERFLOW : Last read rejected * VALID : Last read acknowledged, DOUT bus VALID * WR_ACK : Last write acknowledged * WR_DATA_COUNT: Number of data words in fifo (synchronous to WR_CLK) * SBITERR : Single Bit ECC Error Detected * DBITERR : Double Bit ECC Error Detected ****************************************************************************** */ //---------------------------------------------------------------------------- //- Internal Signals for delayed input signals //- All the input signals except Clock are delayed by 100 ps and then given to //- the models. //---------------------------------------------------------------------------- reg rst_delayed ; reg empty_fb ; reg srst_delayed ; reg wr_rst_delayed ; reg rd_rst_delayed ; reg wr_en_delayed ; reg rd_en_delayed ; reg [C_DIN_WIDTH-1:0] din_delayed ; reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_delayed ; reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_assert_delayed ; reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_negate_delayed ; reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_delayed ; reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_assert_delayed ; reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_negate_delayed ; reg injectdbiterr_delayed ; reg injectsbiterr_delayed ; wire empty_p0_out; always @* rst_delayed <= #`TCQ RST ; always @* empty_fb <= #`TCQ empty_p0_out ; always @* srst_delayed <= #`TCQ SRST ; always @* wr_rst_delayed <= #`TCQ WR_RST ; always @* rd_rst_delayed <= #`TCQ RD_RST ; always @* din_delayed <= #`TCQ DIN ; always @* wr_en_delayed <= #`TCQ WR_EN ; always @* rd_en_delayed <= #`TCQ RD_EN ; always @* prog_empty_thresh_delayed <= #`TCQ PROG_EMPTY_THRESH ; always @* prog_empty_thresh_assert_delayed <= #`TCQ PROG_EMPTY_THRESH_ASSERT ; always @* prog_empty_thresh_negate_delayed <= #`TCQ PROG_EMPTY_THRESH_NEGATE ; always @* prog_full_thresh_delayed <= #`TCQ PROG_FULL_THRESH ; always @* prog_full_thresh_assert_delayed <= #`TCQ PROG_FULL_THRESH_ASSERT ; always @* prog_full_thresh_negate_delayed <= #`TCQ PROG_FULL_THRESH_NEGATE ; always @* injectdbiterr_delayed <= #`TCQ INJECTDBITERR ; always @* injectsbiterr_delayed <= #`TCQ INJECTSBITERR ; /***************************************************************************** * Derived parameters ****************************************************************************/ //There are 2 Verilog behavioral models // 0 = Common-Clock FIFO/ShiftRam FIFO // 1 = Independent Clocks FIFO // 2 = Low Latency Synchronous FIFO // 3 = Low Latency Asynchronous FIFO localparam C_VERILOG_IMPL = (C_FIFO_TYPE == 3) ? 2 : (C_IMPLEMENTATION_TYPE == 2) ? 1 : 0; localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexuplus" || C_FAMILY == "zynquplus" || C_FAMILY == "kintexuplus") ? 1 : 0; //Internal reset signals reg rd_rst_asreg = 0; reg rd_rst_asreg_d1 = 0; reg rd_rst_asreg_d2 = 0; reg rd_rst_asreg_d3 = 0; reg rd_rst_reg = 0; wire rd_rst_comb; reg wr_rst_d0 = 0; reg wr_rst_d1 = 0; reg wr_rst_d2 = 0; reg rd_rst_d0 = 0; reg rd_rst_d1 = 0; reg rd_rst_d2 = 0; reg rd_rst_d3 = 0; reg wrrst_done = 0; reg rdrst_done = 0; reg wr_rst_asreg = 0; reg wr_rst_asreg_d1 = 0; reg wr_rst_asreg_d2 = 0; reg wr_rst_asreg_d3 = 0; reg rd_rst_wr_d0 = 0; reg rd_rst_wr_d1 = 0; reg rd_rst_wr_d2 = 0; reg wr_rst_reg = 0; reg rst_active_i = 1'b1; reg rst_delayed_d1 = 1'b1; reg rst_delayed_d2 = 1'b1; wire wr_rst_comb; wire wr_rst_i; wire rd_rst_i; wire rst_i; //Internal reset signals reg rst_asreg = 0; reg srst_asreg = 0; reg rst_asreg_d1 = 0; reg rst_asreg_d2 = 0; reg srst_asreg_d1 = 0; reg srst_asreg_d2 = 0; reg rst_reg = 0; reg srst_reg = 0; wire rst_comb; wire srst_comb; reg rst_full_gen_i = 0; reg rst_full_ff_i = 0; wire RD_CLK_P0_IN; wire RST_P0_IN; wire RD_EN_FIFO_IN; wire RD_EN_P0_IN; wire ALMOST_EMPTY_FIFO_OUT; wire ALMOST_FULL_FIFO_OUT; wire [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT_FIFO_OUT; wire [C_DOUT_WIDTH-1:0] DOUT_FIFO_OUT; wire EMPTY_FIFO_OUT; wire FULL_FIFO_OUT; wire OVERFLOW_FIFO_OUT; wire PROG_EMPTY_FIFO_OUT; wire PROG_FULL_FIFO_OUT; wire VALID_FIFO_OUT; wire [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT_FIFO_OUT; wire UNDERFLOW_FIFO_OUT; wire WR_ACK_FIFO_OUT; wire [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT_FIFO_OUT; //*************************************************************************** // Internal Signals // The core uses either the internal_ wires or the preload0_ wires depending // on whether the core uses Preload0 or not. // When using preload0, the internal signals connect the internal core to // the preload logic, and the external core's interfaces are tied to the // preload0 signals from the preload logic. //*************************************************************************** wire [C_DOUT_WIDTH-1:0] DATA_P0_OUT; wire VALID_P0_OUT; wire EMPTY_P0_OUT; wire ALMOSTEMPTY_P0_OUT; reg EMPTY_P0_OUT_Q; reg ALMOSTEMPTY_P0_OUT_Q; wire UNDERFLOW_P0_OUT; wire RDEN_P0_OUT; wire [C_DOUT_WIDTH-1:0] DATA_P0_IN; wire EMPTY_P0_IN; reg [31:0] DATA_COUNT_FWFT; reg SS_FWFT_WR ; reg SS_FWFT_RD ; wire sbiterr_fifo_out; wire dbiterr_fifo_out; wire inject_sbit_err; wire inject_dbit_err; wire w_fab_read_data_valid_i; wire w_read_data_valid_i; wire w_ram_valid_i; // Assign 0 if not selected to avoid 'X' propogation to S/DBITERR. assign inject_sbit_err = ((C_ERROR_INJECTION_TYPE == 1) || (C_ERROR_INJECTION_TYPE == 3)) ? injectsbiterr_delayed : 0; assign inject_dbit_err = ((C_ERROR_INJECTION_TYPE == 2) || (C_ERROR_INJECTION_TYPE == 3)) ? injectdbiterr_delayed : 0; assign wr_rst_i_out = wr_rst_i; assign rd_rst_i_out = rd_rst_i; // Choose the behavioral model to instantiate based on the C_VERILOG_IMPL // parameter (1=Independent Clocks, 0=Common Clock) localparam FULL_FLAGS_RST_VAL = (C_HAS_SRST == 1) ? 0 : C_FULL_FLAGS_RST_VAL; generate case (C_VERILOG_IMPL) 0 : begin : block1 //Common Clock Behavioral Model fifo_generator_v13_1_1_bhv_ver_ss #( .C_FAMILY (C_FAMILY), .C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH), .C_DIN_WIDTH (C_DIN_WIDTH), .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_FULL_FLAGS_RST_VAL (FULL_FLAGS_RST_VAL), .C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY), .C_HAS_ALMOST_FULL ((C_AXI_TYPE == 0 && C_FIFO_TYPE == 1) ? 1 : C_HAS_ALMOST_FULL), .C_HAS_DATA_COUNT (C_HAS_DATA_COUNT), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT), .C_HAS_RST (C_HAS_RST), .C_HAS_SRST (C_HAS_SRST), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_HAS_VALID (C_HAS_VALID), .C_HAS_WR_ACK (C_HAS_WR_ACK), .C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT), .C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_PRELOAD_LATENCY (C_PRELOAD_LATENCY), .C_PRELOAD_REGS (C_PRELOAD_REGS), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL), .C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL), .C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE), .C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH), .C_RD_DEPTH (C_RD_DEPTH), .C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT), .C_VALID_LOW (C_VALID_LOW), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH), .C_WR_DEPTH (C_WR_DEPTH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH), .C_USE_ECC (C_USE_ECC), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE), .C_FIFO_TYPE (C_FIFO_TYPE) ) gen_ss ( .CLK (CLK), .RST (rst_i), .SRST (srst_delayed), .RST_FULL_GEN (rst_full_gen_i), .RST_FULL_FF (rst_full_ff_i), .DIN (din_delayed), .WR_EN (wr_en_delayed), .RD_EN (RD_EN_FIFO_IN), .RD_EN_USER (rd_en_delayed), .USER_EMPTY_FB (empty_fb), .PROG_EMPTY_THRESH (prog_empty_thresh_delayed), .PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed), .PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed), .PROG_FULL_THRESH (prog_full_thresh_delayed), .PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed), .PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed), .INJECTSBITERR (inject_sbit_err), .INJECTDBITERR (inject_dbit_err), .DOUT (DOUT_FIFO_OUT), .FULL (FULL_FIFO_OUT), .ALMOST_FULL (ALMOST_FULL_FIFO_OUT), .WR_ACK (WR_ACK_FIFO_OUT), .OVERFLOW (OVERFLOW_FIFO_OUT), .EMPTY (EMPTY_FIFO_OUT), .ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT), .VALID (VALID_FIFO_OUT), .UNDERFLOW (UNDERFLOW_FIFO_OUT), .DATA_COUNT (DATA_COUNT_FIFO_OUT), .RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT), .WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT), .PROG_FULL (PROG_FULL_FIFO_OUT), .PROG_EMPTY (PROG_EMPTY_FIFO_OUT), .WR_RST_BUSY (wr_rst_busy), .RD_RST_BUSY (rd_rst_busy), .SBITERR (sbiterr_fifo_out), .DBITERR (dbiterr_fifo_out) ); end 1 : begin : block1 //Independent Clocks Behavioral Model fifo_generator_v13_1_1_bhv_ver_as #( .C_FAMILY (C_FAMILY), .C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH), .C_DIN_WIDTH (C_DIN_WIDTH), .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL), .C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY), .C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL), .C_HAS_DATA_COUNT (C_HAS_DATA_COUNT), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT), .C_HAS_RST (C_HAS_RST), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_HAS_VALID (C_HAS_VALID), .C_HAS_WR_ACK (C_HAS_WR_ACK), .C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT), .C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_PRELOAD_LATENCY (C_PRELOAD_LATENCY), .C_PRELOAD_REGS (C_PRELOAD_REGS), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL), .C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL), .C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE), .C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH), .C_RD_DEPTH (C_RD_DEPTH), .C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT), .C_VALID_LOW (C_VALID_LOW), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH), .C_WR_DEPTH (C_WR_DEPTH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH), .C_USE_ECC (C_USE_ECC), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE) ) gen_as ( .WR_CLK (WR_CLK), .RD_CLK (RD_CLK), .RST (rst_i), .RST_FULL_GEN (rst_full_gen_i), .RST_FULL_FF (rst_full_ff_i), .WR_RST (wr_rst_i), .RD_RST (rd_rst_i), .DIN (din_delayed), .WR_EN (wr_en_delayed), .RD_EN (RD_EN_FIFO_IN), .RD_EN_USER (rd_en_delayed), .PROG_EMPTY_THRESH (prog_empty_thresh_delayed), .PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed), .PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed), .PROG_FULL_THRESH (prog_full_thresh_delayed), .PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed), .PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed), .INJECTSBITERR (inject_sbit_err), .INJECTDBITERR (inject_dbit_err), .USER_EMPTY_FB (EMPTY_P0_OUT), .DOUT (DOUT_FIFO_OUT), .FULL (FULL_FIFO_OUT), .ALMOST_FULL (ALMOST_FULL_FIFO_OUT), .WR_ACK (WR_ACK_FIFO_OUT), .OVERFLOW (OVERFLOW_FIFO_OUT), .EMPTY (EMPTY_FIFO_OUT), .ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT), .VALID (VALID_FIFO_OUT), .UNDERFLOW (UNDERFLOW_FIFO_OUT), .RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT), .WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT), .PROG_FULL (PROG_FULL_FIFO_OUT), .PROG_EMPTY (PROG_EMPTY_FIFO_OUT), .SBITERR (sbiterr_fifo_out), .fab_read_data_valid_i (w_fab_read_data_valid_i), .read_data_valid_i (w_read_data_valid_i), .ram_valid_i (w_ram_valid_i), .DBITERR (dbiterr_fifo_out) ); end 2 : begin : ll_afifo_inst fifo_generator_v13_1_1_beh_ver_ll_afifo #( .C_DIN_WIDTH (C_DIN_WIDTH), .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL), .C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT), .C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT), .C_RD_DEPTH (C_RD_DEPTH), .C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH), .C_WR_DEPTH (C_WR_DEPTH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH), .C_FIFO_TYPE (C_FIFO_TYPE) ) gen_ll_afifo ( .DIN (din_delayed), .RD_CLK (RD_CLK), .RD_EN (rd_en_delayed), .WR_RST (wr_rst_i), .RD_RST (rd_rst_i), .WR_CLK (WR_CLK), .WR_EN (wr_en_delayed), .DOUT (DOUT), .EMPTY (EMPTY), .FULL (FULL) ); end default : begin : block1 //Independent Clocks Behavioral Model fifo_generator_v13_1_1_bhv_ver_as #( .C_FAMILY (C_FAMILY), .C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH), .C_DIN_WIDTH (C_DIN_WIDTH), .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL), .C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY), .C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL), .C_HAS_DATA_COUNT (C_HAS_DATA_COUNT), .C_HAS_OVERFLOW (C_HAS_OVERFLOW), .C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT), .C_HAS_RST (C_HAS_RST), .C_HAS_UNDERFLOW (C_HAS_UNDERFLOW), .C_HAS_VALID (C_HAS_VALID), .C_HAS_WR_ACK (C_HAS_WR_ACK), .C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT), .C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_OVERFLOW_LOW (C_OVERFLOW_LOW), .C_PRELOAD_LATENCY (C_PRELOAD_LATENCY), .C_PRELOAD_REGS (C_PRELOAD_REGS), .C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL), .C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL), .C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE), .C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL), .C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL), .C_PROG_FULL_TYPE (C_PROG_FULL_TYPE), .C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH), .C_RD_DEPTH (C_RD_DEPTH), .C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH), .C_UNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT), .C_VALID_LOW (C_VALID_LOW), .C_WR_ACK_LOW (C_WR_ACK_LOW), .C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH), .C_WR_DEPTH (C_WR_DEPTH), .C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH), .C_USE_ECC (C_USE_ECC), .C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE) ) gen_as ( .WR_CLK (WR_CLK), .RD_CLK (RD_CLK), .RST (rst_i), .RST_FULL_GEN (rst_full_gen_i), .RST_FULL_FF (rst_full_ff_i), .WR_RST (wr_rst_i), .RD_RST (rd_rst_i), .DIN (din_delayed), .WR_EN (wr_en_delayed), .RD_EN (RD_EN_FIFO_IN), .RD_EN_USER (rd_en_delayed), .PROG_EMPTY_THRESH (prog_empty_thresh_delayed), .PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed), .PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed), .PROG_FULL_THRESH (prog_full_thresh_delayed), .PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed), .PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed), .INJECTSBITERR (inject_sbit_err), .INJECTDBITERR (inject_dbit_err), .USER_EMPTY_FB (EMPTY_P0_OUT), .DOUT (DOUT_FIFO_OUT), .FULL (FULL_FIFO_OUT), .ALMOST_FULL (ALMOST_FULL_FIFO_OUT), .WR_ACK (WR_ACK_FIFO_OUT), .OVERFLOW (OVERFLOW_FIFO_OUT), .EMPTY (EMPTY_FIFO_OUT), .ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT), .VALID (VALID_FIFO_OUT), .UNDERFLOW (UNDERFLOW_FIFO_OUT), .RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT), .WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT), .PROG_FULL (PROG_FULL_FIFO_OUT), .PROG_EMPTY (PROG_EMPTY_FIFO_OUT), .SBITERR (sbiterr_fifo_out), .DBITERR (dbiterr_fifo_out) ); end endcase endgenerate //************************************************************************** // Connect Internal Signals // (Signals labeled internal_*) // In the normal case, these signals tie directly to the FIFO's inputs and // outputs. // In the case of Preload Latency 0 or 1, there are intermediate // signals between the internal FIFO and the preload logic. //************************************************************************** //*********************************************** // If First-Word Fall-Through, instantiate // the preload0 (FWFT) module //*********************************************** wire rd_en_to_fwft_fifo; wire sbiterr_fwft; wire dbiterr_fwft; wire [C_DOUT_WIDTH-1:0] dout_fwft; wire empty_fwft; wire rd_en_fifo_in; wire stage2_reg_en_i; wire [1:0] valid_stages_i; wire rst_fwft; //wire empty_p0_out; reg [C_SYNCHRONIZER_STAGE-1:0] pkt_empty_sync = 'b1; localparam IS_FWFT = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? 1 : 0; localparam IS_PKT_FIFO = (C_FIFO_TYPE == 1) ? 1 : 0; localparam IS_AXIS_PKT_FIFO = (C_FIFO_TYPE == 1 && C_AXI_TYPE == 0) ? 1 : 0; assign rst_fwft = (C_COMMON_CLOCK == 0) ? rd_rst_i : (C_HAS_RST == 1) ? rst_i : 1'b0; generate if (IS_FWFT == 1 && C_FIFO_TYPE != 3) begin : block2 fifo_generator_v13_1_1_bhv_ver_preload0 #( .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_HAS_RST (C_HAS_RST), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_HAS_SRST (C_HAS_SRST), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG), .C_USE_ECC (C_USE_ECC), .C_USERVALID_LOW (C_VALID_LOW), .C_USERUNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_FIFO_TYPE (C_FIFO_TYPE) ) fgpl0 ( .RD_CLK (RD_CLK_P0_IN), .RD_RST (RST_P0_IN), .SRST (srst_delayed), .WR_RST_BUSY (wr_rst_busy), .RD_RST_BUSY (rd_rst_busy), .RD_EN (RD_EN_P0_IN), .FIFOEMPTY (EMPTY_P0_IN), .FIFODATA (DATA_P0_IN), .FIFOSBITERR (sbiterr_fifo_out), .FIFODBITERR (dbiterr_fifo_out), // Output .USERDATA (dout_fwft), .USERVALID (VALID_P0_OUT), .USEREMPTY (empty_fwft), .USERALMOSTEMPTY (ALMOSTEMPTY_P0_OUT), .USERUNDERFLOW (UNDERFLOW_P0_OUT), .RAMVALID (), .FIFORDEN (rd_en_fifo_in), .USERSBITERR (sbiterr_fwft), .USERDBITERR (dbiterr_fwft), .STAGE2_REG_EN (stage2_reg_en_i), .fab_read_data_valid_i_o (w_fab_read_data_valid_i), .read_data_valid_i_o (w_read_data_valid_i), .ram_valid_i_o (w_ram_valid_i), .VALID_STAGES (valid_stages_i) ); //*********************************************** // Connect inputs to preload (FWFT) module //*********************************************** //Connect the RD_CLK of the Preload (FWFT) module to CLK if we // have a common-clock FIFO, or RD_CLK if we have an // independent clock FIFO assign RD_CLK_P0_IN = ((C_VERILOG_IMPL == 0) ? CLK : RD_CLK); assign RST_P0_IN = (C_COMMON_CLOCK == 0) ? rd_rst_i : (C_HAS_RST == 1) ? rst_i : 0; assign RD_EN_P0_IN = (C_FIFO_TYPE != 1) ? rd_en_delayed : rd_en_to_fwft_fifo; assign EMPTY_P0_IN = EMPTY_FIFO_OUT; assign DATA_P0_IN = DOUT_FIFO_OUT; //*********************************************** // Connect outputs from preload (FWFT) module //*********************************************** assign VALID = VALID_P0_OUT ; assign ALMOST_EMPTY = ALMOSTEMPTY_P0_OUT; assign UNDERFLOW = UNDERFLOW_P0_OUT ; assign RD_EN_FIFO_IN = rd_en_fifo_in; //*********************************************** // Create DATA_COUNT from First-Word Fall-Through // data count //*********************************************** assign DATA_COUNT = (C_USE_FWFT_DATA_COUNT == 0)? DATA_COUNT_FIFO_OUT: (C_DATA_COUNT_WIDTH>C_RD_PNTR_WIDTH) ? DATA_COUNT_FWFT[C_RD_PNTR_WIDTH:0] : DATA_COUNT_FWFT[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH-C_DATA_COUNT_WIDTH+1]; //*********************************************** // Create DATA_COUNT from First-Word Fall-Through // data count //*********************************************** always @ (posedge RD_CLK_P0_IN or posedge RST_P0_IN) begin if (RST_P0_IN) begin EMPTY_P0_OUT_Q <= #`TCQ 1; ALMOSTEMPTY_P0_OUT_Q <= #`TCQ 1; end else begin EMPTY_P0_OUT_Q <= #`TCQ empty_p0_out; // EMPTY_P0_OUT_Q <= #`TCQ EMPTY_FIFO_OUT; ALMOSTEMPTY_P0_OUT_Q <= #`TCQ ALMOSTEMPTY_P0_OUT; end end //always //*********************************************** // logic for common-clock data count when FWFT is selected //*********************************************** initial begin SS_FWFT_RD = 1'b0; DATA_COUNT_FWFT = 0 ; SS_FWFT_WR = 1'b0 ; end //initial //*********************************************** // common-clock data count is implemented as an // up-down counter. SS_FWFT_WR and SS_FWFT_RD // are the up/down enables for the counter. //*********************************************** always @ (RD_EN or VALID_P0_OUT or WR_EN or FULL_FIFO_OUT or empty_p0_out) begin if (C_VALID_LOW == 1) begin SS_FWFT_RD = (C_FIFO_TYPE != 1) ? (RD_EN && ~VALID_P0_OUT) : (~empty_p0_out && RD_EN && ~VALID_P0_OUT) ; end else begin SS_FWFT_RD = (C_FIFO_TYPE != 1) ? (RD_EN && VALID_P0_OUT) : (~empty_p0_out && RD_EN && VALID_P0_OUT) ; end SS_FWFT_WR = (WR_EN && (~FULL_FIFO_OUT)) ; end //*********************************************** // common-clock data count is implemented as an // up-down counter for FWFT. This always block // calculates the counter. //*********************************************** always @ (posedge RD_CLK_P0_IN or posedge RST_P0_IN) begin if (RST_P0_IN) begin DATA_COUNT_FWFT <= #`TCQ 0; end else begin //if (srst_delayed && (C_HAS_SRST == 1) ) begin if ((srst_delayed | wr_rst_busy | rd_rst_busy) && (C_HAS_SRST == 1) ) begin DATA_COUNT_FWFT <= #`TCQ 0; end else begin case ( {SS_FWFT_WR, SS_FWFT_RD}) 2'b00: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT ; 2'b01: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT - 1 ; 2'b10: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT + 1 ; 2'b11: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT ; endcase end //if SRST end //IF RST end //always end endgenerate // : block2 // AXI Streaming Packet FIFO reg [C_WR_PNTR_WIDTH-1:0] wr_pkt_count = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count_plus1 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count_reg = 0; reg partial_packet = 0; reg stage1_eop_d1 = 0; reg rd_en_fifo_in_d1 = 0; reg eop_at_stage2 = 0; reg ram_pkt_empty = 0; reg ram_pkt_empty_d1 = 0; wire [C_DOUT_WIDTH-1:0] dout_p0_out; wire packet_empty_wr; wire wr_rst_fwft_pkt_fifo; wire dummy_wr_eop; wire ram_wr_en_pkt_fifo; wire wr_eop; wire ram_rd_en_compare; wire stage1_eop; wire pkt_ready_to_read; wire rd_en_2_stage2; // Generate Dummy WR_EOP for partial packet (Only for AXI Streaming) // When Packet EMPTY is high, and FIFO is full, then generate the dummy WR_EOP // When dummy WR_EOP is high, mask the actual EOP to avoid double increment of // write packet count generate if (IS_FWFT == 1 && IS_AXIS_PKT_FIFO == 1) begin // gdummy_wr_eop always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin if (wr_rst_fwft_pkt_fifo) partial_packet <= 1'b0; else begin if (srst_delayed | wr_rst_busy | rd_rst_busy) partial_packet <= #`TCQ 1'b0; else if (ALMOST_FULL_FIFO_OUT && ram_wr_en_pkt_fifo && packet_empty_wr && (~din_delayed[0])) partial_packet <= #`TCQ 1'b1; else if (partial_packet && din_delayed[0] && ram_wr_en_pkt_fifo) partial_packet <= #`TCQ 1'b0; end end end endgenerate // gdummy_wr_eop generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1) begin // gpkt_fifo_fwft assign wr_rst_fwft_pkt_fifo = (C_COMMON_CLOCK == 0) ? wr_rst_i : (C_HAS_RST == 1) ? rst_i:1'b0; assign dummy_wr_eop = ALMOST_FULL_FIFO_OUT && ram_wr_en_pkt_fifo && packet_empty_wr && (~din_delayed[0]) && (~partial_packet); assign packet_empty_wr = (C_COMMON_CLOCK == 1) ? empty_p0_out : pkt_empty_sync[C_SYNCHRONIZER_STAGE-1]; always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) begin stage1_eop_d1 <= 1'b0; rd_en_fifo_in_d1 <= 1'b0; end else begin if (srst_delayed | wr_rst_busy | rd_rst_busy) begin stage1_eop_d1 <= #`TCQ 1'b0; rd_en_fifo_in_d1 <= #`TCQ 1'b0; end else begin stage1_eop_d1 <= #`TCQ stage1_eop; rd_en_fifo_in_d1 <= #`TCQ rd_en_fifo_in; end end end assign stage1_eop = (rd_en_fifo_in_d1) ? DOUT_FIFO_OUT[0] : stage1_eop_d1; assign ram_wr_en_pkt_fifo = wr_en_delayed && (~FULL_FIFO_OUT); assign wr_eop = ram_wr_en_pkt_fifo && ((din_delayed[0] && (~partial_packet)) || dummy_wr_eop); assign ram_rd_en_compare = stage2_reg_en_i && stage1_eop; fifo_generator_v13_1_1_bhv_ver_preload0 #( .C_DOUT_RST_VAL (C_DOUT_RST_VAL), .C_DOUT_WIDTH (C_DOUT_WIDTH), .C_HAS_RST (C_HAS_RST), .C_HAS_SRST (C_HAS_SRST), .C_USE_DOUT_RST (C_USE_DOUT_RST), .C_USE_ECC (C_USE_ECC), .C_USERVALID_LOW (C_VALID_LOW), .C_EN_SAFETY_CKT (C_EN_SAFETY_CKT), .C_USERUNDERFLOW_LOW (C_UNDERFLOW_LOW), .C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC), .C_MEMORY_TYPE (C_MEMORY_TYPE), .C_FIFO_TYPE (2) // Enable low latency fwft logic ) pkt_fifo_fwft ( .RD_CLK (RD_CLK_P0_IN), .RD_RST (rst_fwft), .SRST (srst_delayed), .WR_RST_BUSY (wr_rst_busy), .RD_RST_BUSY (rd_rst_busy), .RD_EN (rd_en_delayed), .FIFOEMPTY (pkt_ready_to_read), .FIFODATA (dout_fwft), .FIFOSBITERR (sbiterr_fwft), .FIFODBITERR (dbiterr_fwft), // Output .USERDATA (dout_p0_out), .USERVALID (), .USEREMPTY (empty_p0_out), .USERALMOSTEMPTY (), .USERUNDERFLOW (), .RAMVALID (), .FIFORDEN (rd_en_2_stage2), .USERSBITERR (SBITERR), .USERDBITERR (DBITERR), .STAGE2_REG_EN (), .VALID_STAGES () ); assign pkt_ready_to_read = ~(!(ram_pkt_empty || empty_fwft) && ((valid_stages_i[0] && valid_stages_i[1]) || eop_at_stage2)); assign rd_en_to_fwft_fifo = ~empty_fwft && rd_en_2_stage2; always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) eop_at_stage2 <= 1'b0; else if (stage2_reg_en_i) eop_at_stage2 <= #`TCQ stage1_eop; end //--------------------------------------------------------------------------- // Write and Read Packet Count //--------------------------------------------------------------------------- always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin if (wr_rst_fwft_pkt_fifo) wr_pkt_count <= 0; else if (srst_delayed | wr_rst_busy | rd_rst_busy) wr_pkt_count <= #`TCQ 0; else if (wr_eop) wr_pkt_count <= #`TCQ wr_pkt_count + 1; end end endgenerate // gpkt_fifo_fwft assign DOUT = (C_FIFO_TYPE != 1) ? dout_fwft : dout_p0_out; assign EMPTY = (C_FIFO_TYPE != 1) ? empty_fwft : empty_p0_out; generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1 && C_COMMON_CLOCK == 1) begin // grss_pkt_cnt always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) begin rd_pkt_count <= 0; rd_pkt_count_plus1 <= 1; end else if (srst_delayed | wr_rst_busy | rd_rst_busy) begin rd_pkt_count <= #`TCQ 0; rd_pkt_count_plus1 <= #`TCQ 1; end else if (stage2_reg_en_i && stage1_eop) begin rd_pkt_count <= #`TCQ rd_pkt_count + 1; rd_pkt_count_plus1 <= #`TCQ rd_pkt_count_plus1 + 1; end end always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) begin ram_pkt_empty <= 1'b1; ram_pkt_empty_d1 <= 1'b1; end else if (SRST | wr_rst_busy | rd_rst_busy) begin ram_pkt_empty <= #`TCQ 1'b1; ram_pkt_empty_d1 <= #`TCQ 1'b1; end else if ((rd_pkt_count == wr_pkt_count) && wr_eop) begin ram_pkt_empty <= #`TCQ 1'b0; ram_pkt_empty_d1 <= #`TCQ 1'b0; end else if (ram_pkt_empty_d1 && rd_en_to_fwft_fifo) begin ram_pkt_empty <= #`TCQ 1'b1; end else if ((rd_pkt_count_plus1 == wr_pkt_count) && ~wr_eop && ~ALMOST_FULL_FIFO_OUT && ram_rd_en_compare) begin ram_pkt_empty_d1 <= #`TCQ 1'b1; end end end endgenerate //grss_pkt_cnt localparam SYNC_STAGE_WIDTH = (C_SYNCHRONIZER_STAGE+1)*C_WR_PNTR_WIDTH; reg [SYNC_STAGE_WIDTH-1:0] wr_pkt_count_q = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pkt_count_b2g = 0; wire [C_WR_PNTR_WIDTH-1:0] wr_pkt_count_rd; generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1 && C_COMMON_CLOCK == 0) begin // gras_pkt_cnt // Delay the write packet count in write clock domain to accomodate the binary to gray conversion delay always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin if (wr_rst_fwft_pkt_fifo) wr_pkt_count_b2g <= 0; else wr_pkt_count_b2g <= #`TCQ wr_pkt_count; end // Synchronize the delayed write packet count in read domain, and also compensate the gray to binay conversion delay always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) wr_pkt_count_q <= 0; else wr_pkt_count_q <= #`TCQ {wr_pkt_count_q[SYNC_STAGE_WIDTH-C_WR_PNTR_WIDTH-1:0],wr_pkt_count_b2g}; end always @* begin if (stage1_eop) rd_pkt_count <= rd_pkt_count_reg + 1; else rd_pkt_count <= rd_pkt_count_reg; end assign wr_pkt_count_rd = wr_pkt_count_q[SYNC_STAGE_WIDTH-1:SYNC_STAGE_WIDTH-C_WR_PNTR_WIDTH]; always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) rd_pkt_count_reg <= 0; else if (rd_en_fifo_in) rd_pkt_count_reg <= #`TCQ rd_pkt_count; end always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin if (rst_fwft) begin ram_pkt_empty <= 1'b1; ram_pkt_empty_d1 <= 1'b1; end else if (rd_pkt_count != wr_pkt_count_rd) begin ram_pkt_empty <= #`TCQ 1'b0; ram_pkt_empty_d1 <= #`TCQ 1'b0; end else if (ram_pkt_empty_d1 && rd_en_to_fwft_fifo) begin ram_pkt_empty <= #`TCQ 1'b1; end else if ((rd_pkt_count == wr_pkt_count_rd) && stage2_reg_en_i) begin ram_pkt_empty_d1 <= #`TCQ 1'b1; end end // Synchronize the empty in write domain always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin if (wr_rst_fwft_pkt_fifo) pkt_empty_sync <= 'b1; else pkt_empty_sync <= #`TCQ {pkt_empty_sync[C_SYNCHRONIZER_STAGE-2:0], empty_p0_out}; end end endgenerate //gras_pkt_cnt generate if (IS_FWFT == 0 || C_FIFO_TYPE == 3) begin : STD_FIFO //*********************************************** // If NOT First-Word Fall-Through, wire the outputs // of the internal _ss or _as FIFO directly to the // output, and do not instantiate the preload0 // module. //*********************************************** assign RD_CLK_P0_IN = 0; assign RST_P0_IN = 0; assign RD_EN_P0_IN = 0; assign RD_EN_FIFO_IN = rd_en_delayed; assign DOUT = DOUT_FIFO_OUT; assign DATA_P0_IN = 0; assign VALID = VALID_FIFO_OUT; assign EMPTY = EMPTY_FIFO_OUT; assign ALMOST_EMPTY = ALMOST_EMPTY_FIFO_OUT; assign EMPTY_P0_IN = 0; assign UNDERFLOW = UNDERFLOW_FIFO_OUT; assign DATA_COUNT = DATA_COUNT_FIFO_OUT; assign SBITERR = sbiterr_fifo_out; assign DBITERR = dbiterr_fifo_out; end endgenerate // STD_FIFO generate if (IS_FWFT == 1 && C_FIFO_TYPE != 1) begin : NO_PKT_FIFO assign empty_p0_out = empty_fwft; assign SBITERR = sbiterr_fwft; assign DBITERR = dbiterr_fwft; assign DOUT = dout_fwft; assign RD_EN_P0_IN = (C_FIFO_TYPE != 1) ? rd_en_delayed : rd_en_to_fwft_fifo; end endgenerate // NO_PKT_FIFO //*********************************************** // Connect user flags to internal signals //*********************************************** //If we are using extra logic for the FWFT data count, then override the //RD_DATA_COUNT output when we are EMPTY or ALMOST_EMPTY. //RD_DATA_COUNT is 0 when EMPTY and 1 when ALMOST_EMPTY. generate if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH>C_RD_PNTR_WIDTH) && (C_USE_EMBEDDED_REG < 3) ) begin : block3 if (C_COMMON_CLOCK == 0) begin : block_ic assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 1 : RD_DATA_COUNT_FIFO_OUT); end //block_ic else begin assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT; end end //block3 endgenerate //If we are using extra logic for the FWFT data count, then override the //RD_DATA_COUNT output when we are EMPTY or ALMOST_EMPTY. //Due to asymmetric ports, RD_DATA_COUNT is 0 when EMPTY or ALMOST_EMPTY. generate if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH <=C_RD_PNTR_WIDTH) && (C_USE_EMBEDDED_REG < 3) ) begin : block30 if (C_COMMON_CLOCK == 0) begin : block_ic assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 0 : RD_DATA_COUNT_FIFO_OUT); end else begin assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT; end end //block30 endgenerate //If we are using extra logic for the FWFT data count, then override the //RD_DATA_COUNT output when we are EMPTY or ALMOST_EMPTY. //Due to asymmetric ports, RD_DATA_COUNT is 0 when EMPTY or ALMOST_EMPTY. generate if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH <=C_RD_PNTR_WIDTH) && (C_USE_EMBEDDED_REG == 3) ) begin : block30_both if (C_COMMON_CLOCK == 0) begin : block_ic_both assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 0 : (RD_DATA_COUNT_FIFO_OUT)); end else begin assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT; end end //block30_both endgenerate generate if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH>C_RD_PNTR_WIDTH) && (C_USE_EMBEDDED_REG == 3) ) begin : block3_both if (C_COMMON_CLOCK == 0) begin : block_ic_both assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 1 : (RD_DATA_COUNT_FIFO_OUT)); end //block_ic_both else begin assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT; end end //block3_both endgenerate //If we are not using extra logic for the FWFT data count, //then connect RD_DATA_COUNT to the RD_DATA_COUNT from the //internal FIFO instance generate if (C_USE_FWFT_DATA_COUNT==0 ) begin : block31 assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT; end endgenerate //Always connect WR_DATA_COUNT to the WR_DATA_COUNT from the internal //FIFO instance generate if (C_USE_FWFT_DATA_COUNT==1) begin : block4 assign WR_DATA_COUNT = WR_DATA_COUNT_FIFO_OUT; end else begin : block4 assign WR_DATA_COUNT = WR_DATA_COUNT_FIFO_OUT; end endgenerate //Connect other flags to the internal FIFO instance assign FULL = FULL_FIFO_OUT; assign ALMOST_FULL = ALMOST_FULL_FIFO_OUT; assign WR_ACK = WR_ACK_FIFO_OUT; assign OVERFLOW = OVERFLOW_FIFO_OUT; assign PROG_FULL = PROG_FULL_FIFO_OUT; assign PROG_EMPTY = PROG_EMPTY_FIFO_OUT; /************************************************************************** * find_log2 * Returns the 'log2' value for the input value for the supported ratios ***************************************************************************/ function integer find_log2; input integer int_val; integer i,j; begin i = 1; j = 0; for (i = 1; i < int_val; i = i*2) begin j = j + 1; end find_log2 = j; end endfunction // if an asynchronous FIFO has been selected, display a message that the FIFO // will not be cycle-accurate in simulation initial begin if (C_IMPLEMENTATION_TYPE == 2) begin $display("WARNING: Behavioral models for independent clock FIFO configurations do not model synchronization delays. The behavioral models are functionally correct, and will represent the behavior of the configured FIFO. See the FIFO Generator User Guide for more information."); end else if (C_MEMORY_TYPE == 4) begin $display("FAILURE : Behavioral models do not support built-in FIFO configurations. Please use post-synthesis or post-implement simulation in Vivado."); $finish; end if (C_WR_PNTR_WIDTH != find_log2(C_WR_DEPTH)) begin $display("FAILURE : C_WR_PNTR_WIDTH is not log2 of C_WR_DEPTH."); $finish; end if (C_RD_PNTR_WIDTH != find_log2(C_RD_DEPTH)) begin $display("FAILURE : C_RD_PNTR_WIDTH is not log2 of C_RD_DEPTH."); $finish; end if (C_USE_ECC == 1) begin if (C_DIN_WIDTH != C_DOUT_WIDTH) begin $display("FAILURE : C_DIN_WIDTH and C_DOUT_WIDTH must be equal for ECC configuration."); $finish; end if (C_DIN_WIDTH == 1 && C_ERROR_INJECTION_TYPE > 1) begin $display("FAILURE : C_DIN_WIDTH and C_DOUT_WIDTH must be > 1 for double bit error injection."); $finish; end end end //initial /************************************************************************** * Internal reset logic **************************************************************************/ assign wr_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? wr_rst_reg : 0; assign rd_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? rd_rst_reg : 0; assign rst_i = C_HAS_RST ? rst_reg : 0; wire rst_2_sync; wire rst_2_sync_safety = (C_ENABLE_RST_SYNC == 1) ? RST : RD_RST; wire clk_2_sync = (C_COMMON_CLOCK == 1) ? CLK : WR_CLK; wire clk_2_sync_safety = (C_COMMON_CLOCK == 1) ? CLK : RD_CLK; generate if (C_EN_SAFETY_CKT == 1 && C_INTERFACE_TYPE == 0) begin : grst_safety_ckt reg[1:0] rst_d1_safety =1; reg[1:0] rst_d2_safety =1; reg[1:0] rst_d3_safety =1; reg[1:0] rst_d4_safety =1; reg[1:0] rst_d5_safety =1; reg[1:0] rst_d6_safety =1; reg[1:0] rst_d7_safety =1; always@(posedge rst_2_sync_safety or posedge clk_2_sync_safety) begin : prst if (rst_2_sync_safety == 1'b1) begin rst_d1_safety <= 1'b1; rst_d2_safety <= 1'b1; rst_d3_safety <= 1'b1; rst_d4_safety <= 1'b1; rst_d5_safety <= 1'b1; rst_d6_safety <= 1'b1; rst_d7_safety <= 1'b1; end else begin rst_d1_safety <= #`TCQ 1'b0; rst_d2_safety <= #`TCQ rst_d1_safety; rst_d3_safety <= #`TCQ rst_d2_safety; rst_d4_safety <= #`TCQ rst_d3_safety; rst_d5_safety <= #`TCQ rst_d4_safety; rst_d6_safety <= #`TCQ rst_d5_safety; rst_d7_safety <= #`TCQ rst_d6_safety; end //if end //prst always@(posedge rst_d7_safety or posedge WR_EN) begin : assert_safety if(rst_d7_safety == 1 && WR_EN == 1) begin $display("WARNING:A write attempt has been made within the 7 clock cycles of reset de-assertion. This can lead to data discrepancy when safety circuit is enabled."); end //if end //always end // grst_safety_ckt endgenerate // if (C_EN_SAFET_CKT == 1) // assertion:the reset shud be atleast 3 cycles wide. generate if (C_ENABLE_RST_SYNC == 0) begin : gnrst_sync always @* begin wr_rst_reg <= wr_rst_delayed; rd_rst_reg <= rd_rst_delayed; rst_reg <= 1'b0; srst_reg <= 1'b0; end assign rst_2_sync = wr_rst_delayed; assign wr_rst_busy = 1'b0; assign rd_rst_busy = 1'b0; end else if (C_HAS_RST == 1 && C_COMMON_CLOCK == 0) begin : g7s_ic_rst assign wr_rst_comb = !wr_rst_asreg_d2 && wr_rst_asreg; assign rd_rst_comb = !rd_rst_asreg_d2 && rd_rst_asreg; assign rst_2_sync = rst_delayed; assign wr_rst_busy = 1'b0; assign rd_rst_busy = 1'b0; always @(posedge WR_CLK or posedge rst_delayed) begin if (rst_delayed == 1'b1) begin wr_rst_asreg <= #`TCQ 1'b1; end else begin if (wr_rst_asreg_d1 == 1'b1) begin wr_rst_asreg <= #`TCQ 1'b0; end else begin wr_rst_asreg <= #`TCQ wr_rst_asreg; end end end always @(posedge WR_CLK) begin wr_rst_asreg_d1 <= #`TCQ wr_rst_asreg; wr_rst_asreg_d2 <= #`TCQ wr_rst_asreg_d1; end always @(posedge WR_CLK or posedge wr_rst_comb) begin if (wr_rst_comb == 1'b1) begin wr_rst_reg <= #`TCQ 1'b1; end else begin wr_rst_reg <= #`TCQ 1'b0; end end always @(posedge RD_CLK or posedge rst_delayed) begin if (rst_delayed == 1'b1) begin rd_rst_asreg <= #`TCQ 1'b1; end else begin if (rd_rst_asreg_d1 == 1'b1) begin rd_rst_asreg <= #`TCQ 1'b0; end else begin rd_rst_asreg <= #`TCQ rd_rst_asreg; end end end always @(posedge RD_CLK) begin rd_rst_asreg_d1 <= #`TCQ rd_rst_asreg; rd_rst_asreg_d2 <= #`TCQ rd_rst_asreg_d1; end always @(posedge RD_CLK or posedge rd_rst_comb) begin if (rd_rst_comb == 1'b1) begin rd_rst_reg <= #`TCQ 1'b1; end else begin rd_rst_reg <= #`TCQ 1'b0; end end end else if (C_HAS_RST == 1 && C_COMMON_CLOCK == 1) begin : g7s_cc_rst assign rst_comb = !rst_asreg_d2 && rst_asreg; assign rst_2_sync = rst_delayed; assign wr_rst_busy = 1'b0; assign rd_rst_busy = 1'b0; always @(posedge CLK or posedge rst_delayed) begin if (rst_delayed == 1'b1) begin rst_asreg <= #`TCQ 1'b1; end else begin if (rst_asreg_d1 == 1'b1) begin rst_asreg <= #`TCQ 1'b0; end else begin rst_asreg <= #`TCQ rst_asreg; end end end always @(posedge CLK) begin rst_asreg_d1 <= #`TCQ rst_asreg; rst_asreg_d2 <= #`TCQ rst_asreg_d1; end always @(posedge CLK or posedge rst_comb) begin if (rst_comb == 1'b1) begin rst_reg <= #`TCQ 1'b1; end else begin rst_reg <= #`TCQ 1'b0; end end end else if (IS_8SERIES == 1 && C_HAS_SRST == 1 && C_COMMON_CLOCK == 1) begin : g8s_cc_rst assign wr_rst_busy = (C_MEMORY_TYPE != 4) ? rst_reg : rst_active_i; assign rd_rst_busy = rst_reg; assign rst_2_sync = srst_delayed; always @* rst_full_ff_i <= rst_reg; always @* rst_full_gen_i <= C_FULL_FLAGS_RST_VAL == 1 ? rst_active_i : 0; always @(posedge CLK) begin rst_delayed_d1 <= #`TCQ srst_delayed; rst_delayed_d2 <= #`TCQ rst_delayed_d1; if (rst_reg || rst_delayed_d2) begin rst_active_i <= #`TCQ 1'b1; end else begin rst_active_i <= #`TCQ rst_reg; end end always @(posedge CLK) begin if (~rst_reg && srst_delayed) begin rst_reg <= #`TCQ 1'b1; end else if (rst_reg) begin rst_reg <= #`TCQ 1'b0; end else begin rst_reg <= #`TCQ rst_reg; end end end else begin assign wr_rst_busy = 1'b0; assign rd_rst_busy = 1'b0; end // end g8s_cc_rst endgenerate reg rst_d1 = 1'b0; reg rst_d2 = 1'b0; reg rst_d3 = 1'b0; reg rst_d4 = 1'b0; reg rst_d5 = 1'b0; reg rst_d6 = 1'b0; reg rst_d7 = 1'b0; generate if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 1 && C_INTERFACE_TYPE == 0) begin : grstd1 // RST_FULL_GEN replaces the reset falling edge detection used to de-assert // FULL, ALMOST_FULL & PROG_FULL flags if C_FULL_FLAGS_RST_VAL = 1. // RST_FULL_FF goes to the reset pin of the final flop of FULL, ALMOST_FULL & // PROG_FULL always @ (posedge rst_2_sync or posedge clk_2_sync) begin if (rst_2_sync) begin rst_d1 <= 1'b1; rst_d2 <= 1'b1; rst_d3 <= 1'b1; rst_d4 <= 1'b1; rst_d5 <= 1'b1; rst_d6 <= 1'b1; rst_d7 <= 1'b1; end else begin if (srst_delayed) begin rst_d1 <= #`TCQ 1'b1; rst_d2 <= #`TCQ 1'b1; rst_d3 <= #`TCQ 1'b1; rst_d4 <= #`TCQ 1'b1; rst_d5 <= #`TCQ 1'b1; rst_d6 <= #`TCQ 1'b1; rst_d7 <= #`TCQ 1'b1; end else begin rst_d1 <= #`TCQ 1'b0; rst_d2 <= #`TCQ rst_d1; rst_d3 <= #`TCQ rst_d2; rst_d4 <= #`TCQ rst_d3; rst_d5 <= #`TCQ rst_d4; rst_d6 <= #`TCQ rst_d5; rst_d7 <= #`TCQ rst_d6; end end end always @* rst_full_ff_i <= (C_HAS_SRST == 0 && C_EN_SAFETY_CKT == 0) ? rst_d2 : (C_HAS_SRST == 0 && C_EN_SAFETY_CKT == 1) ? rst_d6 : 1'b0 ; //always @* rst_full_gen_i <= rst_d4; always @* rst_full_gen_i <= (C_HAS_SRST == 1) ? rst_d4 : (C_EN_SAFETY_CKT == 0) ? rst_d3 : rst_d7; end else if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 0 && C_INTERFACE_TYPE == 0) begin : gnrst_full always @* rst_full_ff_i <= (C_COMMON_CLOCK == 0) ? wr_rst_i : rst_i; end endgenerate // grstd1 generate if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 1 && C_INTERFACE_TYPE > 0) begin : grstd1_axis // RST_FULL_GEN replaces the reset falling edge detection used to de-assert // FULL, ALMOST_FULL & PROG_FULL flags if C_FULL_FLAGS_RST_VAL = 1. // RST_FULL_FF goes to the reset pin of the final flop of FULL, ALMOST_FULL & // PROG_FULL always @ (posedge rst_2_sync or posedge clk_2_sync) begin if (rst_2_sync) begin rst_d1 <= 1'b1; rst_d2 <= 1'b1; rst_d3 <= 1'b1; rst_d4 <= 1'b1; rst_d5 <= 1'b1; rst_d6 <= 1'b1; rst_d7 <= 1'b1; end else begin if (srst_delayed) begin rst_d1 <= #`TCQ 1'b1; rst_d2 <= #`TCQ 1'b1; rst_d3 <= #`TCQ 1'b1; rst_d4 <= #`TCQ 1'b1; rst_d5 <= #`TCQ 1'b1; rst_d6 <= #`TCQ 1'b1; rst_d7 <= #`TCQ 1'b1; end else begin rst_d1 <= #`TCQ 1'b0; rst_d2 <= #`TCQ rst_d1; rst_d3 <= #`TCQ rst_d2; rst_d4 <= #`TCQ rst_d3; rst_d5 <= #`TCQ rst_d4; rst_d6 <= #`TCQ rst_d5; rst_d7 <= #`TCQ rst_d6; end end end always @* rst_full_ff_i <= (C_HAS_SRST == 0) ? rst_d2 : 1'b0 ; //always @* rst_full_gen_i <= rst_d4; always @* rst_full_gen_i <= (C_HAS_SRST == 1) ? rst_d4 : (C_EN_SAFETY_CKT == 0) ? rst_d3 : rst_d5; end else if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 0 && C_INTERFACE_TYPE > 0) begin : gnrst_full_axis always @* rst_full_ff_i <= (C_COMMON_CLOCK == 0) ? wr_rst_i : rst_i; end endgenerate // grstd1_axis endmodule //fifo_generator_v13_1_1_CONV_VER module fifo_generator_v13_1_1_sync_stage #( parameter C_WIDTH = 10 ) ( input RST, input CLK, input [C_WIDTH-1:0] DIN, output reg [C_WIDTH-1:0] DOUT = 0 ); always @ (posedge RST or posedge CLK) begin if (RST) DOUT <= 0; else DOUT <= #`TCQ DIN; end endmodule // fifo_generator_v13_1_1_sync_stage /******************************************************************************* * Declaration of Independent-Clocks FIFO Module ******************************************************************************/ module fifo_generator_v13_1_1_bhv_ver_as /*************************************************************************** * Declare user parameters and their defaults ***************************************************************************/ #( parameter C_FAMILY = "virtex7", parameter C_DATA_COUNT_WIDTH = 2, parameter C_DIN_WIDTH = 8, parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_FULL_FLAGS_RST_VAL = 1, parameter C_HAS_ALMOST_EMPTY = 0, parameter C_HAS_ALMOST_FULL = 0, parameter C_HAS_DATA_COUNT = 0, parameter C_HAS_OVERFLOW = 0, parameter C_HAS_RD_DATA_COUNT = 0, parameter C_HAS_RST = 0, parameter C_HAS_UNDERFLOW = 0, parameter C_HAS_VALID = 0, parameter C_HAS_WR_ACK = 0, parameter C_HAS_WR_DATA_COUNT = 0, parameter C_IMPLEMENTATION_TYPE = 0, parameter C_MEMORY_TYPE = 1, parameter C_OVERFLOW_LOW = 0, parameter C_PRELOAD_LATENCY = 1, parameter C_PRELOAD_REGS = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0, parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0, parameter C_PROG_EMPTY_TYPE = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0, parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0, parameter C_PROG_FULL_TYPE = 0, parameter C_RD_DATA_COUNT_WIDTH = 2, parameter C_RD_DEPTH = 256, parameter C_RD_PNTR_WIDTH = 8, parameter C_UNDERFLOW_LOW = 0, parameter C_USE_DOUT_RST = 0, parameter C_USE_EMBEDDED_REG = 0, parameter C_EN_SAFETY_CKT = 0, parameter C_USE_FWFT_DATA_COUNT = 0, parameter C_VALID_LOW = 0, parameter C_WR_ACK_LOW = 0, parameter C_WR_DATA_COUNT_WIDTH = 2, parameter C_WR_DEPTH = 256, parameter C_WR_PNTR_WIDTH = 8, parameter C_USE_ECC = 0, parameter C_ENABLE_RST_SYNC = 1, parameter C_ERROR_INJECTION_TYPE = 0, parameter C_SYNCHRONIZER_STAGE = 2 ) /*************************************************************************** * Declare Input and Output Ports ***************************************************************************/ ( input [C_DIN_WIDTH-1:0] DIN, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE, input RD_CLK, input RD_EN, input RD_EN_USER, input RST, input RST_FULL_GEN, input RST_FULL_FF, input WR_RST, input RD_RST, input WR_CLK, input WR_EN, input INJECTDBITERR, input INJECTSBITERR, input USER_EMPTY_FB, input fab_read_data_valid_i, input read_data_valid_i, input ram_valid_i, output reg ALMOST_EMPTY = 1'b1, output reg ALMOST_FULL = C_FULL_FLAGS_RST_VAL, output [C_DOUT_WIDTH-1:0] DOUT, output reg EMPTY = 1'b1, output reg FULL = C_FULL_FLAGS_RST_VAL, output OVERFLOW, output PROG_EMPTY, output PROG_FULL, output VALID, output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT, output UNDERFLOW, output WR_ACK, output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT, output SBITERR, output DBITERR ); reg [C_RD_PNTR_WIDTH:0] rd_data_count_int = 0; reg [C_WR_PNTR_WIDTH:0] wr_data_count_int = 0; reg [C_WR_PNTR_WIDTH:0] wdc_fwft_ext_as = 0; /*************************************************************************** * Parameters used as constants **************************************************************************/ localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexuplus" || C_FAMILY == "zynquplus" || C_FAMILY == "kintexuplus") ? 1 : 0; //When RST is present, set FULL reset value to '1'. //If core has no RST, make sure FULL powers-on as '0'. localparam C_DEPTH_RATIO_WR = (C_WR_DEPTH>C_RD_DEPTH) ? (C_WR_DEPTH/C_RD_DEPTH) : 1; localparam C_DEPTH_RATIO_RD = (C_RD_DEPTH>C_WR_DEPTH) ? (C_RD_DEPTH/C_WR_DEPTH) : 1; localparam C_FIFO_WR_DEPTH = C_WR_DEPTH - 1; localparam C_FIFO_RD_DEPTH = C_RD_DEPTH - 1; // C_DEPTH_RATIO_WR | C_DEPTH_RATIO_RD | C_PNTR_WIDTH | EXTRA_WORDS_DC // -----------------|------------------|-----------------|--------------- // 1 | 8 | C_RD_PNTR_WIDTH | 2 // 1 | 4 | C_RD_PNTR_WIDTH | 2 // 1 | 2 | C_RD_PNTR_WIDTH | 2 // 1 | 1 | C_WR_PNTR_WIDTH | 2 // 2 | 1 | C_WR_PNTR_WIDTH | 4 // 4 | 1 | C_WR_PNTR_WIDTH | 8 // 8 | 1 | C_WR_PNTR_WIDTH | 16 localparam C_PNTR_WIDTH = (C_WR_PNTR_WIDTH>=C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH; wire [C_PNTR_WIDTH:0] EXTRA_WORDS_DC = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD); localparam [31:0] reads_per_write = C_DIN_WIDTH/C_DOUT_WIDTH; localparam [31:0] log2_reads_per_write = log2_val(reads_per_write); localparam [31:0] writes_per_read = C_DOUT_WIDTH/C_DIN_WIDTH; localparam [31:0] log2_writes_per_read = log2_val(writes_per_read); /************************************************************************** * FIFO Contents Tracking and Data Count Calculations *************************************************************************/ // Memory which will be used to simulate a FIFO reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0]; // Local parameters used to determine whether to inject ECC error or not localparam SYMMETRIC_PORT = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 1 : 0; localparam ERR_INJECTION = (C_ERROR_INJECTION_TYPE != 0) ? 1 : 0; localparam C_USE_ECC_1 = (C_USE_ECC == 1 || C_USE_ECC ==2) ? 1:0; localparam ENABLE_ERR_INJECTION = C_USE_ECC_1 && SYMMETRIC_PORT && ERR_INJECTION; // Array that holds the error injection type (single/double bit error) on // a specific write operation, which is returned on read to corrupt the // output data. reg [1:0] ecc_err[C_WR_DEPTH-1:0]; //The amount of data stored in the FIFO at any time is given // by num_wr_bits (in the WR_CLK domain) and num_rd_bits (in the RD_CLK // domain. //num_wr_bits is calculated by considering the total words in the FIFO, // and the state of the read pointer (which may not have yet crossed clock // domains.) //num_rd_bits is calculated by considering the total words in the FIFO, // and the state of the write pointer (which may not have yet crossed clock // domains.) reg [31:0] num_wr_bits; reg [31:0] num_rd_bits; reg [31:0] next_num_wr_bits; reg [31:0] next_num_rd_bits; //The write pointer - tracks write operations // (Works opposite to core: wr_ptr is a DOWN counter) reg [31:0] wr_ptr; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr = 0; // UP counter: Rolls back to 0 when reaches to max value. reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd1 = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd2 = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd3 = 0; wire [C_RD_PNTR_WIDTH-1:0] adj_wr_pntr_rd; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd = 0; wire wr_rst_i = WR_RST; reg wr_rst_d1 =0; //The read pointer - tracks read operations // (rd_ptr Works opposite to core: rd_ptr is a DOWN counter) reg [31:0] rd_ptr; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr = 0; // UP counter: Rolls back to 0 when reaches to max value. reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr1 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr2 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr3 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr4 = 0; wire [C_WR_PNTR_WIDTH-1:0] adj_rd_pntr_wr; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr = 0; wire rd_rst_i = RD_RST; wire ram_rd_en; wire empty_int; wire almost_empty_int; wire ram_wr_en; wire full_int; wire almost_full_int; reg ram_rd_en_d1 = 1'b0; reg fab_rd_en_d1 = 1'b0; // Delayed ram_rd_en is needed only for STD Embedded register option generate if (C_PRELOAD_LATENCY == 2) begin : grd_d always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) ram_rd_en_d1 <= #`TCQ 1'b0; else ram_rd_en_d1 <= #`TCQ ram_rd_en; end end endgenerate generate if (C_PRELOAD_LATENCY == 2 && C_USE_EMBEDDED_REG == 3) begin : grd_d1 always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) ram_rd_en_d1 <= #`TCQ 1'b0; else ram_rd_en_d1 <= #`TCQ ram_rd_en; fab_rd_en_d1 <= #`TCQ ram_rd_en_d1; end end endgenerate // Write pointer adjustment based on pointers width for EMPTY/ALMOST_EMPTY generation generate if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin : rdg // Read depth greater than write depth assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr_rd; assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1:0] = 0; end else begin : rdl // Read depth lesser than or equal to write depth assign adj_wr_pntr_rd = wr_pntr_rd[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH]; end endgenerate // Generate Empty and Almost Empty // ram_rd_en used to determine EMPTY should depend on the EMPTY. assign ram_rd_en = RD_EN & !EMPTY; assign empty_int = ((adj_wr_pntr_rd == rd_pntr) || (ram_rd_en && (adj_wr_pntr_rd == (rd_pntr+1'h1)))); assign almost_empty_int = ((adj_wr_pntr_rd == (rd_pntr+1'h1)) || (ram_rd_en && (adj_wr_pntr_rd == (rd_pntr+2'h2)))); // Register Empty and Almost Empty always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin EMPTY <= #`TCQ 1'b1; ALMOST_EMPTY <= #`TCQ 1'b1; rd_data_count_int <= #`TCQ {C_RD_PNTR_WIDTH{1'b0}}; end else begin rd_data_count_int <= #`TCQ {(adj_wr_pntr_rd[C_RD_PNTR_WIDTH-1:0] - rd_pntr[C_RD_PNTR_WIDTH-1:0]), 1'b0}; if (empty_int) EMPTY <= #`TCQ 1'b1; else EMPTY <= #`TCQ 1'b0; if (!EMPTY) begin if (almost_empty_int) ALMOST_EMPTY <= #`TCQ 1'b1; else ALMOST_EMPTY <= #`TCQ 1'b0; end end // rd_rst_i end // always // Read pointer adjustment based on pointers width for EMPTY/ALMOST_EMPTY generation generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : wdg // Write depth greater than read depth assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr_wr; assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1:0] = 0; end else begin : wdl // Write depth lesser than or equal to read depth assign adj_rd_pntr_wr = rd_pntr_wr[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH]; end endgenerate // Generate FULL and ALMOST_FULL // ram_wr_en used to determine FULL should depend on the FULL. assign ram_wr_en = WR_EN & !FULL; assign full_int = ((adj_rd_pntr_wr == (wr_pntr+1'h1)) || (ram_wr_en && (adj_rd_pntr_wr == (wr_pntr+2'h2)))); assign almost_full_int = ((adj_rd_pntr_wr == (wr_pntr+2'h2)) || (ram_wr_en && (adj_rd_pntr_wr == (wr_pntr+3'h3)))); // Register FULL and ALMOST_FULL Empty always @ (posedge WR_CLK or posedge RST_FULL_FF) begin if (RST_FULL_FF) begin FULL <= #`TCQ C_FULL_FLAGS_RST_VAL; ALMOST_FULL <= #`TCQ C_FULL_FLAGS_RST_VAL; end else begin if (full_int) begin FULL <= #`TCQ 1'b1; end else begin FULL <= #`TCQ 1'b0; end if (RST_FULL_GEN) begin ALMOST_FULL <= #`TCQ 1'b0; end else if (!FULL) begin if (almost_full_int) ALMOST_FULL <= #`TCQ 1'b1; else ALMOST_FULL <= #`TCQ 1'b0; end end // wr_rst_i end // always always @ (posedge WR_CLK or posedge wr_rst_i) begin if (wr_rst_i) begin wr_data_count_int <= #`TCQ {C_WR_DATA_COUNT_WIDTH{1'b0}}; end else begin wr_data_count_int <= #`TCQ {(wr_pntr[C_WR_PNTR_WIDTH-1:0] - adj_rd_pntr_wr[C_WR_PNTR_WIDTH-1:0]), 1'b0}; end // wr_rst_i end // always // Determine which stage in FWFT registers are valid reg stage1_valid = 0; reg stage2_valid = 0; generate if (C_PRELOAD_LATENCY == 0) begin : grd_fwft_proc always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin stage1_valid <= #`TCQ 0; stage2_valid <= #`TCQ 0; end else begin if (!stage1_valid && !stage2_valid) begin if (!EMPTY) stage1_valid <= #`TCQ 1'b1; else stage1_valid <= #`TCQ 1'b0; end else if (stage1_valid && !stage2_valid) begin if (EMPTY) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end end else if (!stage1_valid && stage2_valid) begin if (EMPTY && RD_EN_USER) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b0; end else if (!EMPTY && RD_EN_USER) begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b0; end else if (!EMPTY && !RD_EN_USER) begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end end else if (stage1_valid && stage2_valid) begin if (EMPTY && RD_EN_USER) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end end else begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b0; end end // rd_rst_i end // always end endgenerate //Pointers passed into opposite clock domain reg [31:0] wr_ptr_rdclk; reg [31:0] wr_ptr_rdclk_next; reg [31:0] rd_ptr_wrclk; reg [31:0] rd_ptr_wrclk_next; //Amount of data stored in the FIFO scaled to the narrowest (deepest) port // (Do not include data in FWFT stages) //Used to calculate PROG_EMPTY. wire [31:0] num_read_words_pe = num_rd_bits/(C_DOUT_WIDTH/C_DEPTH_RATIO_WR); //Amount of data stored in the FIFO scaled to the narrowest (deepest) port // (Do not include data in FWFT stages) //Used to calculate PROG_FULL. wire [31:0] num_write_words_pf = num_wr_bits/(C_DIN_WIDTH/C_DEPTH_RATIO_RD); /************************** * Read Data Count *************************/ reg [31:0] num_read_words_dc; reg [C_RD_DATA_COUNT_WIDTH-1:0] num_read_words_sized_i; always @(num_rd_bits) begin if (C_USE_FWFT_DATA_COUNT) begin //If using extra logic for FWFT Data Counts, // then scale FIFO contents to read domain, // and add two read words for FWFT stages //This value is only a temporary value and not used in the code. num_read_words_dc = (num_rd_bits/C_DOUT_WIDTH+2); //Trim the read words for use with RD_DATA_COUNT num_read_words_sized_i = num_read_words_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH+1]; end else begin //If not using extra logic for FWFT Data Counts, // then scale FIFO contents to read domain. //This value is only a temporary value and not used in the code. num_read_words_dc = num_rd_bits/C_DOUT_WIDTH; //Trim the read words for use with RD_DATA_COUNT num_read_words_sized_i = num_read_words_dc[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH]; end //if (C_USE_FWFT_DATA_COUNT) end //always /************************** * Write Data Count *************************/ reg [31:0] num_write_words_dc; reg [C_WR_DATA_COUNT_WIDTH-1:0] num_write_words_sized_i; always @(num_wr_bits) begin if (C_USE_FWFT_DATA_COUNT) begin //Calculate the Data Count value for the number of write words, // when using First-Word Fall-Through with extra logic for Data // Counts. This takes into consideration the number of words that // are expected to be stored in the FWFT register stages (it always // assumes they are filled). //This value is scaled to the Write Domain. //The expression (((A-1)/B))+1 divides A/B, but takes the // ceiling of the result. //When num_wr_bits==0, set the result manually to prevent // division errors. //EXTRA_WORDS_DC is the number of words added to write_words // due to FWFT. //This value is only a temporary value and not used in the code. num_write_words_dc = (num_wr_bits==0) ? EXTRA_WORDS_DC : (((num_wr_bits-1)/C_DIN_WIDTH)+1) + EXTRA_WORDS_DC ; //Trim the write words for use with WR_DATA_COUNT num_write_words_sized_i = num_write_words_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH+1]; end else begin //Calculate the Data Count value for the number of write words, when NOT // using First-Word Fall-Through with extra logic for Data Counts. This // calculates only the number of words in the internal FIFO. //The expression (((A-1)/B))+1 divides A/B, but takes the // ceiling of the result. //This value is scaled to the Write Domain. //When num_wr_bits==0, set the result manually to prevent // division errors. //This value is only a temporary value and not used in the code. num_write_words_dc = (num_wr_bits==0) ? 0 : ((num_wr_bits-1)/C_DIN_WIDTH)+1; //Trim the read words for use with RD_DATA_COUNT num_write_words_sized_i = num_write_words_dc[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH]; end //if (C_USE_FWFT_DATA_COUNT) end //always /*************************************************************************** * Internal registers and wires **************************************************************************/ //Temporary signals used for calculating the model's outputs. These //are only used in the assign statements immediately following wire, //parameter, and function declarations. wire [C_DOUT_WIDTH-1:0] ideal_dout_out; wire valid_i; wire valid_out1; wire valid_out2; wire valid_out; wire underflow_i; //Ideal FIFO signals. These are the raw output of the behavioral model, //which behaves like an ideal FIFO. reg [1:0] err_type = 0; reg [1:0] err_type_d1 = 0; reg [1:0] err_type_both = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout_d1 = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout_both = 0; reg ideal_wr_ack = 0; reg ideal_valid = 0; reg ideal_overflow = C_OVERFLOW_LOW; reg ideal_underflow = C_UNDERFLOW_LOW; reg ideal_prog_full = 0; reg ideal_prog_empty = 1; reg [C_WR_DATA_COUNT_WIDTH-1 : 0] ideal_wr_count = 0; reg [C_RD_DATA_COUNT_WIDTH-1 : 0] ideal_rd_count = 0; //Assorted reg values for delayed versions of signals reg valid_d1 = 0; reg valid_d2 = 0; //user specified value for reseting the size of the fifo reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0; //temporary registers for WR_RESPONSE_LATENCY feature integer tmp_wr_listsize; integer tmp_rd_listsize; //Signal for registered version of prog full and empty //Threshold values for Programmable Flags integer prog_empty_actual_thresh_assert; integer prog_empty_actual_thresh_negate; integer prog_full_actual_thresh_assert; integer prog_full_actual_thresh_negate; /**************************************************************************** * Function Declarations ***************************************************************************/ /************************************************************************** * write_fifo * This task writes a word to the FIFO memory and updates the * write pointer. * FIFO size is relative to write domain. ***************************************************************************/ task write_fifo; begin memory[wr_ptr] <= DIN; wr_pntr <= #`TCQ wr_pntr + 1; // Store the type of error injection (double/single) on write case (C_ERROR_INJECTION_TYPE) 3: ecc_err[wr_ptr] <= {INJECTDBITERR,INJECTSBITERR}; 2: ecc_err[wr_ptr] <= {INJECTDBITERR,1'b0}; 1: ecc_err[wr_ptr] <= {1'b0,INJECTSBITERR}; default: ecc_err[wr_ptr] <= 0; endcase // (Works opposite to core: wr_ptr is a DOWN counter) if (wr_ptr == 0) begin wr_ptr <= C_WR_DEPTH - 1; end else begin wr_ptr <= wr_ptr - 1; end end endtask // write_fifo /************************************************************************** * read_fifo * This task reads a word from the FIFO memory and updates the read * pointer. It's output is the ideal_dout bus. * FIFO size is relative to write domain. ***************************************************************************/ task read_fifo; integer i; reg [C_DOUT_WIDTH-1:0] tmp_dout; reg [C_DIN_WIDTH-1:0] memory_read; reg [31:0] tmp_rd_ptr; reg [31:0] rd_ptr_high; reg [31:0] rd_ptr_low; reg [1:0] tmp_ecc_err; begin rd_pntr <= #`TCQ rd_pntr + 1; // output is wider than input if (reads_per_write == 0) begin tmp_dout = 0; tmp_rd_ptr = (rd_ptr << log2_writes_per_read)+(writes_per_read-1); for (i = writes_per_read - 1; i >= 0; i = i - 1) begin tmp_dout = tmp_dout << C_DIN_WIDTH; tmp_dout = tmp_dout | memory[tmp_rd_ptr]; // (Works opposite to core: rd_ptr is a DOWN counter) if (tmp_rd_ptr == 0) begin tmp_rd_ptr = C_WR_DEPTH - 1; end else begin tmp_rd_ptr = tmp_rd_ptr - 1; end end // output is symmetric end else if (reads_per_write == 1) begin tmp_dout = memory[rd_ptr][C_DIN_WIDTH-1:0]; // Retreive the error injection type. Based on the error injection type // corrupt the output data. tmp_ecc_err = ecc_err[rd_ptr]; if (ENABLE_ERR_INJECTION && C_DIN_WIDTH == C_DOUT_WIDTH) begin if (tmp_ecc_err[1]) begin // Corrupt the output data only for double bit error if (C_DOUT_WIDTH == 1) begin $display("FAILURE : Data width must be >= 2 for double bit error injection."); $finish; end else if (C_DOUT_WIDTH == 2) tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2]}; else tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2],(tmp_dout << 2)}; end else begin tmp_dout = tmp_dout[C_DOUT_WIDTH-1:0]; end err_type <= {tmp_ecc_err[1], tmp_ecc_err[0] & !tmp_ecc_err[1]}; end else begin err_type <= 0; end // input is wider than output end else begin rd_ptr_high = rd_ptr >> log2_reads_per_write; rd_ptr_low = rd_ptr & (reads_per_write - 1); memory_read = memory[rd_ptr_high]; tmp_dout = memory_read >> (rd_ptr_low*C_DOUT_WIDTH); end ideal_dout <= tmp_dout; // (Works opposite to core: rd_ptr is a DOWN counter) if (rd_ptr == 0) begin rd_ptr <= C_RD_DEPTH - 1; end else begin rd_ptr <= rd_ptr - 1; end end endtask /************************************************************************** * log2_val * Returns the 'log2' value for the input value for the supported ratios ***************************************************************************/ function [31:0] log2_val; input [31:0] binary_val; begin if (binary_val == 8) begin log2_val = 3; end else if (binary_val == 4) begin log2_val = 2; end else begin log2_val = 1; end end endfunction /*********************************************************************** * hexstr_conv * Converts a string of type hex to a binary value (for C_DOUT_RST_VAL) ***********************************************************************/ function [C_DOUT_WIDTH-1:0] hexstr_conv; input [(C_DOUT_WIDTH*8)-1:0] def_data; integer index,i,j; reg [3:0] bin; begin index = 0; hexstr_conv = 'b0; for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 ) begin case (def_data[7:0]) 8'b00000000 : begin bin = 4'b0000; i = -1; end 8'b00110000 : bin = 4'b0000; 8'b00110001 : bin = 4'b0001; 8'b00110010 : bin = 4'b0010; 8'b00110011 : bin = 4'b0011; 8'b00110100 : bin = 4'b0100; 8'b00110101 : bin = 4'b0101; 8'b00110110 : bin = 4'b0110; 8'b00110111 : bin = 4'b0111; 8'b00111000 : bin = 4'b1000; 8'b00111001 : bin = 4'b1001; 8'b01000001 : bin = 4'b1010; 8'b01000010 : bin = 4'b1011; 8'b01000011 : bin = 4'b1100; 8'b01000100 : bin = 4'b1101; 8'b01000101 : bin = 4'b1110; 8'b01000110 : bin = 4'b1111; 8'b01100001 : bin = 4'b1010; 8'b01100010 : bin = 4'b1011; 8'b01100011 : bin = 4'b1100; 8'b01100100 : bin = 4'b1101; 8'b01100101 : bin = 4'b1110; 8'b01100110 : bin = 4'b1111; default : begin bin = 4'bx; end endcase for( j=0; j<4; j=j+1) begin if ((index*4)+j < C_DOUT_WIDTH) begin hexstr_conv[(index*4)+j] = bin[j]; end end index = index + 1; def_data = def_data >> 8; end end endfunction /************************************************************************* * Initialize Signals for clean power-on simulation *************************************************************************/ initial begin num_wr_bits = 0; num_rd_bits = 0; next_num_wr_bits = 0; next_num_rd_bits = 0; rd_ptr = C_RD_DEPTH - 1; wr_ptr = C_WR_DEPTH - 1; wr_pntr = 0; rd_pntr = 0; rd_ptr_wrclk = rd_ptr; wr_ptr_rdclk = wr_ptr; dout_reset_val = hexstr_conv(C_DOUT_RST_VAL); ideal_dout = dout_reset_val; err_type = 0; ideal_dout_d1 = dout_reset_val; ideal_wr_ack = 1'b0; ideal_valid = 1'b0; valid_d1 = 1'b0; valid_d2 = 1'b0; ideal_overflow = C_OVERFLOW_LOW; ideal_underflow = C_UNDERFLOW_LOW; ideal_wr_count = 0; ideal_rd_count = 0; ideal_prog_full = 1'b0; ideal_prog_empty = 1'b1; end /************************************************************************* * Connect the module inputs and outputs to the internal signals of the * behavioral model. *************************************************************************/ //Inputs /* wire [C_DIN_WIDTH-1:0] DIN; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE; wire RD_CLK; wire RD_EN; wire RST; wire WR_CLK; wire WR_EN; */ //*************************************************************************** // Dout may change behavior based on latency //*************************************************************************** assign ideal_dout_out[C_DOUT_WIDTH-1:0] = (C_PRELOAD_LATENCY==2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) )? ideal_dout_d1: ideal_dout; assign DOUT[C_DOUT_WIDTH-1:0] = ideal_dout_out; //*************************************************************************** // Assign SBITERR and DBITERR based on latency //*************************************************************************** assign SBITERR = (C_ERROR_INJECTION_TYPE == 1 || C_ERROR_INJECTION_TYPE == 3) && (C_PRELOAD_LATENCY == 2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) ) ? err_type_d1[0]: err_type[0]; assign DBITERR = (C_ERROR_INJECTION_TYPE == 2 || C_ERROR_INJECTION_TYPE == 3) && (C_PRELOAD_LATENCY==2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ? err_type_d1[1]: err_type[1]; //*************************************************************************** // Safety-ckt logic with embedded reg/fabric reg //*************************************************************************** generate if ((C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_EN_SAFETY_CKT==1 && C_USE_EMBEDDED_REG < 3) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; // if (C_HAS_VALID == 1) begin // assign valid_out = valid_d1; // end always@(posedge RD_CLK) begin rst_delayed_sft1 <= #`TCQ rd_rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always@(posedge rst_delayed_sft4 or posedge rd_rst_i or posedge RD_CLK) begin if( rst_delayed_sft4 == 1'b1 || rd_rst_i == 1'b1) ram_rd_en_d1 <= #`TCQ 1'b0; else ram_rd_en_d1 <= #`TCQ ram_rd_en; end always@(posedge rst_delayed_sft2 or posedge RD_CLK) begin if (rst_delayed_sft2 == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge RD_CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; end end else begin if (ram_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout; err_type_d1[0] <= #`TCQ err_type[0]; err_type_d1[1] <= #`TCQ err_type[1]; end end end end endgenerate //*************************************************************************** // Safety-ckt logic with embedded reg + fabric reg //*************************************************************************** generate if ((C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_EN_SAFETY_CKT==1 && C_USE_EMBEDDED_REG == 3) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; // if (C_HAS_VALID == 1) begin // assign valid_out = valid_d2; // end always@(posedge RD_CLK) begin rst_delayed_sft1 <= #`TCQ rd_rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always@(posedge rst_delayed_sft4 or posedge rd_rst_i or posedge RD_CLK) begin if( rst_delayed_sft4 == 1'b1 || rd_rst_i == 1'b1) ram_rd_en_d1 <= #`TCQ 1'b0; else ram_rd_en_d1 <= #`TCQ ram_rd_en; fab_rd_en_d1 <= #`TCQ ram_rd_en_d1; end always@(posedge rst_delayed_sft2 or posedge RD_CLK) begin if (rst_delayed_sft2 == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge RD_CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; ideal_dout_both <= #`TCQ dout_reset_val; end end else begin if (ram_rd_en_d1) begin ideal_dout_both <= #`TCQ ideal_dout; err_type_both[0] <= #`TCQ err_type[0]; err_type_both[1] <= #`TCQ err_type[1]; end if (fab_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout_both; err_type_d1[0] <= #`TCQ err_type_both[0]; err_type_d1[1] <= #`TCQ err_type_both[1]; end end end end endgenerate //*************************************************************************** // Overflow may be active-low //*************************************************************************** generate if (C_HAS_OVERFLOW==1) begin : blockOF1 assign OVERFLOW = ideal_overflow ? !C_OVERFLOW_LOW : C_OVERFLOW_LOW; end endgenerate assign PROG_EMPTY = ideal_prog_empty; assign PROG_FULL = ideal_prog_full; //*************************************************************************** // Valid may change behavior based on latency or active-low //*************************************************************************** generate if (C_HAS_VALID==1) begin : blockVL1 assign valid_i = (C_PRELOAD_LATENCY==0) ? (RD_EN & ~EMPTY) : ideal_valid; assign valid_out1 = (C_PRELOAD_LATENCY==2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_USE_EMBEDDED_REG < 3)? valid_d1: valid_i; assign valid_out2 = (C_PRELOAD_LATENCY==2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_USE_EMBEDDED_REG == 3)? valid_d2: valid_i; assign valid_out = (C_USE_EMBEDDED_REG == 3) ? valid_out2 : valid_out1; assign VALID = valid_out ? !C_VALID_LOW : C_VALID_LOW; end endgenerate //*************************************************************************** // Underflow may change behavior based on latency or active-low //*************************************************************************** generate if (C_HAS_UNDERFLOW==1) begin : blockUF1 assign underflow_i = (C_PRELOAD_LATENCY==0) ? (RD_EN & EMPTY) : ideal_underflow; assign UNDERFLOW = underflow_i ? !C_UNDERFLOW_LOW : C_UNDERFLOW_LOW; end endgenerate //*************************************************************************** // Write acknowledge may be active low //*************************************************************************** generate if (C_HAS_WR_ACK==1) begin : blockWK1 assign WR_ACK = ideal_wr_ack ? !C_WR_ACK_LOW : C_WR_ACK_LOW; end endgenerate //*************************************************************************** // Generate RD_DATA_COUNT if Use Extra Logic option is selected //*************************************************************************** generate if (C_HAS_WR_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : wdc_fwft_ext reg [C_PNTR_WIDTH-1:0] adjusted_wr_pntr = 0; reg [C_PNTR_WIDTH-1:0] adjusted_rd_pntr = 0; wire [C_PNTR_WIDTH-1:0] diff_wr_rd_tmp; wire [C_PNTR_WIDTH:0] diff_wr_rd; reg [C_PNTR_WIDTH:0] wr_data_count_i = 0; always @* begin if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin adjusted_wr_pntr = wr_pntr; adjusted_rd_pntr = 0; adjusted_rd_pntr[C_PNTR_WIDTH-1:C_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr_wr; end else if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin adjusted_rd_pntr = rd_pntr_wr; adjusted_wr_pntr = 0; adjusted_wr_pntr[C_PNTR_WIDTH-1:C_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr; end else begin adjusted_wr_pntr = wr_pntr; adjusted_rd_pntr = rd_pntr_wr; end end // always @* assign diff_wr_rd_tmp = adjusted_wr_pntr - adjusted_rd_pntr; assign diff_wr_rd = {1'b0,diff_wr_rd_tmp}; always @ (posedge wr_rst_i or posedge WR_CLK) begin if (wr_rst_i) wr_data_count_i <= #`TCQ 0; else wr_data_count_i <= #`TCQ diff_wr_rd + EXTRA_WORDS_DC; end // always @ (posedge WR_CLK or posedge WR_CLK) always @* begin if (C_WR_PNTR_WIDTH >= C_RD_PNTR_WIDTH) wdc_fwft_ext_as = wr_data_count_i[C_PNTR_WIDTH:0]; else wdc_fwft_ext_as = wr_data_count_i[C_PNTR_WIDTH:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH]; end // always @* end // wdc_fwft_ext endgenerate //*************************************************************************** // Generate RD_DATA_COUNT if Use Extra Logic option is selected //*************************************************************************** reg [C_RD_PNTR_WIDTH:0] rdc_fwft_ext_as = 0; generate if (C_USE_EMBEDDED_REG < 3) begin: rdc_fwft_ext_both if (C_HAS_RD_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : rdc_fwft_ext reg [C_RD_PNTR_WIDTH-1:0] adjusted_wr_pntr_rd = 0; wire [C_RD_PNTR_WIDTH-1:0] diff_rd_wr_tmp; wire [C_RD_PNTR_WIDTH:0] diff_rd_wr; always @* begin if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin adjusted_wr_pntr_rd = 0; adjusted_wr_pntr_rd[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr_rd; end else begin adjusted_wr_pntr_rd = wr_pntr_rd[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH]; end end // always @* assign diff_rd_wr_tmp = adjusted_wr_pntr_rd - rd_pntr; assign diff_rd_wr = {1'b0,diff_rd_wr_tmp}; always @ (posedge rd_rst_i or posedge RD_CLK) begin if (rd_rst_i) begin rdc_fwft_ext_as <= #`TCQ 0; end else begin if (!stage2_valid) rdc_fwft_ext_as <= #`TCQ 0; else if (!stage1_valid && stage2_valid) rdc_fwft_ext_as <= #`TCQ 1; else rdc_fwft_ext_as <= #`TCQ diff_rd_wr + 2'h2; end end // always @ (posedge WR_CLK or posedge WR_CLK) end // rdc_fwft_ext end endgenerate generate if (C_USE_EMBEDDED_REG == 3) begin if (C_HAS_RD_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : rdc_fwft_ext reg [C_RD_PNTR_WIDTH-1:0] adjusted_wr_pntr_rd = 0; wire [C_RD_PNTR_WIDTH-1:0] diff_rd_wr_tmp; wire [C_RD_PNTR_WIDTH:0] diff_rd_wr; always @* begin if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin adjusted_wr_pntr_rd = 0; adjusted_wr_pntr_rd[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr_rd; end else begin adjusted_wr_pntr_rd = wr_pntr_rd[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH]; end end // always @* assign diff_rd_wr_tmp = adjusted_wr_pntr_rd - rd_pntr; assign diff_rd_wr = {1'b0,diff_rd_wr_tmp}; wire [C_RD_PNTR_WIDTH:0] diff_rd_wr_1; // assign diff_rd_wr_1 = diff_rd_wr +2'h2; always @ (posedge rd_rst_i or posedge RD_CLK) begin if (rd_rst_i) begin rdc_fwft_ext_as <= #`TCQ 0; end else begin //if (fab_read_data_valid_i == 1'b0 && ((ram_valid_i == 1'b0 && read_data_valid_i ==1'b0) || (ram_valid_i == 1'b0 && read_data_valid_i ==1'b1) || (ram_valid_i == 1'b1 && read_data_valid_i ==1'b0) || (ram_valid_i == 1'b1 && read_data_valid_i ==1'b1))) // rdc_fwft_ext_as <= 1'b0; //else if (fab_read_data_valid_i == 1'b1 && ((ram_valid_i == 1'b0 && read_data_valid_i ==1'b0) || (ram_valid_i == 1'b0 && read_data_valid_i ==1'b1))) // rdc_fwft_ext_as <= 1'b1; //else rdc_fwft_ext_as <= diff_rd_wr + 2'h2 ; end end end end endgenerate //*************************************************************************** // Assign the read data count value only if it is selected, // otherwise output zeros. //*************************************************************************** generate if (C_HAS_RD_DATA_COUNT == 1) begin : grdc assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = C_USE_FWFT_DATA_COUNT ? rdc_fwft_ext_as[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH] : rd_data_count_int[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH]; end endgenerate generate if (C_HAS_RD_DATA_COUNT == 0) begin : gnrdc assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = {C_RD_DATA_COUNT_WIDTH{1'b0}}; end endgenerate //*************************************************************************** // Assign the write data count value only if it is selected, // otherwise output zeros //*************************************************************************** generate if (C_HAS_WR_DATA_COUNT == 1) begin : gwdc assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = (C_USE_FWFT_DATA_COUNT == 1) ? wdc_fwft_ext_as[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH] : wr_data_count_int[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH]; end endgenerate generate if (C_HAS_WR_DATA_COUNT == 0) begin : gnwdc assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = {C_WR_DATA_COUNT_WIDTH{1'b0}}; end endgenerate /************************************************************************** * Assorted registers for delayed versions of signals **************************************************************************/ //Capture delayed version of valid generate if (C_HAS_VALID==1) begin : blockVL2 always @(posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i == 1'b1) begin valid_d1 <= #`TCQ 1'b0; valid_d2 <= #`TCQ 1'b0; end else begin valid_d1 <= #`TCQ valid_i; valid_d2 <= #`TCQ valid_d1; end // if (C_USE_EMBEDDED_REG == 3 && (C_EN_SAFETY_CKT == 0 || C_EN_SAFETY_CKT == 1 ) begin // valid_d2 <= #`TCQ valid_d1; // end end end endgenerate //Capture delayed version of dout /************************************************************************** *embedded/fabric reg with no safety ckt **************************************************************************/ generate if (C_EN_SAFETY_CKT==0 && C_USE_EMBEDDED_REG < 3) begin always @(posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge RD_CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; ideal_dout <= #`TCQ dout_reset_val; end // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type_d1 <= #`TCQ 0; end else if (ram_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout; err_type_d1 <= #`TCQ err_type; end end end endgenerate /************************************************************************** *embedded + fabric reg with no safety ckt **************************************************************************/ generate if (C_EN_SAFETY_CKT==0 && C_USE_EMBEDDED_REG == 3) begin always @(posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge RD_CLK) ideal_dout <= #`TCQ dout_reset_val; ideal_dout_d1 <= #`TCQ dout_reset_val; ideal_dout_both <= #`TCQ dout_reset_val; end // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type_d1 <= #`TCQ 0; end else if (ram_rd_en_d1) begin ideal_dout_both <= #`TCQ ideal_dout; err_type_both <= #`TCQ err_type; end if (fab_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout_both; err_type_d1 <= #`TCQ err_type_both; end end end endgenerate /************************************************************************** * Overflow and Underflow Flag calculation * (handled separately because they don't support rst) **************************************************************************/ generate if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 0) begin : g7s_ovflw always @(posedge WR_CLK) begin ideal_overflow <= #`TCQ WR_EN & FULL; end end else if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 1) begin : g8s_ovflw always @(posedge WR_CLK) begin //ideal_overflow <= #`TCQ WR_EN & (FULL | wr_rst_i); ideal_overflow <= #`TCQ WR_EN & (FULL ); end end endgenerate generate if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 0) begin : g7s_unflw always @(posedge RD_CLK) begin ideal_underflow <= #`TCQ EMPTY & RD_EN; end end else if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 1) begin : g8s_unflw always @(posedge RD_CLK) begin ideal_underflow <= #`TCQ (EMPTY) & RD_EN; //ideal_underflow <= #`TCQ (rd_rst_i | EMPTY) & RD_EN; end end endgenerate /************************************************************************** * Write/Read Pointer Synchronization **************************************************************************/ localparam NO_OF_SYNC_STAGE_INC_G2B = C_SYNCHRONIZER_STAGE + 1; wire [C_WR_PNTR_WIDTH-1:0] wr_pntr_sync_stgs [0:NO_OF_SYNC_STAGE_INC_G2B]; wire [C_RD_PNTR_WIDTH-1:0] rd_pntr_sync_stgs [0:NO_OF_SYNC_STAGE_INC_G2B]; genvar gss; generate for (gss = 1; gss <= NO_OF_SYNC_STAGE_INC_G2B; gss = gss + 1) begin : Sync_stage_inst fifo_generator_v13_1_1_sync_stage #( .C_WIDTH (C_WR_PNTR_WIDTH) ) rd_stg_inst ( .RST (rd_rst_i), .CLK (RD_CLK), .DIN (wr_pntr_sync_stgs[gss-1]), .DOUT (wr_pntr_sync_stgs[gss]) ); fifo_generator_v13_1_1_sync_stage #( .C_WIDTH (C_RD_PNTR_WIDTH) ) wr_stg_inst ( .RST (wr_rst_i), .CLK (WR_CLK), .DIN (rd_pntr_sync_stgs[gss-1]), .DOUT (rd_pntr_sync_stgs[gss]) ); end endgenerate // Sync_stage_inst assign wr_pntr_sync_stgs[0] = wr_pntr_rd1; assign rd_pntr_sync_stgs[0] = rd_pntr_wr1; always@* begin wr_pntr_rd <= wr_pntr_sync_stgs[NO_OF_SYNC_STAGE_INC_G2B]; rd_pntr_wr <= rd_pntr_sync_stgs[NO_OF_SYNC_STAGE_INC_G2B]; end /************************************************************************** * Write Domain Logic **************************************************************************/ reg [C_WR_PNTR_WIDTH-1:0] diff_pntr = 0; always @(posedge WR_CLK or posedge wr_rst_i ) begin : gen_fifo_w /****** Reset fifo (case 1)***************************************/ if (wr_rst_i == 1'b1) begin num_wr_bits <= #`TCQ 0; next_num_wr_bits = #`TCQ 0; wr_ptr <= #`TCQ C_WR_DEPTH - 1; rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1; ideal_wr_ack <= #`TCQ 0; ideal_wr_count <= #`TCQ 0; tmp_wr_listsize = #`TCQ 0; rd_ptr_wrclk_next <= #`TCQ 0; wr_pntr <= #`TCQ 0; wr_pntr_rd1 <= #`TCQ 0; end else begin //wr_rst_i==0 wr_pntr_rd1 <= #`TCQ wr_pntr; //Determine the current number of words in the FIFO tmp_wr_listsize = (C_DEPTH_RATIO_RD > 1) ? num_wr_bits/C_DOUT_WIDTH : num_wr_bits/C_DIN_WIDTH; rd_ptr_wrclk_next = rd_ptr; if (rd_ptr_wrclk < rd_ptr_wrclk_next) begin next_num_wr_bits = num_wr_bits - C_DOUT_WIDTH*(rd_ptr_wrclk + C_RD_DEPTH - rd_ptr_wrclk_next); end else begin next_num_wr_bits = num_wr_bits - C_DOUT_WIDTH*(rd_ptr_wrclk - rd_ptr_wrclk_next); end //If this is a write, handle the write by adding the value // to the linked list, and updating all outputs appropriately if (WR_EN == 1'b1) begin if (FULL == 1'b1) begin //If the FIFO is full, do NOT perform the write, // update flags accordingly if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD >= C_FIFO_WR_DEPTH) begin //write unsuccessful - do not change contents //Do not acknowledge the write ideal_wr_ack <= #`TCQ 0; //Reminder that FIFO is still full ideal_wr_count <= #`TCQ num_write_words_sized_i; //If the FIFO is one from full, but reporting full end else if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD == C_FIFO_WR_DEPTH-1) begin //No change to FIFO //Write not successful ideal_wr_ack <= #`TCQ 0; //With DEPTH-1 words in the FIFO, it is almost_full ideal_wr_count <= #`TCQ num_write_words_sized_i; //If the FIFO is completely empty, but it is // reporting FULL for some reason (like reset) end else if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD <= C_FIFO_WR_DEPTH-2) begin //No change to FIFO //Write not successful ideal_wr_ack <= #`TCQ 0; //FIFO is really not close to full, so change flag status. ideal_wr_count <= #`TCQ num_write_words_sized_i; end //(tmp_wr_listsize == 0) end else begin //If the FIFO is full, do NOT perform the write, // update flags accordingly if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD >= C_FIFO_WR_DEPTH) begin //write unsuccessful - do not change contents //Do not acknowledge the write ideal_wr_ack <= #`TCQ 0; //Reminder that FIFO is still full ideal_wr_count <= #`TCQ num_write_words_sized_i; //If the FIFO is one from full end else if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD == C_FIFO_WR_DEPTH-1) begin //Add value on DIN port to FIFO write_fifo; next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH; //Write successful, so issue acknowledge // and no error ideal_wr_ack <= #`TCQ 1; //This write is CAUSING the FIFO to go full ideal_wr_count <= #`TCQ num_write_words_sized_i; //If the FIFO is 2 from full end else if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD == C_FIFO_WR_DEPTH-2) begin //Add value on DIN port to FIFO write_fifo; next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH; //Write successful, so issue acknowledge // and no error ideal_wr_ack <= #`TCQ 1; //Still 2 from full ideal_wr_count <= #`TCQ num_write_words_sized_i; //If the FIFO is not close to being full end else if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD < C_FIFO_WR_DEPTH-2) begin //Add value on DIN port to FIFO write_fifo; next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH; //Write successful, so issue acknowledge // and no error ideal_wr_ack <= #`TCQ 1; //Not even close to full. ideal_wr_count <= num_write_words_sized_i; end end end else begin //(WR_EN == 1'b1) //If user did not attempt a write, then do not // give ack or err ideal_wr_ack <= #`TCQ 0; ideal_wr_count <= #`TCQ num_write_words_sized_i; end num_wr_bits <= #`TCQ next_num_wr_bits; rd_ptr_wrclk <= #`TCQ rd_ptr; end //wr_rst_i==0 end // gen_fifo_w /*************************************************************************** * Programmable FULL flags ***************************************************************************/ wire [C_WR_PNTR_WIDTH-1:0] pf_thr_assert_val; wire [C_WR_PNTR_WIDTH-1:0] pf_thr_negate_val; generate if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin : FWFT assign pf_thr_assert_val = C_PROG_FULL_THRESH_ASSERT_VAL - EXTRA_WORDS_DC; assign pf_thr_negate_val = C_PROG_FULL_THRESH_NEGATE_VAL - EXTRA_WORDS_DC; end else begin // STD assign pf_thr_assert_val = C_PROG_FULL_THRESH_ASSERT_VAL; assign pf_thr_negate_val = C_PROG_FULL_THRESH_NEGATE_VAL; end endgenerate always @(posedge WR_CLK or posedge wr_rst_i) begin if (wr_rst_i == 1'b1) begin diff_pntr <= 0; end else begin if (ram_wr_en) diff_pntr <= #`TCQ (wr_pntr - adj_rd_pntr_wr + 2'h1); else if (!ram_wr_en) diff_pntr <= #`TCQ (wr_pntr - adj_rd_pntr_wr); end end always @(posedge WR_CLK or posedge RST_FULL_FF) begin : gen_pf if (RST_FULL_FF == 1'b1) begin ideal_prog_full <= #`TCQ C_FULL_FLAGS_RST_VAL; end else begin if (RST_FULL_GEN) ideal_prog_full <= #`TCQ 0; //Single Programmable Full Constant Threshold else if (C_PROG_FULL_TYPE == 1) begin if (FULL == 0) begin if (diff_pntr >= pf_thr_assert_val) ideal_prog_full <= #`TCQ 1; else ideal_prog_full <= #`TCQ 0; end else ideal_prog_full <= #`TCQ ideal_prog_full; //Two Programmable Full Constant Thresholds end else if (C_PROG_FULL_TYPE == 2) begin if (FULL == 0) begin if (diff_pntr >= pf_thr_assert_val) ideal_prog_full <= #`TCQ 1; else if (diff_pntr < pf_thr_negate_val) ideal_prog_full <= #`TCQ 0; else ideal_prog_full <= #`TCQ ideal_prog_full; end else ideal_prog_full <= #`TCQ ideal_prog_full; //Single Programmable Full Threshold Input end else if (C_PROG_FULL_TYPE == 3) begin if (FULL == 0) begin if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin // FWFT if (diff_pntr >= (PROG_FULL_THRESH - EXTRA_WORDS_DC)) ideal_prog_full <= #`TCQ 1; else ideal_prog_full <= #`TCQ 0; end else begin // STD if (diff_pntr >= PROG_FULL_THRESH) ideal_prog_full <= #`TCQ 1; else ideal_prog_full <= #`TCQ 0; end end else ideal_prog_full <= #`TCQ ideal_prog_full; //Two Programmable Full Threshold Inputs end else if (C_PROG_FULL_TYPE == 4) begin if (FULL == 0) begin if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin // FWFT if (diff_pntr >= (PROG_FULL_THRESH_ASSERT - EXTRA_WORDS_DC)) ideal_prog_full <= #`TCQ 1; else if (diff_pntr < (PROG_FULL_THRESH_NEGATE - EXTRA_WORDS_DC)) ideal_prog_full <= #`TCQ 0; else ideal_prog_full <= #`TCQ ideal_prog_full; end else begin // STD if (diff_pntr >= PROG_FULL_THRESH_ASSERT) ideal_prog_full <= #`TCQ 1; else if (diff_pntr < PROG_FULL_THRESH_NEGATE) ideal_prog_full <= #`TCQ 0; else ideal_prog_full <= #`TCQ ideal_prog_full; end end else ideal_prog_full <= #`TCQ ideal_prog_full; end // C_PROG_FULL_TYPE end //wr_rst_i==0 end // /************************************************************************** * Read Domain Logic **************************************************************************/ /********************************************************* * Programmable EMPTY flags *********************************************************/ //Determine the Assert and Negate thresholds for Programmable Empty wire [C_RD_PNTR_WIDTH-1:0] pe_thr_assert_val; wire [C_RD_PNTR_WIDTH-1:0] pe_thr_negate_val; reg [C_RD_PNTR_WIDTH-1:0] diff_pntr_rd = 0; always @(posedge RD_CLK or posedge rd_rst_i) begin : gen_pe if (rd_rst_i) begin diff_pntr_rd <= #`TCQ 0; ideal_prog_empty <= #`TCQ 1'b1; end else begin if (ram_rd_en) diff_pntr_rd <= #`TCQ (adj_wr_pntr_rd - rd_pntr) - 1'h1; else if (!ram_rd_en) diff_pntr_rd <= #`TCQ (adj_wr_pntr_rd - rd_pntr); else diff_pntr_rd <= #`TCQ diff_pntr_rd; if (C_PROG_EMPTY_TYPE == 1) begin if (EMPTY == 0) begin if (diff_pntr_rd <= pe_thr_assert_val) ideal_prog_empty <= #`TCQ 1; else ideal_prog_empty <= #`TCQ 0; end else ideal_prog_empty <= #`TCQ ideal_prog_empty; end else if (C_PROG_EMPTY_TYPE == 2) begin if (EMPTY == 0) begin if (diff_pntr_rd <= pe_thr_assert_val) ideal_prog_empty <= #`TCQ 1; else if (diff_pntr_rd > pe_thr_negate_val) ideal_prog_empty <= #`TCQ 0; else ideal_prog_empty <= #`TCQ ideal_prog_empty; end else ideal_prog_empty <= #`TCQ ideal_prog_empty; end else if (C_PROG_EMPTY_TYPE == 3) begin if (EMPTY == 0) begin if (diff_pntr_rd <= pe_thr_assert_val) ideal_prog_empty <= #`TCQ 1; else ideal_prog_empty <= #`TCQ 0; end else ideal_prog_empty <= #`TCQ ideal_prog_empty; end else if (C_PROG_EMPTY_TYPE == 4) begin if (EMPTY == 0) begin if (diff_pntr_rd <= pe_thr_assert_val) ideal_prog_empty <= #`TCQ 1; else if (diff_pntr_rd > pe_thr_negate_val) ideal_prog_empty <= #`TCQ 0; else ideal_prog_empty <= #`TCQ ideal_prog_empty; end else ideal_prog_empty <= #`TCQ ideal_prog_empty; end //C_PROG_EMPTY_TYPE end end // gen_pe generate if (C_PROG_EMPTY_TYPE == 3) begin : single_pe_thr_input assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? PROG_EMPTY_THRESH - 2'h2 : PROG_EMPTY_THRESH; end endgenerate // single_pe_thr_input generate if (C_PROG_EMPTY_TYPE == 4) begin : multiple_pe_thr_input assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? PROG_EMPTY_THRESH_ASSERT - 2'h2 : PROG_EMPTY_THRESH_ASSERT; assign pe_thr_negate_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? PROG_EMPTY_THRESH_NEGATE - 2'h2 : PROG_EMPTY_THRESH_NEGATE; end endgenerate // multiple_pe_thr_input generate if (C_PROG_EMPTY_TYPE < 3) begin : single_multiple_pe_thr_const assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? C_PROG_EMPTY_THRESH_ASSERT_VAL - 2'h2 : C_PROG_EMPTY_THRESH_ASSERT_VAL; assign pe_thr_negate_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? C_PROG_EMPTY_THRESH_NEGATE_VAL - 2'h2 : C_PROG_EMPTY_THRESH_NEGATE_VAL; end endgenerate // single_multiple_pe_thr_const // // block memory has a synchronous reset // always @(posedge RD_CLK) begin : gen_fifo_blkmemdout // // make it consistent with the core. // if (rd_rst_i) begin // // Reset err_type only if ECC is not selected // if (C_USE_ECC == 0 && C_MEMORY_TYPE < 2) // err_type <= #`TCQ 0; // // // BRAM resets synchronously // if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2) begin // //ideal_dout <= #`TCQ dout_reset_val; // //ideal_dout_d1 <= #`TCQ dout_reset_val; // end // end // end //always always @(posedge RD_CLK or posedge rd_rst_i ) begin : gen_fifo_r /****** Reset fifo (case 1)***************************************/ if (rd_rst_i == 1'b1 ) begin num_rd_bits <= #`TCQ 0; next_num_rd_bits = #`TCQ 0; rd_ptr <= #`TCQ C_RD_DEPTH -1; rd_pntr <= #`TCQ 0; rd_pntr_wr1 <= #`TCQ 0; wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1; // DRAM resets asynchronously if (C_MEMORY_TYPE == 2 && C_USE_DOUT_RST == 1) ideal_dout <= #`TCQ dout_reset_val; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type <= #`TCQ 0; ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ 0; end else begin //rd_rst_i==0 rd_pntr_wr1 <= #`TCQ rd_pntr; //Determine the current number of words in the FIFO tmp_rd_listsize = (C_DEPTH_RATIO_WR > 1) ? num_rd_bits/C_DIN_WIDTH : num_rd_bits/C_DOUT_WIDTH; wr_ptr_rdclk_next = wr_ptr; if (wr_ptr_rdclk < wr_ptr_rdclk_next) begin next_num_rd_bits = num_rd_bits + C_DIN_WIDTH*(wr_ptr_rdclk +C_WR_DEPTH - wr_ptr_rdclk_next); end else begin next_num_rd_bits = num_rd_bits + C_DIN_WIDTH*(wr_ptr_rdclk - wr_ptr_rdclk_next); end /*****************************************************************/ // Read Operation - Read Latency 1 /*****************************************************************/ if (C_PRELOAD_LATENCY==1 || C_PRELOAD_LATENCY==2) begin ideal_valid <= #`TCQ 1'b0; if (ram_rd_en == 1'b1) begin if (EMPTY == 1'b1) begin //If the FIFO is completely empty, and is reporting empty if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Reminder that FIFO is still empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize <= 0) //If the FIFO is one from empty, but it is reporting empty else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Note that FIFO is no longer empty, but is almost empty (has one word left) ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == 1) //If the FIFO is two from empty, and is reporting empty else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Fifo has two words, so is neither empty or almost empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == 2) //If the FIFO is not close to empty, but is reporting that it is // Treat the FIFO as empty this time, but unset EMPTY flags. if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<C_FIFO_RD_DEPTH)) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Note that the FIFO is No Longer Empty or Almost Empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1)) end // else: if(ideal_empty == 1'b1) else //if (ideal_empty == 1'b0) begin //If the FIFO is completely full, and we are successfully reading from it if (tmp_rd_listsize/C_DEPTH_RATIO_WR >= C_FIFO_RD_DEPTH) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Not close to empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == C_FIFO_RD_DEPTH) //If the FIFO is not close to being empty else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<=C_FIFO_RD_DEPTH)) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Not close to empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1)) //If the FIFO is two from empty else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Fifo is not yet empty. It is going almost_empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == 2) //If the FIFO is one from empty else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR == 1)) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Note that FIFO is GOING empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == 1) //If the FIFO is completely empty else if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize <= 0) end // if (ideal_empty == 1'b0) end //(RD_EN == 1'b1) else //if (RD_EN == 1'b0) begin //If user did not attempt a read, do not give an ack or err ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ num_read_words_sized_i; end // else: !if(RD_EN == 1'b1) /*****************************************************************/ // Read Operation - Read Latency 0 /*****************************************************************/ end else if (C_PRELOAD_REGS==1 && C_PRELOAD_LATENCY==0) begin ideal_valid <= #`TCQ 1'b0; if (ram_rd_en == 1'b1) begin if (EMPTY == 1'b1) begin //If the FIFO is completely empty, and is reporting empty if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Reminder that FIFO is still empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is one from empty, but it is reporting empty end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Note that FIFO is no longer empty, but is almost empty (has one word left) ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is two from empty, and is reporting empty end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Fifo has two words, so is neither empty or almost empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is not close to empty, but is reporting that it is // Treat the FIFO as empty this time, but unset EMPTY flags. end else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<C_FIFO_RD_DEPTH)) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Note that the FIFO is No Longer Empty or Almost Empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1)) end else begin //If the FIFO is completely full, and we are successfully reading from it if (tmp_rd_listsize/C_DEPTH_RATIO_WR >= C_FIFO_RD_DEPTH) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Not close to empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is not close to being empty end else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<=C_FIFO_RD_DEPTH)) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Not close to empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is two from empty end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Fifo is not yet empty. It is going almost_empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is one from empty end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1) begin //Read the value from the FIFO read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; //Note that FIFO is GOING empty ideal_rd_count <= #`TCQ num_read_words_sized_i; //If the FIFO is completely empty end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin //Do not change the contents of the FIFO //Do not acknowledge the read from empty FIFO ideal_valid <= #`TCQ 1'b0; //Reminder that FIFO is still empty ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize <= 0) end // if (ideal_empty == 1'b0) end else begin//(RD_EN == 1'b0) //If user did not attempt a read, do not give an ack or err ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ num_read_words_sized_i; end // else: !if(RD_EN == 1'b1) end //if (C_PRELOAD_REGS==1 && C_PRELOAD_LATENCY==0) num_rd_bits <= #`TCQ next_num_rd_bits; wr_ptr_rdclk <= #`TCQ wr_ptr; end //rd_rst_i==0 end //always endmodule // fifo_generator_v13_1_1_bhv_ver_as /******************************************************************************* * Declaration of Low Latency Asynchronous FIFO ******************************************************************************/ module fifo_generator_v13_1_1_beh_ver_ll_afifo /*************************************************************************** * Declare user parameters and their defaults ***************************************************************************/ #( parameter C_DIN_WIDTH = 8, parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_FULL_FLAGS_RST_VAL = 1, parameter C_HAS_RD_DATA_COUNT = 0, parameter C_HAS_WR_DATA_COUNT = 0, parameter C_RD_DEPTH = 256, parameter C_RD_PNTR_WIDTH = 8, parameter C_USE_DOUT_RST = 0, parameter C_WR_DATA_COUNT_WIDTH = 2, parameter C_WR_DEPTH = 256, parameter C_WR_PNTR_WIDTH = 8, parameter C_FIFO_TYPE = 0 ) /*************************************************************************** * Declare Input and Output Ports ***************************************************************************/ ( input [C_DIN_WIDTH-1:0] DIN, input RD_CLK, input RD_EN, input WR_RST, input RD_RST, input WR_CLK, input WR_EN, output reg [C_DOUT_WIDTH-1:0] DOUT = 0, output reg EMPTY = 1'b1, output reg FULL = C_FULL_FLAGS_RST_VAL ); //----------------------------------------------------------------------------- // Low Latency Asynchronous FIFO //----------------------------------------------------------------------------- // Memory which will be used to simulate a FIFO reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0]; integer i; initial begin for (i = 0; i < C_WR_DEPTH; i = i + 1) memory[i] = 0; end reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_ll_afifo = 0; wire [C_RD_PNTR_WIDTH-1:0] rd_pntr_ll_afifo; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_ll_afifo_q = 0; reg ll_afifo_full = 1'b0; reg ll_afifo_empty = 1'b1; wire write_allow; wire read_allow; assign write_allow = WR_EN & ~ll_afifo_full; assign read_allow = RD_EN & ~ll_afifo_empty; //----------------------------------------------------------------------------- // Write Pointer Generation //----------------------------------------------------------------------------- always @(posedge WR_CLK or posedge WR_RST) begin if (WR_RST) wr_pntr_ll_afifo <= 0; else if (write_allow) wr_pntr_ll_afifo <= #`TCQ wr_pntr_ll_afifo + 1; end //----------------------------------------------------------------------------- // Read Pointer Generation //----------------------------------------------------------------------------- always @(posedge RD_CLK or posedge RD_RST) begin if (RD_RST) rd_pntr_ll_afifo_q <= 0; else rd_pntr_ll_afifo_q <= #`TCQ rd_pntr_ll_afifo; end assign rd_pntr_ll_afifo = read_allow ? rd_pntr_ll_afifo_q + 1 : rd_pntr_ll_afifo_q; //----------------------------------------------------------------------------- // Fill the Memory //----------------------------------------------------------------------------- always @(posedge WR_CLK) begin if (write_allow) memory[wr_pntr_ll_afifo] <= #`TCQ DIN; end //----------------------------------------------------------------------------- // Generate DOUT //----------------------------------------------------------------------------- always @(posedge RD_CLK) begin DOUT <= #`TCQ memory[rd_pntr_ll_afifo]; end //----------------------------------------------------------------------------- // Generate EMPTY //----------------------------------------------------------------------------- always @(posedge RD_CLK or posedge RD_RST) begin if (RD_RST) ll_afifo_empty <= 1'b1; else ll_afifo_empty <= ((wr_pntr_ll_afifo == rd_pntr_ll_afifo_q) | (read_allow & (wr_pntr_ll_afifo == (rd_pntr_ll_afifo_q + 2'h1)))); end //----------------------------------------------------------------------------- // Generate FULL //----------------------------------------------------------------------------- always @(posedge WR_CLK or posedge WR_RST) begin if (WR_RST) ll_afifo_full <= 1'b1; else ll_afifo_full <= ((rd_pntr_ll_afifo_q == (wr_pntr_ll_afifo + 2'h1)) | (write_allow & (rd_pntr_ll_afifo_q == (wr_pntr_ll_afifo + 2'h2)))); end always @* begin FULL <= ll_afifo_full; EMPTY <= ll_afifo_empty; end endmodule // fifo_generator_v13_1_1_beh_ver_ll_afifo /******************************************************************************* * Declaration of top-level module ******************************************************************************/ module fifo_generator_v13_1_1_bhv_ver_ss /************************************************************************** * Declare user parameters and their defaults *************************************************************************/ #( parameter C_FAMILY = "virtex7", parameter C_DATA_COUNT_WIDTH = 2, parameter C_DIN_WIDTH = 8, parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_FULL_FLAGS_RST_VAL = 1, parameter C_HAS_ALMOST_EMPTY = 0, parameter C_HAS_ALMOST_FULL = 0, parameter C_HAS_DATA_COUNT = 0, parameter C_HAS_OVERFLOW = 0, parameter C_HAS_RD_DATA_COUNT = 0, parameter C_HAS_RST = 0, parameter C_HAS_SRST = 0, parameter C_HAS_UNDERFLOW = 0, parameter C_HAS_VALID = 0, parameter C_HAS_WR_ACK = 0, parameter C_HAS_WR_DATA_COUNT = 0, parameter C_IMPLEMENTATION_TYPE = 0, parameter C_MEMORY_TYPE = 1, parameter C_OVERFLOW_LOW = 0, parameter C_PRELOAD_LATENCY = 1, parameter C_PRELOAD_REGS = 0, parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0, parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0, parameter C_PROG_EMPTY_TYPE = 0, parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0, parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0, parameter C_PROG_FULL_TYPE = 0, parameter C_RD_DATA_COUNT_WIDTH = 2, parameter C_RD_DEPTH = 256, parameter C_RD_PNTR_WIDTH = 8, parameter C_UNDERFLOW_LOW = 0, parameter C_USE_DOUT_RST = 0, parameter C_USE_EMBEDDED_REG = 0, parameter C_EN_SAFETY_CKT = 0, parameter C_USE_FWFT_DATA_COUNT = 0, parameter C_VALID_LOW = 0, parameter C_WR_ACK_LOW = 0, parameter C_WR_DATA_COUNT_WIDTH = 2, parameter C_WR_DEPTH = 256, parameter C_WR_PNTR_WIDTH = 8, parameter C_USE_ECC = 0, parameter C_ENABLE_RST_SYNC = 1, parameter C_ERROR_INJECTION_TYPE = 0, parameter C_FIFO_TYPE = 0 ) /************************************************************************** * Declare Input and Output Ports *************************************************************************/ ( //Inputs input CLK, input [C_DIN_WIDTH-1:0] DIN, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT, input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT, input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE, input RD_EN, input RD_EN_USER, input USER_EMPTY_FB, input RST, input RST_FULL_GEN, input RST_FULL_FF, input SRST, input WR_EN, input INJECTDBITERR, input INJECTSBITERR, input WR_RST_BUSY, input RD_RST_BUSY, //Outputs output ALMOST_EMPTY, output ALMOST_FULL, output reg [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT = 0, output [C_DOUT_WIDTH-1:0] DOUT, output EMPTY, output FULL, output OVERFLOW, output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT, output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT, output PROG_EMPTY, output PROG_FULL, output VALID, output UNDERFLOW, output WR_ACK, output SBITERR, output DBITERR ); reg [C_RD_PNTR_WIDTH:0] rd_data_count_int = 0; reg [C_WR_PNTR_WIDTH:0] wr_data_count_int = 0; wire [C_RD_PNTR_WIDTH:0] rd_data_count_i_ss; wire [C_WR_PNTR_WIDTH:0] wr_data_count_i_ss; reg [C_WR_PNTR_WIDTH:0] wdc_fwft_ext_as = 0; /*************************************************************************** * Parameters used as constants **************************************************************************/ localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexuplus" || C_FAMILY == "zynquplus" || C_FAMILY == "kintexuplus") ? 1 : 0; localparam C_DEPTH_RATIO_WR = (C_WR_DEPTH>C_RD_DEPTH) ? (C_WR_DEPTH/C_RD_DEPTH) : 1; localparam C_DEPTH_RATIO_RD = (C_RD_DEPTH>C_WR_DEPTH) ? (C_RD_DEPTH/C_WR_DEPTH) : 1; //localparam C_FIFO_WR_DEPTH = C_WR_DEPTH - 1; //localparam C_FIFO_RD_DEPTH = C_RD_DEPTH - 1; localparam C_GRTR_PNTR_WIDTH = (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH ; // C_DEPTH_RATIO_WR | C_DEPTH_RATIO_RD | C_PNTR_WIDTH | EXTRA_WORDS_DC // -----------------|------------------|-----------------|--------------- // 1 | 8 | C_RD_PNTR_WIDTH | 2 // 1 | 4 | C_RD_PNTR_WIDTH | 2 // 1 | 2 | C_RD_PNTR_WIDTH | 2 // 1 | 1 | C_WR_PNTR_WIDTH | 2 // 2 | 1 | C_WR_PNTR_WIDTH | 4 // 4 | 1 | C_WR_PNTR_WIDTH | 8 // 8 | 1 | C_WR_PNTR_WIDTH | 16 localparam C_PNTR_WIDTH = (C_WR_PNTR_WIDTH>=C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH; wire [C_PNTR_WIDTH:0] EXTRA_WORDS_DC = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD); wire [C_WR_PNTR_WIDTH:0] EXTRA_WORDS_PF = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD); //wire [C_RD_PNTR_WIDTH:0] EXTRA_WORDS_PE = (C_DEPTH_RATIO_RD == 1) ? 2 : (2 * C_DEPTH_RATIO_RD/C_DEPTH_RATIO_WR); localparam EXTRA_WORDS_PF_PARAM = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD); //localparam EXTRA_WORDS_PE_PARAM = (C_DEPTH_RATIO_RD == 1) ? 2 : (2 * C_DEPTH_RATIO_RD/C_DEPTH_RATIO_WR); localparam [31:0] reads_per_write = C_DIN_WIDTH/C_DOUT_WIDTH; localparam [31:0] log2_reads_per_write = log2_val(reads_per_write); localparam [31:0] writes_per_read = C_DOUT_WIDTH/C_DIN_WIDTH; localparam [31:0] log2_writes_per_read = log2_val(writes_per_read); //When RST is present, set FULL reset value to '1'. //If core has no RST, make sure FULL powers-on as '0'. //The reset value assignments for FULL, ALMOST_FULL, and PROG_FULL are not //changed for v3.2(IP2_Im). When the core has Sync Reset, C_HAS_SRST=1 and C_HAS_RST=0. // Therefore, during SRST, all the FULL flags reset to 0. localparam C_HAS_FAST_FIFO = 0; localparam C_FIFO_WR_DEPTH = C_WR_DEPTH; localparam C_FIFO_RD_DEPTH = C_RD_DEPTH; // Local parameters used to determine whether to inject ECC error or not localparam SYMMETRIC_PORT = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 1 : 0; localparam ERR_INJECTION = (C_ERROR_INJECTION_TYPE != 0) ? 1 : 0; localparam C_USE_ECC_1 = (C_USE_ECC == 1 || C_USE_ECC ==2) ? 1:0; localparam ENABLE_ERR_INJECTION = C_USE_ECC && SYMMETRIC_PORT && ERR_INJECTION; localparam C_DATA_WIDTH = (ENABLE_ERR_INJECTION == 1) ? (C_DIN_WIDTH+2) : C_DIN_WIDTH; localparam IS_ASYMMETRY = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 0 : 1; localparam LESSER_WIDTH = (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH; localparam [C_RD_PNTR_WIDTH-1 : 0] DIFF_MAX_RD = {C_RD_PNTR_WIDTH{1'b1}}; localparam [C_WR_PNTR_WIDTH-1 : 0] DIFF_MAX_WR = {C_WR_PNTR_WIDTH{1'b1}}; /************************************************************************** * FIFO Contents Tracking and Data Count Calculations *************************************************************************/ // Memory which will be used to simulate a FIFO reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0]; reg [1:0] ecc_err[C_WR_DEPTH-1:0]; /************************************************************************** * Internal Registers and wires *************************************************************************/ //Temporary signals used for calculating the model's outputs. These //are only used in the assign statements immediately following wire, //parameter, and function declarations. wire underflow_i; wire valid_i; wire valid_out; reg [31:0] num_wr_bits; reg [31:0] num_rd_bits; reg [31:0] next_num_wr_bits; reg [31:0] next_num_rd_bits; //The write pointer - tracks write operations // (Works opposite to core: wr_ptr is a DOWN counter) reg [31:0] wr_ptr; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd1 = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd2 = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd3 = 0; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd = 0; reg wr_rst_d1 =0; //The read pointer - tracks read operations // (rd_ptr Works opposite to core: rd_ptr is a DOWN counter) reg [31:0] rd_ptr; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr1 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr2 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr3 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr4 = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr = 0; wire ram_rd_en; wire empty_int; wire almost_empty_int; wire ram_wr_en; wire full_int; wire almost_full_int; reg ram_rd_en_reg = 1'b0; reg ram_rd_en_d1 = 1'b0; reg fab_rd_en_d1 = 1'b0; wire srst_rrst_busy; //Ideal FIFO signals. These are the raw output of the behavioral model, //which behaves like an ideal FIFO. reg [1:0] err_type = 0; reg [1:0] err_type_d1 = 0; reg [1:0] err_type_both = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout_d1 = 0; reg [C_DOUT_WIDTH-1:0] ideal_dout_both = 0; wire [C_DOUT_WIDTH-1:0] ideal_dout_out; wire fwft_enabled; reg ideal_wr_ack = 0; reg ideal_valid = 0; reg ideal_overflow = C_OVERFLOW_LOW; reg ideal_underflow = C_UNDERFLOW_LOW; reg full_i = C_FULL_FLAGS_RST_VAL; reg full_i_temp = 0; reg empty_i = 1; reg almost_full_i = 0; reg almost_empty_i = 1; reg prog_full_i = 0; reg prog_empty_i = 1; reg [C_WR_PNTR_WIDTH-1:0] wr_pntr = 0; reg [C_RD_PNTR_WIDTH-1:0] rd_pntr = 0; wire [C_RD_PNTR_WIDTH-1:0] adj_wr_pntr_rd; wire [C_WR_PNTR_WIDTH-1:0] adj_rd_pntr_wr; reg [C_RD_PNTR_WIDTH-1:0] diff_count = 0; reg write_allow_q = 0; reg read_allow_q = 0; reg valid_d1 = 0; reg valid_both = 0; reg valid_d2 = 0; wire rst_i; wire srst_i; //user specified value for reseting the size of the fifo reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0; reg [31:0] wr_ptr_rdclk; reg [31:0] wr_ptr_rdclk_next; reg [31:0] rd_ptr_wrclk; reg [31:0] rd_ptr_wrclk_next; /**************************************************************************** * Function Declarations ***************************************************************************/ /**************************************************************************** * hexstr_conv * Converts a string of type hex to a binary value (for C_DOUT_RST_VAL) ***************************************************************************/ function [C_DOUT_WIDTH-1:0] hexstr_conv; input [(C_DOUT_WIDTH*8)-1:0] def_data; integer index,i,j; reg [3:0] bin; begin index = 0; hexstr_conv = 'b0; for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 ) begin case (def_data[7:0]) 8'b00000000 : begin bin = 4'b0000; i = -1; end 8'b00110000 : bin = 4'b0000; 8'b00110001 : bin = 4'b0001; 8'b00110010 : bin = 4'b0010; 8'b00110011 : bin = 4'b0011; 8'b00110100 : bin = 4'b0100; 8'b00110101 : bin = 4'b0101; 8'b00110110 : bin = 4'b0110; 8'b00110111 : bin = 4'b0111; 8'b00111000 : bin = 4'b1000; 8'b00111001 : bin = 4'b1001; 8'b01000001 : bin = 4'b1010; 8'b01000010 : bin = 4'b1011; 8'b01000011 : bin = 4'b1100; 8'b01000100 : bin = 4'b1101; 8'b01000101 : bin = 4'b1110; 8'b01000110 : bin = 4'b1111; 8'b01100001 : bin = 4'b1010; 8'b01100010 : bin = 4'b1011; 8'b01100011 : bin = 4'b1100; 8'b01100100 : bin = 4'b1101; 8'b01100101 : bin = 4'b1110; 8'b01100110 : bin = 4'b1111; default : begin bin = 4'bx; end endcase for( j=0; j<4; j=j+1) begin if ((index*4)+j < C_DOUT_WIDTH) begin hexstr_conv[(index*4)+j] = bin[j]; end end index = index + 1; def_data = def_data >> 8; end end endfunction /************************************************************************** * log2_val * Returns the 'log2' value for the input value for the supported ratios ***************************************************************************/ function [31:0] log2_val; input [31:0] binary_val; begin if (binary_val == 8) begin log2_val = 3; end else if (binary_val == 4) begin log2_val = 2; end else begin log2_val = 1; end end endfunction reg ideal_prog_full = 0; reg ideal_prog_empty = 1; reg [C_WR_DATA_COUNT_WIDTH-1 : 0] ideal_wr_count = 0; reg [C_RD_DATA_COUNT_WIDTH-1 : 0] ideal_rd_count = 0; //Assorted reg values for delayed versions of signals //reg valid_d1 = 0; //user specified value for reseting the size of the fifo //reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0; //temporary registers for WR_RESPONSE_LATENCY feature integer tmp_wr_listsize; integer tmp_rd_listsize; //Signal for registered version of prog full and empty //Threshold values for Programmable Flags integer prog_empty_actual_thresh_assert; integer prog_empty_actual_thresh_negate; integer prog_full_actual_thresh_assert; integer prog_full_actual_thresh_negate; /************************************************************************** * write_fifo * This task writes a word to the FIFO memory and updates the * write pointer. * FIFO size is relative to write domain. ***************************************************************************/ task write_fifo; begin memory[wr_ptr] <= DIN; wr_pntr <= #`TCQ wr_pntr + 1; // Store the type of error injection (double/single) on write case (C_ERROR_INJECTION_TYPE) 3: ecc_err[wr_ptr] <= {INJECTDBITERR,INJECTSBITERR}; 2: ecc_err[wr_ptr] <= {INJECTDBITERR,1'b0}; 1: ecc_err[wr_ptr] <= {1'b0,INJECTSBITERR}; default: ecc_err[wr_ptr] <= 0; endcase // (Works opposite to core: wr_ptr is a DOWN counter) if (wr_ptr == 0) begin wr_ptr <= C_WR_DEPTH - 1; end else begin wr_ptr <= wr_ptr - 1; end end endtask // write_fifo /************************************************************************** * read_fifo * This task reads a word from the FIFO memory and updates the read * pointer. It's output is the ideal_dout bus. * FIFO size is relative to write domain. ***************************************************************************/ task read_fifo; integer i; reg [C_DOUT_WIDTH-1:0] tmp_dout; reg [C_DIN_WIDTH-1:0] memory_read; reg [31:0] tmp_rd_ptr; reg [31:0] rd_ptr_high; reg [31:0] rd_ptr_low; reg [1:0] tmp_ecc_err; begin rd_pntr <= #`TCQ rd_pntr + 1; // output is wider than input if (reads_per_write == 0) begin tmp_dout = 0; tmp_rd_ptr = (rd_ptr << log2_writes_per_read)+(writes_per_read-1); for (i = writes_per_read - 1; i >= 0; i = i - 1) begin tmp_dout = tmp_dout << C_DIN_WIDTH; tmp_dout = tmp_dout | memory[tmp_rd_ptr]; // (Works opposite to core: rd_ptr is a DOWN counter) if (tmp_rd_ptr == 0) begin tmp_rd_ptr = C_WR_DEPTH - 1; end else begin tmp_rd_ptr = tmp_rd_ptr - 1; end end // output is symmetric end else if (reads_per_write == 1) begin tmp_dout = memory[rd_ptr][C_DIN_WIDTH-1:0]; // Retreive the error injection type. Based on the error injection type // corrupt the output data. tmp_ecc_err = ecc_err[rd_ptr]; if (ENABLE_ERR_INJECTION && C_DIN_WIDTH == C_DOUT_WIDTH) begin if (tmp_ecc_err[1]) begin // Corrupt the output data only for double bit error if (C_DOUT_WIDTH == 1) begin $display("FAILURE : Data width must be >= 2 for double bit error injection."); $finish; end else if (C_DOUT_WIDTH == 2) tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2]}; else tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2],(tmp_dout << 2)}; end else begin tmp_dout = tmp_dout[C_DOUT_WIDTH-1:0]; end err_type <= {tmp_ecc_err[1], tmp_ecc_err[0] & !tmp_ecc_err[1]}; end else begin err_type <= 0; end // input is wider than output end else begin rd_ptr_high = rd_ptr >> log2_reads_per_write; rd_ptr_low = rd_ptr & (reads_per_write - 1); memory_read = memory[rd_ptr_high]; tmp_dout = memory_read >> (rd_ptr_low*C_DOUT_WIDTH); end ideal_dout <= tmp_dout; // (Works opposite to core: rd_ptr is a DOWN counter) if (rd_ptr == 0) begin rd_ptr <= C_RD_DEPTH - 1; end else begin rd_ptr <= rd_ptr - 1; end end endtask /************************************************************************* * Initialize Signals for clean power-on simulation *************************************************************************/ initial begin num_wr_bits = 0; num_rd_bits = 0; next_num_wr_bits = 0; next_num_rd_bits = 0; rd_ptr = C_RD_DEPTH - 1; wr_ptr = C_WR_DEPTH - 1; wr_pntr = 0; rd_pntr = 0; rd_ptr_wrclk = rd_ptr; wr_ptr_rdclk = wr_ptr; dout_reset_val = hexstr_conv(C_DOUT_RST_VAL); ideal_dout = dout_reset_val; err_type = 0; ideal_dout_d1 = dout_reset_val; ideal_dout_both = dout_reset_val; ideal_wr_ack = 1'b0; ideal_valid = 1'b0; valid_d1 = 1'b0; valid_both = 1'b0; ideal_overflow = C_OVERFLOW_LOW; ideal_underflow = C_UNDERFLOW_LOW; ideal_wr_count = 0; ideal_rd_count = 0; ideal_prog_full = 1'b0; ideal_prog_empty = 1'b1; end /************************************************************************* * Connect the module inputs and outputs to the internal signals of the * behavioral model. *************************************************************************/ //Inputs /* wire CLK; wire [C_DIN_WIDTH-1:0] DIN; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT; wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT; wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE; wire RD_EN; wire RST; wire WR_EN; */ // Assign ALMOST_EPMTY generate if (C_HAS_ALMOST_EMPTY == 1) begin : gae assign ALMOST_EMPTY = almost_empty_i; end else begin : gnae assign ALMOST_EMPTY = 0; end endgenerate // gae // Assign ALMOST_FULL generate if (C_HAS_ALMOST_FULL==1) begin : gaf assign ALMOST_FULL = almost_full_i; end else begin : gnaf assign ALMOST_FULL = 0; end endgenerate // gaf // Dout may change behavior based on latency localparam C_FWFT_ENABLED = (C_PRELOAD_LATENCY == 0 && C_PRELOAD_REGS == 1)? 1: 0; assign fwft_enabled = (C_PRELOAD_LATENCY == 0 && C_PRELOAD_REGS == 1)? 1: 0; assign ideal_dout_out= ((C_USE_EMBEDDED_REG>0 && (fwft_enabled == 0)) && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1))? ideal_dout_d1: ideal_dout; assign DOUT = ideal_dout_out; // Assign SBITERR and DBITERR based on latency assign SBITERR = (C_ERROR_INJECTION_TYPE == 1 || C_ERROR_INJECTION_TYPE == 3) && ((C_USE_EMBEDDED_REG>0 && (fwft_enabled == 0)) && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ? err_type_d1[0]: err_type[0]; assign DBITERR = (C_ERROR_INJECTION_TYPE == 2 || C_ERROR_INJECTION_TYPE == 3) && ((C_USE_EMBEDDED_REG>0 && (fwft_enabled == 0)) && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ? err_type_d1[1]: err_type[1]; assign EMPTY = empty_i; assign FULL = full_i; //saftey_ckt with one register generate if ((C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_EN_SAFETY_CKT==1 && (C_USE_EMBEDDED_REG == 1 || C_USE_EMBEDDED_REG == 2 )) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; always@(posedge CLK) begin rst_delayed_sft1 <= #`TCQ rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always@(posedge rst_delayed_sft2 or posedge rst_i or posedge CLK) begin if( rst_delayed_sft2 == 1'b1 || rst_i == 1'b1) begin ram_rd_en_d1 <= #`TCQ 1'b0; valid_d1 <= #`TCQ 1'b0; end else begin ram_rd_en_d1 <= #`TCQ (RD_EN && ~(empty_i)); valid_d1 <= #`TCQ valid_i; end end always@(posedge rst_delayed_sft2 or posedge CLK) begin if (rst_delayed_sft2 == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; end end else if (srst_rrst_busy == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; end end else if (ram_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout; err_type_d1[0] <= #`TCQ err_type[0]; err_type_d1[1] <= #`TCQ err_type[1]; end end end //if endgenerate //safety ckt with both registers generate if ((C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1) && C_EN_SAFETY_CKT==1 && C_USE_EMBEDDED_REG == 3) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; always@(posedge CLK) begin rst_delayed_sft1 <= #`TCQ rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always@(posedge rst_delayed_sft2 or posedge rst_i or posedge CLK) begin if( rst_delayed_sft2 == 1'b1 || rst_i == 1'b1) begin ram_rd_en_d1 <= #`TCQ 1'b0; valid_d1 <= #`TCQ 1'b0; end else begin ram_rd_en_d1 <= #`TCQ (RD_EN && ~(empty_i)); fab_rd_en_d1 <= #`TCQ ram_rd_en_d1; valid_both <= #`TCQ valid_i; valid_d1 <= #`TCQ valid_both; end end always@(posedge rst_delayed_sft2 or posedge CLK) begin if (rst_delayed_sft2 == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; end end else if (srst_rrst_busy == 1'b1) begin if (C_USE_DOUT_RST == 1'b1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; end end else if (ram_rd_en_d1) begin ideal_dout_both <= #`TCQ ideal_dout; err_type_both[0] <= #`TCQ err_type[0]; err_type_both[1] <= #`TCQ err_type[1]; end if (fab_rd_en_d1) begin ideal_dout_d1 <= #`TCQ ideal_dout_both; err_type_d1[0] <= #`TCQ err_type_both[0]; err_type_d1[1] <= #`TCQ err_type_both[1]; end end //assign SBITERR = (C_USE_ECC == 0) ? err_type[0]:err_type_d1[0]; //assign DBITERR = (C_USE_ECC == 0) ? err_type[1]:err_type_d1[1]; //assign DOUT[C_DOUT_WIDTH-1:0] = ideal_dout_d1; end //if endgenerate //Overflow may be active-low generate if (C_HAS_OVERFLOW==1) begin : gof assign OVERFLOW = ideal_overflow ? !C_OVERFLOW_LOW : C_OVERFLOW_LOW; end else begin : gnof assign OVERFLOW = 0; end endgenerate // gof assign PROG_EMPTY = prog_empty_i; assign PROG_FULL = prog_full_i; //Valid may change behavior based on latency or active-low generate if (C_HAS_VALID==1) begin : gvalid assign valid_i = (C_PRELOAD_LATENCY == 0) ? (RD_EN & ~EMPTY) : ideal_valid; assign valid_out = (C_PRELOAD_LATENCY == 2 && C_MEMORY_TYPE < 2) ? valid_d1 : valid_i; assign VALID = valid_out ? !C_VALID_LOW : C_VALID_LOW; end else begin : gnvalid assign VALID = 0; end endgenerate // gvalid //Trim data count differently depending on set widths generate if (C_HAS_DATA_COUNT == 1) begin : gdc always @* begin diff_count <= wr_pntr - rd_pntr; if (C_DATA_COUNT_WIDTH > C_RD_PNTR_WIDTH) begin DATA_COUNT[C_RD_PNTR_WIDTH-1:0] <= diff_count; DATA_COUNT[C_DATA_COUNT_WIDTH-1] <= 1'b0 ; end else begin DATA_COUNT <= diff_count[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_DATA_COUNT_WIDTH]; end end // end else begin : gndc // always @* DATA_COUNT <= 0; end endgenerate // gdc //Underflow may change behavior based on latency or active-low generate if (C_HAS_UNDERFLOW==1) begin : guf assign underflow_i = ideal_underflow; assign UNDERFLOW = underflow_i ? !C_UNDERFLOW_LOW : C_UNDERFLOW_LOW; end else begin : gnuf assign UNDERFLOW = 0; end endgenerate // guf //Write acknowledge may be active low generate if (C_HAS_WR_ACK==1) begin : gwr_ack assign WR_ACK = ideal_wr_ack ? !C_WR_ACK_LOW : C_WR_ACK_LOW; end else begin : gnwr_ack assign WR_ACK = 0; end endgenerate // gwr_ack /***************************************************************************** * Internal reset logic ****************************************************************************/ assign srst_i = C_HAS_SRST ? SRST : 0; assign srst_wrst_busy = C_HAS_SRST ? (SRST || WR_RST_BUSY) : 0; assign srst_rrst_busy = C_HAS_SRST ? (SRST || RD_RST_BUSY) : 0; assign rst_i = C_HAS_RST ? RST : 0; /************************************************************************** * Assorted registers for delayed versions of signals **************************************************************************/ //Capture delayed version of valid generate if (C_HAS_VALID == 1 && (C_USE_EMBEDDED_REG <3)) begin : blockVL20 always @(posedge CLK or posedge rst_i) begin if (rst_i == 1'b1) begin valid_d1 <= #`TCQ 1'b0; end else begin if (srst_rrst_busy) begin valid_d1 <= #`TCQ 1'b0; end else begin valid_d1 <= #`TCQ valid_i; end end end // always @ (posedge CLK or posedge rst_i) end endgenerate // blockVL20 generate if (C_HAS_VALID == 1 && (C_USE_EMBEDDED_REG == 3)) begin always @(posedge CLK or posedge rst_i) begin if (rst_i == 1'b1) begin valid_d1 <= #`TCQ 1'b0; valid_both <= #`TCQ 1'b0; end else begin if (srst_rrst_busy) begin valid_d1 <= #`TCQ 1'b0; valid_both <= #`TCQ 1'b0; end else begin valid_both <= #`TCQ valid_i; valid_d1 <= #`TCQ valid_both; end end end // always @ (posedge CLK or posedge rst_i) end endgenerate // blockVL20 // Determine which stage in FWFT registers are valid reg stage1_valid = 0; reg stage2_valid = 0; generate if (C_PRELOAD_LATENCY == 0) begin : grd_fwft_proc always @ (posedge CLK or posedge rst_i) begin if (rst_i) begin stage1_valid <= #`TCQ 0; stage2_valid <= #`TCQ 0; end else begin if (!stage1_valid && !stage2_valid) begin if (!EMPTY) stage1_valid <= #`TCQ 1'b1; else stage1_valid <= #`TCQ 1'b0; end else if (stage1_valid && !stage2_valid) begin if (EMPTY) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end end else if (!stage1_valid && stage2_valid) begin if (EMPTY && RD_EN) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b0; end else if (!EMPTY && RD_EN) begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b0; end else if (!EMPTY && !RD_EN) begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end end else if (stage1_valid && stage2_valid) begin if (EMPTY && RD_EN) begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b1; end else begin stage1_valid <= #`TCQ 1'b1; stage2_valid <= #`TCQ 1'b1; end end else begin stage1_valid <= #`TCQ 1'b0; stage2_valid <= #`TCQ 1'b0; end end // rd_rst_i end // always end endgenerate //*************************************************************************** // Assign the read data count value only if it is selected, // otherwise output zeros. //*************************************************************************** generate if (C_HAS_RD_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT ==1) begin : grdc assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = rd_data_count_i_ss[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH]; end endgenerate generate if (C_HAS_RD_DATA_COUNT == 0) begin : gnrdc assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = {C_RD_DATA_COUNT_WIDTH{1'b0}}; end endgenerate //*************************************************************************** // Assign the write data count value only if it is selected, // otherwise output zeros //*************************************************************************** generate if (C_HAS_WR_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : gwdc assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = wr_data_count_i_ss[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH] ; end endgenerate generate if (C_HAS_WR_DATA_COUNT == 0) begin : gnwdc assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = {C_WR_DATA_COUNT_WIDTH{1'b0}}; end endgenerate // block memory has a synchronous reset // no safety ckt with emb/fabric reg //generate if (C_MEMORY_TYPE < 2 && C_EN_SAFETY_CKT == 0) begin : gen_fifo_blkmemdout_emb // always @(posedge CLK) begin // // BRAM resets synchronously // // make it consistent with the core. // if ((rst_i || srst_rrst_busy) && (C_USE_DOUT_RST == 1)) // ideal_dout_d1 <= #`TCQ dout_reset_val; // ideal_dout_both <= #`TCQ dout_reset_val; // end //always //end endgenerate // gen_fifo_blkmemdout_emb //reg ram_rd_en_d1 = 1'b0; //Capture delayed version of dout generate if (C_EN_SAFETY_CKT == 0 && (C_USE_EMBEDDED_REG<3)) begin always @(posedge CLK or posedge rst_i) begin if (rst_i == 1'b1) begin // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type_d1 <= #`TCQ 0; // DRAM and SRAM reset asynchronously if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; end ram_rd_en_d1 <= #`TCQ 1'b0; if (C_USE_DOUT_RST == 1) begin @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; end end else begin ram_rd_en_d1 <= #`TCQ RD_EN & ~EMPTY; if (srst_rrst_busy) begin ram_rd_en_d1 <= #`TCQ 1'b0; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) begin err_type_d1 <= #`TCQ 0; end // Reset DRAM and SRAM based FIFO, BRAM based FIFO is reset above if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; end if (C_USE_DOUT_RST == 1) begin // @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; end end else begin if (ram_rd_en_d1 ) begin ideal_dout_d1 <= #`TCQ ideal_dout; err_type_d1 <= #`TCQ err_type; end end end end // always end endgenerate //no safety ckt with both registers generate if (C_EN_SAFETY_CKT == 0 && (C_USE_EMBEDDED_REG==3)) begin always @(posedge CLK or posedge rst_i) begin if (rst_i == 1'b1) begin ram_rd_en_d1 <= #`TCQ 1'b0; fab_rd_en_d1 <= #`TCQ 1'b0; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type_d1 <= #`TCQ 0; // DRAM and SRAM reset asynchronously if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; ideal_dout_both <= #`TCQ dout_reset_val; end if (C_USE_DOUT_RST == 1) begin @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; ideal_dout_both <= #`TCQ dout_reset_val; end end else begin ram_rd_en_d1 <= #`TCQ RD_EN & ~EMPTY; fab_rd_en_d1 <= #`TCQ (ram_rd_en_d1); if (srst_rrst_busy) begin ram_rd_en_d1 <= #`TCQ 1'b0; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) begin err_type_d1 <= #`TCQ 0; end // Reset DRAM and SRAM based FIFO, BRAM based FIFO is reset above if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1) begin ideal_dout_d1 <= #`TCQ dout_reset_val; // ideal_dout_both <= #`TCQ dout_reset_val; end if (C_USE_DOUT_RST == 1) begin // @(posedge CLK) ideal_dout_d1 <= #`TCQ dout_reset_val; // ideal_dout_both <= #`TCQ dout_reset_val; end end else begin if (ram_rd_en_d1 ) begin ideal_dout_both <= #`TCQ ideal_dout; err_type_both <= #`TCQ err_type; end if (fab_rd_en_d1 ) begin ideal_dout_d1 <= #`TCQ ideal_dout_both; err_type_d1 <= #`TCQ err_type_both; end end end end // always end endgenerate /************************************************************************** * Overflow and Underflow Flag calculation * (handled separately because they don't support rst) **************************************************************************/ generate if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 0) begin : g7s_ovflw always @(posedge CLK) begin ideal_overflow <= #`TCQ WR_EN & full_i; end end else if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 1) begin : g8s_ovflw always @(posedge CLK) begin //ideal_overflow <= #`TCQ WR_EN & (rst_i | full_i); ideal_overflow <= #`TCQ WR_EN & (WR_RST_BUSY | full_i); end end endgenerate // blockOF20 generate if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 0) begin : g7s_unflw always @(posedge CLK) begin ideal_underflow <= #`TCQ empty_i & RD_EN; end end else if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 1) begin : g8s_unflw always @(posedge CLK) begin //ideal_underflow <= #`TCQ (rst_i | empty_i) & RD_EN; ideal_underflow <= #`TCQ (RD_RST_BUSY | empty_i) & RD_EN; end end endgenerate // blockUF20 /************************** * Read Data Count *************************/ reg [31:0] num_read_words_dc; reg [C_RD_DATA_COUNT_WIDTH-1:0] num_read_words_sized_i; always @(num_rd_bits) begin if (C_USE_FWFT_DATA_COUNT) begin //If using extra logic for FWFT Data Counts, // then scale FIFO contents to read domain, // and add two read words for FWFT stages //This value is only a temporary value and not used in the code. num_read_words_dc = (num_rd_bits/C_DOUT_WIDTH+2); //Trim the read words for use with RD_DATA_COUNT num_read_words_sized_i = num_read_words_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH+1]; end else begin //If not using extra logic for FWFT Data Counts, // then scale FIFO contents to read domain. //This value is only a temporary value and not used in the code. num_read_words_dc = num_rd_bits/C_DOUT_WIDTH; //Trim the read words for use with RD_DATA_COUNT num_read_words_sized_i = num_read_words_dc[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH]; end //if (C_USE_FWFT_DATA_COUNT) end //always /************************** * Write Data Count *************************/ reg [31:0] num_write_words_dc; reg [C_WR_DATA_COUNT_WIDTH-1:0] num_write_words_sized_i; always @(num_wr_bits) begin if (C_USE_FWFT_DATA_COUNT) begin //Calculate the Data Count value for the number of write words, // when using First-Word Fall-Through with extra logic for Data // Counts. This takes into consideration the number of words that // are expected to be stored in the FWFT register stages (it always // assumes they are filled). //This value is scaled to the Write Domain. //The expression (((A-1)/B))+1 divides A/B, but takes the // ceiling of the result. //When num_wr_bits==0, set the result manually to prevent // division errors. //EXTRA_WORDS_DC is the number of words added to write_words // due to FWFT. //This value is only a temporary value and not used in the code. num_write_words_dc = (num_wr_bits==0) ? EXTRA_WORDS_DC : (((num_wr_bits-1)/C_DIN_WIDTH)+1) + EXTRA_WORDS_DC ; //Trim the write words for use with WR_DATA_COUNT num_write_words_sized_i = num_write_words_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH+1]; end else begin //Calculate the Data Count value for the number of write words, when NOT // using First-Word Fall-Through with extra logic for Data Counts. This // calculates only the number of words in the internal FIFO. //The expression (((A-1)/B))+1 divides A/B, but takes the // ceiling of the result. //This value is scaled to the Write Domain. //When num_wr_bits==0, set the result manually to prevent // division errors. //This value is only a temporary value and not used in the code. num_write_words_dc = (num_wr_bits==0) ? 0 : ((num_wr_bits-1)/C_DIN_WIDTH)+1; //Trim the read words for use with RD_DATA_COUNT num_write_words_sized_i = num_write_words_dc[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH]; end //if (C_USE_FWFT_DATA_COUNT) end //always /************************************************************************* * Write and Read Logic ************************************************************************/ wire write_allow; wire read_allow; wire read_allow_dc; wire write_only; wire read_only; //wire write_only_q; reg write_only_q; //wire read_only_q; reg read_only_q; reg full_reg; reg rst_full_ff_reg1; reg rst_full_ff_reg2; wire ram_full_comb; wire carry; assign write_allow = WR_EN & ~full_i; assign read_allow = RD_EN & ~empty_i; assign read_allow_dc = RD_EN_USER & ~USER_EMPTY_FB; //assign write_only = write_allow & ~read_allow; //assign write_only_q = write_allow_q; //assign read_only = read_allow & ~write_allow; //assign read_only_q = read_allow_q ; wire [C_WR_PNTR_WIDTH-1:0] diff_pntr; wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe; reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_reg1 = 0; reg [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe_reg1 = 0; reg [C_RD_PNTR_WIDTH:0] diff_pntr_pe_asym = 0; wire [C_RD_PNTR_WIDTH:0] adj_wr_pntr_rd_asym ; wire [C_RD_PNTR_WIDTH:0] rd_pntr_asym; reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_reg2 = 0; reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_pe_reg2 = 0; wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe_max; wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_max; assign diff_pntr_pe_max = DIFF_MAX_RD; assign diff_pntr_max = DIFF_MAX_WR; generate if (IS_ASYMMETRY == 0) begin : diff_pntr_sym assign write_only = write_allow & ~read_allow; assign read_only = read_allow & ~write_allow; end endgenerate generate if ( IS_ASYMMETRY == 1 && C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : wr_grt_rd assign read_only = read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0]) & ~write_allow; assign write_only = write_allow & ~(read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])); end endgenerate generate if (IS_ASYMMETRY ==1 && C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : rd_grt_wr assign read_only = read_allow & ~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0])); assign write_only = write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]) & ~read_allow; end endgenerate //----------------------------------------------------------------------------- // Write and Read pointer generation //----------------------------------------------------------------------------- always @(posedge CLK or posedge rst_i) begin if (rst_i) begin wr_pntr <= 0; rd_pntr <= 0; end else begin if (srst_i || srst_wrst_busy || srst_rrst_busy ) begin if (srst_wrst_busy) wr_pntr <= #`TCQ 0; if (srst_rrst_busy) rd_pntr <= #`TCQ 0; end else begin if (write_allow) wr_pntr <= #`TCQ wr_pntr + 1; if (read_allow) rd_pntr <= #`TCQ rd_pntr + 1; end end end generate if (C_FIFO_TYPE == 2) begin : gll_dm_dout always @(posedge CLK) begin if (write_allow) begin if (ENABLE_ERR_INJECTION == 1) memory[wr_pntr] <= #`TCQ {INJECTDBITERR,INJECTSBITERR,DIN}; else memory[wr_pntr] <= #`TCQ DIN; end end reg [C_DATA_WIDTH-1:0] dout_tmp_q; reg [C_DATA_WIDTH-1:0] dout_tmp = 0; reg [C_DATA_WIDTH-1:0] dout_tmp1 = 0; always @(posedge CLK) begin dout_tmp_q <= #`TCQ ideal_dout; end always @* begin if (read_allow) ideal_dout <= memory[rd_pntr]; else ideal_dout <= dout_tmp_q; end end endgenerate // gll_dm_dout /************************************************************************** * Write Domain Logic **************************************************************************/ assign ram_rd_en = RD_EN & !EMPTY; //reg [C_WR_PNTR_WIDTH-1:0] diff_pntr = 0; generate if (C_FIFO_TYPE != 2) begin : gnll_din always @(posedge CLK or posedge rst_i) begin : gen_fifo_w /****** Reset fifo (case 1)***************************************/ if (rst_i == 1'b1) begin num_wr_bits <= #`TCQ 0; next_num_wr_bits = #`TCQ 0; wr_ptr <= #`TCQ C_WR_DEPTH - 1; rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1; ideal_wr_ack <= #`TCQ 0; ideal_wr_count <= #`TCQ 0; tmp_wr_listsize = #`TCQ 0; rd_ptr_wrclk_next <= #`TCQ 0; wr_pntr <= #`TCQ 0; wr_pntr_rd1 <= #`TCQ 0; end else begin //rst_i==0 if (srst_wrst_busy) begin num_wr_bits <= #`TCQ 0; next_num_wr_bits = #`TCQ 0; wr_ptr <= #`TCQ C_WR_DEPTH - 1; rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1; ideal_wr_ack <= #`TCQ 0; ideal_wr_count <= #`TCQ 0; tmp_wr_listsize = #`TCQ 0; rd_ptr_wrclk_next <= #`TCQ 0; wr_pntr <= #`TCQ 0; wr_pntr_rd1 <= #`TCQ 0; end else begin//srst_i=0 wr_pntr_rd1 <= #`TCQ wr_pntr; //Determine the current number of words in the FIFO tmp_wr_listsize = (C_DEPTH_RATIO_RD > 1) ? num_wr_bits/C_DOUT_WIDTH : num_wr_bits/C_DIN_WIDTH; rd_ptr_wrclk_next = rd_ptr; if (rd_ptr_wrclk < rd_ptr_wrclk_next) begin next_num_wr_bits = num_wr_bits - C_DOUT_WIDTH*(rd_ptr_wrclk + C_RD_DEPTH - rd_ptr_wrclk_next); end else begin next_num_wr_bits = num_wr_bits - C_DOUT_WIDTH*(rd_ptr_wrclk - rd_ptr_wrclk_next); end if (WR_EN == 1'b1) begin if (FULL == 1'b1) begin ideal_wr_ack <= #`TCQ 0; //Reminder that FIFO is still full ideal_wr_count <= #`TCQ num_write_words_sized_i; end else begin write_fifo; next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH; //Write successful, so issue acknowledge // and no error ideal_wr_ack <= #`TCQ 1; //Not even close to full. ideal_wr_count <= num_write_words_sized_i; //end end end else begin //(WR_EN == 1'b1) //If user did not attempt a write, then do not // give ack or err ideal_wr_ack <= #`TCQ 0; ideal_wr_count <= #`TCQ num_write_words_sized_i; end num_wr_bits <= #`TCQ next_num_wr_bits; rd_ptr_wrclk <= #`TCQ rd_ptr; end //srst_i==0 end //wr_rst_i==0 end // gen_fifo_w end endgenerate generate if (C_FIFO_TYPE < 2 && C_MEMORY_TYPE < 2 && C_EN_SAFETY_CKT == 0) begin : gnll_dm_dout always @(posedge CLK) begin if (rst_i || srst_rrst_busy) begin if (C_USE_DOUT_RST == 1) ideal_dout <= #`TCQ dout_reset_val; ideal_dout_both <= #`TCQ dout_reset_val; end end end endgenerate generate if (C_FIFO_TYPE != 2) begin : gnll_dout always @(posedge CLK or posedge rst_i) begin : gen_fifo_r /****** Reset fifo (case 1)***************************************/ if (rst_i) begin num_rd_bits <= #`TCQ 0; next_num_rd_bits = #`TCQ 0; rd_ptr <= #`TCQ C_RD_DEPTH -1; rd_pntr <= #`TCQ 0; //rd_pntr_wr1 <= #`TCQ 0; wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1; // DRAM resets asynchronously if (C_FIFO_TYPE < 2 && (C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3 )&& C_USE_DOUT_RST == 1) ideal_dout <= #`TCQ dout_reset_val; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type <= #`TCQ 0; ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ 0; end else begin //rd_rst_i==0 if (srst_rrst_busy) begin num_rd_bits <= #`TCQ 0; next_num_rd_bits = #`TCQ 0; rd_ptr <= #`TCQ C_RD_DEPTH -1; rd_pntr <= #`TCQ 0; //rd_pntr_wr1 <= #`TCQ 0; wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1; // DRAM resets synchronously if (C_FIFO_TYPE < 2 && (C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3 )&& C_USE_DOUT_RST == 1) ideal_dout <= #`TCQ dout_reset_val; // Reset err_type only if ECC is not selected if (C_USE_ECC == 0) err_type <= #`TCQ 0; ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ 0; end //srst_i else begin //rd_pntr_wr1 <= #`TCQ rd_pntr; //Determine the current number of words in the FIFO tmp_rd_listsize = (C_DEPTH_RATIO_WR > 1) ? num_rd_bits/C_DIN_WIDTH : num_rd_bits/C_DOUT_WIDTH; wr_ptr_rdclk_next = wr_ptr; if (wr_ptr_rdclk < wr_ptr_rdclk_next) begin next_num_rd_bits = num_rd_bits + C_DIN_WIDTH*(wr_ptr_rdclk +C_WR_DEPTH - wr_ptr_rdclk_next); end else begin next_num_rd_bits = num_rd_bits + C_DIN_WIDTH*(wr_ptr_rdclk - wr_ptr_rdclk_next); end if (RD_EN == 1'b1) begin if (EMPTY == 1'b1) begin ideal_valid <= #`TCQ 1'b0; ideal_rd_count <= #`TCQ num_read_words_sized_i; end else begin read_fifo; next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH; //Acknowledge the read from the FIFO, no error ideal_valid <= #`TCQ 1'b1; ideal_rd_count <= #`TCQ num_read_words_sized_i; end // if (tmp_rd_listsize == 2) end num_rd_bits <= #`TCQ next_num_rd_bits; wr_ptr_rdclk <= #`TCQ wr_ptr; end //s_rst_i==0 end //rd_rst_i==0 end //always end endgenerate //----------------------------------------------------------------------------- // Generate diff_pntr for PROG_FULL generation // Generate diff_pntr_pe for PROG_EMPTY generation //----------------------------------------------------------------------------- generate if ((C_PROG_FULL_TYPE != 0 || C_PROG_EMPTY_TYPE != 0) && IS_ASYMMETRY == 0) begin : reg_write_allow always @(posedge CLK ) begin if (rst_i) begin write_only_q <= 1'b0; read_only_q <= 1'b0; diff_pntr_reg1 <= 0; diff_pntr_pe_reg1 <= 0; diff_pntr_reg2 <= 0; diff_pntr_pe_reg2 <= 0; end else begin if (srst_i || srst_wrst_busy || srst_rrst_busy) begin if (srst_rrst_busy) begin read_only_q <= #`TCQ 1'b0; diff_pntr_pe_reg1 <= #`TCQ 0; diff_pntr_pe_reg2 <= #`TCQ 0; end if (srst_wrst_busy) begin write_only_q <= #`TCQ 1'b0; diff_pntr_reg1 <= #`TCQ 0; diff_pntr_reg2 <= #`TCQ 0; end end else begin write_only_q <= #`TCQ write_only; read_only_q <= #`TCQ read_only; diff_pntr_reg2 <= #`TCQ diff_pntr_reg1; diff_pntr_pe_reg2 <= #`TCQ diff_pntr_pe_reg1; // Add 1 to the difference pointer value when only write happens. if (write_only) diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr + 1; else diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr; // Add 1 to the difference pointer value when write or both write & read or no write & read happen. if (read_only) diff_pntr_pe_reg1 <= #`TCQ adj_wr_pntr_rd - rd_pntr - 1; else diff_pntr_pe_reg1 <= #`TCQ adj_wr_pntr_rd - rd_pntr; end end end assign diff_pntr_pe = diff_pntr_pe_reg1; assign diff_pntr = diff_pntr_reg1; end endgenerate // reg_write_allow generate if ((C_PROG_FULL_TYPE != 0 || C_PROG_EMPTY_TYPE != 0) && IS_ASYMMETRY == 1) begin : reg_write_allow_asym assign adj_wr_pntr_rd_asym[C_RD_PNTR_WIDTH:0] = {adj_wr_pntr_rd,1'b1}; assign rd_pntr_asym[C_RD_PNTR_WIDTH:0] = {~rd_pntr,1'b1}; always @(posedge CLK ) begin if (rst_i) begin diff_pntr_pe_asym <= 0; diff_pntr_reg1 <= 0; full_reg <= 0; rst_full_ff_reg1 <= 1; rst_full_ff_reg2 <= 1; diff_pntr_pe_reg1 <= 0; end else begin if (srst_i || srst_wrst_busy || srst_rrst_busy) begin if (srst_wrst_busy) diff_pntr_reg1 <= #`TCQ 0; if (srst_rrst_busy) full_reg <= #`TCQ 0; rst_full_ff_reg1 <= #`TCQ 1; rst_full_ff_reg2 <= #`TCQ 1; diff_pntr_pe_asym <= #`TCQ 0; diff_pntr_pe_reg1 <= #`TCQ 0; end else begin diff_pntr_pe_asym <= #`TCQ adj_wr_pntr_rd_asym + rd_pntr_asym; full_reg <= #`TCQ full_i; rst_full_ff_reg1 <= #`TCQ RST_FULL_FF; rst_full_ff_reg2 <= #`TCQ rst_full_ff_reg1; if (~full_i) begin diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr; end end end end assign carry = (~(|(diff_pntr_pe_asym [C_RD_PNTR_WIDTH : 1]))); assign diff_pntr_pe = (full_reg && ~rst_full_ff_reg2 && carry ) ? diff_pntr_pe_max : diff_pntr_pe_asym[C_RD_PNTR_WIDTH:1]; assign diff_pntr = diff_pntr_reg1; end endgenerate // reg_write_allow_asym //----------------------------------------------------------------------------- // Generate FULL flag //----------------------------------------------------------------------------- wire comp0; wire comp1; wire going_full; wire leaving_full; generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gpad assign adj_rd_pntr_wr [C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr; assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0] = 0; end endgenerate generate if (C_WR_PNTR_WIDTH <= C_RD_PNTR_WIDTH) begin : gtrim assign adj_rd_pntr_wr = rd_pntr[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH]; end endgenerate assign comp1 = (adj_rd_pntr_wr == (wr_pntr + 1'b1)); assign comp0 = (adj_rd_pntr_wr == wr_pntr); generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gf_wp_eq_rp assign going_full = (comp1 & write_allow & ~read_allow); assign leaving_full = (comp0 & read_allow) | RST_FULL_GEN; end endgenerate // Write data width is bigger than read data width // Write depth is smaller than read depth // One write could be equal to 2 or 4 or 8 reads generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gf_asym assign going_full = (comp1 & write_allow & (~ (read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])))); assign leaving_full = (comp0 & read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])) | RST_FULL_GEN; end endgenerate generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gf_wp_gt_rp assign going_full = (comp1 & write_allow & ~read_allow); assign leaving_full =(comp0 & read_allow) | RST_FULL_GEN; end endgenerate assign ram_full_comb = going_full | (~leaving_full & full_i); always @(posedge CLK or posedge RST_FULL_FF) begin if (RST_FULL_FF) full_i <= C_FULL_FLAGS_RST_VAL; else if (srst_wrst_busy) full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else full_i <= #`TCQ ram_full_comb; end //----------------------------------------------------------------------------- // Generate EMPTY flag //----------------------------------------------------------------------------- wire ecomp0; wire ecomp1; wire going_empty; wire leaving_empty; wire ram_empty_comb; generate if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin : pad assign adj_wr_pntr_rd [C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr; assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0] = 0; end endgenerate generate if (C_RD_PNTR_WIDTH <= C_WR_PNTR_WIDTH) begin : trim assign adj_wr_pntr_rd = wr_pntr[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH]; end endgenerate assign ecomp1 = (adj_wr_pntr_rd == (rd_pntr + 1'b1)); assign ecomp0 = (adj_wr_pntr_rd == rd_pntr); generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : ge_wp_eq_rp assign going_empty = (ecomp1 & ~write_allow & read_allow); assign leaving_empty = (ecomp0 & write_allow); end endgenerate generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : ge_wp_gt_rp assign going_empty = (ecomp1 & read_allow & (~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0])))); assign leaving_empty = (ecomp0 & write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0])); end endgenerate generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : ge_wp_lt_rp assign going_empty = (ecomp1 & ~write_allow & read_allow); assign leaving_empty =(ecomp0 & write_allow); end endgenerate assign ram_empty_comb = going_empty | (~leaving_empty & empty_i); always @(posedge CLK or posedge rst_i) begin if (rst_i) empty_i <= 1'b1; else if (srst_rrst_busy) empty_i <= #`TCQ 1'b1; else empty_i <= #`TCQ ram_empty_comb; end //----------------------------------------------------------------------------- // Generate Read and write data counts for asymmetic common clock //----------------------------------------------------------------------------- reg [C_GRTR_PNTR_WIDTH :0] count_dc = 0; wire [C_GRTR_PNTR_WIDTH :0] ratio; wire decr_by_one; wire incr_by_ratio; wire incr_by_one; wire decr_by_ratio; localparam IS_FWFT = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? 1 : 0; generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : rd_depth_gt_wr assign ratio = C_DEPTH_RATIO_RD; assign decr_by_one = (IS_FWFT == 1)? read_allow_dc : read_allow; assign incr_by_ratio = write_allow; always @(posedge CLK or posedge rst_i) begin if (rst_i) count_dc <= #`TCQ 0; else if (srst_wrst_busy) count_dc <= #`TCQ 0; else begin if (decr_by_one) begin if (!incr_by_ratio) count_dc <= #`TCQ count_dc - 1; else count_dc <= #`TCQ count_dc - 1 + ratio ; end else begin if (!incr_by_ratio) count_dc <= #`TCQ count_dc ; else count_dc <= #`TCQ count_dc + ratio ; end end end assign rd_data_count_i_ss[C_RD_PNTR_WIDTH : 0] = count_dc; assign wr_data_count_i_ss[C_WR_PNTR_WIDTH : 0] = count_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH]; end endgenerate generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : wr_depth_gt_rd assign ratio = C_DEPTH_RATIO_WR; assign incr_by_one = write_allow; assign decr_by_ratio = (IS_FWFT == 1)? read_allow_dc : read_allow; always @(posedge CLK or posedge rst_i) begin if (rst_i) count_dc <= #`TCQ 0; else if (srst_wrst_busy) count_dc <= #`TCQ 0; else begin if (incr_by_one) begin if (!decr_by_ratio) count_dc <= #`TCQ count_dc + 1; else count_dc <= #`TCQ count_dc + 1 - ratio ; end else begin if (!decr_by_ratio) count_dc <= #`TCQ count_dc ; else count_dc <= #`TCQ count_dc - ratio ; end end end assign wr_data_count_i_ss[C_WR_PNTR_WIDTH : 0] = count_dc; assign rd_data_count_i_ss[C_RD_PNTR_WIDTH : 0] = count_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH]; end endgenerate //----------------------------------------------------------------------------- // Generate WR_ACK flag //----------------------------------------------------------------------------- always @(posedge CLK or posedge rst_i) begin if (rst_i) ideal_wr_ack <= 1'b0; else if (srst_wrst_busy) ideal_wr_ack <= #`TCQ 1'b0; else if (WR_EN & ~full_i) ideal_wr_ack <= #`TCQ 1'b1; else ideal_wr_ack <= #`TCQ 1'b0; end //----------------------------------------------------------------------------- // Generate VALID flag //----------------------------------------------------------------------------- always @(posedge CLK or posedge rst_i) begin if (rst_i) ideal_valid <= 1'b0; else if (srst_rrst_busy) ideal_valid <= #`TCQ 1'b0; else if (RD_EN & ~empty_i) ideal_valid <= #`TCQ 1'b1; else ideal_valid <= #`TCQ 1'b0; end //----------------------------------------------------------------------------- // Generate ALMOST_FULL flag //----------------------------------------------------------------------------- //generate if (C_HAS_ALMOST_FULL == 1 || C_PROG_FULL_TYPE > 2 || C_PROG_EMPTY_TYPE > 2) begin : gaf_ss wire fcomp2; wire going_afull; wire leaving_afull; wire ram_afull_comb; assign fcomp2 = (adj_rd_pntr_wr == (wr_pntr + 2'h2)); generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gaf_wp_eq_rp assign going_afull = (fcomp2 & write_allow & ~read_allow); assign leaving_afull = (comp1 & read_allow & ~write_allow) | RST_FULL_GEN; end endgenerate // Write data width is bigger than read data width // Write depth is smaller than read depth // One write could be equal to 2 or 4 or 8 reads generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gaf_asym assign going_afull = (fcomp2 & write_allow & (~ (read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])))); assign leaving_afull = (comp1 & (~write_allow) & read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])) | RST_FULL_GEN; end endgenerate generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gaf_wp_gt_rp assign going_afull = (fcomp2 & write_allow & ~read_allow); assign leaving_afull =((comp0 | comp1 | fcomp2) & read_allow) | RST_FULL_GEN; end endgenerate assign ram_afull_comb = going_afull | (~leaving_afull & almost_full_i); always @(posedge CLK or posedge RST_FULL_FF) begin if (RST_FULL_FF) almost_full_i <= C_FULL_FLAGS_RST_VAL; else if (srst_wrst_busy) almost_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else almost_full_i <= #`TCQ ram_afull_comb; end // end endgenerate // gaf_ss //----------------------------------------------------------------------------- // Generate ALMOST_EMPTY flag //----------------------------------------------------------------------------- //generate if (C_HAS_ALMOST_EMPTY == 1) begin : gae_ss wire ecomp2; wire going_aempty; wire leaving_aempty; wire ram_aempty_comb; assign ecomp2 = (adj_wr_pntr_rd == (rd_pntr + 2'h2)); generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gae_wp_eq_rp assign going_aempty = (ecomp2 & ~write_allow & read_allow); assign leaving_aempty = (ecomp1 & write_allow & ~read_allow); end endgenerate generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gae_wp_gt_rp assign going_aempty = (ecomp2 & read_allow & (~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0])))); assign leaving_aempty = (ecomp1 & ~read_allow & write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0])); end endgenerate generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gae_wp_lt_rp assign going_aempty = (ecomp2 & ~write_allow & read_allow); assign leaving_aempty =((ecomp2 | ecomp1 |ecomp0) & write_allow); end endgenerate assign ram_aempty_comb = going_aempty | (~leaving_aempty & almost_empty_i); always @(posedge CLK or posedge rst_i) begin if (rst_i) almost_empty_i <= 1'b1; else if (srst_rrst_busy) almost_empty_i <= #`TCQ 1'b1; else almost_empty_i <= #`TCQ ram_aempty_comb; end // end endgenerate // gae_ss //----------------------------------------------------------------------------- // Generate PROG_FULL //----------------------------------------------------------------------------- localparam C_PF_ASSERT_VAL = (C_PRELOAD_LATENCY == 0) ? C_PROG_FULL_THRESH_ASSERT_VAL - EXTRA_WORDS_PF_PARAM : // FWFT C_PROG_FULL_THRESH_ASSERT_VAL; // STD localparam C_PF_NEGATE_VAL = (C_PRELOAD_LATENCY == 0) ? C_PROG_FULL_THRESH_NEGATE_VAL - EXTRA_WORDS_PF_PARAM: // FWFT C_PROG_FULL_THRESH_NEGATE_VAL; // STD //----------------------------------------------------------------------------- // Generate PROG_FULL for single programmable threshold constant //----------------------------------------------------------------------------- wire [C_WR_PNTR_WIDTH-1:0] temp = C_PF_ASSERT_VAL; generate if (C_PROG_FULL_TYPE == 1) begin : single_pf_const always @(posedge CLK or posedge RST_FULL_FF) begin if (RST_FULL_FF && C_HAS_RST) prog_full_i <= C_FULL_FLAGS_RST_VAL; else begin if (srst_wrst_busy) prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else if (IS_ASYMMETRY == 0) begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (diff_pntr == C_PF_ASSERT_VAL && write_only_q) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr == C_PF_ASSERT_VAL && read_only_q) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ prog_full_i; end else begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~RST_FULL_GEN ) begin if (diff_pntr>= C_PF_ASSERT_VAL ) prog_full_i <= #`TCQ 1'b1; else if ((diff_pntr) < C_PF_ASSERT_VAL ) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ 1'b0; end else prog_full_i <= #`TCQ prog_full_i; end end end end endgenerate // single_pf_const //----------------------------------------------------------------------------- // Generate PROG_FULL for multiple programmable threshold constants //----------------------------------------------------------------------------- generate if (C_PROG_FULL_TYPE == 2) begin : multiple_pf_const always @(posedge CLK or posedge RST_FULL_FF) begin //if (RST_FULL_FF) if (RST_FULL_FF && C_HAS_RST) prog_full_i <= C_FULL_FLAGS_RST_VAL; else begin if (srst_wrst_busy) prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else if (IS_ASYMMETRY == 0) begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (diff_pntr == C_PF_ASSERT_VAL && write_only_q) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr == C_PF_NEGATE_VAL && read_only_q) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ prog_full_i; end else begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~RST_FULL_GEN ) begin if (diff_pntr >= C_PF_ASSERT_VAL ) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr < C_PF_NEGATE_VAL) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ prog_full_i; end else prog_full_i <= #`TCQ prog_full_i; end end end end endgenerate //multiple_pf_const //----------------------------------------------------------------------------- // Generate PROG_FULL for single programmable threshold input port //----------------------------------------------------------------------------- wire [C_WR_PNTR_WIDTH-1:0] pf3_assert_val = (C_PRELOAD_LATENCY == 0) ? PROG_FULL_THRESH - EXTRA_WORDS_PF: // FWFT PROG_FULL_THRESH; // STD generate if (C_PROG_FULL_TYPE == 3) begin : single_pf_input always @(posedge CLK or posedge RST_FULL_FF) begin//0 //if (RST_FULL_FF) if (RST_FULL_FF && C_HAS_RST) prog_full_i <= C_FULL_FLAGS_RST_VAL; else begin //1 if (srst_wrst_busy) prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else if (IS_ASYMMETRY == 0) begin//2 if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~almost_full_i) begin//3 if (diff_pntr > pf3_assert_val) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr == pf3_assert_val) begin//4 if (read_only_q) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ 1'b1; end else//4 prog_full_i <= #`TCQ 1'b0; end else//3 prog_full_i <= #`TCQ prog_full_i; end //2 else begin//5 if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~full_i ) begin//6 if (diff_pntr >= pf3_assert_val ) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr < pf3_assert_val) begin//7 prog_full_i <= #`TCQ 1'b0; end//7 end//6 else prog_full_i <= #`TCQ prog_full_i; end//5 end//1 end//0 end endgenerate //single_pf_input //----------------------------------------------------------------------------- // Generate PROG_FULL for multiple programmable threshold input ports //----------------------------------------------------------------------------- wire [C_WR_PNTR_WIDTH-1:0] pf_assert_val = (C_PRELOAD_LATENCY == 0) ? (PROG_FULL_THRESH_ASSERT -EXTRA_WORDS_PF) : // FWFT PROG_FULL_THRESH_ASSERT; // STD wire [C_WR_PNTR_WIDTH-1:0] pf_negate_val = (C_PRELOAD_LATENCY == 0) ? (PROG_FULL_THRESH_NEGATE -EXTRA_WORDS_PF) : // FWFT PROG_FULL_THRESH_NEGATE; // STD generate if (C_PROG_FULL_TYPE == 4) begin : multiple_pf_inputs always @(posedge CLK or posedge RST_FULL_FF) begin if (RST_FULL_FF && C_HAS_RST) prog_full_i <= C_FULL_FLAGS_RST_VAL; else begin if (srst_wrst_busy) prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL; else if (IS_ASYMMETRY == 0) begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~almost_full_i) begin if (diff_pntr >= pf_assert_val) prog_full_i <= #`TCQ 1'b1; else if ((diff_pntr == pf_negate_val && read_only_q) || diff_pntr < pf_negate_val) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ prog_full_i; end else prog_full_i <= #`TCQ prog_full_i; end else begin if (RST_FULL_GEN) prog_full_i <= #`TCQ 1'b0; else if (~full_i ) begin if (diff_pntr >= pf_assert_val ) prog_full_i <= #`TCQ 1'b1; else if (diff_pntr < pf_negate_val) prog_full_i <= #`TCQ 1'b0; else prog_full_i <= #`TCQ prog_full_i; end else prog_full_i <= #`TCQ prog_full_i; end end end end endgenerate //multiple_pf_inputs //----------------------------------------------------------------------------- // Generate PROG_EMPTY //----------------------------------------------------------------------------- localparam C_PE_ASSERT_VAL = (C_PRELOAD_LATENCY == 0) ? C_PROG_EMPTY_THRESH_ASSERT_VAL - 2: // FWFT C_PROG_EMPTY_THRESH_ASSERT_VAL; // STD localparam C_PE_NEGATE_VAL = (C_PRELOAD_LATENCY == 0) ? C_PROG_EMPTY_THRESH_NEGATE_VAL - 2: // FWFT C_PROG_EMPTY_THRESH_NEGATE_VAL; // STD //----------------------------------------------------------------------------- // Generate PROG_EMPTY for single programmable threshold constant //----------------------------------------------------------------------------- generate if (C_PROG_EMPTY_TYPE == 1) begin : single_pe_const always @(posedge CLK or posedge rst_i) begin //if (rst_i) if (rst_i && C_HAS_RST) prog_empty_i <= 1'b1; else begin if (srst_rrst_busy) prog_empty_i <= #`TCQ 1'b1; else if (IS_ASYMMETRY == 0) begin if (diff_pntr_pe == C_PE_ASSERT_VAL && read_only_q) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe == C_PE_ASSERT_VAL && write_only_q) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ prog_empty_i; end else begin if (~rst_i ) begin if (diff_pntr_pe <= C_PE_ASSERT_VAL) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe > C_PE_ASSERT_VAL) prog_empty_i <= #`TCQ 1'b0; end else prog_empty_i <= #`TCQ prog_empty_i; end end end end endgenerate // single_pe_const //----------------------------------------------------------------------------- // Generate PROG_EMPTY for multiple programmable threshold constants //----------------------------------------------------------------------------- generate if (C_PROG_EMPTY_TYPE == 2) begin : multiple_pe_const always @(posedge CLK or posedge rst_i) begin //if (rst_i) if (rst_i && C_HAS_RST) prog_empty_i <= 1'b1; else begin if (srst_rrst_busy) prog_empty_i <= #`TCQ 1'b1; else if (IS_ASYMMETRY == 0) begin if (diff_pntr_pe == C_PE_ASSERT_VAL && read_only_q) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe == C_PE_NEGATE_VAL && write_only_q) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ prog_empty_i; end else begin if (~rst_i ) begin if (diff_pntr_pe <= C_PE_ASSERT_VAL ) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe > C_PE_NEGATE_VAL) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ prog_empty_i; end else prog_empty_i <= #`TCQ prog_empty_i; end end end end endgenerate //multiple_pe_const //----------------------------------------------------------------------------- // Generate PROG_EMPTY for single programmable threshold input port //----------------------------------------------------------------------------- wire [C_RD_PNTR_WIDTH-1:0] pe3_assert_val = (C_PRELOAD_LATENCY == 0) ? (PROG_EMPTY_THRESH -2) : // FWFT PROG_EMPTY_THRESH; // STD generate if (C_PROG_EMPTY_TYPE == 3) begin : single_pe_input always @(posedge CLK or posedge rst_i) begin //if (rst_i) if (rst_i && C_HAS_RST) prog_empty_i <= 1'b1; else begin if (srst_rrst_busy) prog_empty_i <= #`TCQ 1'b1; else if (IS_ASYMMETRY == 0) begin if (~almost_full_i) begin if (diff_pntr_pe < pe3_assert_val) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe == pe3_assert_val) begin if (write_only_q) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ 1'b1; end else prog_empty_i <= #`TCQ 1'b0; end else prog_empty_i <= #`TCQ prog_empty_i; end else begin if (diff_pntr_pe <= pe3_assert_val ) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe > pe3_assert_val) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ prog_empty_i; end end end end endgenerate // single_pe_input //----------------------------------------------------------------------------- // Generate PROG_EMPTY for multiple programmable threshold input ports //----------------------------------------------------------------------------- wire [C_RD_PNTR_WIDTH-1:0] pe4_assert_val = (C_PRELOAD_LATENCY == 0) ? (PROG_EMPTY_THRESH_ASSERT - 2) : // FWFT PROG_EMPTY_THRESH_ASSERT; // STD wire [C_RD_PNTR_WIDTH-1:0] pe4_negate_val = (C_PRELOAD_LATENCY == 0) ? (PROG_EMPTY_THRESH_NEGATE - 2) : // FWFT PROG_EMPTY_THRESH_NEGATE; // STD generate if (C_PROG_EMPTY_TYPE == 4) begin : multiple_pe_inputs always @(posedge CLK or posedge rst_i) begin //if (rst_i) if (rst_i && C_HAS_RST) prog_empty_i <= 1'b1; else begin if (srst_rrst_busy) prog_empty_i <= #`TCQ 1'b1; else if (IS_ASYMMETRY == 0) begin if (~almost_full_i) begin if (diff_pntr_pe <= pe4_assert_val) prog_empty_i <= #`TCQ 1'b1; else if (((diff_pntr_pe == pe4_negate_val) && write_only_q) || (diff_pntr_pe > pe4_negate_val)) begin prog_empty_i <= #`TCQ 1'b0; end else prog_empty_i <= #`TCQ prog_empty_i; end else prog_empty_i <= #`TCQ prog_empty_i; end else begin if (diff_pntr_pe <= pe4_assert_val ) prog_empty_i <= #`TCQ 1'b1; else if (diff_pntr_pe > pe4_negate_val) prog_empty_i <= #`TCQ 1'b0; else prog_empty_i <= #`TCQ prog_empty_i; end end end end endgenerate // multiple_pe_inputs endmodule // fifo_generator_v13_1_1_bhv_ver_ss /************************************************************************** * First-Word Fall-Through module (preload 0) **************************************************************************/ module fifo_generator_v13_1_1_bhv_ver_preload0 #( parameter C_DOUT_RST_VAL = "", parameter C_DOUT_WIDTH = 8, parameter C_HAS_RST = 0, parameter C_ENABLE_RST_SYNC = 0, parameter C_HAS_SRST = 0, parameter C_USE_EMBEDDED_REG = 0, parameter C_EN_SAFETY_CKT = 0, parameter C_USE_DOUT_RST = 0, parameter C_USE_ECC = 0, parameter C_USERVALID_LOW = 0, parameter C_USERUNDERFLOW_LOW = 0, parameter C_MEMORY_TYPE = 0, parameter C_FIFO_TYPE = 0 ) ( //Inputs input RD_CLK, input RD_RST, input SRST, input WR_RST_BUSY, input RD_RST_BUSY, input RD_EN, input FIFOEMPTY, input [C_DOUT_WIDTH-1:0] FIFODATA, input FIFOSBITERR, input FIFODBITERR, //Outputs output reg [C_DOUT_WIDTH-1:0] USERDATA, output reg [C_DOUT_WIDTH-1:0] USERDATA_BOTH, output USERVALID, output USERVALID_BOTH, output USERVALID_ONE, output USERUNDERFLOW, output USEREMPTY, output USERALMOSTEMPTY, output RAMVALID, output FIFORDEN, output reg USERSBITERR, output reg USERDBITERR, output reg USERSBITERR_BOTH, output reg USERDBITERR_BOTH, output reg STAGE2_REG_EN, output fab_read_data_valid_i_o, output read_data_valid_i_o, output ram_valid_i_o, output [1:0] VALID_STAGES ); //Internal signals wire preloadstage1; wire preloadstage2; reg ram_valid_i; reg fab_valid; reg read_data_valid_i; reg fab_read_data_valid_i; reg fab_read_data_valid_i_1; reg ram_valid_i_d; reg read_data_valid_i_d; reg fab_read_data_valid_i_d; wire ram_regout_en; reg ram_regout_en_d1; reg ram_regout_en_d2; wire fab_regout_en; wire ram_rd_en; reg empty_i = 1'b1; reg empty_q = 1'b1; reg rd_en_q = 1'b0; reg almost_empty_i = 1'b1; reg almost_empty_q = 1'b1; wire rd_rst_i; wire srst_i; assign ram_valid_i_o = ram_valid_i; assign read_data_valid_i_o = read_data_valid_i; assign fab_read_data_valid_i_o = fab_read_data_valid_i; /************************************************************************* * FUNCTIONS *************************************************************************/ /************************************************************************* * hexstr_conv * Converts a string of type hex to a binary value (for C_DOUT_RST_VAL) ***********************************************************************/ function [C_DOUT_WIDTH-1:0] hexstr_conv; input [(C_DOUT_WIDTH*8)-1:0] def_data; integer index,i,j; reg [3:0] bin; begin index = 0; hexstr_conv = 'b0; for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 ) begin case (def_data[7:0]) 8'b00000000 : begin bin = 4'b0000; i = -1; end 8'b00110000 : bin = 4'b0000; 8'b00110001 : bin = 4'b0001; 8'b00110010 : bin = 4'b0010; 8'b00110011 : bin = 4'b0011; 8'b00110100 : bin = 4'b0100; 8'b00110101 : bin = 4'b0101; 8'b00110110 : bin = 4'b0110; 8'b00110111 : bin = 4'b0111; 8'b00111000 : bin = 4'b1000; 8'b00111001 : bin = 4'b1001; 8'b01000001 : bin = 4'b1010; 8'b01000010 : bin = 4'b1011; 8'b01000011 : bin = 4'b1100; 8'b01000100 : bin = 4'b1101; 8'b01000101 : bin = 4'b1110; 8'b01000110 : bin = 4'b1111; 8'b01100001 : bin = 4'b1010; 8'b01100010 : bin = 4'b1011; 8'b01100011 : bin = 4'b1100; 8'b01100100 : bin = 4'b1101; 8'b01100101 : bin = 4'b1110; 8'b01100110 : bin = 4'b1111; default : begin bin = 4'bx; end endcase for( j=0; j<4; j=j+1) begin if ((index*4)+j < C_DOUT_WIDTH) begin hexstr_conv[(index*4)+j] = bin[j]; end end index = index + 1; def_data = def_data >> 8; end end endfunction //************************************************************************* // Set power-on states for regs //************************************************************************* initial begin ram_valid_i = 1'b0; fab_valid = 1'b0; read_data_valid_i = 1'b0; fab_read_data_valid_i = 1'b0; fab_read_data_valid_i_1 = 1'b0; USERDATA = hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH = hexstr_conv(C_DOUT_RST_VAL); USERSBITERR = 1'b0; USERDBITERR = 1'b0; end //initial //*************************************************************************** // connect up optional reset //*************************************************************************** assign rd_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? RD_RST : 0; assign srst_i = C_HAS_SRST ? SRST || WR_RST_BUSY || RD_RST_BUSY : 0; localparam INVALID = 0; localparam STAGE1_VALID = 2; localparam STAGE2_VALID = 1; localparam BOTH_STAGES_VALID = 3; reg [1:0] curr_fwft_state = INVALID; reg [1:0] next_fwft_state = INVALID; generate if (C_USE_EMBEDDED_REG < 3 && C_FIFO_TYPE != 2) begin always @* begin case (curr_fwft_state) INVALID: begin if (~FIFOEMPTY) next_fwft_state <= STAGE1_VALID; else next_fwft_state <= INVALID; end STAGE1_VALID: begin if (FIFOEMPTY) next_fwft_state <= STAGE2_VALID; else next_fwft_state <= BOTH_STAGES_VALID; end STAGE2_VALID: begin if (FIFOEMPTY && RD_EN) next_fwft_state <= INVALID; else if (~FIFOEMPTY && RD_EN) next_fwft_state <= STAGE1_VALID; else if (~FIFOEMPTY && ~RD_EN) next_fwft_state <= BOTH_STAGES_VALID; else next_fwft_state <= STAGE2_VALID; end BOTH_STAGES_VALID: begin if (FIFOEMPTY && RD_EN) next_fwft_state <= STAGE2_VALID; else if (~FIFOEMPTY && RD_EN) next_fwft_state <= BOTH_STAGES_VALID; else next_fwft_state <= BOTH_STAGES_VALID; end default: next_fwft_state <= INVALID; endcase end always @ (posedge rd_rst_i or posedge RD_CLK) begin if (rd_rst_i) curr_fwft_state <= INVALID; else if (srst_i) curr_fwft_state <= #`TCQ INVALID; else curr_fwft_state <= #`TCQ next_fwft_state; end always @* begin case (curr_fwft_state) INVALID: STAGE2_REG_EN <= 1'b0; STAGE1_VALID: STAGE2_REG_EN <= 1'b1; STAGE2_VALID: STAGE2_REG_EN <= 1'b0; BOTH_STAGES_VALID: STAGE2_REG_EN <= RD_EN; default: STAGE2_REG_EN <= 1'b0; endcase end assign VALID_STAGES = curr_fwft_state; //*************************************************************************** // preloadstage2 indicates that stage2 needs to be updated. This is true // whenever read_data_valid is false, and RAM_valid is true. //*************************************************************************** assign preloadstage2 = ram_valid_i & (~read_data_valid_i | RD_EN ); //*************************************************************************** // preloadstage1 indicates that stage1 needs to be updated. This is true // whenever the RAM has data (RAM_EMPTY is false), and either RAM_Valid is // false (indicating that Stage1 needs updating), or preloadstage2 is active // (indicating that Stage2 is going to update, so Stage1, therefore, must // also be updated to keep it valid. //*************************************************************************** assign preloadstage1 = ((~ram_valid_i | preloadstage2) & ~FIFOEMPTY); //*************************************************************************** // Calculate RAM_REGOUT_EN // The output registers are controlled by the ram_regout_en signal. // These registers should be updated either when the output in Stage2 is // invalid (preloadstage2), OR when the user is reading, in which case the // Stage2 value will go invalid unless it is replenished. //*************************************************************************** assign ram_regout_en = preloadstage2; //*************************************************************************** // Calculate RAM_RD_EN // RAM_RD_EN will be asserted whenever the RAM needs to be read in order to // update the value in Stage1. // One case when this happens is when preloadstage1=true, which indicates // that the data in Stage1 or Stage2 is invalid, and needs to automatically // be updated. // The other case is when the user is reading from the FIFO, which // guarantees that Stage1 or Stage2 will be invalid on the next clock // cycle, unless it is replinished by data from the memory. So, as long // as the RAM has data in it, a read of the RAM should occur. //*************************************************************************** assign ram_rd_en = (RD_EN & ~FIFOEMPTY) | preloadstage1; end endgenerate // gnll_fifo reg curr_state = 0; reg next_state = 0; reg leaving_empty_fwft = 0; reg going_empty_fwft = 0; reg empty_i_q = 0; reg ram_rd_en_fwft = 0; generate if (C_FIFO_TYPE == 2) begin : gll_fifo always @* begin // FSM fo FWFT case (curr_state) 1'b0: begin if (~FIFOEMPTY) next_state <= 1'b1; else next_state <= 1'b0; end 1'b1: begin if (FIFOEMPTY && RD_EN) next_state <= 1'b0; else next_state <= 1'b1; end default: next_state <= 1'b0; endcase end always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin empty_i <= 1'b1; empty_i_q <= 1'b1; curr_state <= 1'b0; ram_valid_i <= 1'b0; end else if (srst_i) begin empty_i <= #`TCQ 1'b1; empty_i_q <= #`TCQ 1'b1; curr_state <= #`TCQ 1'b0; ram_valid_i <= #`TCQ 1'b0; end else begin empty_i <= #`TCQ going_empty_fwft | (~leaving_empty_fwft & empty_i); empty_i_q <= #`TCQ FIFOEMPTY; curr_state <= #`TCQ next_state; ram_valid_i <= #`TCQ next_state; end end //always wire fe_of_empty; assign fe_of_empty = empty_i_q & ~FIFOEMPTY; always @* begin // Finding leaving empty case (curr_state) 1'b0: leaving_empty_fwft <= fe_of_empty; 1'b1: leaving_empty_fwft <= 1'b1; default: leaving_empty_fwft <= 1'b0; endcase end always @* begin // Finding going empty case (curr_state) 1'b1: going_empty_fwft <= FIFOEMPTY & RD_EN; default: going_empty_fwft <= 1'b0; endcase end always @* begin // Generating FWFT rd_en case (curr_state) 1'b0: ram_rd_en_fwft <= ~FIFOEMPTY; 1'b1: ram_rd_en_fwft <= ~FIFOEMPTY & RD_EN; default: ram_rd_en_fwft <= 1'b0; endcase end assign ram_regout_en = ram_rd_en_fwft; //assign ram_regout_en_d1 = ram_rd_en_fwft; //assign ram_regout_en_d2 = ram_rd_en_fwft; assign ram_rd_en = ram_rd_en_fwft; end endgenerate // gll_fifo //*************************************************************************** // Calculate RAMVALID_P0_OUT // RAMVALID_P0_OUT indicates that the data in Stage1 is valid. // // If the RAM is being read from on this clock cycle (ram_rd_en=1), then // RAMVALID_P0_OUT is certainly going to be true. // If the RAM is not being read from, but the output registers are being // updated to fill Stage2 (ram_regout_en=1), then Stage1 will be emptying, // therefore causing RAMVALID_P0_OUT to be false. // Otherwise, RAMVALID_P0_OUT will remain unchanged. //*************************************************************************** // PROCESS regout_valid generate if (C_FIFO_TYPE < 2) begin : gnll_fifo_ram_valid always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin // asynchronous reset (active high) ram_valid_i <= #`TCQ 1'b0; end else begin if (srst_i) begin // synchronous reset (active high) ram_valid_i <= #`TCQ 1'b0; end else begin if (ram_rd_en == 1'b1) begin ram_valid_i <= #`TCQ 1'b1; end else begin if (ram_regout_en == 1'b1) ram_valid_i <= #`TCQ 1'b0; else ram_valid_i <= #`TCQ ram_valid_i; end end //srst_i end //rd_rst_i end //always end endgenerate // gnll_fifo_ram_valid //*************************************************************************** // Calculate READ_DATA_VALID // READ_DATA_VALID indicates whether the value in Stage2 is valid or not. // Stage2 has valid data whenever Stage1 had valid data and // ram_regout_en_i=1, such that the data in Stage1 is propogated // into Stage2. //*************************************************************************** generate if(C_USE_EMBEDDED_REG < 3) begin always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) read_data_valid_i <= #`TCQ 1'b0; else if (srst_i) read_data_valid_i <= #`TCQ 1'b0; else read_data_valid_i <= #`TCQ ram_valid_i | (read_data_valid_i & ~RD_EN); end //always end endgenerate //************************************************************************** // Calculate EMPTY // Defined as the inverse of READ_DATA_VALID // // Description: // // If read_data_valid_i indicates that the output is not valid, // and there is no valid data on the output of the ram to preload it // with, then we will report empty. // // If there is no valid data on the output of the ram and we are // reading, then the FIFO will go empty. // //************************************************************************** generate if (C_FIFO_TYPE < 2 && C_USE_EMBEDDED_REG < 3) begin : gnll_fifo_empty always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin // asynchronous reset (active high) empty_i <= #`TCQ 1'b1; end else begin if (srst_i) begin // synchronous reset (active high) empty_i <= #`TCQ 1'b1; end else begin // rising clock edge empty_i <= #`TCQ (~ram_valid_i & ~read_data_valid_i) | (~ram_valid_i & RD_EN); end end end //always end endgenerate // gnll_fifo_empty // Register RD_EN from user to calculate USERUNDERFLOW. // Register empty_i to calculate USERUNDERFLOW. always @ (posedge RD_CLK) begin rd_en_q <= #`TCQ RD_EN; empty_q <= #`TCQ empty_i; end //always //*************************************************************************** // Calculate user_almost_empty // user_almost_empty is defined such that, unless more words are written // to the FIFO, the next read will cause the FIFO to go EMPTY. // // In most cases, whenever the output registers are updated (due to a user // read or a preload condition), then user_almost_empty will update to // whatever RAM_EMPTY is. // // The exception is when the output is valid, the user is not reading, and // Stage1 is not empty. In this condition, Stage1 will be preloaded from the // memory, so we need to make sure user_almost_empty deasserts properly under // this condition. //*************************************************************************** generate if ( C_USE_EMBEDDED_REG < 3) begin always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin // asynchronous reset (active high) almost_empty_i <= #`TCQ 1'b1; almost_empty_q <= #`TCQ 1'b1; end else begin // rising clock edge if (srst_i) begin // synchronous reset (active high) almost_empty_i <= #`TCQ 1'b1; almost_empty_q <= #`TCQ 1'b1; end else begin if ((ram_regout_en) | (~FIFOEMPTY & read_data_valid_i & ~RD_EN)) begin almost_empty_i <= #`TCQ FIFOEMPTY; end almost_empty_q <= #`TCQ empty_i; end end end //always end endgenerate // BRAM resets synchronously generate if (C_EN_SAFETY_CKT==0 && C_USE_EMBEDDED_REG < 3) begin always @ ( posedge rd_rst_i) begin if (rd_rst_i || srst_i) begin if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2) @(posedge RD_CLK) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end //always always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin //asynchronous reset (active high) if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end // DRAM resets asynchronously if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2) begin //asynchronous reset (active high) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin // rising clock edge if (srst_i) begin if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end if (C_USE_DOUT_RST == 1) begin USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin if (ram_regout_en) begin USERDATA <= #`TCQ FIFODATA; USERSBITERR <= #`TCQ FIFOSBITERR; USERDBITERR <= #`TCQ FIFODBITERR; end end end end //always end //if endgenerate //safety ckt with one register generate if (C_EN_SAFETY_CKT==1 && C_USE_EMBEDDED_REG < 3) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; always@(posedge RD_CLK) begin rst_delayed_sft1 <= #`TCQ rd_rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always @ (posedge RD_CLK) begin if (rd_rst_i || srst_i) begin if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2 && rst_delayed_sft1 == 1'b1) begin @(posedge RD_CLK) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end end //always always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin //asynchronous reset (active high) if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end // DRAM resets asynchronously if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2)begin //asynchronous reset (active high) //@(posedge RD_CLK) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin // rising clock edge if (srst_i) begin if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end if (C_USE_DOUT_RST == 1) begin // @(posedge RD_CLK) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin if (ram_regout_en == 1'b1 && rd_rst_i == 1'b0) begin USERDATA <= #`TCQ FIFODATA; USERSBITERR <= #`TCQ FIFOSBITERR; USERDBITERR <= #`TCQ FIFODBITERR; end end end end //always end //if endgenerate generate if (C_USE_EMBEDDED_REG == 3 && C_FIFO_TYPE != 2) begin always @* begin case (curr_fwft_state) INVALID: begin if (~FIFOEMPTY) next_fwft_state <= STAGE1_VALID; else next_fwft_state <= INVALID; end STAGE1_VALID: begin if (FIFOEMPTY) next_fwft_state <= STAGE2_VALID; else next_fwft_state <= BOTH_STAGES_VALID; end STAGE2_VALID: begin if (FIFOEMPTY && RD_EN) next_fwft_state <= INVALID; else if (~FIFOEMPTY && RD_EN) next_fwft_state <= STAGE1_VALID; else if (~FIFOEMPTY && ~RD_EN) next_fwft_state <= BOTH_STAGES_VALID; else next_fwft_state <= STAGE2_VALID; end BOTH_STAGES_VALID: begin if (FIFOEMPTY && RD_EN) next_fwft_state <= STAGE2_VALID; else if (~FIFOEMPTY && RD_EN) next_fwft_state <= BOTH_STAGES_VALID; else next_fwft_state <= BOTH_STAGES_VALID; end default: next_fwft_state <= INVALID; endcase end always @ (posedge rd_rst_i or posedge RD_CLK) begin if (rd_rst_i) curr_fwft_state <= INVALID; else if (srst_i) curr_fwft_state <= #`TCQ INVALID; else curr_fwft_state <= #`TCQ next_fwft_state; end always @ (posedge RD_CLK or posedge rd_rst_i) begin : proc_delay if (rd_rst_i == 1) begin ram_regout_en_d1 <= #`TCQ 1'b0; end else begin if (srst_i == 1'b1) ram_regout_en_d1 <= #`TCQ 1'b0; else ram_regout_en_d1 <= #`TCQ ram_regout_en; end end //always // assign fab_regout_en = ((ram_regout_en_d1 & ~(ram_regout_en_d2) & empty_i) | (RD_EN & !empty_i)); assign fab_regout_en = ((ram_valid_i == 1'b0 || ram_valid_i == 1'b1) && read_data_valid_i == 1'b1 && fab_read_data_valid_i == 1'b0 )? 1'b1: ((ram_valid_i == 1'b0 || ram_valid_i == 1'b1) && read_data_valid_i == 1'b1 && fab_read_data_valid_i == 1'b1) ? RD_EN : 1'b0; always @ (posedge RD_CLK or posedge rd_rst_i) begin : proc_delay1 if (rd_rst_i == 1) begin ram_regout_en_d2 <= #`TCQ 1'b0; end else begin if (srst_i == 1'b1) ram_regout_en_d2 <= #`TCQ 1'b0; else ram_regout_en_d2 <= #`TCQ ram_regout_en_d1; end end //always always @* begin case (curr_fwft_state) INVALID: STAGE2_REG_EN <= 1'b0; STAGE1_VALID: STAGE2_REG_EN <= 1'b1; STAGE2_VALID: STAGE2_REG_EN <= 1'b0; BOTH_STAGES_VALID: STAGE2_REG_EN <= RD_EN; default: STAGE2_REG_EN <= 1'b0; endcase end always @ (posedge RD_CLK) begin ram_valid_i_d <= #`TCQ ram_valid_i; read_data_valid_i_d <= #`TCQ read_data_valid_i; fab_read_data_valid_i_d <= #`TCQ fab_read_data_valid_i; end assign VALID_STAGES = curr_fwft_state; //*************************************************************************** // preloadstage2 indicates that stage2 needs to be updated. This is true // whenever read_data_valid is false, and RAM_valid is true. //*************************************************************************** assign preloadstage2 = ram_valid_i & (~read_data_valid_i | RD_EN ); //*************************************************************************** // preloadstage1 indicates that stage1 needs to be updated. This is true // whenever the RAM has data (RAM_EMPTY is false), and either RAM_Valid is // false (indicating that Stage1 needs updating), or preloadstage2 is active // (indicating that Stage2 is going to update, so Stage1, therefore, must // also be updated to keep it valid. //*************************************************************************** assign preloadstage1 = ((~ram_valid_i | preloadstage2) & ~FIFOEMPTY); //*************************************************************************** // Calculate RAM_REGOUT_EN // The output registers are controlled by the ram_regout_en signal. // These registers should be updated either when the output in Stage2 is // invalid (preloadstage2), OR when the user is reading, in which case the // Stage2 value will go invalid unless it is replenished. //*************************************************************************** assign ram_regout_en = (ram_valid_i == 1'b1 && (read_data_valid_i == 1'b0 || fab_read_data_valid_i == 1'b0)) ? 1'b1 : (read_data_valid_i == 1'b1 && fab_read_data_valid_i == 1'b1 && ram_valid_i == 1'b1) ? RD_EN : 1'b0; //*************************************************************************** // Calculate RAM_RD_EN // RAM_RD_EN will be asserted whenever the RAM needs to be read in order to // update the value in Stage1. // One case when this happens is when preloadstage1=true, which indicates // that the data in Stage1 or Stage2 is invalid, and needs to automatically // be updated. // The other case is when the user is reading from the FIFO, which // guarantees that Stage1 or Stage2 will be invalid on the next clock // cycle, unless it is replinished by data from the memory. So, as long // as the RAM has data in it, a read of the RAM should occur. //*************************************************************************** assign ram_rd_en = ((RD_EN | ~ fab_read_data_valid_i) & ~FIFOEMPTY) | preloadstage1; end endgenerate // gnll_fifo //*************************************************************************** // Calculate RAMVALID_P0_OUT // RAMVALID_P0_OUT indicates that the data in Stage1 is valid. // // If the RAM is being read from on this clock cycle (ram_rd_en=1), then // RAMVALID_P0_OUT is certainly going to be true. // If the RAM is not being read from, but the output registers are being // updated to fill Stage2 (ram_regout_en=1), then Stage1 will be emptying, // therefore causing RAMVALID_P0_OUT to be false // Otherwise, RAMVALID_P0_OUT will remain unchanged. //*************************************************************************** // PROCESS regout_valid generate if (C_FIFO_TYPE < 2 && C_USE_EMBEDDED_REG == 3) begin : gnll_fifo_fab_valid always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin // asynchronous reset (active high) fab_valid <= #`TCQ 1'b0; end else begin if (srst_i) begin // synchronous reset (active high) fab_valid <= #`TCQ 1'b0; end else begin if (ram_regout_en == 1'b1) begin fab_valid <= #`TCQ 1'b1; end else begin if (fab_regout_en == 1'b1) fab_valid <= #`TCQ 1'b0; else fab_valid <= #`TCQ fab_valid; end end //srst_i end //rd_rst_i end //always end endgenerate // gnll_fifo_fab_valid //*************************************************************************** // Calculate READ_DATA_VALID // READ_DATA_VALID indicates whether the value in Stage2 is valid or not. // Stage2 has valid data whenever Stage1 had valid data and // ram_regout_en_i=1, such that the data in Stage1 is propogated // into Stage2. //*************************************************************************** generate if(C_USE_EMBEDDED_REG == 3) begin always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) read_data_valid_i <= #`TCQ 1'b0; else if (srst_i) read_data_valid_i <= #`TCQ 1'b0; else begin if (ram_regout_en == 1'b1) begin read_data_valid_i <= #`TCQ 1'b1; end else begin if (fab_regout_en == 1'b1) read_data_valid_i <= #`TCQ 1'b0; else read_data_valid_i <= #`TCQ read_data_valid_i; end end end //always end endgenerate //generate if(C_USE_EMBEDDED_REG == 3) begin // always @ (posedge RD_CLK or posedge rd_rst_i) begin // if (rd_rst_i) // read_data_valid_i <= #`TCQ 1'b0; // else if (srst_i) // read_data_valid_i <= #`TCQ 1'b0; // // if (ram_regout_en == 1'b1) begin // fab_read_data_valid_i <= #`TCQ 1'b0; // end else begin // if (fab_regout_en == 1'b1) // fab_read_data_valid_i <= #`TCQ 1'b1; // else // fab_read_data_valid_i <= #`TCQ fab_read_data_valid_i; // end // end //always //end //endgenerate generate if(C_USE_EMBEDDED_REG == 3 ) begin always @ (posedge RD_CLK or posedge rd_rst_i) begin :fabout_dvalid if (rd_rst_i) fab_read_data_valid_i <= #`TCQ 1'b0; else if (srst_i) fab_read_data_valid_i <= #`TCQ 1'b0; else fab_read_data_valid_i <= #`TCQ fab_valid | (fab_read_data_valid_i & ~RD_EN); end //always end endgenerate always @ (posedge RD_CLK ) begin : proc_del1 begin fab_read_data_valid_i_1 <= #`TCQ fab_read_data_valid_i; end end //always //************************************************************************** // Calculate EMPTY // Defined as the inverse of READ_DATA_VALID // // Description: // // If read_data_valid_i indicates that the output is not valid, // and there is no valid data on the output of the ram to preload it // with, then we will report empty. // // If there is no valid data on the output of the ram and we are // reading, then the FIFO will go empty. // //************************************************************************** generate if (C_FIFO_TYPE < 2 && C_USE_EMBEDDED_REG == 3 ) begin : gnll_fifo_empty_both always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin // asynchronous reset (active high) empty_i <= #`TCQ 1'b1; end else begin if (srst_i) begin // synchronous reset (active high) empty_i <= #`TCQ 1'b1; end else begin // rising clock edge empty_i <= #`TCQ (~fab_valid & ~fab_read_data_valid_i) | (~fab_valid & RD_EN); end end end //always end endgenerate // gnll_fifo_empty_both // Register RD_EN from user to calculate USERUNDERFLOW. // Register empty_i to calculate USERUNDERFLOW. always @ (posedge RD_CLK) begin rd_en_q <= #`TCQ RD_EN; empty_q <= #`TCQ empty_i; end //always //*************************************************************************** // Calculate user_almost_empty // user_almost_empty is defined such that, unless more words are written // to the FIFO, the next read will cause the FIFO to go EMPTY. // // In most cases, whenever the output registers are updated (due to a user // read or a preload condition), then user_almost_empty will update to // whatever RAM_EMPTY is. // // The exception is when the output is valid, the user is not reading, and // Stage1 is not empty. In this condition, Stage1 will be preloaded from the // memory, so we need to make sure user_almost_empty deasserts properly under // this condition. //*************************************************************************** reg FIFOEMPTY_1; generate if (C_USE_EMBEDDED_REG == 3 ) begin always @(posedge RD_CLK) begin FIFOEMPTY_1 <= #`TCQ FIFOEMPTY; end end endgenerate generate if (C_USE_EMBEDDED_REG == 3 ) begin always @ (posedge RD_CLK or posedge rd_rst_i) // begin // if (((ram_valid_i == 1'b1) && (read_data_valid_i == 1'b1) && (fab_read_data_valid_i == 1'b1)) || ((ram_valid_i == 1'b0) && (read_data_valid_i == 1'b1) && (fab_read_data_valid_i == 1'b1))) // almost_empty_i <= #`TCQ 1'b0; // else // almost_empty_i <= #`TCQ 1'b1; begin if (rd_rst_i) begin // asynchronous reset (active high) almost_empty_i <= #`TCQ 1'b1; almost_empty_q <= #`TCQ 1'b1; end else begin // rising clock edge if (srst_i) begin // synchronous reset (active high) almost_empty_i <= #`TCQ 1'b1; almost_empty_q <= #`TCQ 1'b1; end else begin if ((fab_regout_en) | (ram_valid_i & fab_read_data_valid_i & ~RD_EN)) begin almost_empty_i <= #`TCQ (~ram_valid_i); end almost_empty_q <= #`TCQ empty_i; end end end //always end endgenerate assign USEREMPTY = empty_i; assign USERALMOSTEMPTY = almost_empty_i; assign FIFORDEN = ram_rd_en; assign RAMVALID = (C_USE_EMBEDDED_REG == 3)? fab_valid : ram_valid_i; assign USERVALID_BOTH = (C_USERVALID_LOW && C_USE_EMBEDDED_REG == 3) ? ~fab_read_data_valid_i : ((C_USERVALID_LOW == 0 && C_USE_EMBEDDED_REG == 3) ? fab_read_data_valid_i : 1'b0); assign USERVALID_ONE = (C_USERVALID_LOW && C_USE_EMBEDDED_REG < 3) ? ~read_data_valid_i :((C_USERVALID_LOW == 0 && C_USE_EMBEDDED_REG < 3) ? read_data_valid_i : 1'b0); assign USERVALID = (C_USE_EMBEDDED_REG == 3) ? USERVALID_BOTH : USERVALID_ONE; assign USERUNDERFLOW = C_USERUNDERFLOW_LOW ? ~(empty_q & rd_en_q) : empty_q & rd_en_q; //no safety ckt with both reg generate if (C_EN_SAFETY_CKT==0 && C_USE_EMBEDDED_REG == 3 ) begin always @ (posedge RD_CLK) begin if (rd_rst_i || srst_i) begin if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end //always always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin //asynchronous reset (active high) if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end // DRAM resets asynchronously if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2) begin //asynchronous reset (active high) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin // rising clock edge if (srst_i) begin if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2) begin USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin if (ram_regout_en) begin USERDATA_BOTH <= #`TCQ FIFODATA; USERDBITERR <= #`TCQ FIFODBITERR; USERSBITERR <= #`TCQ FIFOSBITERR; end if (fab_regout_en) begin USERDATA <= #`TCQ USERDATA_BOTH; end end end end //always end //if endgenerate //safety_ckt with both registers generate if (C_EN_SAFETY_CKT==1 && C_USE_EMBEDDED_REG == 3) begin reg [C_DOUT_WIDTH-1:0] dout_rst_val_d1; reg [C_DOUT_WIDTH-1:0] dout_rst_val_d2; reg [1:0] rst_delayed_sft1 =1; reg [1:0] rst_delayed_sft2 =1; reg [1:0] rst_delayed_sft3 =1; reg [1:0] rst_delayed_sft4 =1; always@(posedge RD_CLK) begin rst_delayed_sft1 <= #`TCQ rd_rst_i; rst_delayed_sft2 <= #`TCQ rst_delayed_sft1; rst_delayed_sft3 <= #`TCQ rst_delayed_sft2; rst_delayed_sft4 <= #`TCQ rst_delayed_sft3; end always @ (posedge RD_CLK) begin if (rd_rst_i || srst_i) begin if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2 && rst_delayed_sft1 == 1'b1) begin @(posedge RD_CLK) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end end //always always @ (posedge RD_CLK or posedge rd_rst_i) begin if (rd_rst_i) begin //asynchronous reset (active high) if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end // DRAM resets asynchronously if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2)begin //asynchronous reset (active high) USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); USERDATA_BOTH <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin // rising clock edge if (srst_i) begin if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF USERSBITERR <= #`TCQ 0; USERDBITERR <= #`TCQ 0; end if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2) begin USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL); end end else begin if (ram_regout_en == 1'b1 && rd_rst_i == 1'b0) begin USERDATA_BOTH <= #`TCQ FIFODATA; USERDBITERR <= #`TCQ FIFODBITERR; USERSBITERR <= #`TCQ FIFOSBITERR; end if (fab_regout_en == 1'b1 && rd_rst_i == 1'b0) begin USERDATA <= #`TCQ USERDATA_BOTH; end end end end //always end //if endgenerate endmodule //fifo_generator_v13_1_1_bhv_ver_preload0 //----------------------------------------------------------------------------- // // Register Slice // Register one AXI channel on forward and/or reverse signal path // // Verilog-standard: Verilog 2001 //-------------------------------------------------------------------------- // // Structure: // reg_slice // //-------------------------------------------------------------------------- module fifo_generator_v13_1_1_axic_reg_slice # ( parameter C_FAMILY = "virtex7", parameter C_DATA_WIDTH = 32, parameter C_REG_CONFIG = 32'h00000000 ) ( // System Signals input wire ACLK, input wire ARESET, // Slave side input wire [C_DATA_WIDTH-1:0] S_PAYLOAD_DATA, input wire S_VALID, output wire S_READY, // Master side output wire [C_DATA_WIDTH-1:0] M_PAYLOAD_DATA, output wire M_VALID, input wire M_READY ); generate //////////////////////////////////////////////////////////////////// // // Both FWD and REV mode // //////////////////////////////////////////////////////////////////// if (C_REG_CONFIG == 32'h00000000) begin reg [1:0] state; localparam [1:0] ZERO = 2'b10, ONE = 2'b11, TWO = 2'b01; reg [C_DATA_WIDTH-1:0] storage_data1 = 0; reg [C_DATA_WIDTH-1:0] storage_data2 = 0; reg load_s1; wire load_s2; wire load_s1_from_s2; reg s_ready_i; //local signal of output wire m_valid_i; //local signal of output // assign local signal to its output signal assign S_READY = s_ready_i; assign M_VALID = m_valid_i; reg areset_d1; // Reset delay register always @(posedge ACLK) begin areset_d1 <= ARESET; end // Load storage1 with either slave side data or from storage2 always @(posedge ACLK) begin if (load_s1) if (load_s1_from_s2) storage_data1 <= storage_data2; else storage_data1 <= S_PAYLOAD_DATA; end // Load storage2 with slave side data always @(posedge ACLK) begin if (load_s2) storage_data2 <= S_PAYLOAD_DATA; end assign M_PAYLOAD_DATA = storage_data1; // Always load s2 on a valid transaction even if it's unnecessary assign load_s2 = S_VALID & s_ready_i; // Loading s1 always @ * begin if ( ((state == ZERO) && (S_VALID == 1)) || // Load when empty on slave transaction // Load when ONE if we both have read and write at the same time ((state == ONE) && (S_VALID == 1) && (M_READY == 1)) || // Load when TWO and we have a transaction on Master side ((state == TWO) && (M_READY == 1))) load_s1 = 1'b1; else load_s1 = 1'b0; end // always @ * assign load_s1_from_s2 = (state == TWO); // State Machine for handling output signals always @(posedge ACLK) begin if (ARESET) begin s_ready_i <= 1'b0; state <= ZERO; end else if (areset_d1) begin s_ready_i <= 1'b1; end else begin case (state) // No transaction stored locally ZERO: if (S_VALID) state <= ONE; // Got one so move to ONE // One transaction stored locally ONE: begin if (M_READY & ~S_VALID) state <= ZERO; // Read out one so move to ZERO if (~M_READY & S_VALID) begin state <= TWO; // Got another one so move to TWO s_ready_i <= 1'b0; end end // TWO transaction stored locally TWO: if (M_READY) begin state <= ONE; // Read out one so move to ONE s_ready_i <= 1'b1; end endcase // case (state) end end // always @ (posedge ACLK) assign m_valid_i = state[0]; end // if (C_REG_CONFIG == 1) //////////////////////////////////////////////////////////////////// // // 1-stage pipeline register with bubble cycle, both FWD and REV pipelining // Operates same as 1-deep FIFO // //////////////////////////////////////////////////////////////////// else if (C_REG_CONFIG == 32'h00000001) begin reg [C_DATA_WIDTH-1:0] storage_data1 = 0; reg s_ready_i; //local signal of output reg m_valid_i; //local signal of output // assign local signal to its output signal assign S_READY = s_ready_i; assign M_VALID = m_valid_i; reg areset_d1; // Reset delay register always @(posedge ACLK) begin areset_d1 <= ARESET; end // Load storage1 with slave side data always @(posedge ACLK) begin if (ARESET) begin s_ready_i <= 1'b0; m_valid_i <= 1'b0; end else if (areset_d1) begin s_ready_i <= 1'b1; end else if (m_valid_i & M_READY) begin s_ready_i <= 1'b1; m_valid_i <= 1'b0; end else if (S_VALID & s_ready_i) begin s_ready_i <= 1'b0; m_valid_i <= 1'b1; end if (~m_valid_i) begin storage_data1 <= S_PAYLOAD_DATA; end end assign M_PAYLOAD_DATA = storage_data1; end // if (C_REG_CONFIG == 7) else begin : default_case // Passthrough assign M_PAYLOAD_DATA = S_PAYLOAD_DATA; assign M_VALID = S_VALID; assign S_READY = M_READY; end endgenerate endmodule // reg_slice
/* ---------------------------------------------------------------------------------- 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
/* ---------------------------------------------------------------------------------- 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
/* ---------------------------------------------------------------------------------- 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
// 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
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2005 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=0; reg [63:0] crc; reg [63:0] sum; `ifdef ALLOW_UNOPT /*verilator lint_off UNOPTFLAT*/ `endif /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [31:0] b; // From file of file.v wire [31:0] c; // From file of file.v wire [31:0] d; // From file of file.v // End of automatics file file (/*AUTOINST*/ // Outputs .b (b[31:0]), .c (c[31:0]), .d (d[31:0]), // Inputs .crc (crc[31:0])); always @ (posedge clk) begin `ifdef TEST_VERBOSE $write("[%0t] cyc=%0d crc=%x sum=%x b=%x d=%x\n",$time,cyc,crc,sum, b, d); `endif cyc <= cyc + 1; crc <= {crc[62:0], crc[63]^crc[2]^crc[0]}; sum <= {b, d} ^ {sum[62:0],sum[63]^sum[2]^sum[0]}; if (cyc==0) begin // Setup crc <= 64'h5aef0c8d_d70a4497; end else if (cyc<10) begin sum <= 64'h0; end else if (cyc<90) begin end else if (cyc==99) begin $write("*-* All Finished *-*\n"); $write("[%0t] cyc==%0d crc=%x %x\n",$time, cyc, crc, sum); if (crc !== 64'hc77bb9b3784ea091) $stop; if (sum !== 64'h649ee1713d624dd9) $stop; $finish; end end endmodule module file (/*AUTOARG*/ // Outputs b, c, d, // Inputs crc ); input [31:0] crc; `ifdef ISOLATE output reg [31:0] b /* verilator isolate_assignments*/; `else output reg [31:0] b; `endif output reg [31:0] c; output reg [31:0] d; always @* begin // Note that while c and b depend on crc, b doesn't depend on c. casez (crc[3:0]) 4'b??01: begin b = {crc[15:0],get_31_16(crc)}; d = c; end 4'b??00: begin b = {crc[15:0],~crc[31:16]}; d = {crc[15:0],~c[31:16]}; end default: begin set_b_d(crc, c); end endcase end function [31:16] get_31_16 /* verilator isolate_assignments*/; input [31:0] t_crc /* verilator isolate_assignments*/; get_31_16 = t_crc[31:16]; endfunction task set_b_d; `ifdef ISOLATE input [31:0] t_crc /* verilator isolate_assignments*/; input [31:0] t_c /* verilator isolate_assignments*/; `else input [31:0] t_crc; input [31:0] t_c; `endif begin b = {t_crc[31:16],~t_crc[23:8]}; d = {t_crc[31:16], ~t_c[23:8]}; end endtask always @* begin // Any complicated equation we can't optimize casez (crc[3:0]) 4'b00??: begin c = {b[29:0],2'b11}; end 4'b01??: begin c = {b[30:1],2'b01}; end 4'b10??: begin c = {b[31:2],2'b10}; end 4'b11??: begin c = {b[31:2],2'b00}; end endcase end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2005 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=0; reg [63:0] crc; reg [63:0] sum; `ifdef ALLOW_UNOPT /*verilator lint_off UNOPTFLAT*/ `endif /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [31:0] b; // From file of file.v wire [31:0] c; // From file of file.v wire [31:0] d; // From file of file.v // End of automatics file file (/*AUTOINST*/ // Outputs .b (b[31:0]), .c (c[31:0]), .d (d[31:0]), // Inputs .crc (crc[31:0])); always @ (posedge clk) begin `ifdef TEST_VERBOSE $write("[%0t] cyc=%0d crc=%x sum=%x b=%x d=%x\n",$time,cyc,crc,sum, b, d); `endif cyc <= cyc + 1; crc <= {crc[62:0], crc[63]^crc[2]^crc[0]}; sum <= {b, d} ^ {sum[62:0],sum[63]^sum[2]^sum[0]}; if (cyc==0) begin // Setup crc <= 64'h5aef0c8d_d70a4497; end else if (cyc<10) begin sum <= 64'h0; end else if (cyc<90) begin end else if (cyc==99) begin $write("*-* All Finished *-*\n"); $write("[%0t] cyc==%0d crc=%x %x\n",$time, cyc, crc, sum); if (crc !== 64'hc77bb9b3784ea091) $stop; if (sum !== 64'h649ee1713d624dd9) $stop; $finish; end end endmodule module file (/*AUTOARG*/ // Outputs b, c, d, // Inputs crc ); input [31:0] crc; `ifdef ISOLATE output reg [31:0] b /* verilator isolate_assignments*/; `else output reg [31:0] b; `endif output reg [31:0] c; output reg [31:0] d; always @* begin // Note that while c and b depend on crc, b doesn't depend on c. casez (crc[3:0]) 4'b??01: begin b = {crc[15:0],get_31_16(crc)}; d = c; end 4'b??00: begin b = {crc[15:0],~crc[31:16]}; d = {crc[15:0],~c[31:16]}; end default: begin set_b_d(crc, c); end endcase end function [31:16] get_31_16 /* verilator isolate_assignments*/; input [31:0] t_crc /* verilator isolate_assignments*/; get_31_16 = t_crc[31:16]; endfunction task set_b_d; `ifdef ISOLATE input [31:0] t_crc /* verilator isolate_assignments*/; input [31:0] t_c /* verilator isolate_assignments*/; `else input [31:0] t_crc; input [31:0] t_c; `endif begin b = {t_crc[31:16],~t_crc[23:8]}; d = {t_crc[31:16], ~t_c[23:8]}; end endtask always @* begin // Any complicated equation we can't optimize casez (crc[3:0]) 4'b00??: begin c = {b[29:0],2'b11}; end 4'b01??: begin c = {b[30:1],2'b01}; end 4'b10??: begin c = {b[31:2],2'b10}; end 4'b11??: begin c = {b[31:2],2'b00}; 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_hcmd_table # ( parameter P_DATA_WIDTH = 128, parameter P_ADDR_WIDTH = 9 ) ( input wr_clk, input wr_en, input [P_ADDR_WIDTH-1:0] wr_addr, input [P_DATA_WIDTH-1:0] wr_data, input rd_clk, input [P_ADDR_WIDTH+1:0] rd_addr, output [31:0] rd_data ); wire [P_DATA_WIDTH-1:0] w_rd_data; reg [31:0] r_rd_data; assign rd_data = r_rd_data; always @ (*) begin case(rd_addr[1:0]) // synthesis parallel_case full_case 2'b00: r_rd_data <= w_rd_data[31:0]; 2'b01: r_rd_data <= w_rd_data[63:32]; 2'b10: r_rd_data <= w_rd_data[95:64]; 2'b11: r_rd_data <= w_rd_data[127:96]; endcase end localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_DATA_WIDTH/2; localparam LP_WRITE_WIDTH = P_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_ADDR_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 = rd_addr[P_ADDR_WIDTH+1:2]; assign wraddr = wr_addr[P_ADDR_WIDTH-1:0]; end else begin wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; assign rdaddr = {zero_padding, rd_addr[P_ADDR_WIDTH+1:2]}; assign wraddr = {zero_padding, wr_addr[P_ADDR_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_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_rd_data[P_DATA_WIDTH-1:LP_READ_WIDTH]), .DI (wr_data[P_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 // // Copyright 2012 by Wilson Snyder. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License // Version 2.0. module t (/*AUTOARG*/); `define ASSERT(x) initial if (!(x)) $stop // See IEEE 6.20.2 on value parameters localparam unsigned [63:0] UNSIGNED =64'h99934567_89abcdef; localparam signed [63:0] SIGNED =64'sh99934567_89abcdef; localparam real REAL=1.234; `ASSERT(UNSIGNED > 0); `ASSERT(SIGNED < 0); // bullet 1 localparam A1_WIDE = UNSIGNED; `ASSERT($bits(A1_WIDE)==64); localparam A2_REAL = REAL; `ASSERT(A2_REAL == 1.234); localparam A3_SIGNED = SIGNED; `ASSERT($bits(A3_SIGNED)==64 && A3_SIGNED < 0); localparam A4_EXPR = (2'b01 + 2'b10); `ASSERT($bits(A4_EXPR)==2 && A4_EXPR==2'b11); // bullet 2 localparam [63:0] B_UNSIGNED = SIGNED; `ASSERT($bits(B_UNSIGNED)==64 && B_UNSIGNED > 0); // bullet 3 localparam signed C_SIGNED = UNSIGNED; `ASSERT($bits(C_SIGNED)==64 && C_SIGNED < 0); localparam unsigned C_UNSIGNED = SIGNED; `ASSERT($bits(C_UNSIGNED)==64 && C_UNSIGNED > 0); // bullet 4 // verilator lint_off WIDTH localparam signed [59:0] D_SIGNED = UNSIGNED; `ASSERT($bits(D_SIGNED)==60 && D_SIGNED < 0); // verilator lint_on WIDTH // verilator lint_off WIDTH localparam unsigned [59:0] D_UNSIGNED = SIGNED; `ASSERT($bits(D_UNSIGNED)==60 && D_UNSIGNED > 0); // verilator lint_on WIDTH // bullet 6 localparam UNSIZED = 23; `ASSERT($bits(UNSIZED)>=32); initial begin $write("*-* All Finished *-*\n"); $finish; end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // Copyright 2012 by Wilson Snyder. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License // Version 2.0. module t (/*AUTOARG*/); `define ASSERT(x) initial if (!(x)) $stop // See IEEE 6.20.2 on value parameters localparam unsigned [63:0] UNSIGNED =64'h99934567_89abcdef; localparam signed [63:0] SIGNED =64'sh99934567_89abcdef; localparam real REAL=1.234; `ASSERT(UNSIGNED > 0); `ASSERT(SIGNED < 0); // bullet 1 localparam A1_WIDE = UNSIGNED; `ASSERT($bits(A1_WIDE)==64); localparam A2_REAL = REAL; `ASSERT(A2_REAL == 1.234); localparam A3_SIGNED = SIGNED; `ASSERT($bits(A3_SIGNED)==64 && A3_SIGNED < 0); localparam A4_EXPR = (2'b01 + 2'b10); `ASSERT($bits(A4_EXPR)==2 && A4_EXPR==2'b11); // bullet 2 localparam [63:0] B_UNSIGNED = SIGNED; `ASSERT($bits(B_UNSIGNED)==64 && B_UNSIGNED > 0); // bullet 3 localparam signed C_SIGNED = UNSIGNED; `ASSERT($bits(C_SIGNED)==64 && C_SIGNED < 0); localparam unsigned C_UNSIGNED = SIGNED; `ASSERT($bits(C_UNSIGNED)==64 && C_UNSIGNED > 0); // bullet 4 // verilator lint_off WIDTH localparam signed [59:0] D_SIGNED = UNSIGNED; `ASSERT($bits(D_SIGNED)==60 && D_SIGNED < 0); // verilator lint_on WIDTH // verilator lint_off WIDTH localparam unsigned [59:0] D_UNSIGNED = SIGNED; `ASSERT($bits(D_UNSIGNED)==60 && D_UNSIGNED > 0); // verilator lint_on WIDTH // bullet 6 localparam UNSIZED = 23; `ASSERT($bits(UNSIZED)>=32); initial begin $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_hcmd_table_prp # ( parameter P_DATA_WIDTH = 45, parameter P_ADDR_WIDTH = 8 ) ( input clk, input wr_en, input [P_ADDR_WIDTH-1:0] wr_addr, input [P_DATA_WIDTH-1:0] wr_data, input [P_ADDR_WIDTH-1:0] rd_addr, output [P_DATA_WIDTH-1:0] rd_data ); localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_DATA_WIDTH; localparam LP_WRITE_WIDTH = P_DATA_WIDTH; localparam LP_WRITE_MODE = "READ_FIRST"; localparam LP_WE_WIDTH = 8; localparam LP_ADDR_TOTAL_WITDH = 9; localparam LP_ADDR_ZERO_PAD_WITDH = LP_ADDR_TOTAL_WITDH - P_ADDR_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 = rd_addr[P_ADDR_WIDTH-1:0]; assign wraddr = wr_addr[P_ADDR_WIDTH-1:0]; end else begin wire [LP_ADDR_ZERO_PAD_WITDH-1:0] zero_padding = 0; assign rdaddr = {zero_padding, rd_addr[P_ADDR_WIDTH-1:0]}; assign wraddr = {zero_padding, wr_addr[P_ADDR_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 (wr_data), .RDADDR (rdaddr), .RDCLK (clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (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; function int int123(); int123 = 32'h123; endfunction function bit f_bit ; input bit i; f_bit = ~i; endfunction function int f_int ; input int i; f_int = ~i; endfunction function byte f_byte ; input byte i; f_byte = ~i; endfunction function shortint f_shortint; input shortint i; f_shortint = ~i; endfunction function longint f_longint ; input longint i; f_longint = ~i; endfunction function chandle f_chandle ; input chandle i; f_chandle = i; endfunction // Note there's no "input" here vvvv, it's the default function bit g_bit (bit i); g_bit = ~i; endfunction function int g_int (int i); g_int = ~i; endfunction function byte g_byte (byte i); g_byte = ~i; endfunction function shortint g_shortint(shortint i); g_shortint = ~i; endfunction function longint g_longint (longint i); g_longint = ~i; endfunction function chandle g_chandle (chandle i); g_chandle = i; endfunction chandle c; initial begin if (int123() !== 32'h123) $stop; if (f_bit(1'h1) !== 1'h0) $stop; if (f_bit(1'h0) !== 1'h1) $stop; if (f_int(32'h1) !== 32'hfffffffe) $stop; if (f_byte(8'h1) !== 8'hfe) $stop; if (f_shortint(16'h1) !== 16'hfffe) $stop; if (f_longint(64'h1) !== 64'hfffffffffffffffe) $stop; if (f_chandle(c) !== c) $stop; if (g_bit(1'h1) !== 1'h0) $stop; if (g_bit(1'h0) !== 1'h1) $stop; if (g_int(32'h1) !== 32'hfffffffe) $stop; if (g_byte(8'h1) !== 8'hfe) $stop; if (g_shortint(16'h1) !== 16'hfffe) $stop; if (g_longint(64'h1) !== 64'hfffffffffffffffe) $stop; if (g_chandle(c) !== c) $stop; $write("*-* All Finished *-*\n"); $finish; end endmodule
module serial_rx #( parameter CLK_PER_BIT = 50 )( input clk, input rst, input rx, output [7:0] data, output new_data ); // clog2 is 'ceiling of log base 2' which gives you the number of bits needed to store a value parameter CTR_SIZE = $clog2(CLK_PER_BIT); localparam STATE_SIZE = 2; localparam IDLE = 2'd0, WAIT_HALF = 2'd1, WAIT_FULL = 2'd2, WAIT_HIGH = 2'd3; reg [CTR_SIZE-1:0] ctr_d, ctr_q; reg [2:0] bit_ctr_d, bit_ctr_q; reg [7:0] data_d, data_q; reg new_data_d, new_data_q; reg [STATE_SIZE-1:0] state_d, state_q = IDLE; reg rx_d, rx_q; assign new_data = new_data_q; assign data = data_q; always @(*) begin rx_d = rx; state_d = state_q; ctr_d = ctr_q; bit_ctr_d = bit_ctr_q; data_d = data_q; new_data_d = 1'b0; case (state_q) IDLE: begin bit_ctr_d = 3'b0; ctr_d = 1'b0; if (rx_q == 1'b0) begin state_d = WAIT_HALF; end end WAIT_HALF: begin ctr_d = ctr_q + 1'b1; if (ctr_q == (CLK_PER_BIT >> 1)) begin ctr_d = 1'b0; state_d = WAIT_FULL; end end WAIT_FULL: begin ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin data_d = {rx_q, data_q[7:1]}; bit_ctr_d = bit_ctr_q + 1'b1; ctr_d = 1'b0; if (bit_ctr_q == 3'd7) begin state_d = WAIT_HIGH; new_data_d = 1'b1; end end end WAIT_HIGH: begin if (rx_q == 1'b1) begin state_d = IDLE; end end default: begin state_d = IDLE; end endcase end always @(posedge clk) begin if (rst) begin ctr_q <= 1'b0; bit_ctr_q <= 3'b0; new_data_q <= 1'b0; state_q <= IDLE; end else begin ctr_q <= ctr_d; bit_ctr_q <= bit_ctr_d; new_data_q <= new_data_d; state_q <= state_d; end rx_q <= rx_d; data_q <= data_d; end endmodule
module serial_rx #( parameter CLK_PER_BIT = 50 )( input clk, input rst, input rx, output [7:0] data, output new_data ); // clog2 is 'ceiling of log base 2' which gives you the number of bits needed to store a value parameter CTR_SIZE = $clog2(CLK_PER_BIT); localparam STATE_SIZE = 2; localparam IDLE = 2'd0, WAIT_HALF = 2'd1, WAIT_FULL = 2'd2, WAIT_HIGH = 2'd3; reg [CTR_SIZE-1:0] ctr_d, ctr_q; reg [2:0] bit_ctr_d, bit_ctr_q; reg [7:0] data_d, data_q; reg new_data_d, new_data_q; reg [STATE_SIZE-1:0] state_d, state_q = IDLE; reg rx_d, rx_q; assign new_data = new_data_q; assign data = data_q; always @(*) begin rx_d = rx; state_d = state_q; ctr_d = ctr_q; bit_ctr_d = bit_ctr_q; data_d = data_q; new_data_d = 1'b0; case (state_q) IDLE: begin bit_ctr_d = 3'b0; ctr_d = 1'b0; if (rx_q == 1'b0) begin state_d = WAIT_HALF; end end WAIT_HALF: begin ctr_d = ctr_q + 1'b1; if (ctr_q == (CLK_PER_BIT >> 1)) begin ctr_d = 1'b0; state_d = WAIT_FULL; end end WAIT_FULL: begin ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin data_d = {rx_q, data_q[7:1]}; bit_ctr_d = bit_ctr_q + 1'b1; ctr_d = 1'b0; if (bit_ctr_q == 3'd7) begin state_d = WAIT_HIGH; new_data_d = 1'b1; end end end WAIT_HIGH: begin if (rx_q == 1'b1) begin state_d = IDLE; end end default: begin state_d = IDLE; end endcase end always @(posedge clk) begin if (rst) begin ctr_q <= 1'b0; bit_ctr_q <= 3'b0; new_data_q <= 1'b0; state_q <= IDLE; end else begin ctr_q <= ctr_d; bit_ctr_q <= bit_ctr_d; new_data_q <= new_data_d; state_q <= state_d; end rx_q <= rx_d; data_q <= data_d; end endmodule
module serial_rx #( parameter CLK_PER_BIT = 50 )( input clk, input rst, input rx, output [7:0] data, output new_data ); // clog2 is 'ceiling of log base 2' which gives you the number of bits needed to store a value parameter CTR_SIZE = $clog2(CLK_PER_BIT); localparam STATE_SIZE = 2; localparam IDLE = 2'd0, WAIT_HALF = 2'd1, WAIT_FULL = 2'd2, WAIT_HIGH = 2'd3; reg [CTR_SIZE-1:0] ctr_d, ctr_q; reg [2:0] bit_ctr_d, bit_ctr_q; reg [7:0] data_d, data_q; reg new_data_d, new_data_q; reg [STATE_SIZE-1:0] state_d, state_q = IDLE; reg rx_d, rx_q; assign new_data = new_data_q; assign data = data_q; always @(*) begin rx_d = rx; state_d = state_q; ctr_d = ctr_q; bit_ctr_d = bit_ctr_q; data_d = data_q; new_data_d = 1'b0; case (state_q) IDLE: begin bit_ctr_d = 3'b0; ctr_d = 1'b0; if (rx_q == 1'b0) begin state_d = WAIT_HALF; end end WAIT_HALF: begin ctr_d = ctr_q + 1'b1; if (ctr_q == (CLK_PER_BIT >> 1)) begin ctr_d = 1'b0; state_d = WAIT_FULL; end end WAIT_FULL: begin ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin data_d = {rx_q, data_q[7:1]}; bit_ctr_d = bit_ctr_q + 1'b1; ctr_d = 1'b0; if (bit_ctr_q == 3'd7) begin state_d = WAIT_HIGH; new_data_d = 1'b1; end end end WAIT_HIGH: begin if (rx_q == 1'b1) begin state_d = IDLE; end end default: begin state_d = IDLE; end endcase end always @(posedge clk) begin if (rst) begin ctr_q <= 1'b0; bit_ctr_q <= 3'b0; new_data_q <= 1'b0; state_q <= IDLE; end else begin ctr_q <= ctr_d; bit_ctr_q <= bit_ctr_d; new_data_q <= new_data_d; state_q <= state_d; end rx_q <= rx_d; data_q <= data_d; 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 dev_rx_cmd_fifo # ( parameter P_FIFO_DATA_WIDTH = 30, parameter P_FIFO_DEPTH_WIDTH = 4 ) ( input wr_clk, input wr_rst_n, input wr_en, input [P_FIFO_DATA_WIDTH-1:0] wr_data, output full_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; 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; assign 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 (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 = "18Kb"; 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 = 4; 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) ) ramb18sdp_0( .DO (rd_data), .DI (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 (wr_en) ); endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2008 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; reg [63:0] crc; reg [63:0] sum; wire [31:0] inp = crc[31:0]; wire reset = (cyc < 5); /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [31:0] outp; // From test of Test.v // End of automatics Test test (/*AUTOINST*/ // Outputs .outp (outp[31:0]), // Inputs .reset (reset), .clk (clk), .inp (inp[31:0])); // Aggregate outputs into a single result vector wire [63:0] result = {32'h0, outp}; // What checksum will we end up with `define EXPECTED_SUM 64'ha7f0a34f9cf56ccb // 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; 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; if (sum !== `EXPECTED_SUM) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module Test (/*AUTOARG*/ // Outputs outp, // Inputs reset, clk, inp ); input reset; input clk; input [31:0] inp; output [31:0] outp; function [31:0] no_inline_function; input [31:0] var1; input [31:0] var2; /*verilator no_inline_task*/ reg [31*2:0] product1 ; reg [31*2:0] product2 ; integer i; reg [31:0] tmp; begin product2 = {(31*2+1){1'b0}}; for (i = 0; i < 32; i = i + 1) if (var2[i]) begin product1 = { {31*2+1-32{1'b0}}, var1} << i; product2 = product2 ^ product1; end no_inline_function = 0; for (i= 0; i < 31; i = i + 1 ) no_inline_function[i+1] = no_inline_function[i] ^ product2[i] ^ var1[i]; end endfunction reg [31:0] outp; reg [31:0] inp_d; always @( posedge clk ) begin if( reset ) begin outp <= 0; end else begin inp_d <= inp; outp <= no_inline_function(inp, inp_d); end 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. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; reg [63:0] crc; reg [63:0] sum; wire [31:0] inp = crc[31:0]; wire reset = (cyc < 5); /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [31:0] outp; // From test of Test.v // End of automatics Test test (/*AUTOINST*/ // Outputs .outp (outp[31:0]), // Inputs .reset (reset), .clk (clk), .inp (inp[31:0])); // Aggregate outputs into a single result vector wire [63:0] result = {32'h0, outp}; // What checksum will we end up with `define EXPECTED_SUM 64'ha7f0a34f9cf56ccb // 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; 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; if (sum !== `EXPECTED_SUM) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module Test (/*AUTOARG*/ // Outputs outp, // Inputs reset, clk, inp ); input reset; input clk; input [31:0] inp; output [31:0] outp; function [31:0] no_inline_function; input [31:0] var1; input [31:0] var2; /*verilator no_inline_task*/ reg [31*2:0] product1 ; reg [31*2:0] product2 ; integer i; reg [31:0] tmp; begin product2 = {(31*2+1){1'b0}}; for (i = 0; i < 32; i = i + 1) if (var2[i]) begin product1 = { {31*2+1-32{1'b0}}, var1} << i; product2 = product2 ^ product1; end no_inline_function = 0; for (i= 0; i < 31; i = i + 1 ) no_inline_function[i+1] = no_inline_function[i] ^ product2[i] ^ var1[i]; end endfunction reg [31:0] outp; reg [31:0] inp_d; always @( posedge clk ) begin if( reset ) begin outp <= 0; end else begin inp_d <= inp; outp <= no_inline_function(inp, inp_d); end 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_cntl_rx_fifo # ( parameter P_FIFO_DATA_WIDTH = 128, parameter P_FIFO_DEPTH_WIDTH = 5 ) ( input clk, input rst_n, input wr_en, input [P_FIFO_DATA_WIDTH-1:0] wr_data, output full_n, output almost_full_n, input rd_en, output [P_FIFO_DATA_WIDTH-1:0] rd_data, output empty_n ); localparam P_FIFO_ALLOC_WIDTH = 0; //128 bits reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr_p1; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_addr; reg r_almost_full_n; wire w_almost_full_n; wire [P_FIFO_DEPTH_WIDTH:0] w_invalid_space; wire [P_FIFO_DEPTH_WIDTH:0] w_invalid_front_addr; assign full_n = ~(( r_rear_addr[P_FIFO_DEPTH_WIDTH] ^ r_front_addr[P_FIFO_DEPTH_WIDTH]) & (r_rear_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH] == r_front_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH])); assign almost_full_n = r_almost_full_n; assign w_invalid_front_addr = {~r_front_addr[P_FIFO_DEPTH_WIDTH], r_front_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH]}; assign w_invalid_space = w_invalid_front_addr - r_rear_addr; assign w_almost_full_n = (w_invalid_space > 8); always @(posedge clk) begin r_almost_full_n <= w_almost_full_n; end assign empty_n = ~(r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH] == r_rear_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]); always @(posedge clk or negedge rst_n) begin if (rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; r_rear_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 (wr_en == 1) begin r_rear_addr <= r_rear_addr + 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]; localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "36Kb"; localparam LP_DOB_REG = 0; localparam LP_READ_WIDTH = P_FIFO_DATA_WIDTH/2; localparam LP_WRITE_WIDTH = P_FIFO_DATA_WIDTH/2; localparam LP_WRITE_MODE = "READ_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 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], 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[LP_READ_WIDTH-1:0]), .DI (wr_data[LP_WRITE_WIDTH-1:0]), .RDADDR (rdaddr), .RDCLK (clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (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 (rd_data[P_FIFO_DATA_WIDTH-1:LP_READ_WIDTH]), .DI (wr_data[P_FIFO_DATA_WIDTH-1:LP_WRITE_WIDTH]), .RDADDR (rdaddr), .RDCLK (clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (clk), .WREN (wr_en) ); endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003-2007 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; wire out; reg in; Genit g (.clk(clk), .value(in), .result(out)); always @ (posedge clk) begin //$write("[%0t] cyc==%0d %x %x\n",$time, cyc, in, out); cyc <= cyc + 1; if (cyc==0) begin // Setup in <= 1'b1; end else if (cyc==1) begin in <= 1'b0; end else if (cyc==2) begin if (out != 1'b1) $stop; end else if (cyc==3) begin if (out != 1'b0) $stop; end else if (cyc==9) begin $write("*-* All Finished *-*\n"); $finish; end end //`define WAVES `ifdef WAVES initial begin $dumpfile("obj_dir/t_gen_intdot/t_gen_intdot.vcd"); $dumpvars(12, t); end `endif endmodule module Generate (clk, value, result); input clk; input value; output result; reg Internal; assign result = Internal ^ clk; always @(posedge clk) Internal <= #1 value; endmodule module Checker (clk, value); input clk, value; always @(posedge clk) begin $write ("[%0t] value=%h\n", $time, value); end endmodule module Test (clk, value, result); input clk; input value; output result; Generate gen (clk, value, result); Checker chk (clk, gen.Internal); endmodule module Genit (clk, value, result); input clk; input value; output result; `ifndef ATSIM // else unsupported `ifndef NC // else unsupported `define WITH_FOR_GENVAR `endif `endif `define WITH_GENERATE `ifdef WITH_GENERATE `ifndef WITH_FOR_GENVAR genvar i; `endif generate for ( `ifdef WITH_FOR_GENVAR genvar `endif i = 0; i < 1; i = i + 1) begin : foo Test tt (clk, value, result); end endgenerate `else Test tt (clk, value, result); `endif wire Result2 = t.g.foo[0].tt.gen.Internal; // Works - Do not change! always @ (posedge clk) begin $write("[%0t] Result2 = %x\n", $time, Result2); end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003-2007 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; wire out; reg in; Genit g (.clk(clk), .value(in), .result(out)); always @ (posedge clk) begin //$write("[%0t] cyc==%0d %x %x\n",$time, cyc, in, out); cyc <= cyc + 1; if (cyc==0) begin // Setup in <= 1'b1; end else if (cyc==1) begin in <= 1'b0; end else if (cyc==2) begin if (out != 1'b1) $stop; end else if (cyc==3) begin if (out != 1'b0) $stop; end else if (cyc==9) begin $write("*-* All Finished *-*\n"); $finish; end end //`define WAVES `ifdef WAVES initial begin $dumpfile("obj_dir/t_gen_intdot/t_gen_intdot.vcd"); $dumpvars(12, t); end `endif endmodule module Generate (clk, value, result); input clk; input value; output result; reg Internal; assign result = Internal ^ clk; always @(posedge clk) Internal <= #1 value; endmodule module Checker (clk, value); input clk, value; always @(posedge clk) begin $write ("[%0t] value=%h\n", $time, value); end endmodule module Test (clk, value, result); input clk; input value; output result; Generate gen (clk, value, result); Checker chk (clk, gen.Internal); endmodule module Genit (clk, value, result); input clk; input value; output result; `ifndef ATSIM // else unsupported `ifndef NC // else unsupported `define WITH_FOR_GENVAR `endif `endif `define WITH_GENERATE `ifdef WITH_GENERATE `ifndef WITH_FOR_GENVAR genvar i; `endif generate for ( `ifdef WITH_FOR_GENVAR genvar `endif i = 0; i < 1; i = i + 1) begin : foo Test tt (clk, value, result); end endgenerate `else Test tt (clk, value, result); `endif wire Result2 = t.g.foo[0].tt.gen.Internal; // Works - Do not change! always @ (posedge clk) begin $write("[%0t] Result2 = %x\n", $time, Result2); 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 `include "def_nvme.vh" module pcie_cntl_reg # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, output rx_np_ok, output rx_np_req, output mreq_fifo_rd_en, input [C_PCIE_DATA_WIDTH-1:0] mreq_fifo_rd_data, input mreq_fifo_empty_n, output tx_cpld_req, output [7:0] tx_cpld_tag, output [15:0] tx_cpld_req_id, output [11:2] tx_cpld_len, output [11:0] tx_cpld_bc, output [6:0] tx_cpld_laddr, output [63:0] tx_cpld_data, input tx_cpld_req_ack, output nvme_cc_en, output [1:0] nvme_cc_shn, input [1:0] nvme_csts_shst, input nvme_csts_rdy, output nvme_intms_ivms, output nvme_intmc_ivmc, input cq_irq_status, input [8:0] sq_rst_n, input [8:0] cq_rst_n, output [C_PCIE_ADDR_WIDTH-1:2] admin_sq_bs_addr, output [C_PCIE_ADDR_WIDTH-1:2] admin_cq_bs_addr, output [7:0] admin_sq_size, output [7:0] admin_cq_size, output [7:0] admin_sq_tail_ptr, output [7:0] io_sq1_tail_ptr, output [7:0] io_sq2_tail_ptr, output [7:0] io_sq3_tail_ptr, output [7:0] io_sq4_tail_ptr, output [7:0] io_sq5_tail_ptr, output [7:0] io_sq6_tail_ptr, output [7:0] io_sq7_tail_ptr, output [7:0] io_sq8_tail_ptr, output [7:0] admin_cq_head_ptr, output [7:0] io_cq1_head_ptr, output [7:0] io_cq2_head_ptr, output [7:0] io_cq3_head_ptr, output [7:0] io_cq4_head_ptr, output [7:0] io_cq5_head_ptr, output [7:0] io_cq6_head_ptr, output [7:0] io_cq7_head_ptr, output [7:0] io_cq8_head_ptr, output [8:0] cq_head_update ); localparam S_IDLE = 9'b000000001; localparam S_PCIE_RD_HEAD = 9'b000000010; localparam S_PCIE_ADDR = 9'b000000100; localparam S_PCIE_WAIT_WR_DATA = 9'b000001000; localparam S_PCIE_WR_DATA = 9'b000010000; localparam S_PCIE_MWR = 9'b000100000; localparam S_PCIE_MRD = 9'b001000000; localparam S_PCIE_CPLD_REQ = 9'b010000000; localparam S_PCIE_CPLD_ACK = 9'b100000000; reg [8:0] cur_state; reg [8:0] next_state; reg r_intms_ivms; reg r_intmc_ivmc; reg r_cq_irq_status; reg [23:20] r_cc_iocqes; reg [19:16] r_cc_iosqes; reg [15:14] r_cc_shn; reg [13:11] r_cc_asm; reg [10:7] r_cc_mps; reg [6:4] r_cc_ccs; reg [0:0] r_cc_en; reg [23:16] r_aqa_acqs; reg [7:0] r_aqa_asqs; reg [C_PCIE_ADDR_WIDTH-1:2] r_asq_asqb; reg [C_PCIE_ADDR_WIDTH-1:2] r_acq_acqb; reg [7:0] r_reg_sq0tdbl; reg [7:0] r_reg_sq1tdbl; reg [7:0] r_reg_sq2tdbl; reg [7:0] r_reg_sq3tdbl; reg [7:0] r_reg_sq4tdbl; reg [7:0] r_reg_sq5tdbl; reg [7:0] r_reg_sq6tdbl; reg [7:0] r_reg_sq7tdbl; reg [7:0] r_reg_sq8tdbl; reg [7:0] r_reg_cq0hdbl; reg [7:0] r_reg_cq1hdbl; reg [7:0] r_reg_cq2hdbl; reg [7:0] r_reg_cq3hdbl; reg [7:0] r_reg_cq4hdbl; reg [7:0] r_reg_cq5hdbl; reg [7:0] r_reg_cq6hdbl; reg [7:0] r_reg_cq7hdbl; reg [7:0] r_reg_cq8hdbl; reg [8:0] r_cq_head_update; wire [31:0] w_pcie_head0; wire [31:0] w_pcie_head1; wire [31:0] w_pcie_head2; wire [31:0] w_pcie_head3; reg [31:0] r_pcie_head2; reg [31:0] r_pcie_head3; wire [2:0] w_mreq_head_fmt; //wire [4:0] w_mreq_head_type; //wire [2:0] w_mreq_head_tc; //wire w_mreq_head_attr1; //wire w_mreq_head_th; //wire w_mreq_head_td; //wire w_mreq_head_ep; //wire [1:0] w_mreq_head_attr0; //wire [1:0] w_mreq_head_at; wire [9:0] w_mreq_head_len; wire [7:0] w_mreq_head_req_bus_num; wire [4:0] w_mreq_head_req_dev_num; wire [2:0] w_mreq_head_req_func_num; wire [15:0] w_mreq_head_req_id; wire [7:0] w_mreq_head_tag; wire [3:0] w_mreq_head_last_be; wire [3:0] w_mreq_head_1st_be; //reg [4:0] r_rx_np_req_cnt; //reg r_rx_np_req; wire w_mwr; wire w_4dw; reg [2:0] r_mreq_head_fmt; reg [9:0] r_mreq_head_len; reg [15:0] r_mreq_head_req_id; reg [7:0] r_mreq_head_tag; reg [3:0] r_mreq_head_last_be; reg [3:0] r_mreq_head_1st_be; reg [12:0] r_mreq_addr; reg [63:0] r_mreq_data; reg [3:0] r_cpld_bc; reg r_lbytes_en; reg r_hbytes_en; reg r_wr_reg; reg r_wr_doorbell; reg r_tx_cpld_req; reg [63:0] r_rd_data; reg [63:0] r_rd_reg; reg [63:0] r_rd_doorbell; reg r_mreq_fifo_rd_en; wire [8:0] w_sq_rst_n; wire [8:0] w_cq_rst_n; //pcie mrd or mwr, memory rd/wr request assign w_pcie_head0 = mreq_fifo_rd_data[31:0]; assign w_pcie_head1 = mreq_fifo_rd_data[63:32]; assign w_pcie_head2 = mreq_fifo_rd_data[95:64]; assign w_pcie_head3 = mreq_fifo_rd_data[127:96]; assign w_mreq_head_fmt = w_pcie_head0[31:29]; //assign w_mreq_head_type = w_pcie_head0[28:24]; //assign w_mreq_head_tc = w_pcie_head0[22:20]; //assign w_mreq_head_attr1 = w_pcie_head0[18]; //assign w_mreq_head_th = w_pcie_head0[16]; //assign w_mreq_head_td = w_pcie_head0[15]; //assign w_mreq_head_ep = w_pcie_head0[14]; //assign w_mreq_head_attr0 = w_pcie_head0[13:12]; //assign w_mreq_head_at = w_pcie_head0[11:10]; assign w_mreq_head_len = w_pcie_head0[9:0]; assign w_mreq_head_req_bus_num = w_pcie_head1[31:24]; assign w_mreq_head_req_dev_num = w_pcie_head1[23:19]; assign w_mreq_head_req_func_num = w_pcie_head1[18:16]; assign w_mreq_head_req_id = {w_mreq_head_req_bus_num, w_mreq_head_req_dev_num, w_mreq_head_req_func_num}; assign w_mreq_head_tag = w_pcie_head1[15:8]; assign w_mreq_head_last_be = w_pcie_head1[7:4]; assign w_mreq_head_1st_be = w_pcie_head1[3:0]; assign w_mwr = r_mreq_head_fmt[1]; assign w_4dw = r_mreq_head_fmt[0]; assign tx_cpld_req = r_tx_cpld_req; assign tx_cpld_tag = r_mreq_head_tag; assign tx_cpld_req_id = r_mreq_head_req_id; assign tx_cpld_len = {8'b0, r_mreq_head_len[1:0]}; assign tx_cpld_bc = {8'b0, r_cpld_bc}; assign tx_cpld_laddr = r_mreq_addr[6:0]; assign tx_cpld_data = (r_mreq_addr[2] == 1) ? {32'b0, r_rd_data[63:32]} : r_rd_data; assign rx_np_ok = 1'b1; assign rx_np_req = 1'b1; assign mreq_fifo_rd_en = r_mreq_fifo_rd_en; assign admin_sq_bs_addr = r_asq_asqb; assign admin_cq_bs_addr = r_acq_acqb; assign nvme_cc_en = r_cc_en; assign nvme_cc_shn = r_cc_shn; assign nvme_intms_ivms = r_intms_ivms; assign nvme_intmc_ivmc = r_intmc_ivmc; assign admin_sq_size = r_aqa_asqs; assign admin_cq_size = r_aqa_acqs; assign admin_sq_tail_ptr = r_reg_sq0tdbl; assign io_sq1_tail_ptr = r_reg_sq1tdbl; assign io_sq2_tail_ptr = r_reg_sq2tdbl; assign io_sq3_tail_ptr = r_reg_sq3tdbl; assign io_sq4_tail_ptr = r_reg_sq4tdbl; assign io_sq5_tail_ptr = r_reg_sq5tdbl; assign io_sq6_tail_ptr = r_reg_sq6tdbl; assign io_sq7_tail_ptr = r_reg_sq7tdbl; assign io_sq8_tail_ptr = r_reg_sq8tdbl; assign admin_cq_head_ptr = r_reg_cq0hdbl; assign io_cq1_head_ptr = r_reg_cq1hdbl; assign io_cq2_head_ptr = r_reg_cq2hdbl; assign io_cq3_head_ptr = r_reg_cq3hdbl; assign io_cq4_head_ptr = r_reg_cq4hdbl; assign io_cq5_head_ptr = r_reg_cq5hdbl; assign io_cq6_head_ptr = r_reg_cq6hdbl; assign io_cq7_head_ptr = r_reg_cq7hdbl; assign io_cq8_head_ptr = r_reg_cq8hdbl; assign cq_head_update = r_cq_head_update; always @ (posedge pcie_user_clk) begin r_cq_irq_status <= cq_irq_status; end 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(mreq_fifo_empty_n == 1) next_state <= S_PCIE_RD_HEAD; else next_state <= S_IDLE; end S_PCIE_RD_HEAD: begin next_state <= S_PCIE_ADDR; end S_PCIE_ADDR: begin if(w_mwr == 1) begin if(w_4dw == 1 || r_mreq_head_len[1] == 1) begin if(mreq_fifo_empty_n == 1) next_state <= S_PCIE_WR_DATA; else next_state <= S_PCIE_WAIT_WR_DATA; end else next_state <= S_PCIE_MWR; end else begin next_state <= S_PCIE_MRD; end end S_PCIE_WAIT_WR_DATA: begin if(mreq_fifo_empty_n == 1) next_state <= S_PCIE_WR_DATA; else next_state <= S_PCIE_WAIT_WR_DATA; end S_PCIE_WR_DATA: begin next_state <= S_PCIE_MWR; end S_PCIE_MWR: begin next_state <= S_IDLE; end S_PCIE_MRD: begin next_state <= S_PCIE_CPLD_REQ; end S_PCIE_CPLD_REQ: begin next_state <= S_PCIE_CPLD_ACK; end S_PCIE_CPLD_ACK: begin if(tx_cpld_req_ack == 1) next_state <= S_IDLE; else next_state <= S_PCIE_CPLD_ACK; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_RD_HEAD: begin r_mreq_head_fmt <= w_mreq_head_fmt; r_mreq_head_len <= w_mreq_head_len; r_mreq_head_req_id <= w_mreq_head_req_id; r_mreq_head_tag <= w_mreq_head_tag; r_mreq_head_last_be <= w_mreq_head_last_be; r_mreq_head_1st_be <= w_mreq_head_1st_be; r_pcie_head2 <= w_pcie_head2; r_pcie_head3 <= w_pcie_head3; end S_PCIE_ADDR: begin if(w_4dw == 1) begin r_mreq_addr[12:2] <= r_pcie_head3[12:2]; r_lbytes_en <= ~r_pcie_head3[2] & (r_pcie_head3[11:7] == 0); r_hbytes_en <= (r_pcie_head3[2] | r_mreq_head_len[1]) & (r_pcie_head3[11:7] == 0); end else begin r_mreq_addr[12:2] <= r_pcie_head2[12:2]; r_lbytes_en <= ~r_pcie_head2[2] & (r_pcie_head2[11:7] == 0);; r_hbytes_en <= (r_pcie_head2[2] | r_mreq_head_len[1]) & (r_pcie_head2[11:7] == 0); if(r_pcie_head2[2] == 1) r_mreq_data[63:32] <= {r_pcie_head3[7:0], r_pcie_head3[15:8], r_pcie_head3[23:16], r_pcie_head3[31:24]}; else r_mreq_data[31:0] <= {r_pcie_head3[7:0], r_pcie_head3[15:8], r_pcie_head3[23:16], r_pcie_head3[31:24]}; end end S_PCIE_WAIT_WR_DATA: begin end S_PCIE_WR_DATA: begin if(w_4dw == 1) begin if(r_mreq_addr[2] == 1) r_mreq_data[63:32] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; else begin r_mreq_data[31:0] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; r_mreq_data[63:32] <= {mreq_fifo_rd_data[39:32], mreq_fifo_rd_data[47:40], mreq_fifo_rd_data[55:48], mreq_fifo_rd_data[63:56]}; end end else r_mreq_data[63:32] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; end S_PCIE_MWR: begin end S_PCIE_MRD: begin if(r_lbytes_en | r_hbytes_en) begin if(r_mreq_addr[12] == 1) begin r_rd_data[31:0] <= {r_rd_doorbell[7:0], r_rd_doorbell[15:8], r_rd_doorbell[23:16], r_rd_doorbell[31:24]}; r_rd_data[63:32] <= {r_rd_doorbell[39:32], r_rd_doorbell[47:40], r_rd_doorbell[55:48], r_rd_doorbell[63:56]}; end else begin r_rd_data[31:0] <= {r_rd_reg[7:0], r_rd_reg[15:8], r_rd_reg[23:16], r_rd_reg[31:24]}; r_rd_data[63:32] <= {r_rd_reg[39:32], r_rd_reg[47:40], r_rd_reg[55:48], r_rd_reg[63:56]}; end end else r_rd_data <= 64'b0; if(r_mreq_head_1st_be[0] == 1) r_mreq_addr[1:0] <= 2'b00; else if(r_mreq_head_1st_be[1] == 1) r_mreq_addr[1:0] <= 2'b01; else if(r_mreq_head_1st_be[2] == 1) r_mreq_addr[1:0] <= 2'b10; else r_mreq_addr[1:0] <= 2'b11; r_cpld_bc <= ((r_mreq_head_1st_be[0] + r_mreq_head_1st_be[1]) + (r_mreq_head_1st_be[2] + r_mreq_head_1st_be[3])) + ((r_mreq_head_last_be[0] + r_mreq_head_last_be[1]) + (r_mreq_head_last_be[2] + r_mreq_head_last_be[3])); end S_PCIE_CPLD_REQ: begin end S_PCIE_CPLD_ACK: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_RD_HEAD: begin r_mreq_fifo_rd_en <= 1; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_ADDR: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_WAIT_WR_DATA: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_WR_DATA: begin r_mreq_fifo_rd_en <= 1; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_MWR: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= ~r_mreq_addr[12]; r_wr_doorbell <= r_mreq_addr[12]; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_MRD: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_CPLD_REQ: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 1; //r_rx_np_req <= 1; end S_PCIE_CPLD_ACK: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end default: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end endcase end always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) begin r_intms_ivms <= 0; r_intmc_ivmc <= 0; {r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, r_cc_en} <= 0; {r_aqa_acqs, r_aqa_asqs} <= 0; r_asq_asqb <= 0; r_acq_acqb <= 0; end else begin if(r_wr_reg == 1) begin if(r_lbytes_en == 1) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h5: r_asq_asqb[31:2] <= r_mreq_data[31:2]; 4'h6: r_acq_acqb[31:2] <= r_mreq_data[31:2]; endcase if(r_mreq_addr[6:3] == 4'h1) r_intmc_ivmc <= r_mreq_data[0]; else r_intmc_ivmc <= 0; end if(r_hbytes_en == 1) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h2: {r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, r_cc_en} <= {r_mreq_data[55:52], r_mreq_data[51:48], r_mreq_data[47:46], r_mreq_data[45:43], r_mreq_data[42:39], r_mreq_data[38:36], r_mreq_data[32]}; 4'h4: {r_aqa_acqs, r_aqa_asqs} <= {r_mreq_data[55:48], r_mreq_data[39:32]}; 4'h5: r_asq_asqb[C_PCIE_ADDR_WIDTH-1:32] <= r_mreq_data[C_PCIE_ADDR_WIDTH-1:32]; 4'h6: r_acq_acqb[C_PCIE_ADDR_WIDTH-1:32] <= r_mreq_data[C_PCIE_ADDR_WIDTH-1:32]; endcase if(r_mreq_addr[6:3] == 4'h1) r_intms_ivms <= r_mreq_data[32]; else r_intms_ivms <= 0; end end else begin r_intms_ivms <= 0; r_intmc_ivmc <= 0; end end end assign w_sq_rst_n[0] = pcie_user_rst_n & sq_rst_n[0]; assign w_sq_rst_n[1] = pcie_user_rst_n & sq_rst_n[1]; assign w_sq_rst_n[2] = pcie_user_rst_n & sq_rst_n[2]; assign w_sq_rst_n[3] = pcie_user_rst_n & sq_rst_n[3]; assign w_sq_rst_n[4] = pcie_user_rst_n & sq_rst_n[4]; assign w_sq_rst_n[5] = pcie_user_rst_n & sq_rst_n[5]; assign w_sq_rst_n[6] = pcie_user_rst_n & sq_rst_n[6]; assign w_sq_rst_n[7] = pcie_user_rst_n & sq_rst_n[7]; assign w_sq_rst_n[8] = pcie_user_rst_n & sq_rst_n[8]; always @ (posedge pcie_user_clk or negedge w_sq_rst_n[0]) begin if(w_sq_rst_n[0] == 0) begin r_reg_sq0tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h0)) == 1) r_reg_sq0tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[1]) begin if(w_sq_rst_n[1] == 0) begin r_reg_sq1tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h1)) == 1) r_reg_sq1tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[2]) begin if(w_sq_rst_n[2] == 0) begin r_reg_sq2tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h2)) == 1) r_reg_sq2tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[3]) begin if(w_sq_rst_n[3] == 0) begin r_reg_sq3tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h3)) == 1) r_reg_sq3tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[4]) begin if(w_sq_rst_n[4] == 0) begin r_reg_sq4tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h4)) == 1) r_reg_sq4tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[5]) begin if(w_sq_rst_n[5] == 0) begin r_reg_sq5tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h5)) == 1) r_reg_sq5tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[6]) begin if(w_sq_rst_n[6] == 0) begin r_reg_sq6tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h6)) == 1) r_reg_sq6tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[7]) begin if(w_sq_rst_n[7] == 0) begin r_reg_sq7tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h7)) == 1) r_reg_sq7tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[8]) begin if(w_sq_rst_n[8] == 0) begin r_reg_sq8tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h8)) == 1) r_reg_sq8tdbl <= r_mreq_data[7:0]; end end assign w_cq_rst_n[0] = pcie_user_rst_n & cq_rst_n[0]; assign w_cq_rst_n[1] = pcie_user_rst_n & cq_rst_n[1]; assign w_cq_rst_n[2] = pcie_user_rst_n & cq_rst_n[2]; assign w_cq_rst_n[3] = pcie_user_rst_n & cq_rst_n[3]; assign w_cq_rst_n[4] = pcie_user_rst_n & cq_rst_n[4]; assign w_cq_rst_n[5] = pcie_user_rst_n & cq_rst_n[5]; assign w_cq_rst_n[6] = pcie_user_rst_n & cq_rst_n[6]; assign w_cq_rst_n[7] = pcie_user_rst_n & cq_rst_n[7]; assign w_cq_rst_n[8] = pcie_user_rst_n & cq_rst_n[8]; always @ (posedge pcie_user_clk or negedge w_cq_rst_n[0]) begin if(w_cq_rst_n[0] == 0) begin r_reg_cq0hdbl <= 0; r_cq_head_update[0] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h0)) == 1) begin r_reg_cq0hdbl <= r_mreq_data[39:32]; r_cq_head_update[0] <= 1; end else r_cq_head_update[0] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[1]) begin if(w_cq_rst_n[1] == 0) begin r_reg_cq1hdbl <= 0; r_cq_head_update[1] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h1)) == 1) begin r_reg_cq1hdbl <= r_mreq_data[39:32]; r_cq_head_update[1] <= 1; end else r_cq_head_update[1] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[2]) begin if(w_cq_rst_n[2] == 0) begin r_reg_cq2hdbl <= 0; r_cq_head_update[2] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h2)) == 1) begin r_reg_cq2hdbl <= r_mreq_data[39:32]; r_cq_head_update[2] <= 1; end else r_cq_head_update[2] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[3]) begin if(w_cq_rst_n[3] == 0) begin r_reg_cq3hdbl <= 0; r_cq_head_update[3] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h3)) == 1) begin r_reg_cq3hdbl <= r_mreq_data[39:32]; r_cq_head_update[3] <= 1; end else r_cq_head_update[3] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[4]) begin if(w_cq_rst_n[4] == 0) begin r_reg_cq4hdbl <= 0; r_cq_head_update[4] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h4)) == 1) begin r_reg_cq4hdbl <= r_mreq_data[39:32]; r_cq_head_update[4] <= 1; end else r_cq_head_update[4] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[5]) begin if(w_cq_rst_n[5] == 0) begin r_reg_cq5hdbl <= 0; r_cq_head_update[5] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h5)) == 1) begin r_reg_cq5hdbl <= r_mreq_data[39:32]; r_cq_head_update[5] <= 1; end else r_cq_head_update[5] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[6]) begin if(w_cq_rst_n[6] == 0) begin r_reg_cq6hdbl <= 0; r_cq_head_update[6] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h6)) == 1) begin r_reg_cq6hdbl <= r_mreq_data[39:32]; r_cq_head_update[6] <= 1; end else r_cq_head_update[6] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[7]) begin if(w_cq_rst_n[7] == 0) begin r_reg_cq7hdbl <= 0; r_cq_head_update[7] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h7)) == 1) begin r_reg_cq7hdbl <= r_mreq_data[39:32]; r_cq_head_update[7] <= 1; end else r_cq_head_update[7] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[8]) begin if(w_cq_rst_n[8] == 0) begin r_reg_cq8hdbl <= 0; r_cq_head_update[8] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h8)) == 1) begin r_reg_cq8hdbl <= r_mreq_data[39:32]; r_cq_head_update[8] <= 1; end else r_cq_head_update[8] <= 0; end end always @ (*) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h0: r_rd_reg <= {8'h0, `D_CAP_MPSMAX, `D_CAP_MPSMIN, 3'h0, `D_CAP_CSS, `D_CAP_NSSRS, `D_CAP_DSTRD, `D_CAP_TO, 5'h0, `D_CAP_AMS, `D_CAP_CQR, `D_CAP_MQES}; 4'h1: r_rd_reg <= {31'b0, r_cq_irq_status, `D_VS_MJR, `D_VS_MNR, 8'b0}; 4'h2: r_rd_reg <= {8'b0, r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, 3'b0, r_cc_en, 31'b0, r_cq_irq_status}; 4'h3: r_rd_reg <= {28'b0, nvme_csts_shst, 1'b0, nvme_csts_rdy, 32'b0}; 4'h4: r_rd_reg <= {8'b0, r_aqa_acqs, 8'b0, r_aqa_asqs, 32'b0}; 4'h5: r_rd_reg <= {26'b0, r_asq_asqb, 2'b0}; 4'h6: r_rd_reg <= {26'b0, r_acq_acqb, 2'b0}; default: r_rd_reg <= 64'b0; endcase end always @ (*) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h0: r_rd_doorbell <= {24'b0, r_reg_cq0hdbl, 24'b0, r_reg_sq0tdbl}; 4'h1: r_rd_doorbell <= {24'b0, r_reg_cq1hdbl, 24'b0, r_reg_sq1tdbl}; 4'h2: r_rd_doorbell <= {24'b0, r_reg_cq2hdbl, 24'b0, r_reg_sq2tdbl}; 4'h3: r_rd_doorbell <= {24'b0, r_reg_cq3hdbl, 24'b0, r_reg_sq3tdbl}; 4'h4: r_rd_doorbell <= {24'b0, r_reg_cq4hdbl, 24'b0, r_reg_sq4tdbl}; 4'h5: r_rd_doorbell <= {24'b0, r_reg_cq5hdbl, 24'b0, r_reg_sq5tdbl}; 4'h6: r_rd_doorbell <= {24'b0, r_reg_cq6hdbl, 24'b0, r_reg_sq6tdbl}; 4'h7: r_rd_doorbell <= {24'b0, r_reg_cq7hdbl, 24'b0, r_reg_sq7tdbl}; 4'h8: r_rd_doorbell <= {24'b0, r_reg_cq8hdbl, 24'b0, r_reg_sq8tdbl}; default: r_rd_doorbell <= 64'b0; 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 `include "def_nvme.vh" module pcie_cntl_reg # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, output rx_np_ok, output rx_np_req, output mreq_fifo_rd_en, input [C_PCIE_DATA_WIDTH-1:0] mreq_fifo_rd_data, input mreq_fifo_empty_n, output tx_cpld_req, output [7:0] tx_cpld_tag, output [15:0] tx_cpld_req_id, output [11:2] tx_cpld_len, output [11:0] tx_cpld_bc, output [6:0] tx_cpld_laddr, output [63:0] tx_cpld_data, input tx_cpld_req_ack, output nvme_cc_en, output [1:0] nvme_cc_shn, input [1:0] nvme_csts_shst, input nvme_csts_rdy, output nvme_intms_ivms, output nvme_intmc_ivmc, input cq_irq_status, input [8:0] sq_rst_n, input [8:0] cq_rst_n, output [C_PCIE_ADDR_WIDTH-1:2] admin_sq_bs_addr, output [C_PCIE_ADDR_WIDTH-1:2] admin_cq_bs_addr, output [7:0] admin_sq_size, output [7:0] admin_cq_size, output [7:0] admin_sq_tail_ptr, output [7:0] io_sq1_tail_ptr, output [7:0] io_sq2_tail_ptr, output [7:0] io_sq3_tail_ptr, output [7:0] io_sq4_tail_ptr, output [7:0] io_sq5_tail_ptr, output [7:0] io_sq6_tail_ptr, output [7:0] io_sq7_tail_ptr, output [7:0] io_sq8_tail_ptr, output [7:0] admin_cq_head_ptr, output [7:0] io_cq1_head_ptr, output [7:0] io_cq2_head_ptr, output [7:0] io_cq3_head_ptr, output [7:0] io_cq4_head_ptr, output [7:0] io_cq5_head_ptr, output [7:0] io_cq6_head_ptr, output [7:0] io_cq7_head_ptr, output [7:0] io_cq8_head_ptr, output [8:0] cq_head_update ); localparam S_IDLE = 9'b000000001; localparam S_PCIE_RD_HEAD = 9'b000000010; localparam S_PCIE_ADDR = 9'b000000100; localparam S_PCIE_WAIT_WR_DATA = 9'b000001000; localparam S_PCIE_WR_DATA = 9'b000010000; localparam S_PCIE_MWR = 9'b000100000; localparam S_PCIE_MRD = 9'b001000000; localparam S_PCIE_CPLD_REQ = 9'b010000000; localparam S_PCIE_CPLD_ACK = 9'b100000000; reg [8:0] cur_state; reg [8:0] next_state; reg r_intms_ivms; reg r_intmc_ivmc; reg r_cq_irq_status; reg [23:20] r_cc_iocqes; reg [19:16] r_cc_iosqes; reg [15:14] r_cc_shn; reg [13:11] r_cc_asm; reg [10:7] r_cc_mps; reg [6:4] r_cc_ccs; reg [0:0] r_cc_en; reg [23:16] r_aqa_acqs; reg [7:0] r_aqa_asqs; reg [C_PCIE_ADDR_WIDTH-1:2] r_asq_asqb; reg [C_PCIE_ADDR_WIDTH-1:2] r_acq_acqb; reg [7:0] r_reg_sq0tdbl; reg [7:0] r_reg_sq1tdbl; reg [7:0] r_reg_sq2tdbl; reg [7:0] r_reg_sq3tdbl; reg [7:0] r_reg_sq4tdbl; reg [7:0] r_reg_sq5tdbl; reg [7:0] r_reg_sq6tdbl; reg [7:0] r_reg_sq7tdbl; reg [7:0] r_reg_sq8tdbl; reg [7:0] r_reg_cq0hdbl; reg [7:0] r_reg_cq1hdbl; reg [7:0] r_reg_cq2hdbl; reg [7:0] r_reg_cq3hdbl; reg [7:0] r_reg_cq4hdbl; reg [7:0] r_reg_cq5hdbl; reg [7:0] r_reg_cq6hdbl; reg [7:0] r_reg_cq7hdbl; reg [7:0] r_reg_cq8hdbl; reg [8:0] r_cq_head_update; wire [31:0] w_pcie_head0; wire [31:0] w_pcie_head1; wire [31:0] w_pcie_head2; wire [31:0] w_pcie_head3; reg [31:0] r_pcie_head2; reg [31:0] r_pcie_head3; wire [2:0] w_mreq_head_fmt; //wire [4:0] w_mreq_head_type; //wire [2:0] w_mreq_head_tc; //wire w_mreq_head_attr1; //wire w_mreq_head_th; //wire w_mreq_head_td; //wire w_mreq_head_ep; //wire [1:0] w_mreq_head_attr0; //wire [1:0] w_mreq_head_at; wire [9:0] w_mreq_head_len; wire [7:0] w_mreq_head_req_bus_num; wire [4:0] w_mreq_head_req_dev_num; wire [2:0] w_mreq_head_req_func_num; wire [15:0] w_mreq_head_req_id; wire [7:0] w_mreq_head_tag; wire [3:0] w_mreq_head_last_be; wire [3:0] w_mreq_head_1st_be; //reg [4:0] r_rx_np_req_cnt; //reg r_rx_np_req; wire w_mwr; wire w_4dw; reg [2:0] r_mreq_head_fmt; reg [9:0] r_mreq_head_len; reg [15:0] r_mreq_head_req_id; reg [7:0] r_mreq_head_tag; reg [3:0] r_mreq_head_last_be; reg [3:0] r_mreq_head_1st_be; reg [12:0] r_mreq_addr; reg [63:0] r_mreq_data; reg [3:0] r_cpld_bc; reg r_lbytes_en; reg r_hbytes_en; reg r_wr_reg; reg r_wr_doorbell; reg r_tx_cpld_req; reg [63:0] r_rd_data; reg [63:0] r_rd_reg; reg [63:0] r_rd_doorbell; reg r_mreq_fifo_rd_en; wire [8:0] w_sq_rst_n; wire [8:0] w_cq_rst_n; //pcie mrd or mwr, memory rd/wr request assign w_pcie_head0 = mreq_fifo_rd_data[31:0]; assign w_pcie_head1 = mreq_fifo_rd_data[63:32]; assign w_pcie_head2 = mreq_fifo_rd_data[95:64]; assign w_pcie_head3 = mreq_fifo_rd_data[127:96]; assign w_mreq_head_fmt = w_pcie_head0[31:29]; //assign w_mreq_head_type = w_pcie_head0[28:24]; //assign w_mreq_head_tc = w_pcie_head0[22:20]; //assign w_mreq_head_attr1 = w_pcie_head0[18]; //assign w_mreq_head_th = w_pcie_head0[16]; //assign w_mreq_head_td = w_pcie_head0[15]; //assign w_mreq_head_ep = w_pcie_head0[14]; //assign w_mreq_head_attr0 = w_pcie_head0[13:12]; //assign w_mreq_head_at = w_pcie_head0[11:10]; assign w_mreq_head_len = w_pcie_head0[9:0]; assign w_mreq_head_req_bus_num = w_pcie_head1[31:24]; assign w_mreq_head_req_dev_num = w_pcie_head1[23:19]; assign w_mreq_head_req_func_num = w_pcie_head1[18:16]; assign w_mreq_head_req_id = {w_mreq_head_req_bus_num, w_mreq_head_req_dev_num, w_mreq_head_req_func_num}; assign w_mreq_head_tag = w_pcie_head1[15:8]; assign w_mreq_head_last_be = w_pcie_head1[7:4]; assign w_mreq_head_1st_be = w_pcie_head1[3:0]; assign w_mwr = r_mreq_head_fmt[1]; assign w_4dw = r_mreq_head_fmt[0]; assign tx_cpld_req = r_tx_cpld_req; assign tx_cpld_tag = r_mreq_head_tag; assign tx_cpld_req_id = r_mreq_head_req_id; assign tx_cpld_len = {8'b0, r_mreq_head_len[1:0]}; assign tx_cpld_bc = {8'b0, r_cpld_bc}; assign tx_cpld_laddr = r_mreq_addr[6:0]; assign tx_cpld_data = (r_mreq_addr[2] == 1) ? {32'b0, r_rd_data[63:32]} : r_rd_data; assign rx_np_ok = 1'b1; assign rx_np_req = 1'b1; assign mreq_fifo_rd_en = r_mreq_fifo_rd_en; assign admin_sq_bs_addr = r_asq_asqb; assign admin_cq_bs_addr = r_acq_acqb; assign nvme_cc_en = r_cc_en; assign nvme_cc_shn = r_cc_shn; assign nvme_intms_ivms = r_intms_ivms; assign nvme_intmc_ivmc = r_intmc_ivmc; assign admin_sq_size = r_aqa_asqs; assign admin_cq_size = r_aqa_acqs; assign admin_sq_tail_ptr = r_reg_sq0tdbl; assign io_sq1_tail_ptr = r_reg_sq1tdbl; assign io_sq2_tail_ptr = r_reg_sq2tdbl; assign io_sq3_tail_ptr = r_reg_sq3tdbl; assign io_sq4_tail_ptr = r_reg_sq4tdbl; assign io_sq5_tail_ptr = r_reg_sq5tdbl; assign io_sq6_tail_ptr = r_reg_sq6tdbl; assign io_sq7_tail_ptr = r_reg_sq7tdbl; assign io_sq8_tail_ptr = r_reg_sq8tdbl; assign admin_cq_head_ptr = r_reg_cq0hdbl; assign io_cq1_head_ptr = r_reg_cq1hdbl; assign io_cq2_head_ptr = r_reg_cq2hdbl; assign io_cq3_head_ptr = r_reg_cq3hdbl; assign io_cq4_head_ptr = r_reg_cq4hdbl; assign io_cq5_head_ptr = r_reg_cq5hdbl; assign io_cq6_head_ptr = r_reg_cq6hdbl; assign io_cq7_head_ptr = r_reg_cq7hdbl; assign io_cq8_head_ptr = r_reg_cq8hdbl; assign cq_head_update = r_cq_head_update; always @ (posedge pcie_user_clk) begin r_cq_irq_status <= cq_irq_status; end 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(mreq_fifo_empty_n == 1) next_state <= S_PCIE_RD_HEAD; else next_state <= S_IDLE; end S_PCIE_RD_HEAD: begin next_state <= S_PCIE_ADDR; end S_PCIE_ADDR: begin if(w_mwr == 1) begin if(w_4dw == 1 || r_mreq_head_len[1] == 1) begin if(mreq_fifo_empty_n == 1) next_state <= S_PCIE_WR_DATA; else next_state <= S_PCIE_WAIT_WR_DATA; end else next_state <= S_PCIE_MWR; end else begin next_state <= S_PCIE_MRD; end end S_PCIE_WAIT_WR_DATA: begin if(mreq_fifo_empty_n == 1) next_state <= S_PCIE_WR_DATA; else next_state <= S_PCIE_WAIT_WR_DATA; end S_PCIE_WR_DATA: begin next_state <= S_PCIE_MWR; end S_PCIE_MWR: begin next_state <= S_IDLE; end S_PCIE_MRD: begin next_state <= S_PCIE_CPLD_REQ; end S_PCIE_CPLD_REQ: begin next_state <= S_PCIE_CPLD_ACK; end S_PCIE_CPLD_ACK: begin if(tx_cpld_req_ack == 1) next_state <= S_IDLE; else next_state <= S_PCIE_CPLD_ACK; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_RD_HEAD: begin r_mreq_head_fmt <= w_mreq_head_fmt; r_mreq_head_len <= w_mreq_head_len; r_mreq_head_req_id <= w_mreq_head_req_id; r_mreq_head_tag <= w_mreq_head_tag; r_mreq_head_last_be <= w_mreq_head_last_be; r_mreq_head_1st_be <= w_mreq_head_1st_be; r_pcie_head2 <= w_pcie_head2; r_pcie_head3 <= w_pcie_head3; end S_PCIE_ADDR: begin if(w_4dw == 1) begin r_mreq_addr[12:2] <= r_pcie_head3[12:2]; r_lbytes_en <= ~r_pcie_head3[2] & (r_pcie_head3[11:7] == 0); r_hbytes_en <= (r_pcie_head3[2] | r_mreq_head_len[1]) & (r_pcie_head3[11:7] == 0); end else begin r_mreq_addr[12:2] <= r_pcie_head2[12:2]; r_lbytes_en <= ~r_pcie_head2[2] & (r_pcie_head2[11:7] == 0);; r_hbytes_en <= (r_pcie_head2[2] | r_mreq_head_len[1]) & (r_pcie_head2[11:7] == 0); if(r_pcie_head2[2] == 1) r_mreq_data[63:32] <= {r_pcie_head3[7:0], r_pcie_head3[15:8], r_pcie_head3[23:16], r_pcie_head3[31:24]}; else r_mreq_data[31:0] <= {r_pcie_head3[7:0], r_pcie_head3[15:8], r_pcie_head3[23:16], r_pcie_head3[31:24]}; end end S_PCIE_WAIT_WR_DATA: begin end S_PCIE_WR_DATA: begin if(w_4dw == 1) begin if(r_mreq_addr[2] == 1) r_mreq_data[63:32] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; else begin r_mreq_data[31:0] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; r_mreq_data[63:32] <= {mreq_fifo_rd_data[39:32], mreq_fifo_rd_data[47:40], mreq_fifo_rd_data[55:48], mreq_fifo_rd_data[63:56]}; end end else r_mreq_data[63:32] <= {mreq_fifo_rd_data[7:0], mreq_fifo_rd_data[15:8], mreq_fifo_rd_data[23:16], mreq_fifo_rd_data[31:24]}; end S_PCIE_MWR: begin end S_PCIE_MRD: begin if(r_lbytes_en | r_hbytes_en) begin if(r_mreq_addr[12] == 1) begin r_rd_data[31:0] <= {r_rd_doorbell[7:0], r_rd_doorbell[15:8], r_rd_doorbell[23:16], r_rd_doorbell[31:24]}; r_rd_data[63:32] <= {r_rd_doorbell[39:32], r_rd_doorbell[47:40], r_rd_doorbell[55:48], r_rd_doorbell[63:56]}; end else begin r_rd_data[31:0] <= {r_rd_reg[7:0], r_rd_reg[15:8], r_rd_reg[23:16], r_rd_reg[31:24]}; r_rd_data[63:32] <= {r_rd_reg[39:32], r_rd_reg[47:40], r_rd_reg[55:48], r_rd_reg[63:56]}; end end else r_rd_data <= 64'b0; if(r_mreq_head_1st_be[0] == 1) r_mreq_addr[1:0] <= 2'b00; else if(r_mreq_head_1st_be[1] == 1) r_mreq_addr[1:0] <= 2'b01; else if(r_mreq_head_1st_be[2] == 1) r_mreq_addr[1:0] <= 2'b10; else r_mreq_addr[1:0] <= 2'b11; r_cpld_bc <= ((r_mreq_head_1st_be[0] + r_mreq_head_1st_be[1]) + (r_mreq_head_1st_be[2] + r_mreq_head_1st_be[3])) + ((r_mreq_head_last_be[0] + r_mreq_head_last_be[1]) + (r_mreq_head_last_be[2] + r_mreq_head_last_be[3])); end S_PCIE_CPLD_REQ: begin end S_PCIE_CPLD_ACK: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_RD_HEAD: begin r_mreq_fifo_rd_en <= 1; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_ADDR: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_WAIT_WR_DATA: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_WR_DATA: begin r_mreq_fifo_rd_en <= 1; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_MWR: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= ~r_mreq_addr[12]; r_wr_doorbell <= r_mreq_addr[12]; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_MRD: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end S_PCIE_CPLD_REQ: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 1; //r_rx_np_req <= 1; end S_PCIE_CPLD_ACK: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end default: begin r_mreq_fifo_rd_en <= 0; r_wr_reg <= 0; r_wr_doorbell <= 0; r_tx_cpld_req <= 0; //r_rx_np_req <= 0; end endcase end always @ (posedge pcie_user_clk or negedge pcie_user_rst_n) begin if(pcie_user_rst_n == 0) begin r_intms_ivms <= 0; r_intmc_ivmc <= 0; {r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, r_cc_en} <= 0; {r_aqa_acqs, r_aqa_asqs} <= 0; r_asq_asqb <= 0; r_acq_acqb <= 0; end else begin if(r_wr_reg == 1) begin if(r_lbytes_en == 1) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h5: r_asq_asqb[31:2] <= r_mreq_data[31:2]; 4'h6: r_acq_acqb[31:2] <= r_mreq_data[31:2]; endcase if(r_mreq_addr[6:3] == 4'h1) r_intmc_ivmc <= r_mreq_data[0]; else r_intmc_ivmc <= 0; end if(r_hbytes_en == 1) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h2: {r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, r_cc_en} <= {r_mreq_data[55:52], r_mreq_data[51:48], r_mreq_data[47:46], r_mreq_data[45:43], r_mreq_data[42:39], r_mreq_data[38:36], r_mreq_data[32]}; 4'h4: {r_aqa_acqs, r_aqa_asqs} <= {r_mreq_data[55:48], r_mreq_data[39:32]}; 4'h5: r_asq_asqb[C_PCIE_ADDR_WIDTH-1:32] <= r_mreq_data[C_PCIE_ADDR_WIDTH-1:32]; 4'h6: r_acq_acqb[C_PCIE_ADDR_WIDTH-1:32] <= r_mreq_data[C_PCIE_ADDR_WIDTH-1:32]; endcase if(r_mreq_addr[6:3] == 4'h1) r_intms_ivms <= r_mreq_data[32]; else r_intms_ivms <= 0; end end else begin r_intms_ivms <= 0; r_intmc_ivmc <= 0; end end end assign w_sq_rst_n[0] = pcie_user_rst_n & sq_rst_n[0]; assign w_sq_rst_n[1] = pcie_user_rst_n & sq_rst_n[1]; assign w_sq_rst_n[2] = pcie_user_rst_n & sq_rst_n[2]; assign w_sq_rst_n[3] = pcie_user_rst_n & sq_rst_n[3]; assign w_sq_rst_n[4] = pcie_user_rst_n & sq_rst_n[4]; assign w_sq_rst_n[5] = pcie_user_rst_n & sq_rst_n[5]; assign w_sq_rst_n[6] = pcie_user_rst_n & sq_rst_n[6]; assign w_sq_rst_n[7] = pcie_user_rst_n & sq_rst_n[7]; assign w_sq_rst_n[8] = pcie_user_rst_n & sq_rst_n[8]; always @ (posedge pcie_user_clk or negedge w_sq_rst_n[0]) begin if(w_sq_rst_n[0] == 0) begin r_reg_sq0tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h0)) == 1) r_reg_sq0tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[1]) begin if(w_sq_rst_n[1] == 0) begin r_reg_sq1tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h1)) == 1) r_reg_sq1tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[2]) begin if(w_sq_rst_n[2] == 0) begin r_reg_sq2tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h2)) == 1) r_reg_sq2tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[3]) begin if(w_sq_rst_n[3] == 0) begin r_reg_sq3tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h3)) == 1) r_reg_sq3tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[4]) begin if(w_sq_rst_n[4] == 0) begin r_reg_sq4tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h4)) == 1) r_reg_sq4tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[5]) begin if(w_sq_rst_n[5] == 0) begin r_reg_sq5tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h5)) == 1) r_reg_sq5tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[6]) begin if(w_sq_rst_n[6] == 0) begin r_reg_sq6tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h6)) == 1) r_reg_sq6tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[7]) begin if(w_sq_rst_n[7] == 0) begin r_reg_sq7tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h7)) == 1) r_reg_sq7tdbl <= r_mreq_data[7:0]; end end always @ (posedge pcie_user_clk or negedge w_sq_rst_n[8]) begin if(w_sq_rst_n[8] == 0) begin r_reg_sq8tdbl <= 0; end else begin if((r_wr_doorbell & r_lbytes_en & (r_mreq_addr[6:3] == 4'h8)) == 1) r_reg_sq8tdbl <= r_mreq_data[7:0]; end end assign w_cq_rst_n[0] = pcie_user_rst_n & cq_rst_n[0]; assign w_cq_rst_n[1] = pcie_user_rst_n & cq_rst_n[1]; assign w_cq_rst_n[2] = pcie_user_rst_n & cq_rst_n[2]; assign w_cq_rst_n[3] = pcie_user_rst_n & cq_rst_n[3]; assign w_cq_rst_n[4] = pcie_user_rst_n & cq_rst_n[4]; assign w_cq_rst_n[5] = pcie_user_rst_n & cq_rst_n[5]; assign w_cq_rst_n[6] = pcie_user_rst_n & cq_rst_n[6]; assign w_cq_rst_n[7] = pcie_user_rst_n & cq_rst_n[7]; assign w_cq_rst_n[8] = pcie_user_rst_n & cq_rst_n[8]; always @ (posedge pcie_user_clk or negedge w_cq_rst_n[0]) begin if(w_cq_rst_n[0] == 0) begin r_reg_cq0hdbl <= 0; r_cq_head_update[0] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h0)) == 1) begin r_reg_cq0hdbl <= r_mreq_data[39:32]; r_cq_head_update[0] <= 1; end else r_cq_head_update[0] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[1]) begin if(w_cq_rst_n[1] == 0) begin r_reg_cq1hdbl <= 0; r_cq_head_update[1] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h1)) == 1) begin r_reg_cq1hdbl <= r_mreq_data[39:32]; r_cq_head_update[1] <= 1; end else r_cq_head_update[1] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[2]) begin if(w_cq_rst_n[2] == 0) begin r_reg_cq2hdbl <= 0; r_cq_head_update[2] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h2)) == 1) begin r_reg_cq2hdbl <= r_mreq_data[39:32]; r_cq_head_update[2] <= 1; end else r_cq_head_update[2] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[3]) begin if(w_cq_rst_n[3] == 0) begin r_reg_cq3hdbl <= 0; r_cq_head_update[3] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h3)) == 1) begin r_reg_cq3hdbl <= r_mreq_data[39:32]; r_cq_head_update[3] <= 1; end else r_cq_head_update[3] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[4]) begin if(w_cq_rst_n[4] == 0) begin r_reg_cq4hdbl <= 0; r_cq_head_update[4] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h4)) == 1) begin r_reg_cq4hdbl <= r_mreq_data[39:32]; r_cq_head_update[4] <= 1; end else r_cq_head_update[4] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[5]) begin if(w_cq_rst_n[5] == 0) begin r_reg_cq5hdbl <= 0; r_cq_head_update[5] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h5)) == 1) begin r_reg_cq5hdbl <= r_mreq_data[39:32]; r_cq_head_update[5] <= 1; end else r_cq_head_update[5] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[6]) begin if(w_cq_rst_n[6] == 0) begin r_reg_cq6hdbl <= 0; r_cq_head_update[6] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h6)) == 1) begin r_reg_cq6hdbl <= r_mreq_data[39:32]; r_cq_head_update[6] <= 1; end else r_cq_head_update[6] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[7]) begin if(w_cq_rst_n[7] == 0) begin r_reg_cq7hdbl <= 0; r_cq_head_update[7] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h7)) == 1) begin r_reg_cq7hdbl <= r_mreq_data[39:32]; r_cq_head_update[7] <= 1; end else r_cq_head_update[7] <= 0; end end always @ (posedge pcie_user_clk or negedge w_cq_rst_n[8]) begin if(w_cq_rst_n[8] == 0) begin r_reg_cq8hdbl <= 0; r_cq_head_update[8] <= 0; end else begin if((r_wr_doorbell & r_hbytes_en & (r_mreq_addr[6:3] == 4'h8)) == 1) begin r_reg_cq8hdbl <= r_mreq_data[39:32]; r_cq_head_update[8] <= 1; end else r_cq_head_update[8] <= 0; end end always @ (*) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h0: r_rd_reg <= {8'h0, `D_CAP_MPSMAX, `D_CAP_MPSMIN, 3'h0, `D_CAP_CSS, `D_CAP_NSSRS, `D_CAP_DSTRD, `D_CAP_TO, 5'h0, `D_CAP_AMS, `D_CAP_CQR, `D_CAP_MQES}; 4'h1: r_rd_reg <= {31'b0, r_cq_irq_status, `D_VS_MJR, `D_VS_MNR, 8'b0}; 4'h2: r_rd_reg <= {8'b0, r_cc_iocqes, r_cc_iosqes, r_cc_shn, r_cc_asm, r_cc_mps, r_cc_ccs, 3'b0, r_cc_en, 31'b0, r_cq_irq_status}; 4'h3: r_rd_reg <= {28'b0, nvme_csts_shst, 1'b0, nvme_csts_rdy, 32'b0}; 4'h4: r_rd_reg <= {8'b0, r_aqa_acqs, 8'b0, r_aqa_asqs, 32'b0}; 4'h5: r_rd_reg <= {26'b0, r_asq_asqb, 2'b0}; 4'h6: r_rd_reg <= {26'b0, r_acq_acqb, 2'b0}; default: r_rd_reg <= 64'b0; endcase end always @ (*) begin case(r_mreq_addr[6:3]) // synthesis parallel_case 4'h0: r_rd_doorbell <= {24'b0, r_reg_cq0hdbl, 24'b0, r_reg_sq0tdbl}; 4'h1: r_rd_doorbell <= {24'b0, r_reg_cq1hdbl, 24'b0, r_reg_sq1tdbl}; 4'h2: r_rd_doorbell <= {24'b0, r_reg_cq2hdbl, 24'b0, r_reg_sq2tdbl}; 4'h3: r_rd_doorbell <= {24'b0, r_reg_cq3hdbl, 24'b0, r_reg_sq3tdbl}; 4'h4: r_rd_doorbell <= {24'b0, r_reg_cq4hdbl, 24'b0, r_reg_sq4tdbl}; 4'h5: r_rd_doorbell <= {24'b0, r_reg_cq5hdbl, 24'b0, r_reg_sq5tdbl}; 4'h6: r_rd_doorbell <= {24'b0, r_reg_cq6hdbl, 24'b0, r_reg_sq6tdbl}; 4'h7: r_rd_doorbell <= {24'b0, r_reg_cq7hdbl, 24'b0, r_reg_sq7tdbl}; 4'h8: r_rd_doorbell <= {24'b0, r_reg_cq8hdbl, 24'b0, r_reg_sq8tdbl}; default: r_rd_doorbell <= 64'b0; 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_fifo # ( parameter P_FIFO_WR_DATA_WIDTH = 64, parameter P_FIFO_RD_DATA_WIDTH = 128, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input alloc_en, input [9:4] alloc_len, input wr_en, input [P_FIFO_WR_DATA_WIDTH-1:0] wr_data, 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_WR_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; reg [P_FIFO_WR_DEPTH_WIDTH:0] r_rear_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_full_addr; wire [1:0] w_wr_en; (* 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_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_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_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 w_invalid_space = r_front_sync_addr - r_rear_full_addr; assign full_n = (w_invalid_space >= alloc_len); assign w_wr_en[0] = wr_en & ~r_rear_addr[0]; assign w_wr_en[1] = wr_en & r_rear_addr[0]; always @(posedge wr_clk or negedge wr_rst_n) begin if (wr_rst_n == 0) begin r_rear_addr <= 0; r_rear_full_addr <= 0; end else begin if (alloc_en == 1) r_rear_full_addr <= r_rear_full_addr + alloc_len; if (wr_en == 1) r_rear_addr <= r_rear_addr + 1; end end 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[P_FIFO_DEPTH_WIDTH-1:0] = (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[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 <= r_rear_addr[P_FIFO_WR_DEPTH_WIDTH:1]; 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_DEPTH_WIDTH]; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= r_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; 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/2; localparam LP_WRITE_WIDTH = P_FIFO_WR_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_WR_DEPTH_WIDTH-1:1]; 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], r_rear_addr[P_FIFO_WR_DEPTH_WIDTH-1:1]}; 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[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 (w_wr_en[0]) ); 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 (rd_data[P_FIFO_RD_DATA_WIDTH-1:LP_READ_WIDTH]), .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 (w_wr_en[1]) ); 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_fifo # ( parameter P_FIFO_WR_DATA_WIDTH = 64, parameter P_FIFO_RD_DATA_WIDTH = 128, parameter P_FIFO_DEPTH_WIDTH = 9 ) ( input wr_clk, input wr_rst_n, input alloc_en, input [9:4] alloc_len, input wr_en, input [P_FIFO_WR_DATA_WIDTH-1:0] wr_data, 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_WR_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; reg [P_FIFO_WR_DEPTH_WIDTH:0] r_rear_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_full_addr; wire [1:0] w_wr_en; (* 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_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_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_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 w_invalid_space = r_front_sync_addr - r_rear_full_addr; assign full_n = (w_invalid_space >= alloc_len); assign w_wr_en[0] = wr_en & ~r_rear_addr[0]; assign w_wr_en[1] = wr_en & r_rear_addr[0]; always @(posedge wr_clk or negedge wr_rst_n) begin if (wr_rst_n == 0) begin r_rear_addr <= 0; r_rear_full_addr <= 0; end else begin if (alloc_en == 1) r_rear_full_addr <= r_rear_full_addr + alloc_len; if (wr_en == 1) r_rear_addr <= r_rear_addr + 1; end end 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[P_FIFO_DEPTH_WIDTH-1:0] = (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[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 <= r_rear_addr[P_FIFO_WR_DEPTH_WIDTH:1]; 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_DEPTH_WIDTH]; r_front_sync_data[P_FIFO_DEPTH_WIDTH-1:0] <= r_front_addr[P_FIFO_DEPTH_WIDTH-1:0]; 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/2; localparam LP_WRITE_WIDTH = P_FIFO_WR_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_WR_DEPTH_WIDTH-1:1]; 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], r_rear_addr[P_FIFO_WR_DEPTH_WIDTH-1:1]}; 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[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 (w_wr_en[0]) ); 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 (rd_data[P_FIFO_RD_DATA_WIDTH-1:LP_READ_WIDTH]), .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 (w_wr_en[1]) ); 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 (/*AUTOARG*/ // Inputs rst_sync_l, rst_both_l, rst_async_l, d, clk ); /*AUTOINPUT*/ // Beginning of automatic inputs (from unused autoinst inputs) input clk; // To sub1 of sub1.v, ... input d; // To sub1 of sub1.v, ... input rst_async_l; // To sub2 of sub2.v input rst_both_l; // To sub1 of sub1.v, ... input rst_sync_l; // To sub1 of sub1.v // End of automatics sub1 sub1 (/*AUTOINST*/ // Inputs .clk (clk), .rst_both_l (rst_both_l), .rst_sync_l (rst_sync_l), .d (d)); sub2 sub2 (/*AUTOINST*/ // Inputs .clk (clk), .rst_both_l (rst_both_l), .rst_async_l (rst_async_l), .d (d)); endmodule module sub1 (/*AUTOARG*/ // Inputs clk, rst_both_l, rst_sync_l, d ); input clk; input rst_both_l; input rst_sync_l; //input rst_async_l; input d; reg q1; reg q2; always @(posedge clk) begin if (~rst_sync_l) begin /*AUTORESET*/ // Beginning of autoreset for uninitialized flops q1 <= 1'h0; // End of automatics end else begin q1 <= d; end end always @(posedge clk) begin q2 <= (~rst_both_l) ? 1'b0 : d; if (0 && q1 && q2) ; end endmodule module sub2 (/*AUTOARG*/ // Inputs clk, rst_both_l, rst_async_l, d ); input clk; input rst_both_l; //input rst_sync_l; input rst_async_l; input d; reg q1; reg q2; reg q3; always @(posedge clk or negedge rst_async_l) begin if (~rst_async_l) begin /*AUTORESET*/ // Beginning of autoreset for uninitialized flops q1 <= 1'h0; // End of automatics end else begin q1 <= d; end end always @(posedge clk or negedge rst_both_l) begin q2 <= (~rst_both_l) ? 1'b0 : d; end // Make there be more async uses than sync uses always @(posedge clk or negedge rst_both_l) begin q3 <= (~rst_both_l) ? 1'b0 : d; if (0 && q1 && q2 && q3) ; end endmodule
// DESCRIPTION: Verilator: Verilog Test module // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2010 by Wilson Snyder. // bug291 module t (/*AUTOARG*/ // Inputs clk ); input clk; integer out18; /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire out1; // From test of Test.v wire out19; // From test of Test.v wire out1b; // From test of Test.v // End of automatics Test test (/*AUTOINST*/ // Outputs .out1 (out1), .out18 (out18), .out1b (out1b), .out19 (out19)); // Test loop always @ (posedge clk) begin if (out1 !== 1'b1) $stop; if (out18 !== 32'h18) $stop; if (out1b !== 1'b1) $stop; if (out19 !== 1'b1) $stop; $write("*-* All Finished *-*\n"); $finish; end endmodule module Test ( output wire out1 = 1'b1, output integer out18 = 32'h18, output var out1b = 1'b1, output var logic out19 = 1'b1 ); endmodule
// DESCRIPTION: Verilator: Verilog Test module // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2010 by Wilson Snyder. // bug291 module t (/*AUTOARG*/ // Inputs clk ); input clk; integer out18; /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire out1; // From test of Test.v wire out19; // From test of Test.v wire out1b; // From test of Test.v // End of automatics Test test (/*AUTOINST*/ // Outputs .out1 (out1), .out18 (out18), .out1b (out1b), .out19 (out19)); // Test loop always @ (posedge clk) begin if (out1 !== 1'b1) $stop; if (out18 !== 32'h18) $stop; if (out1b !== 1'b1) $stop; if (out19 !== 1'b1) $stop; $write("*-* All Finished *-*\n"); $finish; end endmodule module Test ( output wire out1 = 1'b1, output integer out18 = 32'h18, output var out1b = 1'b1, output var logic out19 = 1'b1 ); endmodule
(** * PE: Partial Evaluation *) (* Chapter author/maintainer: Chung-chieh Shan *) (** Equiv.v introduced constant folding as an example of a program transformation and proved that it preserves the meaning of the program. Constant folding operates on manifest constants such as [ANum] expressions. For example, it simplifies the command [Y ::= APlus (ANum 3) (ANum 1)] to the command [Y ::= ANum 4]. However, it does not propagate known constants along data flow. For example, it does not simplify the sequence X ::= ANum 3;; Y ::= APlus (AId X) (ANum 1) to X ::= ANum 3;; Y ::= ANum 4 because it forgets that [X] is [3] by the time it gets to [Y]. We naturally want to enhance constant folding so that it propagates known constants and uses them to simplify programs. Doing so constitutes a rudimentary form of _partial evaluation_. As we will see, partial evaluation is so called because it is like running a program, except only part of the program can be evaluated because only part of the input to the program is known. For example, we can only simplify the program X ::= ANum 3;; Y ::= AMinus (APlus (AId X) (ANum 1)) (AId Y) to X ::= ANum 3;; Y ::= AMinus (ANum 4) (AId Y) without knowing the initial value of [Y]. *) Require Export Imp. Require Import FunctionalExtensionality. (* ####################################################### *) (** * Generalizing Constant Folding *) (** The starting point of partial evaluation is to represent our partial knowledge about the state. For example, between the two assignments above, the partial evaluator may know only that [X] is [3] and nothing about any other variable. *) (** ** Partial States *) (** Conceptually speaking, we can think of such partial states as the type [id -> option nat] (as opposed to the type [id -> nat] of concrete, full states). However, in addition to looking up and updating the values of individual variables in a partial state, we may also want to compare two partial states to see if and where they differ, to handle conditional control flow. It is not possible to compare two arbitrary functions in this way, so we represent partial states in a more concrete format: as a list of [id * nat] pairs. *) Definition pe_state := list (id * nat). (** The idea is that a variable [id] appears in the list if and only if we know its current [nat] value. The [pe_lookup] function thus interprets this concrete representation. (If the same variable [id] appears multiple times in the list, the first occurrence wins, but we will define our partial evaluator to never construct such a [pe_state].) *) Fixpoint pe_lookup (pe_st : pe_state) (V:id) : option nat := match pe_st with | [] => None | (V',n')::pe_st => if eq_id_dec V V' then Some n' else pe_lookup pe_st V end. (** For example, [empty_pe_state] represents complete ignorance about every variable -- the function that maps every [id] to [None]. *) Definition empty_pe_state : pe_state := []. (** More generally, if the [list] representing a [pe_state] does not contain some [id], then that [pe_state] must map that [id] to [None]. Before we prove this fact, we first define a useful tactic for reasoning with [id] equality. The tactic compare V V' SCase means to reason by cases over [eq_id_dec V V']. In the case where [V = V'], the tactic substitutes [V] for [V'] throughout. *) Tactic Notation "compare" ident(i) ident(j) ident(c) := let H := fresh "Heq" i j in destruct (eq_id_dec i j); [ Case_aux c "equal"; subst j | Case_aux c "not equal" ]. Theorem pe_domain: forall pe_st V n, pe_lookup pe_st V = Some n -> In V (map (@fst _ _) pe_st). Proof. intros pe_st V n H. induction pe_st as [| [V' n'] pe_st]. Case "[]". inversion H. Case "::". simpl in H. simpl. compare V V' SCase; auto. Qed. (** *** Aside on [In]. We will make heavy use of the [In] predicate from the standard library. [In] is equivalent to the [appears_in] predicate introduced in Logic.v, but defined using a [Fixpoint] rather than an [Inductive]. *) Print In. (* ===> Fixpoint In {A:Type} (a: A) (l:list A) : Prop := match l with | [] => False | b :: m => b = a \/ In a m end : forall A : Type, A -> list A -> Prop *) (** [In] comes with various useful lemmas. *) Check in_or_app. (* ===> in_or_app: forall (A : Type) (l m : list A) (a : A), In a l \/ In a m -> In a (l ++ m) *) Check filter_In. (* ===> filter_In : forall (A : Type) (f : A -> bool) (x : A) (l : list A), In x (filter f l) <-> In x l /\ f x = true *) Check in_dec. (* ===> in_dec : forall A : Type, (forall x y : A, {x = y} + {x <> y}) -> forall (a : A) (l : list A), {In a l} + {~ In a l}] *) (** Note that we can compute with [in_dec], just as with [eq_id_dec]. *) (** ** Arithmetic Expressions *) (** Partial evaluation of [aexp] is straightforward -- it is basically the same as constant folding, [fold_constants_aexp], except that sometimes the partial state tells us the current value of a variable and we can replace it by a constant expression. *) Fixpoint pe_aexp (pe_st : pe_state) (a : aexp) : aexp := match a with | ANum n => ANum n | AId i => match pe_lookup pe_st i with (* <----- NEW *) | Some n => ANum n | None => AId i end | APlus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 + n2) | (a1', a2') => APlus a1' a2' end | AMinus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 - n2) | (a1', a2') => AMinus a1' a2' end | AMult a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 * n2) | (a1', a2') => AMult a1' a2' end end. (** This partial evaluator folds constants but does not apply the associativity of addition. *) Example test_pe_aexp1: pe_aexp [(X,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (ANum 4) (AId Y). Proof. reflexivity. Qed. Example text_pe_aexp2: pe_aexp [(Y,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (APlus (AId X) (ANum 1)) (ANum 3). Proof. reflexivity. Qed. (** Now, in what sense is [pe_aexp] correct? It is reasonable to define the correctness of [pe_aexp] as follows: whenever a full state [st:state] is _consistent_ with a partial state [pe_st:pe_state] (in other words, every variable to which [pe_st] assigns a value is assigned the same value by [st]), evaluating [a] and evaluating [pe_aexp pe_st a] in [st] yields the same result. This statement is indeed true. *) Definition pe_consistent (st:state) (pe_st:pe_state) := forall V n, Some n = pe_lookup pe_st V -> st V = n. Theorem pe_aexp_correct_weak: forall st pe_st, pe_consistent st pe_st -> forall a, aeval st a = aeval st (pe_aexp pe_st a). Proof. unfold pe_consistent. intros st pe_st H a. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId *) Case "AId". remember (pe_lookup pe_st i) as l. destruct l. SCase "Some". rewrite H with (n:=n) by apply Heql. reflexivity. SCase "None". reflexivity. Qed. (** However, we will soon want our partial evaluator to remove assignments. For example, it will simplify X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to just Y ::= AMinus (ANum 3) (AId Y);; X ::= ANum 4 by delaying the assignment to [X] until the end. To accomplish this simplification, we need the result of partial evaluating pe_aexp [(X,3)] (AMinus (AId X) (AId Y)) to be equal to [AMinus (ANum 3) (AId Y)] and _not_ the original expression [AMinus (AId X) (AId Y)]. After all, it would be incorrect, not just inefficient, to transform X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 even though the output expressions [AMinus (ANum 3) (AId Y)] and [AMinus (AId X) (AId Y)] both satisfy the correctness criterion that we just proved. Indeed, if we were to just define [pe_aexp pe_st a = a] then the theorem [pe_aexp_correct'] would already trivially hold. Instead, we want to prove that the [pe_aexp] is correct in a stronger sense: evaluating the expression produced by partial evaluation ([aeval st (pe_aexp pe_st a)]) must not depend on those parts of the full state [st] that are already specified in the partial state [pe_st]. To be more precise, let us define a function [pe_override], which updates [st] with the contents of [pe_st]. In other words, [pe_override] carries out the assignments listed in [pe_st] on top of [st]. *) Fixpoint pe_override (st:state) (pe_st:pe_state) : state := match pe_st with | [] => st | (V,n)::pe_st => update (pe_override st pe_st) V n end. Example test_pe_override: pe_override (update empty_state Y 1) [(X,3);(Z,2)] = update (update (update empty_state Y 1) Z 2) X 3. Proof. reflexivity. Qed. (** Although [pe_override] operates on a concrete [list] representing a [pe_state], its behavior is defined entirely by the [pe_lookup] interpretation of the [pe_state]. *) Theorem pe_override_correct: forall st pe_st V0, pe_override st pe_st V0 = match pe_lookup pe_st V0 with | Some n => n | None => st V0 end. Proof. intros. induction pe_st as [| [V n] pe_st]. reflexivity. simpl in *. unfold update. compare V0 V Case; auto. rewrite eq_id; auto. rewrite neq_id; auto. Qed. (** We can relate [pe_consistent] to [pe_override] in two ways. First, overriding a state with a partial state always gives a state that is consistent with the partial state. Second, if a state is already consistent with a partial state, then overriding the state with the partial state gives the same state. *) Theorem pe_override_consistent: forall st pe_st, pe_consistent (pe_override st pe_st) pe_st. Proof. intros st pe_st V n H. rewrite pe_override_correct. destruct (pe_lookup pe_st V); inversion H. reflexivity. Qed. Theorem pe_consistent_override: forall st pe_st, pe_consistent st pe_st -> forall V, st V = pe_override st pe_st V. Proof. intros st pe_st H V. rewrite pe_override_correct. remember (pe_lookup pe_st V) as l. destruct l; auto. Qed. (** Now we can state and prove that [pe_aexp] is correct in the stronger sense that will help us define the rest of the partial evaluator. Intuitively, running a program using partial evaluation is a two-stage process. In the first, _static_ stage, we partially evaluate the given program with respect to some partial state to get a _residual_ program. In the second, _dynamic_ stage, we evaluate the residual program with respect to the rest of the state. This dynamic state provides values for those variables that are unknown in the static (partial) state. Thus, the residual program should be equivalent to _prepending_ the assignments listed in the partial state to the original program. *) Theorem pe_aexp_correct: forall (pe_st:pe_state) (a:aexp) (st:state), aeval (pe_override st pe_st) a = aeval st (pe_aexp pe_st a). Proof. intros pe_st a st. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId. *) rewrite pe_override_correct. destruct (pe_lookup pe_st i); reflexivity. Qed. (** ** Boolean Expressions *) (** The partial evaluation of boolean expressions is similar. In fact, it is entirely analogous to the constant folding of boolean expressions, because our language has no boolean variables. *) Fixpoint pe_bexp (pe_st : pe_state) (b : bexp) : bexp := match b with | BTrue => BTrue | BFalse => BFalse | BEq a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if beq_nat n1 n2 then BTrue else BFalse | (a1', a2') => BEq a1' a2' end | BLe a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if ble_nat n1 n2 then BTrue else BFalse | (a1', a2') => BLe a1' a2' end | BNot b1 => match (pe_bexp pe_st b1) with | BTrue => BFalse | BFalse => BTrue | b1' => BNot b1' end | BAnd b1 b2 => match (pe_bexp pe_st b1, pe_bexp pe_st b2) with | (BTrue, BTrue) => BTrue | (BTrue, BFalse) => BFalse | (BFalse, BTrue) => BFalse | (BFalse, BFalse) => BFalse | (b1', b2') => BAnd b1' b2' end end. Example test_pe_bexp1: pe_bexp [(X,3)] (BNot (BLe (AId X) (ANum 3))) = BFalse. Proof. reflexivity. Qed. Example test_pe_bexp2: forall b, b = BNot (BLe (AId X) (APlus (AId X) (ANum 1))) -> pe_bexp [] b = b. Proof. intros b H. rewrite -> H. reflexivity. Qed. (** The correctness of [pe_bexp] is analogous to the correctness of [pe_aexp] above. *) Theorem pe_bexp_correct: forall (pe_st:pe_state) (b:bexp) (st:state), beval (pe_override st pe_st) b = beval st (pe_bexp pe_st b). Proof. intros pe_st b st. bexp_cases (induction b) Case; simpl; try reflexivity; try (remember (pe_aexp pe_st a) as a'; remember (pe_aexp pe_st a0) as a0'; assert (Ha: aeval (pe_override st pe_st) a = aeval st a'); assert (Ha0: aeval (pe_override st pe_st) a0 = aeval st a0'); try (subst; apply pe_aexp_correct); destruct a'; destruct a0'; rewrite Ha; rewrite Ha0; simpl; try destruct (beq_nat n n0); try destruct (ble_nat n n0); reflexivity); try (destruct (pe_bexp pe_st b); rewrite IHb; reflexivity); try (destruct (pe_bexp pe_st b1); destruct (pe_bexp pe_st b2); rewrite IHb1; rewrite IHb2; reflexivity). Qed. (* ####################################################### *) (** * Partial Evaluation of Commands, Without Loops *) (** What about the partial evaluation of commands? The analogy between partial evaluation and full evaluation continues: Just as full evaluation of a command turns an initial state into a final state, partial evaluation of a command turns an initial partial state into a final partial state. The difference is that, because the state is partial, some parts of the command may not be executable at the static stage. Therefore, just as [pe_aexp] returns a residual [aexp] and [pe_bexp] returns a residual [bexp] above, partially evaluating a command yields a residual command. Another way in which our partial evaluator is similar to a full evaluator is that it does not terminate on all commands. It is not hard to build a partial evaluator that terminates on all commands; what is hard is building a partial evaluator that terminates on all commands yet automatically performs desired optimizations such as unrolling loops. Often a partial evaluator can be coaxed into terminating more often and performing more optimizations by writing the source program differently so that the separation between static and dynamic information becomes more apparent. Such coaxing is the art of _binding-time improvement_. The binding time of a variable tells when its value is known -- either "static", or "dynamic." Anyway, for now we will just live with the fact that our partial evaluator is not a total function from the source command and the initial partial state to the residual command and the final partial state. To model this non-termination, just as with the full evaluation of commands, we use an inductively defined relation. We write c1 / st || c1' / st' to mean that partially evaluating the source command [c1] in the initial partial state [st] yields the residual command [c1'] and the final partial state [st']. For example, we want something like (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (Y ::= AMult (AId Z) (ANum 6)) / [(X,3)] to hold. The assignment to [X] appears in the final partial state, not the residual command. *) (** ** Assignment *) (** Let's start by considering how to partially evaluate an assignment. The two assignments in the source program above needs to be treated differently. The first assignment [X ::= ANum 3], is _static_: its right-hand-side is a constant (more generally, simplifies to a constant), so we should update our partial state at [X] to [3] and produce no residual code. (Actually, we produce a residual [SKIP].) The second assignment [Y ::= AMult (AId Z) (APlus (AId X) (AId X))] is _dynamic_: its right-hand-side does not simplify to a constant, so we should leave it in the residual code and remove [Y], if present, from our partial state. To implement these two cases, we define the functions [pe_add] and [pe_remove]. Like [pe_override] above, these functions operate on a concrete [list] representing a [pe_state], but the theorems [pe_add_correct] and [pe_remove_correct] specify their behavior by the [pe_lookup] interpretation of the [pe_state]. *) Fixpoint pe_remove (pe_st:pe_state) (V:id) : pe_state := match pe_st with | [] => [] | (V',n')::pe_st => if eq_id_dec V V' then pe_remove pe_st V else (V',n') :: pe_remove pe_st V end. Theorem pe_remove_correct: forall pe_st V V0, pe_lookup (pe_remove pe_st V) V0 = if eq_id_dec V V0 then None else pe_lookup pe_st V0. Proof. intros pe_st V V0. induction pe_st as [| [V' n'] pe_st]. Case "[]". destruct (eq_id_dec V V0); reflexivity. Case "::". simpl. compare V V' SCase. SCase "equal". rewrite IHpe_st. destruct (eq_id_dec V V0). reflexivity. rewrite neq_id; auto. SCase "not equal". simpl. compare V0 V' SSCase. SSCase "equal". rewrite neq_id; auto. SSCase "not equal". rewrite IHpe_st. reflexivity. Qed. Definition pe_add (pe_st:pe_state) (V:id) (n:nat) : pe_state := (V,n) :: pe_remove pe_st V. Theorem pe_add_correct: forall pe_st V n V0, pe_lookup (pe_add pe_st V n) V0 = if eq_id_dec V V0 then Some n else pe_lookup pe_st V0. Proof. intros pe_st V n V0. unfold pe_add. simpl. compare V V0 Case. Case "equal". rewrite eq_id; auto. Case "not equal". rewrite pe_remove_correct. repeat rewrite neq_id; auto. Qed. (** We will use the two theorems below to show that our partial evaluator correctly deals with dynamic assignments and static assignments, respectively. *) Theorem pe_override_update_remove: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override (update st V n) (pe_remove pe_st V). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_remove_correct. destruct (eq_id_dec V V0); reflexivity. Qed. Theorem pe_override_update_add: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override st (pe_add pe_st V n). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_add_correct. destruct (eq_id_dec V V0); reflexivity. Qed. (** ** Conditional *) (** Trickier than assignments to partially evaluate is the conditional, [IFB b1 THEN c1 ELSE c2 FI]. If [b1] simplifies to [BTrue] or [BFalse] then it's easy: we know which branch will be taken, so just take that branch. If [b1] does not simplify to a constant, then we need to take both branches, and the final partial state may differ between the two branches! The following program illustrates the difficulty: X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI Suppose the initial partial state is empty. We don't know statically how [Y] compares to [4], so we must partially evaluate both branches of the (outer) conditional. On the [THEN] branch, we know that [Y] is set to [4] and can even use that knowledge to simplify the code somewhat. On the [ELSE] branch, we still don't know the exact value of [Y] at the end. What should the final partial state and residual program be? One way to handle such a dynamic conditional is to take the intersection of the final partial states of the two branches. In this example, we take the intersection of [(Y,4),(X,3)] and [(X,3)], so the overall final partial state is [(X,3)]. To compensate for forgetting that [Y] is [4], we need to add an assignment [Y ::= ANum 4] to the end of the [THEN] branch. So, the residual program will be something like SKIP;; IFB BLe (AId Y) (ANum 4) THEN SKIP;; SKIP;; Y ::= ANum 4 ELSE SKIP FI Programming this case in Coq calls for several auxiliary functions: we need to compute the intersection of two [pe_state]s and turn their difference into sequences of assignments. First, we show how to compute whether two [pe_state]s to disagree at a given variable. In the theorem [pe_disagree_domain], we prove that two [pe_state]s can only disagree at variables that appear in at least one of them. *) Definition pe_disagree_at (pe_st1 pe_st2 : pe_state) (V:id) : bool := match pe_lookup pe_st1 V, pe_lookup pe_st2 V with | Some x, Some y => negb (beq_nat x y) | None, None => false | _, _ => true end. Theorem pe_disagree_domain: forall (pe_st1 pe_st2 : pe_state) (V:id), true = pe_disagree_at pe_st1 pe_st2 V -> In V (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2). Proof. unfold pe_disagree_at. intros pe_st1 pe_st2 V H. apply in_or_app. remember (pe_lookup pe_st1 V) as lookup1. destruct lookup1 as [n1|]. left. apply pe_domain with n1. auto. remember (pe_lookup pe_st2 V) as lookup2. destruct lookup2 as [n2|]. right. apply pe_domain with n2. auto. inversion H. Qed. (** We define the [pe_compare] function to list the variables where two given [pe_state]s disagree. This list is exact, according to the theorem [pe_compare_correct]: a variable appears on the list if and only if the two given [pe_state]s disagree at that variable. Furthermore, we use the [pe_unique] function to eliminate duplicates from the list. *) Fixpoint pe_unique (l : list id) : list id := match l with | [] => [] | x::l => x :: filter (fun y => if eq_id_dec x y then false else true) (pe_unique l) end. Theorem pe_unique_correct: forall l x, In x l <-> In x (pe_unique l). Proof. intros l x. induction l as [| h t]. reflexivity. simpl in *. split. Case "->". intros. inversion H; clear H. left. assumption. destruct (eq_id_dec h x). left. assumption. right. apply filter_In. split. apply IHt. assumption. rewrite neq_id; auto. Case "<-". intros. inversion H; clear H. left. assumption. apply filter_In in H0. inversion H0. right. apply IHt. assumption. Qed. Definition pe_compare (pe_st1 pe_st2 : pe_state) : list id := pe_unique (filter (pe_disagree_at pe_st1 pe_st2) (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2)). Theorem pe_compare_correct: forall pe_st1 pe_st2 V, pe_lookup pe_st1 V = pe_lookup pe_st2 V <-> ~ In V (pe_compare pe_st1 pe_st2). Proof. intros pe_st1 pe_st2 V. unfold pe_compare. rewrite <- pe_unique_correct. rewrite filter_In. split; intros Heq. Case "->". intro. destruct H. unfold pe_disagree_at in H0. rewrite Heq in H0. destruct (pe_lookup pe_st2 V). rewrite <- beq_nat_refl in H0. inversion H0. inversion H0. Case "<-". assert (Hagree: pe_disagree_at pe_st1 pe_st2 V = false). SCase "Proof of assertion". remember (pe_disagree_at pe_st1 pe_st2 V) as disagree. destruct disagree; [| reflexivity]. apply pe_disagree_domain in Heqdisagree. apply ex_falso_quodlibet. apply Heq. split. assumption. reflexivity. unfold pe_disagree_at in Hagree. destruct (pe_lookup pe_st1 V) as [n1|]; destruct (pe_lookup pe_st2 V) as [n2|]; try reflexivity; try solve by inversion. rewrite negb_false_iff in Hagree. apply beq_nat_true in Hagree. subst. reflexivity. Qed. (** The intersection of two partial states is the result of removing from one of them all the variables where the two disagree. We define the function [pe_removes], in terms of [pe_remove] above, to perform such a removal of a whole list of variables at once. The theorem [pe_compare_removes] testifies that the [pe_lookup] interpretation of the result of this intersection operation is the same no matter which of the two partial states we remove the variables from. Because [pe_override] only depends on the [pe_lookup] interpretation of partial states, [pe_override] also does not care which of the two partial states we remove the variables from; that theorem [pe_compare_override] is used in the correctness proof shortly. *) Fixpoint pe_removes (pe_st:pe_state) (ids : list id) : pe_state := match ids with | [] => pe_st | V::ids => pe_remove (pe_removes pe_st ids) V end. Theorem pe_removes_correct: forall pe_st ids V, pe_lookup (pe_removes pe_st ids) V = if in_dec eq_id_dec V ids then None else pe_lookup pe_st V. Proof. intros pe_st ids V. induction ids as [| V' ids]. reflexivity. simpl. rewrite pe_remove_correct. rewrite IHids. compare V' V Case. reflexivity. destruct (in_dec eq_id_dec V ids); reflexivity. Qed. Theorem pe_compare_removes: forall pe_st1 pe_st2 V, pe_lookup (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) V = pe_lookup (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)) V. Proof. intros pe_st1 pe_st2 V. rewrite !pe_removes_correct. destruct (in_dec eq_id_dec V (pe_compare pe_st1 pe_st2)). reflexivity. apply pe_compare_correct. auto. Qed. Theorem pe_compare_override: forall pe_st1 pe_st2 st, pe_override st (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) = pe_override st (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)). Proof. intros. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_compare_removes. reflexivity. Qed. (** Finally, we define an [assign] function to turn the difference between two partial states into a sequence of assignment commands. More precisely, [assign pe_st ids] generates an assignment command for each variable listed in [ids]. *) Fixpoint assign (pe_st : pe_state) (ids : list id) : com := match ids with | [] => SKIP | V::ids => match pe_lookup pe_st V with | Some n => (assign pe_st ids;; V ::= ANum n) | None => assign pe_st ids end end. (** The command generated by [assign] always terminates, because it is just a sequence of assignments. The (total) function [assigned] below computes the effect of the command on the (dynamic state). The theorem [assign_removes] then confirms that the generated assignments perfectly compensate for removing the variables from the partial state. *) Definition assigned (pe_st:pe_state) (ids : list id) (st:state) : state := fun V => if in_dec eq_id_dec V ids then match pe_lookup pe_st V with | Some n => n | None => st V end else st V. Theorem assign_removes: forall pe_st ids st, pe_override st pe_st = pe_override (assigned pe_st ids st) (pe_removes pe_st ids). Proof. intros pe_st ids st. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_removes_correct. unfold assigned. destruct (in_dec eq_id_dec V ids); destruct (pe_lookup pe_st V); reflexivity. Qed. Lemma ceval_extensionality: forall c st st1 st2, c / st || st1 -> (forall V, st1 V = st2 V) -> c / st || st2. Proof. intros c st st1 st2 H Heq. apply functional_extensionality in Heq. rewrite <- Heq. apply H. Qed. Theorem eval_assign: forall pe_st ids st, assign pe_st ids / st || assigned pe_st ids st. Proof. intros pe_st ids st. induction ids as [| V ids]; simpl. Case "[]". eapply ceval_extensionality. apply E_Skip. reflexivity. Case "V::ids". remember (pe_lookup pe_st V) as lookup. destruct lookup. SCase "Some". eapply E_Seq. apply IHids. unfold assigned. simpl. eapply ceval_extensionality. apply E_Ass. simpl. reflexivity. intros V0. unfold update. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); auto. SCase "None". eapply ceval_extensionality. apply IHids. unfold assigned. intros V0. simpl. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. destruct (in_dec eq_id_dec V ids); reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); reflexivity. Qed. (** ** The Partial Evaluation Relation *) (** At long last, we can define a partial evaluator for commands without loops, as an inductive relation! The inequality conditions in [PE_AssDynamic] and [PE_If] are just to keep the partial evaluator deterministic; they are not required for correctness. *) Reserved Notation "c1 '/' st '||' c1' '/' st'" (at level 40, st at level 39, c1' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2', c1 / pe_st || c1' / pe_st' -> c2 / pe_st' || c2' / pe_st'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 -> c2 / pe_st || c2' / pe_st2 -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) where "c1 '/' st '||' c1' '/' st'" := (pe_com c1 st c1' st'). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" ]. Hint Constructors pe_com. Hint Constructors ceval. (** ** Examples *) (** Below are some examples of using the partial evaluator. To make the [pe_com] relation actually usable for automatic partial evaluation, we would need to define more automation tactics in Coq. That is not hard to do, but it is not needed here. *) Example pe_example1: (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (SKIP;; Y ::= AMult (AId Z) (ANum 6)) / [(X,3)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_AssDynamic. reflexivity. intros n H. inversion H. Qed. Example pe_example2: (X ::= ANum 3 ;; IFB BLe (AId X) (ANum 4) THEN X ::= ANum 4 ELSE SKIP FI) / [] || (SKIP;; SKIP) / [(X,4)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_IfTrue. reflexivity. eapply PE_AssStatic. reflexivity. Qed. Example pe_example3: (X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI) / [] || (SKIP;; IFB BLe (AId Y) (ANum 4) THEN (SKIP;; SKIP);; (SKIP;; Y ::= ANum 4) ELSE SKIP;; SKIP FI) / [(X,3)]. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st). eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_If; intuition eauto; try solve by inversion. econstructor. eapply PE_AssStatic. reflexivity. eapply PE_IfFalse. reflexivity. econstructor. reflexivity. reflexivity. Qed. (** ** Correctness of Partial Evaluation *) (** Finally let's prove that this partial evaluator is correct! *) Reserved Notation "c' '/' pe_st' '/' st '||' st''" (at level 40, pe_st' at level 39, st at level 39). Inductive pe_ceval (c':com) (pe_st':pe_state) (st:state) (st'':state) : Prop := | pe_ceval_intro : forall st', c' / st || st' -> pe_override st' pe_st' = st'' -> c' / pe_st' / st || st'' where "c' '/' pe_st' '/' st '||' st''" := (pe_ceval c' pe_st' st st''). Hint Constructors pe_ceval. Theorem pe_com_complete: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') -> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. reflexivity. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. reflexivity. Case "PE_Seq". edestruct IHHpe1. eassumption. subst. edestruct IHHpe2. eassumption. eauto. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c' / pe_st' / st || st'') -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' [st' Heval Heq]; try (inversion Heval; []; subst); auto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_If". inversion Heval; subst; inversion H7; (eapply ceval_deterministic in H8; [| apply eval_assign]); subst. SCase "E_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. SCase "E_IfFalse". rewrite -> pe_compare_override. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. Qed. (** The main theorem. Thanks to David Menendez for this formulation! *) Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') <-> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". apply pe_com_complete. apply H. Case "<-". apply pe_com_sound. apply H. Qed. (* ####################################################### *) (** * Partial Evaluation of Loops *) (** It may seem straightforward at first glance to extend the partial evaluation relation [pe_com] above to loops. Indeed, many loops are easy to deal with. Considered this repeated-squaring loop, for example: WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END If we know neither [X] nor [Y] statically, then the entire loop is dynamic and the residual command should be the same. If we know [X] but not [Y], then the loop can be unrolled all the way and the residual command should be Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y) if [X] is initially [3] (and finally [0]). In general, a loop is easy to partially evaluate if the final partial state of the loop body is equal to the initial state, or if its guard condition is static. But there are other loops for which it is hard to express the residual program we want in Imp. For example, take this program for checking if [Y] is even or odd: X ::= ANum 0;; WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; X ::= AMinus (ANum 1) (AId X) END The value of [X] alternates between [0] and [1] during the loop. Ideally, we would like to unroll this loop, not all the way but _two-fold_, into something like WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; IF BLe (ANum 1) (AId Y) THEN Y ::= AMinus (AId Y) (ANum 1) ELSE X ::= ANum 1;; EXIT FI END;; X ::= ANum 0 Unfortunately, there is no [EXIT] command in Imp. Without extending the range of control structures available in our language, the best we can do is to repeat loop-guard tests or add flag variables. Neither option is terribly attractive. Still, as a digression, below is an attempt at performing partial evaluation on Imp commands. We add one more command argument [c''] to the [pe_com] relation, which keeps track of a loop to roll up. *) Module Loop. Reserved Notation "c1 '/' st '||' c1' '/' st' '/' c''" (at level 40, st at level 39, c1' at level 39, st' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> com -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st / SKIP | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 / SKIP | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l / SKIP | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2' c'', c1 / pe_st || c1' / pe_st' / SKIP -> c2 / pe_st' || c2' / pe_st'' / c'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' / c'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1' c'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' / c'' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2' c'', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' / c'' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2' c'', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 / c'' -> c2 / pe_st || c2' / pe_st2 / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) / c'' | PE_WhileEnd : forall pe_st b1 c1, pe_bexp pe_st b1 = BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / SKIP | PE_WhileLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (WHILE b1 DO c1 END) / pe_st || (c1';;c2') / pe_st'' / c2'' | PE_While : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (c2'' = SKIP \/ c2'' = WHILE b1 DO c1 END) -> (WHILE b1 DO c1 END) / pe_st || (IFB pe_bexp pe_st b1 THEN c1';; c2';; assign pe_st'' (pe_compare pe_st pe_st'') ELSE assign pe_st (pe_compare pe_st pe_st'') FI) / pe_removes pe_st (pe_compare pe_st pe_st'') / c2'' | PE_WhileFixedEnd : forall pe_st b1 c1, pe_bexp pe_st b1 <> BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE b1 DO c1 END) | PE_WhileFixedLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE BTrue DO SKIP END) / pe_st / SKIP (* Because we have an infinite loop, we should actually start to throw away the rest of the program: (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE BTrue DO SKIP END) *) | PE_WhileFixed : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE pe_bexp pe_st b1 DO c1';; c2' END) / pe_st / SKIP where "c1 '/' st '||' c1' '/' st' '/' c''" := (pe_com c1 st c1' st' c''). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" | Case_aux c "PE_WhileEnd" | Case_aux c "PE_WhileLoop" | Case_aux c "PE_While" | Case_aux c "PE_WhileFixedEnd" | Case_aux c "PE_WhileFixedLoop" | Case_aux c "PE_WhileFixed" ]. Hint Constructors pe_com. (** ** Examples *) Ltac step i := (eapply i; intuition eauto; try solve by inversion); repeat (try eapply PE_Seq; try (eapply PE_AssStatic; simpl; reflexivity); try (eapply PE_AssDynamic; [ simpl; reflexivity | intuition eauto; solve by inversion ])). Definition square_loop: com := WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END. Example pe_loop_example1: square_loop / [] || (WHILE BLe (ANum 1) (AId X) DO (Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1));; SKIP END) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. reflexivity. reflexivity. Qed. Example pe_loop_example2: (X ::= ANum 3;; square_loop) / [] || (SKIP;; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; SKIP) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileEnd. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example3: (Z ::= ANum 3;; subtract_slowly) / [] || (SKIP;; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; WHILE BNot (BEq (AId X) (ANum 0)) DO (SKIP;; X ::= AMinus (AId X) (ANum 1));; SKIP END;; SKIP;; Z ::= ANum 0 ELSE SKIP;; Z ::= ANum 1 FI;; SKIP ELSE SKIP;; Z ::= ANum 2 FI;; SKIP ELSE SKIP;; Z ::= ANum 3 FI) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_While. step PE_While. step PE_While. step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example4: (X ::= ANum 0;; WHILE BLe (AId X) (ANum 2) DO X ::= AMinus (ANum 1) (AId X) END) / [] || (SKIP;; WHILE BTrue DO SKIP END) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileFixedLoop. step PE_WhileLoop. step PE_WhileFixedEnd. inversion H. reflexivity. reflexivity. reflexivity. Qed. (** ** Correctness *) (** Because this partial evaluator can unroll a loop n-fold where n is a (finite) integer greater than one, in order to show it correct we need to perform induction not structurally on dynamic evaluation but on the number of times dynamic evaluation enters a loop body. *) Reserved Notation "c1 '/' st '||' st' '#' n" (at level 40, st at level 39, st' at level 39). Inductive ceval_count : com -> state -> state -> nat -> Prop := | E'Skip : forall st, SKIP / st || st # 0 | E'Ass : forall st a1 n l, aeval st a1 = n -> (l ::= a1) / st || (update st l n) # 0 | E'Seq : forall c1 c2 st st' st'' n1 n2, c1 / st || st' # n1 -> c2 / st' || st'' # n2 -> (c1 ;; c2) / st || st'' # (n1 + n2) | E'IfTrue : forall st st' b1 c1 c2 n, beval st b1 = true -> c1 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'IfFalse : forall st st' b1 c1 c2 n, beval st b1 = false -> c2 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'WhileEnd : forall b1 st c1, beval st b1 = false -> (WHILE b1 DO c1 END) / st || st # 0 | E'WhileLoop : forall st st' st'' b1 c1 n1 n2, beval st b1 = true -> c1 / st || st' # n1 -> (WHILE b1 DO c1 END) / st' || st'' # n2 -> (WHILE b1 DO c1 END) / st || st'' # S (n1 + n2) where "c1 '/' st '||' st' # n" := (ceval_count c1 st st' n). Tactic Notation "ceval_count_cases" tactic(first) ident(c) := first; [ Case_aux c "E'Skip" | Case_aux c "E'Ass" | Case_aux c "E'Seq" | Case_aux c "E'IfTrue" | Case_aux c "E'IfFalse" | Case_aux c "E'WhileEnd" | Case_aux c "E'WhileLoop" ]. Hint Constructors ceval_count. Theorem ceval_count_complete: forall c st st', c / st || st' -> exists n, c / st || st' # n. Proof. intros c st st' Heval. induction Heval; try inversion IHHeval1; try inversion IHHeval2; try inversion IHHeval; eauto. Qed. Theorem ceval_count_sound: forall c st st' n, c / st || st' # n -> c / st || st'. Proof. intros c st st' n Heval. induction Heval; eauto. Qed. Theorem pe_compare_nil_lookup: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall V, pe_lookup pe_st1 V = pe_lookup pe_st2 V. Proof. intros pe_st1 pe_st2 H V. apply (pe_compare_correct pe_st1 pe_st2 V). rewrite H. intro. inversion H0. Qed. Theorem pe_compare_nil_override: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall st, pe_override st pe_st1 = pe_override st pe_st2. Proof. intros pe_st1 pe_st2 H st. apply functional_extensionality. intros V. rewrite !pe_override_correct. apply pe_compare_nil_lookup with (V:=V) in H. rewrite H. reflexivity. Qed. Reserved Notation "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" (at level 40, pe_st' at level 39, c'' at level 39, st at level 39, st'' at level 39). Inductive pe_ceval_count (c':com) (pe_st':pe_state) (c'':com) (st:state) (st'':state) (n:nat) : Prop := | pe_ceval_count_intro : forall st' n', c' / st || st' -> c'' / pe_override st' pe_st' || st'' # n' -> n' <= n -> c' / pe_st' / c'' / st || st'' # n where "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" := (pe_ceval_count c' pe_st' c'' st st'' n). Hint Constructors pe_ceval_count. Lemma pe_ceval_count_le: forall c' pe_st' c'' st st'' n n', n' <= n -> c' / pe_st' / c'' / st || st'' # n' -> c' / pe_st' / c'' / st || st'' # n. Proof. intros c' pe_st' c'' st st'' n n' Hle H. inversion H. econstructor; try eassumption. omega. Qed. Theorem pe_com_complete: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c / pe_override st pe_st || st'' # n) -> (c' / pe_st' / c'' / st || st'' # n). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. apply E'Skip. auto. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. apply E'Skip. auto. Case "PE_Seq". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. eassumption. Case "PE_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_While". inversion Heval; subst. SCase "E_WhileEnd". econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. apply eval_assign. rewrite <- assign_removes. inversion H2; subst; auto. auto. SCase "E_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. repeat eapply E_Seq; eauto. apply eval_assign. rewrite -> pe_compare_override, <- assign_removes. eassumption. omega. Case "PE_WhileFixedLoop". apply ex_falso_quodlibet. generalize dependent (S (n1 + n2)). intros n. clear - Case H H0 IHHpe1 IHHpe2. generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct, H in H7. inversion H7. SCase "E'WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H0) in H7. apply H1 in H7; [| omega]. inversion H7. Case "PE_WhileFixed". generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct in H8. eauto. SCase "E'WhileLoop". rewrite pe_bexp_correct in H5. edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H1) in H8. apply H2 in H8; [| omega]. inversion H8. econstructor; [ eapply E_WhileLoop; eauto | eassumption | omega]. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c' / pe_st' / c'' / st || st'' # n) -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n [st' n' Heval Heval' Hle]; try (inversion Heval; []; subst); try (inversion Heval'; []; subst); eauto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_If". inversion Heval; subst; inversion H7; subst; clear H7. SCase "E_IfTrue". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. SCase "E_IfFalse". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. eapply IHHpe2. eauto. Case "PE_WhileEnd". apply E_WhileEnd. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. Case "PE_WhileLoop". eapply E_WhileLoop. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe1. eauto. eapply IHHpe2. eauto. Case "PE_While". inversion Heval; subst. SCase "E_IfTrue". inversion H9. subst. clear H9. inversion H10. subst. clear H10. eapply ceval_deterministic in H11; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. eapply E_WhileLoop. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. eapply IHHpe2. eauto. SCase "E_IfFalse". apply ceval_count_sound in Heval'. eapply ceval_deterministic in H9; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. inversion H2; subst. SSCase "c2'' = SKIP". inversion Heval'. subst. apply E_WhileEnd. rewrite -> pe_bexp_correct. assumption. SSCase "c2'' = WHILE b1 DO c1 END". assumption. Case "PE_WhileFixedEnd". eapply ceval_count_sound. apply Heval'. Case "PE_WhileFixedLoop". apply loop_never_stops in Heval. inversion Heval. Case "PE_WhileFixed". clear - Case H1 IHHpe1 IHHpe2 Heval. remember (WHILE pe_bexp pe_st b1 DO c1';; c2' END) as c'. ceval_cases (induction Heval) SCase; inversion Heqc'; subst; clear Heqc'. SCase "E_WhileEnd". apply E_WhileEnd. rewrite pe_bexp_correct. assumption. SCase "E_WhileLoop". assert (IHHeval2' := IHHeval2 (refl_equal _)). apply ceval_count_complete in IHHeval2'. inversion IHHeval2'. clear IHHeval1 IHHeval2 IHHeval2'. inversion Heval1. subst. eapply E_WhileLoop. rewrite pe_bexp_correct. assumption. eauto. eapply IHHpe2. econstructor. eassumption. rewrite <- (pe_compare_nil_override _ _ H1). eassumption. apply le_n. Qed. Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' / SKIP -> forall st st'', (c / pe_override st pe_st || st'') <-> (exists st', c' / st || st' /\ pe_override st' pe_st' = st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". intros Heval. apply ceval_count_complete in Heval. inversion Heval as [n Heval']. apply pe_com_complete with (st:=st) (st'':=st'') (n:=n) in H. inversion H as [? ? ? Hskip ?]. inversion Hskip. subst. eauto. assumption. Case "<-". intros [st' [Heval Heq]]. subst st''. eapply pe_com_sound in H. apply H. econstructor. apply Heval. apply E'Skip. apply le_n. Qed. End Loop. (* ####################################################### *) (** * Partial Evaluation of Flowchart Programs *) (** Instead of partially evaluating [WHILE] loops directly, the standard approach to partially evaluating imperative programs is to convert them into _flowcharts_. In other words, it turns out that adding labels and jumps to our language makes it much easier to partially evaluate. The result of partially evaluating a flowchart is a residual flowchart. If we are lucky, the jumps in the residual flowchart can be converted back to [WHILE] loops, but that is not possible in general; we do not pursue it here. *) (** ** Basic blocks *) (** A flowchart is made of _basic blocks_, which we represent with the inductive type [block]. A basic block is a sequence of assignments (the constructor [Assign]), concluding with a conditional jump (the constructor [If]) or an unconditional jump (the constructor [Goto]). The destinations of the jumps are specified by _labels_, which can be of any type. Therefore, we parameterize the [block] type by the type of labels. *) Inductive block (Label:Type) : Type := | Goto : Label -> block Label | If : bexp -> Label -> Label -> block Label | Assign : id -> aexp -> block Label -> block Label. Tactic Notation "block_cases" tactic(first) ident(c) := first; [ Case_aux c "Goto" | Case_aux c "If" | Case_aux c "Assign" ]. Arguments Goto {Label} _. Arguments If {Label} _ _ _. Arguments Assign {Label} _ _ _. (** We use the "even or odd" program, expressed above in Imp, as our running example. Converting this program into a flowchart turns out to require 4 labels, so we define the following type. *) Inductive parity_label : Type := | entry : parity_label | loop : parity_label | body : parity_label | done : parity_label. (** The following [block] is the basic block found at the [body] label of the example program. *) Definition parity_body : block parity_label := Assign Y (AMinus (AId Y) (ANum 1)) (Assign X (AMinus (ANum 1) (AId X)) (Goto loop)). (** To evaluate a basic block, given an initial state, is to compute the final state and the label to jump to next. Because basic blocks do not _contain_ loops or other control structures, evaluation of basic blocks is a total function -- we don't need to worry about non-termination. *) Fixpoint keval {L:Type} (st:state) (k : block L) : state * L := match k with | Goto l => (st, l) | If b l1 l2 => (st, if beval st b then l1 else l2) | Assign i a k => keval (update st i (aeval st a)) k end. Example keval_example: keval empty_state parity_body = (update (update empty_state Y 0) X 1, loop). Proof. reflexivity. Qed. (** ** Flowchart programs *) (** A flowchart program is simply a lookup function that maps labels to basic blocks. Actually, some labels are _halting states_ and do not map to any basic block. So, more precisely, a flowchart [program] whose labels are of type [L] is a function from [L] to [option (block L)]. *) Definition program (L:Type) : Type := L -> option (block L). Definition parity : program parity_label := fun l => match l with | entry => Some (Assign X (ANum 0) (Goto loop)) | loop => Some (If (BLe (ANum 1) (AId Y)) body done) | body => Some parity_body | done => None (* halt *) end. (** Unlike a basic block, a program may not terminate, so we model the evaluation of programs by an inductive relation [peval] rather than a recursive function. *) Inductive peval {L:Type} (p : program L) : state -> L -> state -> L -> Prop := | E_None: forall st l, p l = None -> peval p st l st l | E_Some: forall st l k st' l' st'' l'', p l = Some k -> keval st k = (st', l') -> peval p st' l' st'' l'' -> peval p st l st'' l''. Example parity_eval: peval parity empty_state entry empty_state done. Proof. erewrite f_equal with (f := fun st => peval _ _ _ st _). eapply E_Some. reflexivity. reflexivity. eapply E_Some. reflexivity. reflexivity. apply E_None. reflexivity. apply functional_extensionality. intros i. rewrite update_same; auto. Qed. Tactic Notation "peval_cases" tactic(first) ident(c) := first; [ Case_aux c "E_None" | Case_aux c "E_Some" ]. (** ** Partial evaluation of basic blocks and flowchart programs *) (** Partial evaluation changes the label type in a systematic way: if the label type used to be [L], it becomes [pe_state * L]. So the same label in the original program may be unfolded, or blown up, into multiple labels by being paired with different partial states. For example, the label [loop] in the [parity] program will become two labels: [([(X,0)], loop)] and [([(X,1)], loop)]. This change of label type is reflected in the types of [pe_block] and [pe_program] defined presently. *) Fixpoint pe_block {L:Type} (pe_st:pe_state) (k : block L) : block (pe_state * L) := match k with | Goto l => Goto (pe_st, l) | If b l1 l2 => match pe_bexp pe_st b with | BTrue => Goto (pe_st, l1) | BFalse => Goto (pe_st, l2) | b' => If b' (pe_st, l1) (pe_st, l2) end | Assign i a k => match pe_aexp pe_st a with | ANum n => pe_block (pe_add pe_st i n) k | a' => Assign i a' (pe_block (pe_remove pe_st i) k) end end. Example pe_block_example: pe_block [(X,0)] parity_body = Assign Y (AMinus (AId Y) (ANum 1)) (Goto ([(X,1)], loop)). Proof. reflexivity. Qed. Theorem pe_block_correct: forall (L:Type) st pe_st k st' pe_st' (l':L), keval st (pe_block pe_st k) = (st', (pe_st', l')) -> keval (pe_override st pe_st) k = (pe_override st' pe_st', l'). Proof. intros. generalize dependent pe_st. generalize dependent st. block_cases (induction k as [l | b l1 l2 | i a k]) Case; intros st pe_st H. Case "Goto". inversion H; reflexivity. Case "If". replace (keval st (pe_block pe_st (If b l1 l2))) with (keval st (If (pe_bexp pe_st b) (pe_st, l1) (pe_st, l2))) in H by (simpl; destruct (pe_bexp pe_st b); reflexivity). simpl in *. rewrite pe_bexp_correct. destruct (beval st (pe_bexp pe_st b)); inversion H; reflexivity. Case "Assign". simpl in *. rewrite pe_aexp_correct. destruct (pe_aexp pe_st a); simpl; try solve [rewrite pe_override_update_add; apply IHk; apply H]; solve [rewrite pe_override_update_remove; apply IHk; apply H]. Qed. Definition pe_program {L:Type} (p : program L) : program (pe_state * L) := fun pe_l => match pe_l with (pe_st, l) => option_map (pe_block pe_st) (p l) end. Inductive pe_peval {L:Type} (p : program L) (st:state) (pe_st:pe_state) (l:L) (st'o:state) (l':L) : Prop := | pe_peval_intro : forall st' pe_st', peval (pe_program p) st (pe_st, l) st' (pe_st', l') -> pe_override st' pe_st' = st'o -> pe_peval p st pe_st l st'o l'. Theorem pe_program_correct: forall (L:Type) (p : program L) st pe_st l st'o l', peval p (pe_override st pe_st) l st'o l' <-> pe_peval p st pe_st l st'o l'. Proof. intros. split; [Case "->" | Case "<-"]. Case "->". intros Heval. remember (pe_override st pe_st) as sto. generalize dependent pe_st. generalize dependent st. peval_cases (induction Heval as [ sto l Hlookup | sto l k st'o l' st''o l'' Hlookup Hkeval Heval ]) SCase; intros st pe_st Heqsto; subst sto. SCase "E_None". eapply pe_peval_intro. apply E_None. simpl. rewrite Hlookup. reflexivity. reflexivity. SCase "E_Some". remember (keval st (pe_block pe_st k)) as x. destruct x as [st' [pe_st' l'_]]. symmetry in Heqx. erewrite pe_block_correct in Hkeval by apply Heqx. inversion Hkeval. subst st'o l'_. clear Hkeval. edestruct IHHeval. reflexivity. subst st''o. clear IHHeval. eapply pe_peval_intro; [| reflexivity]. eapply E_Some; eauto. simpl. rewrite Hlookup. reflexivity. Case "<-". intros [st' pe_st' Heval Heqst'o]. remember (pe_st, l) as pe_st_l. remember (pe_st', l') as pe_st'_l'. generalize dependent pe_st. generalize dependent l. peval_cases (induction Heval as [ st [pe_st_ l_] Hlookup | st [pe_st_ l_] pe_k st' [pe_st'_ l'_] st'' [pe_st'' l''] Hlookup Hkeval Heval ]) SCase; intros l pe_st Heqpe_st_l; inversion Heqpe_st_l; inversion Heqpe_st'_l'; repeat subst. SCase "E_None". apply E_None. simpl in Hlookup. destruct (p l'); [ solve [ inversion Hlookup ] | reflexivity ]. SCase "E_Some". simpl in Hlookup. remember (p l) as k. destruct k as [k|]; inversion Hlookup; subst. eapply E_Some; eauto. apply pe_block_correct. apply Hkeval. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * PE: Partial Evaluation *) (* Chapter author/maintainer: Chung-chieh Shan *) (** Equiv.v introduced constant folding as an example of a program transformation and proved that it preserves the meaning of the program. Constant folding operates on manifest constants such as [ANum] expressions. For example, it simplifies the command [Y ::= APlus (ANum 3) (ANum 1)] to the command [Y ::= ANum 4]. However, it does not propagate known constants along data flow. For example, it does not simplify the sequence X ::= ANum 3;; Y ::= APlus (AId X) (ANum 1) to X ::= ANum 3;; Y ::= ANum 4 because it forgets that [X] is [3] by the time it gets to [Y]. We naturally want to enhance constant folding so that it propagates known constants and uses them to simplify programs. Doing so constitutes a rudimentary form of _partial evaluation_. As we will see, partial evaluation is so called because it is like running a program, except only part of the program can be evaluated because only part of the input to the program is known. For example, we can only simplify the program X ::= ANum 3;; Y ::= AMinus (APlus (AId X) (ANum 1)) (AId Y) to X ::= ANum 3;; Y ::= AMinus (ANum 4) (AId Y) without knowing the initial value of [Y]. *) Require Export Imp. Require Import FunctionalExtensionality. (* ####################################################### *) (** * Generalizing Constant Folding *) (** The starting point of partial evaluation is to represent our partial knowledge about the state. For example, between the two assignments above, the partial evaluator may know only that [X] is [3] and nothing about any other variable. *) (** ** Partial States *) (** Conceptually speaking, we can think of such partial states as the type [id -> option nat] (as opposed to the type [id -> nat] of concrete, full states). However, in addition to looking up and updating the values of individual variables in a partial state, we may also want to compare two partial states to see if and where they differ, to handle conditional control flow. It is not possible to compare two arbitrary functions in this way, so we represent partial states in a more concrete format: as a list of [id * nat] pairs. *) Definition pe_state := list (id * nat). (** The idea is that a variable [id] appears in the list if and only if we know its current [nat] value. The [pe_lookup] function thus interprets this concrete representation. (If the same variable [id] appears multiple times in the list, the first occurrence wins, but we will define our partial evaluator to never construct such a [pe_state].) *) Fixpoint pe_lookup (pe_st : pe_state) (V:id) : option nat := match pe_st with | [] => None | (V',n')::pe_st => if eq_id_dec V V' then Some n' else pe_lookup pe_st V end. (** For example, [empty_pe_state] represents complete ignorance about every variable -- the function that maps every [id] to [None]. *) Definition empty_pe_state : pe_state := []. (** More generally, if the [list] representing a [pe_state] does not contain some [id], then that [pe_state] must map that [id] to [None]. Before we prove this fact, we first define a useful tactic for reasoning with [id] equality. The tactic compare V V' SCase means to reason by cases over [eq_id_dec V V']. In the case where [V = V'], the tactic substitutes [V] for [V'] throughout. *) Tactic Notation "compare" ident(i) ident(j) ident(c) := let H := fresh "Heq" i j in destruct (eq_id_dec i j); [ Case_aux c "equal"; subst j | Case_aux c "not equal" ]. Theorem pe_domain: forall pe_st V n, pe_lookup pe_st V = Some n -> In V (map (@fst _ _) pe_st). Proof. intros pe_st V n H. induction pe_st as [| [V' n'] pe_st]. Case "[]". inversion H. Case "::". simpl in H. simpl. compare V V' SCase; auto. Qed. (** *** Aside on [In]. We will make heavy use of the [In] predicate from the standard library. [In] is equivalent to the [appears_in] predicate introduced in Logic.v, but defined using a [Fixpoint] rather than an [Inductive]. *) Print In. (* ===> Fixpoint In {A:Type} (a: A) (l:list A) : Prop := match l with | [] => False | b :: m => b = a \/ In a m end : forall A : Type, A -> list A -> Prop *) (** [In] comes with various useful lemmas. *) Check in_or_app. (* ===> in_or_app: forall (A : Type) (l m : list A) (a : A), In a l \/ In a m -> In a (l ++ m) *) Check filter_In. (* ===> filter_In : forall (A : Type) (f : A -> bool) (x : A) (l : list A), In x (filter f l) <-> In x l /\ f x = true *) Check in_dec. (* ===> in_dec : forall A : Type, (forall x y : A, {x = y} + {x <> y}) -> forall (a : A) (l : list A), {In a l} + {~ In a l}] *) (** Note that we can compute with [in_dec], just as with [eq_id_dec]. *) (** ** Arithmetic Expressions *) (** Partial evaluation of [aexp] is straightforward -- it is basically the same as constant folding, [fold_constants_aexp], except that sometimes the partial state tells us the current value of a variable and we can replace it by a constant expression. *) Fixpoint pe_aexp (pe_st : pe_state) (a : aexp) : aexp := match a with | ANum n => ANum n | AId i => match pe_lookup pe_st i with (* <----- NEW *) | Some n => ANum n | None => AId i end | APlus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 + n2) | (a1', a2') => APlus a1' a2' end | AMinus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 - n2) | (a1', a2') => AMinus a1' a2' end | AMult a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 * n2) | (a1', a2') => AMult a1' a2' end end. (** This partial evaluator folds constants but does not apply the associativity of addition. *) Example test_pe_aexp1: pe_aexp [(X,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (ANum 4) (AId Y). Proof. reflexivity. Qed. Example text_pe_aexp2: pe_aexp [(Y,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (APlus (AId X) (ANum 1)) (ANum 3). Proof. reflexivity. Qed. (** Now, in what sense is [pe_aexp] correct? It is reasonable to define the correctness of [pe_aexp] as follows: whenever a full state [st:state] is _consistent_ with a partial state [pe_st:pe_state] (in other words, every variable to which [pe_st] assigns a value is assigned the same value by [st]), evaluating [a] and evaluating [pe_aexp pe_st a] in [st] yields the same result. This statement is indeed true. *) Definition pe_consistent (st:state) (pe_st:pe_state) := forall V n, Some n = pe_lookup pe_st V -> st V = n. Theorem pe_aexp_correct_weak: forall st pe_st, pe_consistent st pe_st -> forall a, aeval st a = aeval st (pe_aexp pe_st a). Proof. unfold pe_consistent. intros st pe_st H a. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId *) Case "AId". remember (pe_lookup pe_st i) as l. destruct l. SCase "Some". rewrite H with (n:=n) by apply Heql. reflexivity. SCase "None". reflexivity. Qed. (** However, we will soon want our partial evaluator to remove assignments. For example, it will simplify X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to just Y ::= AMinus (ANum 3) (AId Y);; X ::= ANum 4 by delaying the assignment to [X] until the end. To accomplish this simplification, we need the result of partial evaluating pe_aexp [(X,3)] (AMinus (AId X) (AId Y)) to be equal to [AMinus (ANum 3) (AId Y)] and _not_ the original expression [AMinus (AId X) (AId Y)]. After all, it would be incorrect, not just inefficient, to transform X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 even though the output expressions [AMinus (ANum 3) (AId Y)] and [AMinus (AId X) (AId Y)] both satisfy the correctness criterion that we just proved. Indeed, if we were to just define [pe_aexp pe_st a = a] then the theorem [pe_aexp_correct'] would already trivially hold. Instead, we want to prove that the [pe_aexp] is correct in a stronger sense: evaluating the expression produced by partial evaluation ([aeval st (pe_aexp pe_st a)]) must not depend on those parts of the full state [st] that are already specified in the partial state [pe_st]. To be more precise, let us define a function [pe_override], which updates [st] with the contents of [pe_st]. In other words, [pe_override] carries out the assignments listed in [pe_st] on top of [st]. *) Fixpoint pe_override (st:state) (pe_st:pe_state) : state := match pe_st with | [] => st | (V,n)::pe_st => update (pe_override st pe_st) V n end. Example test_pe_override: pe_override (update empty_state Y 1) [(X,3);(Z,2)] = update (update (update empty_state Y 1) Z 2) X 3. Proof. reflexivity. Qed. (** Although [pe_override] operates on a concrete [list] representing a [pe_state], its behavior is defined entirely by the [pe_lookup] interpretation of the [pe_state]. *) Theorem pe_override_correct: forall st pe_st V0, pe_override st pe_st V0 = match pe_lookup pe_st V0 with | Some n => n | None => st V0 end. Proof. intros. induction pe_st as [| [V n] pe_st]. reflexivity. simpl in *. unfold update. compare V0 V Case; auto. rewrite eq_id; auto. rewrite neq_id; auto. Qed. (** We can relate [pe_consistent] to [pe_override] in two ways. First, overriding a state with a partial state always gives a state that is consistent with the partial state. Second, if a state is already consistent with a partial state, then overriding the state with the partial state gives the same state. *) Theorem pe_override_consistent: forall st pe_st, pe_consistent (pe_override st pe_st) pe_st. Proof. intros st pe_st V n H. rewrite pe_override_correct. destruct (pe_lookup pe_st V); inversion H. reflexivity. Qed. Theorem pe_consistent_override: forall st pe_st, pe_consistent st pe_st -> forall V, st V = pe_override st pe_st V. Proof. intros st pe_st H V. rewrite pe_override_correct. remember (pe_lookup pe_st V) as l. destruct l; auto. Qed. (** Now we can state and prove that [pe_aexp] is correct in the stronger sense that will help us define the rest of the partial evaluator. Intuitively, running a program using partial evaluation is a two-stage process. In the first, _static_ stage, we partially evaluate the given program with respect to some partial state to get a _residual_ program. In the second, _dynamic_ stage, we evaluate the residual program with respect to the rest of the state. This dynamic state provides values for those variables that are unknown in the static (partial) state. Thus, the residual program should be equivalent to _prepending_ the assignments listed in the partial state to the original program. *) Theorem pe_aexp_correct: forall (pe_st:pe_state) (a:aexp) (st:state), aeval (pe_override st pe_st) a = aeval st (pe_aexp pe_st a). Proof. intros pe_st a st. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId. *) rewrite pe_override_correct. destruct (pe_lookup pe_st i); reflexivity. Qed. (** ** Boolean Expressions *) (** The partial evaluation of boolean expressions is similar. In fact, it is entirely analogous to the constant folding of boolean expressions, because our language has no boolean variables. *) Fixpoint pe_bexp (pe_st : pe_state) (b : bexp) : bexp := match b with | BTrue => BTrue | BFalse => BFalse | BEq a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if beq_nat n1 n2 then BTrue else BFalse | (a1', a2') => BEq a1' a2' end | BLe a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if ble_nat n1 n2 then BTrue else BFalse | (a1', a2') => BLe a1' a2' end | BNot b1 => match (pe_bexp pe_st b1) with | BTrue => BFalse | BFalse => BTrue | b1' => BNot b1' end | BAnd b1 b2 => match (pe_bexp pe_st b1, pe_bexp pe_st b2) with | (BTrue, BTrue) => BTrue | (BTrue, BFalse) => BFalse | (BFalse, BTrue) => BFalse | (BFalse, BFalse) => BFalse | (b1', b2') => BAnd b1' b2' end end. Example test_pe_bexp1: pe_bexp [(X,3)] (BNot (BLe (AId X) (ANum 3))) = BFalse. Proof. reflexivity. Qed. Example test_pe_bexp2: forall b, b = BNot (BLe (AId X) (APlus (AId X) (ANum 1))) -> pe_bexp [] b = b. Proof. intros b H. rewrite -> H. reflexivity. Qed. (** The correctness of [pe_bexp] is analogous to the correctness of [pe_aexp] above. *) Theorem pe_bexp_correct: forall (pe_st:pe_state) (b:bexp) (st:state), beval (pe_override st pe_st) b = beval st (pe_bexp pe_st b). Proof. intros pe_st b st. bexp_cases (induction b) Case; simpl; try reflexivity; try (remember (pe_aexp pe_st a) as a'; remember (pe_aexp pe_st a0) as a0'; assert (Ha: aeval (pe_override st pe_st) a = aeval st a'); assert (Ha0: aeval (pe_override st pe_st) a0 = aeval st a0'); try (subst; apply pe_aexp_correct); destruct a'; destruct a0'; rewrite Ha; rewrite Ha0; simpl; try destruct (beq_nat n n0); try destruct (ble_nat n n0); reflexivity); try (destruct (pe_bexp pe_st b); rewrite IHb; reflexivity); try (destruct (pe_bexp pe_st b1); destruct (pe_bexp pe_st b2); rewrite IHb1; rewrite IHb2; reflexivity). Qed. (* ####################################################### *) (** * Partial Evaluation of Commands, Without Loops *) (** What about the partial evaluation of commands? The analogy between partial evaluation and full evaluation continues: Just as full evaluation of a command turns an initial state into a final state, partial evaluation of a command turns an initial partial state into a final partial state. The difference is that, because the state is partial, some parts of the command may not be executable at the static stage. Therefore, just as [pe_aexp] returns a residual [aexp] and [pe_bexp] returns a residual [bexp] above, partially evaluating a command yields a residual command. Another way in which our partial evaluator is similar to a full evaluator is that it does not terminate on all commands. It is not hard to build a partial evaluator that terminates on all commands; what is hard is building a partial evaluator that terminates on all commands yet automatically performs desired optimizations such as unrolling loops. Often a partial evaluator can be coaxed into terminating more often and performing more optimizations by writing the source program differently so that the separation between static and dynamic information becomes more apparent. Such coaxing is the art of _binding-time improvement_. The binding time of a variable tells when its value is known -- either "static", or "dynamic." Anyway, for now we will just live with the fact that our partial evaluator is not a total function from the source command and the initial partial state to the residual command and the final partial state. To model this non-termination, just as with the full evaluation of commands, we use an inductively defined relation. We write c1 / st || c1' / st' to mean that partially evaluating the source command [c1] in the initial partial state [st] yields the residual command [c1'] and the final partial state [st']. For example, we want something like (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (Y ::= AMult (AId Z) (ANum 6)) / [(X,3)] to hold. The assignment to [X] appears in the final partial state, not the residual command. *) (** ** Assignment *) (** Let's start by considering how to partially evaluate an assignment. The two assignments in the source program above needs to be treated differently. The first assignment [X ::= ANum 3], is _static_: its right-hand-side is a constant (more generally, simplifies to a constant), so we should update our partial state at [X] to [3] and produce no residual code. (Actually, we produce a residual [SKIP].) The second assignment [Y ::= AMult (AId Z) (APlus (AId X) (AId X))] is _dynamic_: its right-hand-side does not simplify to a constant, so we should leave it in the residual code and remove [Y], if present, from our partial state. To implement these two cases, we define the functions [pe_add] and [pe_remove]. Like [pe_override] above, these functions operate on a concrete [list] representing a [pe_state], but the theorems [pe_add_correct] and [pe_remove_correct] specify their behavior by the [pe_lookup] interpretation of the [pe_state]. *) Fixpoint pe_remove (pe_st:pe_state) (V:id) : pe_state := match pe_st with | [] => [] | (V',n')::pe_st => if eq_id_dec V V' then pe_remove pe_st V else (V',n') :: pe_remove pe_st V end. Theorem pe_remove_correct: forall pe_st V V0, pe_lookup (pe_remove pe_st V) V0 = if eq_id_dec V V0 then None else pe_lookup pe_st V0. Proof. intros pe_st V V0. induction pe_st as [| [V' n'] pe_st]. Case "[]". destruct (eq_id_dec V V0); reflexivity. Case "::". simpl. compare V V' SCase. SCase "equal". rewrite IHpe_st. destruct (eq_id_dec V V0). reflexivity. rewrite neq_id; auto. SCase "not equal". simpl. compare V0 V' SSCase. SSCase "equal". rewrite neq_id; auto. SSCase "not equal". rewrite IHpe_st. reflexivity. Qed. Definition pe_add (pe_st:pe_state) (V:id) (n:nat) : pe_state := (V,n) :: pe_remove pe_st V. Theorem pe_add_correct: forall pe_st V n V0, pe_lookup (pe_add pe_st V n) V0 = if eq_id_dec V V0 then Some n else pe_lookup pe_st V0. Proof. intros pe_st V n V0. unfold pe_add. simpl. compare V V0 Case. Case "equal". rewrite eq_id; auto. Case "not equal". rewrite pe_remove_correct. repeat rewrite neq_id; auto. Qed. (** We will use the two theorems below to show that our partial evaluator correctly deals with dynamic assignments and static assignments, respectively. *) Theorem pe_override_update_remove: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override (update st V n) (pe_remove pe_st V). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_remove_correct. destruct (eq_id_dec V V0); reflexivity. Qed. Theorem pe_override_update_add: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override st (pe_add pe_st V n). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_add_correct. destruct (eq_id_dec V V0); reflexivity. Qed. (** ** Conditional *) (** Trickier than assignments to partially evaluate is the conditional, [IFB b1 THEN c1 ELSE c2 FI]. If [b1] simplifies to [BTrue] or [BFalse] then it's easy: we know which branch will be taken, so just take that branch. If [b1] does not simplify to a constant, then we need to take both branches, and the final partial state may differ between the two branches! The following program illustrates the difficulty: X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI Suppose the initial partial state is empty. We don't know statically how [Y] compares to [4], so we must partially evaluate both branches of the (outer) conditional. On the [THEN] branch, we know that [Y] is set to [4] and can even use that knowledge to simplify the code somewhat. On the [ELSE] branch, we still don't know the exact value of [Y] at the end. What should the final partial state and residual program be? One way to handle such a dynamic conditional is to take the intersection of the final partial states of the two branches. In this example, we take the intersection of [(Y,4),(X,3)] and [(X,3)], so the overall final partial state is [(X,3)]. To compensate for forgetting that [Y] is [4], we need to add an assignment [Y ::= ANum 4] to the end of the [THEN] branch. So, the residual program will be something like SKIP;; IFB BLe (AId Y) (ANum 4) THEN SKIP;; SKIP;; Y ::= ANum 4 ELSE SKIP FI Programming this case in Coq calls for several auxiliary functions: we need to compute the intersection of two [pe_state]s and turn their difference into sequences of assignments. First, we show how to compute whether two [pe_state]s to disagree at a given variable. In the theorem [pe_disagree_domain], we prove that two [pe_state]s can only disagree at variables that appear in at least one of them. *) Definition pe_disagree_at (pe_st1 pe_st2 : pe_state) (V:id) : bool := match pe_lookup pe_st1 V, pe_lookup pe_st2 V with | Some x, Some y => negb (beq_nat x y) | None, None => false | _, _ => true end. Theorem pe_disagree_domain: forall (pe_st1 pe_st2 : pe_state) (V:id), true = pe_disagree_at pe_st1 pe_st2 V -> In V (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2). Proof. unfold pe_disagree_at. intros pe_st1 pe_st2 V H. apply in_or_app. remember (pe_lookup pe_st1 V) as lookup1. destruct lookup1 as [n1|]. left. apply pe_domain with n1. auto. remember (pe_lookup pe_st2 V) as lookup2. destruct lookup2 as [n2|]. right. apply pe_domain with n2. auto. inversion H. Qed. (** We define the [pe_compare] function to list the variables where two given [pe_state]s disagree. This list is exact, according to the theorem [pe_compare_correct]: a variable appears on the list if and only if the two given [pe_state]s disagree at that variable. Furthermore, we use the [pe_unique] function to eliminate duplicates from the list. *) Fixpoint pe_unique (l : list id) : list id := match l with | [] => [] | x::l => x :: filter (fun y => if eq_id_dec x y then false else true) (pe_unique l) end. Theorem pe_unique_correct: forall l x, In x l <-> In x (pe_unique l). Proof. intros l x. induction l as [| h t]. reflexivity. simpl in *. split. Case "->". intros. inversion H; clear H. left. assumption. destruct (eq_id_dec h x). left. assumption. right. apply filter_In. split. apply IHt. assumption. rewrite neq_id; auto. Case "<-". intros. inversion H; clear H. left. assumption. apply filter_In in H0. inversion H0. right. apply IHt. assumption. Qed. Definition pe_compare (pe_st1 pe_st2 : pe_state) : list id := pe_unique (filter (pe_disagree_at pe_st1 pe_st2) (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2)). Theorem pe_compare_correct: forall pe_st1 pe_st2 V, pe_lookup pe_st1 V = pe_lookup pe_st2 V <-> ~ In V (pe_compare pe_st1 pe_st2). Proof. intros pe_st1 pe_st2 V. unfold pe_compare. rewrite <- pe_unique_correct. rewrite filter_In. split; intros Heq. Case "->". intro. destruct H. unfold pe_disagree_at in H0. rewrite Heq in H0. destruct (pe_lookup pe_st2 V). rewrite <- beq_nat_refl in H0. inversion H0. inversion H0. Case "<-". assert (Hagree: pe_disagree_at pe_st1 pe_st2 V = false). SCase "Proof of assertion". remember (pe_disagree_at pe_st1 pe_st2 V) as disagree. destruct disagree; [| reflexivity]. apply pe_disagree_domain in Heqdisagree. apply ex_falso_quodlibet. apply Heq. split. assumption. reflexivity. unfold pe_disagree_at in Hagree. destruct (pe_lookup pe_st1 V) as [n1|]; destruct (pe_lookup pe_st2 V) as [n2|]; try reflexivity; try solve by inversion. rewrite negb_false_iff in Hagree. apply beq_nat_true in Hagree. subst. reflexivity. Qed. (** The intersection of two partial states is the result of removing from one of them all the variables where the two disagree. We define the function [pe_removes], in terms of [pe_remove] above, to perform such a removal of a whole list of variables at once. The theorem [pe_compare_removes] testifies that the [pe_lookup] interpretation of the result of this intersection operation is the same no matter which of the two partial states we remove the variables from. Because [pe_override] only depends on the [pe_lookup] interpretation of partial states, [pe_override] also does not care which of the two partial states we remove the variables from; that theorem [pe_compare_override] is used in the correctness proof shortly. *) Fixpoint pe_removes (pe_st:pe_state) (ids : list id) : pe_state := match ids with | [] => pe_st | V::ids => pe_remove (pe_removes pe_st ids) V end. Theorem pe_removes_correct: forall pe_st ids V, pe_lookup (pe_removes pe_st ids) V = if in_dec eq_id_dec V ids then None else pe_lookup pe_st V. Proof. intros pe_st ids V. induction ids as [| V' ids]. reflexivity. simpl. rewrite pe_remove_correct. rewrite IHids. compare V' V Case. reflexivity. destruct (in_dec eq_id_dec V ids); reflexivity. Qed. Theorem pe_compare_removes: forall pe_st1 pe_st2 V, pe_lookup (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) V = pe_lookup (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)) V. Proof. intros pe_st1 pe_st2 V. rewrite !pe_removes_correct. destruct (in_dec eq_id_dec V (pe_compare pe_st1 pe_st2)). reflexivity. apply pe_compare_correct. auto. Qed. Theorem pe_compare_override: forall pe_st1 pe_st2 st, pe_override st (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) = pe_override st (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)). Proof. intros. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_compare_removes. reflexivity. Qed. (** Finally, we define an [assign] function to turn the difference between two partial states into a sequence of assignment commands. More precisely, [assign pe_st ids] generates an assignment command for each variable listed in [ids]. *) Fixpoint assign (pe_st : pe_state) (ids : list id) : com := match ids with | [] => SKIP | V::ids => match pe_lookup pe_st V with | Some n => (assign pe_st ids;; V ::= ANum n) | None => assign pe_st ids end end. (** The command generated by [assign] always terminates, because it is just a sequence of assignments. The (total) function [assigned] below computes the effect of the command on the (dynamic state). The theorem [assign_removes] then confirms that the generated assignments perfectly compensate for removing the variables from the partial state. *) Definition assigned (pe_st:pe_state) (ids : list id) (st:state) : state := fun V => if in_dec eq_id_dec V ids then match pe_lookup pe_st V with | Some n => n | None => st V end else st V. Theorem assign_removes: forall pe_st ids st, pe_override st pe_st = pe_override (assigned pe_st ids st) (pe_removes pe_st ids). Proof. intros pe_st ids st. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_removes_correct. unfold assigned. destruct (in_dec eq_id_dec V ids); destruct (pe_lookup pe_st V); reflexivity. Qed. Lemma ceval_extensionality: forall c st st1 st2, c / st || st1 -> (forall V, st1 V = st2 V) -> c / st || st2. Proof. intros c st st1 st2 H Heq. apply functional_extensionality in Heq. rewrite <- Heq. apply H. Qed. Theorem eval_assign: forall pe_st ids st, assign pe_st ids / st || assigned pe_st ids st. Proof. intros pe_st ids st. induction ids as [| V ids]; simpl. Case "[]". eapply ceval_extensionality. apply E_Skip. reflexivity. Case "V::ids". remember (pe_lookup pe_st V) as lookup. destruct lookup. SCase "Some". eapply E_Seq. apply IHids. unfold assigned. simpl. eapply ceval_extensionality. apply E_Ass. simpl. reflexivity. intros V0. unfold update. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); auto. SCase "None". eapply ceval_extensionality. apply IHids. unfold assigned. intros V0. simpl. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. destruct (in_dec eq_id_dec V ids); reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); reflexivity. Qed. (** ** The Partial Evaluation Relation *) (** At long last, we can define a partial evaluator for commands without loops, as an inductive relation! The inequality conditions in [PE_AssDynamic] and [PE_If] are just to keep the partial evaluator deterministic; they are not required for correctness. *) Reserved Notation "c1 '/' st '||' c1' '/' st'" (at level 40, st at level 39, c1' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2', c1 / pe_st || c1' / pe_st' -> c2 / pe_st' || c2' / pe_st'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 -> c2 / pe_st || c2' / pe_st2 -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) where "c1 '/' st '||' c1' '/' st'" := (pe_com c1 st c1' st'). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" ]. Hint Constructors pe_com. Hint Constructors ceval. (** ** Examples *) (** Below are some examples of using the partial evaluator. To make the [pe_com] relation actually usable for automatic partial evaluation, we would need to define more automation tactics in Coq. That is not hard to do, but it is not needed here. *) Example pe_example1: (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (SKIP;; Y ::= AMult (AId Z) (ANum 6)) / [(X,3)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_AssDynamic. reflexivity. intros n H. inversion H. Qed. Example pe_example2: (X ::= ANum 3 ;; IFB BLe (AId X) (ANum 4) THEN X ::= ANum 4 ELSE SKIP FI) / [] || (SKIP;; SKIP) / [(X,4)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_IfTrue. reflexivity. eapply PE_AssStatic. reflexivity. Qed. Example pe_example3: (X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI) / [] || (SKIP;; IFB BLe (AId Y) (ANum 4) THEN (SKIP;; SKIP);; (SKIP;; Y ::= ANum 4) ELSE SKIP;; SKIP FI) / [(X,3)]. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st). eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_If; intuition eauto; try solve by inversion. econstructor. eapply PE_AssStatic. reflexivity. eapply PE_IfFalse. reflexivity. econstructor. reflexivity. reflexivity. Qed. (** ** Correctness of Partial Evaluation *) (** Finally let's prove that this partial evaluator is correct! *) Reserved Notation "c' '/' pe_st' '/' st '||' st''" (at level 40, pe_st' at level 39, st at level 39). Inductive pe_ceval (c':com) (pe_st':pe_state) (st:state) (st'':state) : Prop := | pe_ceval_intro : forall st', c' / st || st' -> pe_override st' pe_st' = st'' -> c' / pe_st' / st || st'' where "c' '/' pe_st' '/' st '||' st''" := (pe_ceval c' pe_st' st st''). Hint Constructors pe_ceval. Theorem pe_com_complete: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') -> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. reflexivity. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. reflexivity. Case "PE_Seq". edestruct IHHpe1. eassumption. subst. edestruct IHHpe2. eassumption. eauto. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c' / pe_st' / st || st'') -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' [st' Heval Heq]; try (inversion Heval; []; subst); auto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_If". inversion Heval; subst; inversion H7; (eapply ceval_deterministic in H8; [| apply eval_assign]); subst. SCase "E_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. SCase "E_IfFalse". rewrite -> pe_compare_override. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. Qed. (** The main theorem. Thanks to David Menendez for this formulation! *) Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') <-> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". apply pe_com_complete. apply H. Case "<-". apply pe_com_sound. apply H. Qed. (* ####################################################### *) (** * Partial Evaluation of Loops *) (** It may seem straightforward at first glance to extend the partial evaluation relation [pe_com] above to loops. Indeed, many loops are easy to deal with. Considered this repeated-squaring loop, for example: WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END If we know neither [X] nor [Y] statically, then the entire loop is dynamic and the residual command should be the same. If we know [X] but not [Y], then the loop can be unrolled all the way and the residual command should be Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y) if [X] is initially [3] (and finally [0]). In general, a loop is easy to partially evaluate if the final partial state of the loop body is equal to the initial state, or if its guard condition is static. But there are other loops for which it is hard to express the residual program we want in Imp. For example, take this program for checking if [Y] is even or odd: X ::= ANum 0;; WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; X ::= AMinus (ANum 1) (AId X) END The value of [X] alternates between [0] and [1] during the loop. Ideally, we would like to unroll this loop, not all the way but _two-fold_, into something like WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; IF BLe (ANum 1) (AId Y) THEN Y ::= AMinus (AId Y) (ANum 1) ELSE X ::= ANum 1;; EXIT FI END;; X ::= ANum 0 Unfortunately, there is no [EXIT] command in Imp. Without extending the range of control structures available in our language, the best we can do is to repeat loop-guard tests or add flag variables. Neither option is terribly attractive. Still, as a digression, below is an attempt at performing partial evaluation on Imp commands. We add one more command argument [c''] to the [pe_com] relation, which keeps track of a loop to roll up. *) Module Loop. Reserved Notation "c1 '/' st '||' c1' '/' st' '/' c''" (at level 40, st at level 39, c1' at level 39, st' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> com -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st / SKIP | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 / SKIP | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l / SKIP | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2' c'', c1 / pe_st || c1' / pe_st' / SKIP -> c2 / pe_st' || c2' / pe_st'' / c'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' / c'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1' c'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' / c'' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2' c'', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' / c'' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2' c'', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 / c'' -> c2 / pe_st || c2' / pe_st2 / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) / c'' | PE_WhileEnd : forall pe_st b1 c1, pe_bexp pe_st b1 = BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / SKIP | PE_WhileLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (WHILE b1 DO c1 END) / pe_st || (c1';;c2') / pe_st'' / c2'' | PE_While : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (c2'' = SKIP \/ c2'' = WHILE b1 DO c1 END) -> (WHILE b1 DO c1 END) / pe_st || (IFB pe_bexp pe_st b1 THEN c1';; c2';; assign pe_st'' (pe_compare pe_st pe_st'') ELSE assign pe_st (pe_compare pe_st pe_st'') FI) / pe_removes pe_st (pe_compare pe_st pe_st'') / c2'' | PE_WhileFixedEnd : forall pe_st b1 c1, pe_bexp pe_st b1 <> BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE b1 DO c1 END) | PE_WhileFixedLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE BTrue DO SKIP END) / pe_st / SKIP (* Because we have an infinite loop, we should actually start to throw away the rest of the program: (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE BTrue DO SKIP END) *) | PE_WhileFixed : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE pe_bexp pe_st b1 DO c1';; c2' END) / pe_st / SKIP where "c1 '/' st '||' c1' '/' st' '/' c''" := (pe_com c1 st c1' st' c''). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" | Case_aux c "PE_WhileEnd" | Case_aux c "PE_WhileLoop" | Case_aux c "PE_While" | Case_aux c "PE_WhileFixedEnd" | Case_aux c "PE_WhileFixedLoop" | Case_aux c "PE_WhileFixed" ]. Hint Constructors pe_com. (** ** Examples *) Ltac step i := (eapply i; intuition eauto; try solve by inversion); repeat (try eapply PE_Seq; try (eapply PE_AssStatic; simpl; reflexivity); try (eapply PE_AssDynamic; [ simpl; reflexivity | intuition eauto; solve by inversion ])). Definition square_loop: com := WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END. Example pe_loop_example1: square_loop / [] || (WHILE BLe (ANum 1) (AId X) DO (Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1));; SKIP END) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. reflexivity. reflexivity. Qed. Example pe_loop_example2: (X ::= ANum 3;; square_loop) / [] || (SKIP;; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; SKIP) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileEnd. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example3: (Z ::= ANum 3;; subtract_slowly) / [] || (SKIP;; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; WHILE BNot (BEq (AId X) (ANum 0)) DO (SKIP;; X ::= AMinus (AId X) (ANum 1));; SKIP END;; SKIP;; Z ::= ANum 0 ELSE SKIP;; Z ::= ANum 1 FI;; SKIP ELSE SKIP;; Z ::= ANum 2 FI;; SKIP ELSE SKIP;; Z ::= ANum 3 FI) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_While. step PE_While. step PE_While. step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example4: (X ::= ANum 0;; WHILE BLe (AId X) (ANum 2) DO X ::= AMinus (ANum 1) (AId X) END) / [] || (SKIP;; WHILE BTrue DO SKIP END) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileFixedLoop. step PE_WhileLoop. step PE_WhileFixedEnd. inversion H. reflexivity. reflexivity. reflexivity. Qed. (** ** Correctness *) (** Because this partial evaluator can unroll a loop n-fold where n is a (finite) integer greater than one, in order to show it correct we need to perform induction not structurally on dynamic evaluation but on the number of times dynamic evaluation enters a loop body. *) Reserved Notation "c1 '/' st '||' st' '#' n" (at level 40, st at level 39, st' at level 39). Inductive ceval_count : com -> state -> state -> nat -> Prop := | E'Skip : forall st, SKIP / st || st # 0 | E'Ass : forall st a1 n l, aeval st a1 = n -> (l ::= a1) / st || (update st l n) # 0 | E'Seq : forall c1 c2 st st' st'' n1 n2, c1 / st || st' # n1 -> c2 / st' || st'' # n2 -> (c1 ;; c2) / st || st'' # (n1 + n2) | E'IfTrue : forall st st' b1 c1 c2 n, beval st b1 = true -> c1 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'IfFalse : forall st st' b1 c1 c2 n, beval st b1 = false -> c2 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'WhileEnd : forall b1 st c1, beval st b1 = false -> (WHILE b1 DO c1 END) / st || st # 0 | E'WhileLoop : forall st st' st'' b1 c1 n1 n2, beval st b1 = true -> c1 / st || st' # n1 -> (WHILE b1 DO c1 END) / st' || st'' # n2 -> (WHILE b1 DO c1 END) / st || st'' # S (n1 + n2) where "c1 '/' st '||' st' # n" := (ceval_count c1 st st' n). Tactic Notation "ceval_count_cases" tactic(first) ident(c) := first; [ Case_aux c "E'Skip" | Case_aux c "E'Ass" | Case_aux c "E'Seq" | Case_aux c "E'IfTrue" | Case_aux c "E'IfFalse" | Case_aux c "E'WhileEnd" | Case_aux c "E'WhileLoop" ]. Hint Constructors ceval_count. Theorem ceval_count_complete: forall c st st', c / st || st' -> exists n, c / st || st' # n. Proof. intros c st st' Heval. induction Heval; try inversion IHHeval1; try inversion IHHeval2; try inversion IHHeval; eauto. Qed. Theorem ceval_count_sound: forall c st st' n, c / st || st' # n -> c / st || st'. Proof. intros c st st' n Heval. induction Heval; eauto. Qed. Theorem pe_compare_nil_lookup: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall V, pe_lookup pe_st1 V = pe_lookup pe_st2 V. Proof. intros pe_st1 pe_st2 H V. apply (pe_compare_correct pe_st1 pe_st2 V). rewrite H. intro. inversion H0. Qed. Theorem pe_compare_nil_override: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall st, pe_override st pe_st1 = pe_override st pe_st2. Proof. intros pe_st1 pe_st2 H st. apply functional_extensionality. intros V. rewrite !pe_override_correct. apply pe_compare_nil_lookup with (V:=V) in H. rewrite H. reflexivity. Qed. Reserved Notation "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" (at level 40, pe_st' at level 39, c'' at level 39, st at level 39, st'' at level 39). Inductive pe_ceval_count (c':com) (pe_st':pe_state) (c'':com) (st:state) (st'':state) (n:nat) : Prop := | pe_ceval_count_intro : forall st' n', c' / st || st' -> c'' / pe_override st' pe_st' || st'' # n' -> n' <= n -> c' / pe_st' / c'' / st || st'' # n where "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" := (pe_ceval_count c' pe_st' c'' st st'' n). Hint Constructors pe_ceval_count. Lemma pe_ceval_count_le: forall c' pe_st' c'' st st'' n n', n' <= n -> c' / pe_st' / c'' / st || st'' # n' -> c' / pe_st' / c'' / st || st'' # n. Proof. intros c' pe_st' c'' st st'' n n' Hle H. inversion H. econstructor; try eassumption. omega. Qed. Theorem pe_com_complete: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c / pe_override st pe_st || st'' # n) -> (c' / pe_st' / c'' / st || st'' # n). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. apply E'Skip. auto. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. apply E'Skip. auto. Case "PE_Seq". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. eassumption. Case "PE_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_While". inversion Heval; subst. SCase "E_WhileEnd". econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. apply eval_assign. rewrite <- assign_removes. inversion H2; subst; auto. auto. SCase "E_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. repeat eapply E_Seq; eauto. apply eval_assign. rewrite -> pe_compare_override, <- assign_removes. eassumption. omega. Case "PE_WhileFixedLoop". apply ex_falso_quodlibet. generalize dependent (S (n1 + n2)). intros n. clear - Case H H0 IHHpe1 IHHpe2. generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct, H in H7. inversion H7. SCase "E'WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H0) in H7. apply H1 in H7; [| omega]. inversion H7. Case "PE_WhileFixed". generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct in H8. eauto. SCase "E'WhileLoop". rewrite pe_bexp_correct in H5. edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H1) in H8. apply H2 in H8; [| omega]. inversion H8. econstructor; [ eapply E_WhileLoop; eauto | eassumption | omega]. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c' / pe_st' / c'' / st || st'' # n) -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n [st' n' Heval Heval' Hle]; try (inversion Heval; []; subst); try (inversion Heval'; []; subst); eauto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_If". inversion Heval; subst; inversion H7; subst; clear H7. SCase "E_IfTrue". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. SCase "E_IfFalse". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. eapply IHHpe2. eauto. Case "PE_WhileEnd". apply E_WhileEnd. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. Case "PE_WhileLoop". eapply E_WhileLoop. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe1. eauto. eapply IHHpe2. eauto. Case "PE_While". inversion Heval; subst. SCase "E_IfTrue". inversion H9. subst. clear H9. inversion H10. subst. clear H10. eapply ceval_deterministic in H11; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. eapply E_WhileLoop. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. eapply IHHpe2. eauto. SCase "E_IfFalse". apply ceval_count_sound in Heval'. eapply ceval_deterministic in H9; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. inversion H2; subst. SSCase "c2'' = SKIP". inversion Heval'. subst. apply E_WhileEnd. rewrite -> pe_bexp_correct. assumption. SSCase "c2'' = WHILE b1 DO c1 END". assumption. Case "PE_WhileFixedEnd". eapply ceval_count_sound. apply Heval'. Case "PE_WhileFixedLoop". apply loop_never_stops in Heval. inversion Heval. Case "PE_WhileFixed". clear - Case H1 IHHpe1 IHHpe2 Heval. remember (WHILE pe_bexp pe_st b1 DO c1';; c2' END) as c'. ceval_cases (induction Heval) SCase; inversion Heqc'; subst; clear Heqc'. SCase "E_WhileEnd". apply E_WhileEnd. rewrite pe_bexp_correct. assumption. SCase "E_WhileLoop". assert (IHHeval2' := IHHeval2 (refl_equal _)). apply ceval_count_complete in IHHeval2'. inversion IHHeval2'. clear IHHeval1 IHHeval2 IHHeval2'. inversion Heval1. subst. eapply E_WhileLoop. rewrite pe_bexp_correct. assumption. eauto. eapply IHHpe2. econstructor. eassumption. rewrite <- (pe_compare_nil_override _ _ H1). eassumption. apply le_n. Qed. Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' / SKIP -> forall st st'', (c / pe_override st pe_st || st'') <-> (exists st', c' / st || st' /\ pe_override st' pe_st' = st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". intros Heval. apply ceval_count_complete in Heval. inversion Heval as [n Heval']. apply pe_com_complete with (st:=st) (st'':=st'') (n:=n) in H. inversion H as [? ? ? Hskip ?]. inversion Hskip. subst. eauto. assumption. Case "<-". intros [st' [Heval Heq]]. subst st''. eapply pe_com_sound in H. apply H. econstructor. apply Heval. apply E'Skip. apply le_n. Qed. End Loop. (* ####################################################### *) (** * Partial Evaluation of Flowchart Programs *) (** Instead of partially evaluating [WHILE] loops directly, the standard approach to partially evaluating imperative programs is to convert them into _flowcharts_. In other words, it turns out that adding labels and jumps to our language makes it much easier to partially evaluate. The result of partially evaluating a flowchart is a residual flowchart. If we are lucky, the jumps in the residual flowchart can be converted back to [WHILE] loops, but that is not possible in general; we do not pursue it here. *) (** ** Basic blocks *) (** A flowchart is made of _basic blocks_, which we represent with the inductive type [block]. A basic block is a sequence of assignments (the constructor [Assign]), concluding with a conditional jump (the constructor [If]) or an unconditional jump (the constructor [Goto]). The destinations of the jumps are specified by _labels_, which can be of any type. Therefore, we parameterize the [block] type by the type of labels. *) Inductive block (Label:Type) : Type := | Goto : Label -> block Label | If : bexp -> Label -> Label -> block Label | Assign : id -> aexp -> block Label -> block Label. Tactic Notation "block_cases" tactic(first) ident(c) := first; [ Case_aux c "Goto" | Case_aux c "If" | Case_aux c "Assign" ]. Arguments Goto {Label} _. Arguments If {Label} _ _ _. Arguments Assign {Label} _ _ _. (** We use the "even or odd" program, expressed above in Imp, as our running example. Converting this program into a flowchart turns out to require 4 labels, so we define the following type. *) Inductive parity_label : Type := | entry : parity_label | loop : parity_label | body : parity_label | done : parity_label. (** The following [block] is the basic block found at the [body] label of the example program. *) Definition parity_body : block parity_label := Assign Y (AMinus (AId Y) (ANum 1)) (Assign X (AMinus (ANum 1) (AId X)) (Goto loop)). (** To evaluate a basic block, given an initial state, is to compute the final state and the label to jump to next. Because basic blocks do not _contain_ loops or other control structures, evaluation of basic blocks is a total function -- we don't need to worry about non-termination. *) Fixpoint keval {L:Type} (st:state) (k : block L) : state * L := match k with | Goto l => (st, l) | If b l1 l2 => (st, if beval st b then l1 else l2) | Assign i a k => keval (update st i (aeval st a)) k end. Example keval_example: keval empty_state parity_body = (update (update empty_state Y 0) X 1, loop). Proof. reflexivity. Qed. (** ** Flowchart programs *) (** A flowchart program is simply a lookup function that maps labels to basic blocks. Actually, some labels are _halting states_ and do not map to any basic block. So, more precisely, a flowchart [program] whose labels are of type [L] is a function from [L] to [option (block L)]. *) Definition program (L:Type) : Type := L -> option (block L). Definition parity : program parity_label := fun l => match l with | entry => Some (Assign X (ANum 0) (Goto loop)) | loop => Some (If (BLe (ANum 1) (AId Y)) body done) | body => Some parity_body | done => None (* halt *) end. (** Unlike a basic block, a program may not terminate, so we model the evaluation of programs by an inductive relation [peval] rather than a recursive function. *) Inductive peval {L:Type} (p : program L) : state -> L -> state -> L -> Prop := | E_None: forall st l, p l = None -> peval p st l st l | E_Some: forall st l k st' l' st'' l'', p l = Some k -> keval st k = (st', l') -> peval p st' l' st'' l'' -> peval p st l st'' l''. Example parity_eval: peval parity empty_state entry empty_state done. Proof. erewrite f_equal with (f := fun st => peval _ _ _ st _). eapply E_Some. reflexivity. reflexivity. eapply E_Some. reflexivity. reflexivity. apply E_None. reflexivity. apply functional_extensionality. intros i. rewrite update_same; auto. Qed. Tactic Notation "peval_cases" tactic(first) ident(c) := first; [ Case_aux c "E_None" | Case_aux c "E_Some" ]. (** ** Partial evaluation of basic blocks and flowchart programs *) (** Partial evaluation changes the label type in a systematic way: if the label type used to be [L], it becomes [pe_state * L]. So the same label in the original program may be unfolded, or blown up, into multiple labels by being paired with different partial states. For example, the label [loop] in the [parity] program will become two labels: [([(X,0)], loop)] and [([(X,1)], loop)]. This change of label type is reflected in the types of [pe_block] and [pe_program] defined presently. *) Fixpoint pe_block {L:Type} (pe_st:pe_state) (k : block L) : block (pe_state * L) := match k with | Goto l => Goto (pe_st, l) | If b l1 l2 => match pe_bexp pe_st b with | BTrue => Goto (pe_st, l1) | BFalse => Goto (pe_st, l2) | b' => If b' (pe_st, l1) (pe_st, l2) end | Assign i a k => match pe_aexp pe_st a with | ANum n => pe_block (pe_add pe_st i n) k | a' => Assign i a' (pe_block (pe_remove pe_st i) k) end end. Example pe_block_example: pe_block [(X,0)] parity_body = Assign Y (AMinus (AId Y) (ANum 1)) (Goto ([(X,1)], loop)). Proof. reflexivity. Qed. Theorem pe_block_correct: forall (L:Type) st pe_st k st' pe_st' (l':L), keval st (pe_block pe_st k) = (st', (pe_st', l')) -> keval (pe_override st pe_st) k = (pe_override st' pe_st', l'). Proof. intros. generalize dependent pe_st. generalize dependent st. block_cases (induction k as [l | b l1 l2 | i a k]) Case; intros st pe_st H. Case "Goto". inversion H; reflexivity. Case "If". replace (keval st (pe_block pe_st (If b l1 l2))) with (keval st (If (pe_bexp pe_st b) (pe_st, l1) (pe_st, l2))) in H by (simpl; destruct (pe_bexp pe_st b); reflexivity). simpl in *. rewrite pe_bexp_correct. destruct (beval st (pe_bexp pe_st b)); inversion H; reflexivity. Case "Assign". simpl in *. rewrite pe_aexp_correct. destruct (pe_aexp pe_st a); simpl; try solve [rewrite pe_override_update_add; apply IHk; apply H]; solve [rewrite pe_override_update_remove; apply IHk; apply H]. Qed. Definition pe_program {L:Type} (p : program L) : program (pe_state * L) := fun pe_l => match pe_l with (pe_st, l) => option_map (pe_block pe_st) (p l) end. Inductive pe_peval {L:Type} (p : program L) (st:state) (pe_st:pe_state) (l:L) (st'o:state) (l':L) : Prop := | pe_peval_intro : forall st' pe_st', peval (pe_program p) st (pe_st, l) st' (pe_st', l') -> pe_override st' pe_st' = st'o -> pe_peval p st pe_st l st'o l'. Theorem pe_program_correct: forall (L:Type) (p : program L) st pe_st l st'o l', peval p (pe_override st pe_st) l st'o l' <-> pe_peval p st pe_st l st'o l'. Proof. intros. split; [Case "->" | Case "<-"]. Case "->". intros Heval. remember (pe_override st pe_st) as sto. generalize dependent pe_st. generalize dependent st. peval_cases (induction Heval as [ sto l Hlookup | sto l k st'o l' st''o l'' Hlookup Hkeval Heval ]) SCase; intros st pe_st Heqsto; subst sto. SCase "E_None". eapply pe_peval_intro. apply E_None. simpl. rewrite Hlookup. reflexivity. reflexivity. SCase "E_Some". remember (keval st (pe_block pe_st k)) as x. destruct x as [st' [pe_st' l'_]]. symmetry in Heqx. erewrite pe_block_correct in Hkeval by apply Heqx. inversion Hkeval. subst st'o l'_. clear Hkeval. edestruct IHHeval. reflexivity. subst st''o. clear IHHeval. eapply pe_peval_intro; [| reflexivity]. eapply E_Some; eauto. simpl. rewrite Hlookup. reflexivity. Case "<-". intros [st' pe_st' Heval Heqst'o]. remember (pe_st, l) as pe_st_l. remember (pe_st', l') as pe_st'_l'. generalize dependent pe_st. generalize dependent l. peval_cases (induction Heval as [ st [pe_st_ l_] Hlookup | st [pe_st_ l_] pe_k st' [pe_st'_ l'_] st'' [pe_st'' l''] Hlookup Hkeval Heval ]) SCase; intros l pe_st Heqpe_st_l; inversion Heqpe_st_l; inversion Heqpe_st'_l'; repeat subst. SCase "E_None". apply E_None. simpl in Hlookup. destruct (p l'); [ solve [ inversion Hlookup ] | reflexivity ]. SCase "E_Some". simpl in Hlookup. remember (p l) as k. destruct k as [k|]; inversion Hlookup; subst. eapply E_Some; eauto. apply pe_block_correct. apply Hkeval. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
(** * PE: Partial Evaluation *) (* Chapter author/maintainer: Chung-chieh Shan *) (** Equiv.v introduced constant folding as an example of a program transformation and proved that it preserves the meaning of the program. Constant folding operates on manifest constants such as [ANum] expressions. For example, it simplifies the command [Y ::= APlus (ANum 3) (ANum 1)] to the command [Y ::= ANum 4]. However, it does not propagate known constants along data flow. For example, it does not simplify the sequence X ::= ANum 3;; Y ::= APlus (AId X) (ANum 1) to X ::= ANum 3;; Y ::= ANum 4 because it forgets that [X] is [3] by the time it gets to [Y]. We naturally want to enhance constant folding so that it propagates known constants and uses them to simplify programs. Doing so constitutes a rudimentary form of _partial evaluation_. As we will see, partial evaluation is so called because it is like running a program, except only part of the program can be evaluated because only part of the input to the program is known. For example, we can only simplify the program X ::= ANum 3;; Y ::= AMinus (APlus (AId X) (ANum 1)) (AId Y) to X ::= ANum 3;; Y ::= AMinus (ANum 4) (AId Y) without knowing the initial value of [Y]. *) Require Export Imp. Require Import FunctionalExtensionality. (* ####################################################### *) (** * Generalizing Constant Folding *) (** The starting point of partial evaluation is to represent our partial knowledge about the state. For example, between the two assignments above, the partial evaluator may know only that [X] is [3] and nothing about any other variable. *) (** ** Partial States *) (** Conceptually speaking, we can think of such partial states as the type [id -> option nat] (as opposed to the type [id -> nat] of concrete, full states). However, in addition to looking up and updating the values of individual variables in a partial state, we may also want to compare two partial states to see if and where they differ, to handle conditional control flow. It is not possible to compare two arbitrary functions in this way, so we represent partial states in a more concrete format: as a list of [id * nat] pairs. *) Definition pe_state := list (id * nat). (** The idea is that a variable [id] appears in the list if and only if we know its current [nat] value. The [pe_lookup] function thus interprets this concrete representation. (If the same variable [id] appears multiple times in the list, the first occurrence wins, but we will define our partial evaluator to never construct such a [pe_state].) *) Fixpoint pe_lookup (pe_st : pe_state) (V:id) : option nat := match pe_st with | [] => None | (V',n')::pe_st => if eq_id_dec V V' then Some n' else pe_lookup pe_st V end. (** For example, [empty_pe_state] represents complete ignorance about every variable -- the function that maps every [id] to [None]. *) Definition empty_pe_state : pe_state := []. (** More generally, if the [list] representing a [pe_state] does not contain some [id], then that [pe_state] must map that [id] to [None]. Before we prove this fact, we first define a useful tactic for reasoning with [id] equality. The tactic compare V V' SCase means to reason by cases over [eq_id_dec V V']. In the case where [V = V'], the tactic substitutes [V] for [V'] throughout. *) Tactic Notation "compare" ident(i) ident(j) ident(c) := let H := fresh "Heq" i j in destruct (eq_id_dec i j); [ Case_aux c "equal"; subst j | Case_aux c "not equal" ]. Theorem pe_domain: forall pe_st V n, pe_lookup pe_st V = Some n -> In V (map (@fst _ _) pe_st). Proof. intros pe_st V n H. induction pe_st as [| [V' n'] pe_st]. Case "[]". inversion H. Case "::". simpl in H. simpl. compare V V' SCase; auto. Qed. (** *** Aside on [In]. We will make heavy use of the [In] predicate from the standard library. [In] is equivalent to the [appears_in] predicate introduced in Logic.v, but defined using a [Fixpoint] rather than an [Inductive]. *) Print In. (* ===> Fixpoint In {A:Type} (a: A) (l:list A) : Prop := match l with | [] => False | b :: m => b = a \/ In a m end : forall A : Type, A -> list A -> Prop *) (** [In] comes with various useful lemmas. *) Check in_or_app. (* ===> in_or_app: forall (A : Type) (l m : list A) (a : A), In a l \/ In a m -> In a (l ++ m) *) Check filter_In. (* ===> filter_In : forall (A : Type) (f : A -> bool) (x : A) (l : list A), In x (filter f l) <-> In x l /\ f x = true *) Check in_dec. (* ===> in_dec : forall A : Type, (forall x y : A, {x = y} + {x <> y}) -> forall (a : A) (l : list A), {In a l} + {~ In a l}] *) (** Note that we can compute with [in_dec], just as with [eq_id_dec]. *) (** ** Arithmetic Expressions *) (** Partial evaluation of [aexp] is straightforward -- it is basically the same as constant folding, [fold_constants_aexp], except that sometimes the partial state tells us the current value of a variable and we can replace it by a constant expression. *) Fixpoint pe_aexp (pe_st : pe_state) (a : aexp) : aexp := match a with | ANum n => ANum n | AId i => match pe_lookup pe_st i with (* <----- NEW *) | Some n => ANum n | None => AId i end | APlus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 + n2) | (a1', a2') => APlus a1' a2' end | AMinus a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 - n2) | (a1', a2') => AMinus a1' a2' end | AMult a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => ANum (n1 * n2) | (a1', a2') => AMult a1' a2' end end. (** This partial evaluator folds constants but does not apply the associativity of addition. *) Example test_pe_aexp1: pe_aexp [(X,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (ANum 4) (AId Y). Proof. reflexivity. Qed. Example text_pe_aexp2: pe_aexp [(Y,3)] (APlus (APlus (AId X) (ANum 1)) (AId Y)) = APlus (APlus (AId X) (ANum 1)) (ANum 3). Proof. reflexivity. Qed. (** Now, in what sense is [pe_aexp] correct? It is reasonable to define the correctness of [pe_aexp] as follows: whenever a full state [st:state] is _consistent_ with a partial state [pe_st:pe_state] (in other words, every variable to which [pe_st] assigns a value is assigned the same value by [st]), evaluating [a] and evaluating [pe_aexp pe_st a] in [st] yields the same result. This statement is indeed true. *) Definition pe_consistent (st:state) (pe_st:pe_state) := forall V n, Some n = pe_lookup pe_st V -> st V = n. Theorem pe_aexp_correct_weak: forall st pe_st, pe_consistent st pe_st -> forall a, aeval st a = aeval st (pe_aexp pe_st a). Proof. unfold pe_consistent. intros st pe_st H a. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId *) Case "AId". remember (pe_lookup pe_st i) as l. destruct l. SCase "Some". rewrite H with (n:=n) by apply Heql. reflexivity. SCase "None". reflexivity. Qed. (** However, we will soon want our partial evaluator to remove assignments. For example, it will simplify X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to just Y ::= AMinus (ANum 3) (AId Y);; X ::= ANum 4 by delaying the assignment to [X] until the end. To accomplish this simplification, we need the result of partial evaluating pe_aexp [(X,3)] (AMinus (AId X) (AId Y)) to be equal to [AMinus (ANum 3) (AId Y)] and _not_ the original expression [AMinus (AId X) (AId Y)]. After all, it would be incorrect, not just inefficient, to transform X ::= ANum 3;; Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 to Y ::= AMinus (AId X) (AId Y);; X ::= ANum 4 even though the output expressions [AMinus (ANum 3) (AId Y)] and [AMinus (AId X) (AId Y)] both satisfy the correctness criterion that we just proved. Indeed, if we were to just define [pe_aexp pe_st a = a] then the theorem [pe_aexp_correct'] would already trivially hold. Instead, we want to prove that the [pe_aexp] is correct in a stronger sense: evaluating the expression produced by partial evaluation ([aeval st (pe_aexp pe_st a)]) must not depend on those parts of the full state [st] that are already specified in the partial state [pe_st]. To be more precise, let us define a function [pe_override], which updates [st] with the contents of [pe_st]. In other words, [pe_override] carries out the assignments listed in [pe_st] on top of [st]. *) Fixpoint pe_override (st:state) (pe_st:pe_state) : state := match pe_st with | [] => st | (V,n)::pe_st => update (pe_override st pe_st) V n end. Example test_pe_override: pe_override (update empty_state Y 1) [(X,3);(Z,2)] = update (update (update empty_state Y 1) Z 2) X 3. Proof. reflexivity. Qed. (** Although [pe_override] operates on a concrete [list] representing a [pe_state], its behavior is defined entirely by the [pe_lookup] interpretation of the [pe_state]. *) Theorem pe_override_correct: forall st pe_st V0, pe_override st pe_st V0 = match pe_lookup pe_st V0 with | Some n => n | None => st V0 end. Proof. intros. induction pe_st as [| [V n] pe_st]. reflexivity. simpl in *. unfold update. compare V0 V Case; auto. rewrite eq_id; auto. rewrite neq_id; auto. Qed. (** We can relate [pe_consistent] to [pe_override] in two ways. First, overriding a state with a partial state always gives a state that is consistent with the partial state. Second, if a state is already consistent with a partial state, then overriding the state with the partial state gives the same state. *) Theorem pe_override_consistent: forall st pe_st, pe_consistent (pe_override st pe_st) pe_st. Proof. intros st pe_st V n H. rewrite pe_override_correct. destruct (pe_lookup pe_st V); inversion H. reflexivity. Qed. Theorem pe_consistent_override: forall st pe_st, pe_consistent st pe_st -> forall V, st V = pe_override st pe_st V. Proof. intros st pe_st H V. rewrite pe_override_correct. remember (pe_lookup pe_st V) as l. destruct l; auto. Qed. (** Now we can state and prove that [pe_aexp] is correct in the stronger sense that will help us define the rest of the partial evaluator. Intuitively, running a program using partial evaluation is a two-stage process. In the first, _static_ stage, we partially evaluate the given program with respect to some partial state to get a _residual_ program. In the second, _dynamic_ stage, we evaluate the residual program with respect to the rest of the state. This dynamic state provides values for those variables that are unknown in the static (partial) state. Thus, the residual program should be equivalent to _prepending_ the assignments listed in the partial state to the original program. *) Theorem pe_aexp_correct: forall (pe_st:pe_state) (a:aexp) (st:state), aeval (pe_override st pe_st) a = aeval st (pe_aexp pe_st a). Proof. intros pe_st a st. aexp_cases (induction a) Case; simpl; try reflexivity; try (destruct (pe_aexp pe_st a1); destruct (pe_aexp pe_st a2); rewrite IHa1; rewrite IHa2; reflexivity). (* Compared to fold_constants_aexp_sound, the only interesting case is AId. *) rewrite pe_override_correct. destruct (pe_lookup pe_st i); reflexivity. Qed. (** ** Boolean Expressions *) (** The partial evaluation of boolean expressions is similar. In fact, it is entirely analogous to the constant folding of boolean expressions, because our language has no boolean variables. *) Fixpoint pe_bexp (pe_st : pe_state) (b : bexp) : bexp := match b with | BTrue => BTrue | BFalse => BFalse | BEq a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if beq_nat n1 n2 then BTrue else BFalse | (a1', a2') => BEq a1' a2' end | BLe a1 a2 => match (pe_aexp pe_st a1, pe_aexp pe_st a2) with | (ANum n1, ANum n2) => if ble_nat n1 n2 then BTrue else BFalse | (a1', a2') => BLe a1' a2' end | BNot b1 => match (pe_bexp pe_st b1) with | BTrue => BFalse | BFalse => BTrue | b1' => BNot b1' end | BAnd b1 b2 => match (pe_bexp pe_st b1, pe_bexp pe_st b2) with | (BTrue, BTrue) => BTrue | (BTrue, BFalse) => BFalse | (BFalse, BTrue) => BFalse | (BFalse, BFalse) => BFalse | (b1', b2') => BAnd b1' b2' end end. Example test_pe_bexp1: pe_bexp [(X,3)] (BNot (BLe (AId X) (ANum 3))) = BFalse. Proof. reflexivity. Qed. Example test_pe_bexp2: forall b, b = BNot (BLe (AId X) (APlus (AId X) (ANum 1))) -> pe_bexp [] b = b. Proof. intros b H. rewrite -> H. reflexivity. Qed. (** The correctness of [pe_bexp] is analogous to the correctness of [pe_aexp] above. *) Theorem pe_bexp_correct: forall (pe_st:pe_state) (b:bexp) (st:state), beval (pe_override st pe_st) b = beval st (pe_bexp pe_st b). Proof. intros pe_st b st. bexp_cases (induction b) Case; simpl; try reflexivity; try (remember (pe_aexp pe_st a) as a'; remember (pe_aexp pe_st a0) as a0'; assert (Ha: aeval (pe_override st pe_st) a = aeval st a'); assert (Ha0: aeval (pe_override st pe_st) a0 = aeval st a0'); try (subst; apply pe_aexp_correct); destruct a'; destruct a0'; rewrite Ha; rewrite Ha0; simpl; try destruct (beq_nat n n0); try destruct (ble_nat n n0); reflexivity); try (destruct (pe_bexp pe_st b); rewrite IHb; reflexivity); try (destruct (pe_bexp pe_st b1); destruct (pe_bexp pe_st b2); rewrite IHb1; rewrite IHb2; reflexivity). Qed. (* ####################################################### *) (** * Partial Evaluation of Commands, Without Loops *) (** What about the partial evaluation of commands? The analogy between partial evaluation and full evaluation continues: Just as full evaluation of a command turns an initial state into a final state, partial evaluation of a command turns an initial partial state into a final partial state. The difference is that, because the state is partial, some parts of the command may not be executable at the static stage. Therefore, just as [pe_aexp] returns a residual [aexp] and [pe_bexp] returns a residual [bexp] above, partially evaluating a command yields a residual command. Another way in which our partial evaluator is similar to a full evaluator is that it does not terminate on all commands. It is not hard to build a partial evaluator that terminates on all commands; what is hard is building a partial evaluator that terminates on all commands yet automatically performs desired optimizations such as unrolling loops. Often a partial evaluator can be coaxed into terminating more often and performing more optimizations by writing the source program differently so that the separation between static and dynamic information becomes more apparent. Such coaxing is the art of _binding-time improvement_. The binding time of a variable tells when its value is known -- either "static", or "dynamic." Anyway, for now we will just live with the fact that our partial evaluator is not a total function from the source command and the initial partial state to the residual command and the final partial state. To model this non-termination, just as with the full evaluation of commands, we use an inductively defined relation. We write c1 / st || c1' / st' to mean that partially evaluating the source command [c1] in the initial partial state [st] yields the residual command [c1'] and the final partial state [st']. For example, we want something like (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (Y ::= AMult (AId Z) (ANum 6)) / [(X,3)] to hold. The assignment to [X] appears in the final partial state, not the residual command. *) (** ** Assignment *) (** Let's start by considering how to partially evaluate an assignment. The two assignments in the source program above needs to be treated differently. The first assignment [X ::= ANum 3], is _static_: its right-hand-side is a constant (more generally, simplifies to a constant), so we should update our partial state at [X] to [3] and produce no residual code. (Actually, we produce a residual [SKIP].) The second assignment [Y ::= AMult (AId Z) (APlus (AId X) (AId X))] is _dynamic_: its right-hand-side does not simplify to a constant, so we should leave it in the residual code and remove [Y], if present, from our partial state. To implement these two cases, we define the functions [pe_add] and [pe_remove]. Like [pe_override] above, these functions operate on a concrete [list] representing a [pe_state], but the theorems [pe_add_correct] and [pe_remove_correct] specify their behavior by the [pe_lookup] interpretation of the [pe_state]. *) Fixpoint pe_remove (pe_st:pe_state) (V:id) : pe_state := match pe_st with | [] => [] | (V',n')::pe_st => if eq_id_dec V V' then pe_remove pe_st V else (V',n') :: pe_remove pe_st V end. Theorem pe_remove_correct: forall pe_st V V0, pe_lookup (pe_remove pe_st V) V0 = if eq_id_dec V V0 then None else pe_lookup pe_st V0. Proof. intros pe_st V V0. induction pe_st as [| [V' n'] pe_st]. Case "[]". destruct (eq_id_dec V V0); reflexivity. Case "::". simpl. compare V V' SCase. SCase "equal". rewrite IHpe_st. destruct (eq_id_dec V V0). reflexivity. rewrite neq_id; auto. SCase "not equal". simpl. compare V0 V' SSCase. SSCase "equal". rewrite neq_id; auto. SSCase "not equal". rewrite IHpe_st. reflexivity. Qed. Definition pe_add (pe_st:pe_state) (V:id) (n:nat) : pe_state := (V,n) :: pe_remove pe_st V. Theorem pe_add_correct: forall pe_st V n V0, pe_lookup (pe_add pe_st V n) V0 = if eq_id_dec V V0 then Some n else pe_lookup pe_st V0. Proof. intros pe_st V n V0. unfold pe_add. simpl. compare V V0 Case. Case "equal". rewrite eq_id; auto. Case "not equal". rewrite pe_remove_correct. repeat rewrite neq_id; auto. Qed. (** We will use the two theorems below to show that our partial evaluator correctly deals with dynamic assignments and static assignments, respectively. *) Theorem pe_override_update_remove: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override (update st V n) (pe_remove pe_st V). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_remove_correct. destruct (eq_id_dec V V0); reflexivity. Qed. Theorem pe_override_update_add: forall st pe_st V n, update (pe_override st pe_st) V n = pe_override st (pe_add pe_st V n). Proof. intros st pe_st V n. apply functional_extensionality. intros V0. unfold update. rewrite !pe_override_correct. rewrite pe_add_correct. destruct (eq_id_dec V V0); reflexivity. Qed. (** ** Conditional *) (** Trickier than assignments to partially evaluate is the conditional, [IFB b1 THEN c1 ELSE c2 FI]. If [b1] simplifies to [BTrue] or [BFalse] then it's easy: we know which branch will be taken, so just take that branch. If [b1] does not simplify to a constant, then we need to take both branches, and the final partial state may differ between the two branches! The following program illustrates the difficulty: X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI Suppose the initial partial state is empty. We don't know statically how [Y] compares to [4], so we must partially evaluate both branches of the (outer) conditional. On the [THEN] branch, we know that [Y] is set to [4] and can even use that knowledge to simplify the code somewhat. On the [ELSE] branch, we still don't know the exact value of [Y] at the end. What should the final partial state and residual program be? One way to handle such a dynamic conditional is to take the intersection of the final partial states of the two branches. In this example, we take the intersection of [(Y,4),(X,3)] and [(X,3)], so the overall final partial state is [(X,3)]. To compensate for forgetting that [Y] is [4], we need to add an assignment [Y ::= ANum 4] to the end of the [THEN] branch. So, the residual program will be something like SKIP;; IFB BLe (AId Y) (ANum 4) THEN SKIP;; SKIP;; Y ::= ANum 4 ELSE SKIP FI Programming this case in Coq calls for several auxiliary functions: we need to compute the intersection of two [pe_state]s and turn their difference into sequences of assignments. First, we show how to compute whether two [pe_state]s to disagree at a given variable. In the theorem [pe_disagree_domain], we prove that two [pe_state]s can only disagree at variables that appear in at least one of them. *) Definition pe_disagree_at (pe_st1 pe_st2 : pe_state) (V:id) : bool := match pe_lookup pe_st1 V, pe_lookup pe_st2 V with | Some x, Some y => negb (beq_nat x y) | None, None => false | _, _ => true end. Theorem pe_disagree_domain: forall (pe_st1 pe_st2 : pe_state) (V:id), true = pe_disagree_at pe_st1 pe_st2 V -> In V (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2). Proof. unfold pe_disagree_at. intros pe_st1 pe_st2 V H. apply in_or_app. remember (pe_lookup pe_st1 V) as lookup1. destruct lookup1 as [n1|]. left. apply pe_domain with n1. auto. remember (pe_lookup pe_st2 V) as lookup2. destruct lookup2 as [n2|]. right. apply pe_domain with n2. auto. inversion H. Qed. (** We define the [pe_compare] function to list the variables where two given [pe_state]s disagree. This list is exact, according to the theorem [pe_compare_correct]: a variable appears on the list if and only if the two given [pe_state]s disagree at that variable. Furthermore, we use the [pe_unique] function to eliminate duplicates from the list. *) Fixpoint pe_unique (l : list id) : list id := match l with | [] => [] | x::l => x :: filter (fun y => if eq_id_dec x y then false else true) (pe_unique l) end. Theorem pe_unique_correct: forall l x, In x l <-> In x (pe_unique l). Proof. intros l x. induction l as [| h t]. reflexivity. simpl in *. split. Case "->". intros. inversion H; clear H. left. assumption. destruct (eq_id_dec h x). left. assumption. right. apply filter_In. split. apply IHt. assumption. rewrite neq_id; auto. Case "<-". intros. inversion H; clear H. left. assumption. apply filter_In in H0. inversion H0. right. apply IHt. assumption. Qed. Definition pe_compare (pe_st1 pe_st2 : pe_state) : list id := pe_unique (filter (pe_disagree_at pe_st1 pe_st2) (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2)). Theorem pe_compare_correct: forall pe_st1 pe_st2 V, pe_lookup pe_st1 V = pe_lookup pe_st2 V <-> ~ In V (pe_compare pe_st1 pe_st2). Proof. intros pe_st1 pe_st2 V. unfold pe_compare. rewrite <- pe_unique_correct. rewrite filter_In. split; intros Heq. Case "->". intro. destruct H. unfold pe_disagree_at in H0. rewrite Heq in H0. destruct (pe_lookup pe_st2 V). rewrite <- beq_nat_refl in H0. inversion H0. inversion H0. Case "<-". assert (Hagree: pe_disagree_at pe_st1 pe_st2 V = false). SCase "Proof of assertion". remember (pe_disagree_at pe_st1 pe_st2 V) as disagree. destruct disagree; [| reflexivity]. apply pe_disagree_domain in Heqdisagree. apply ex_falso_quodlibet. apply Heq. split. assumption. reflexivity. unfold pe_disagree_at in Hagree. destruct (pe_lookup pe_st1 V) as [n1|]; destruct (pe_lookup pe_st2 V) as [n2|]; try reflexivity; try solve by inversion. rewrite negb_false_iff in Hagree. apply beq_nat_true in Hagree. subst. reflexivity. Qed. (** The intersection of two partial states is the result of removing from one of them all the variables where the two disagree. We define the function [pe_removes], in terms of [pe_remove] above, to perform such a removal of a whole list of variables at once. The theorem [pe_compare_removes] testifies that the [pe_lookup] interpretation of the result of this intersection operation is the same no matter which of the two partial states we remove the variables from. Because [pe_override] only depends on the [pe_lookup] interpretation of partial states, [pe_override] also does not care which of the two partial states we remove the variables from; that theorem [pe_compare_override] is used in the correctness proof shortly. *) Fixpoint pe_removes (pe_st:pe_state) (ids : list id) : pe_state := match ids with | [] => pe_st | V::ids => pe_remove (pe_removes pe_st ids) V end. Theorem pe_removes_correct: forall pe_st ids V, pe_lookup (pe_removes pe_st ids) V = if in_dec eq_id_dec V ids then None else pe_lookup pe_st V. Proof. intros pe_st ids V. induction ids as [| V' ids]. reflexivity. simpl. rewrite pe_remove_correct. rewrite IHids. compare V' V Case. reflexivity. destruct (in_dec eq_id_dec V ids); reflexivity. Qed. Theorem pe_compare_removes: forall pe_st1 pe_st2 V, pe_lookup (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) V = pe_lookup (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)) V. Proof. intros pe_st1 pe_st2 V. rewrite !pe_removes_correct. destruct (in_dec eq_id_dec V (pe_compare pe_st1 pe_st2)). reflexivity. apply pe_compare_correct. auto. Qed. Theorem pe_compare_override: forall pe_st1 pe_st2 st, pe_override st (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) = pe_override st (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)). Proof. intros. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_compare_removes. reflexivity. Qed. (** Finally, we define an [assign] function to turn the difference between two partial states into a sequence of assignment commands. More precisely, [assign pe_st ids] generates an assignment command for each variable listed in [ids]. *) Fixpoint assign (pe_st : pe_state) (ids : list id) : com := match ids with | [] => SKIP | V::ids => match pe_lookup pe_st V with | Some n => (assign pe_st ids;; V ::= ANum n) | None => assign pe_st ids end end. (** The command generated by [assign] always terminates, because it is just a sequence of assignments. The (total) function [assigned] below computes the effect of the command on the (dynamic state). The theorem [assign_removes] then confirms that the generated assignments perfectly compensate for removing the variables from the partial state. *) Definition assigned (pe_st:pe_state) (ids : list id) (st:state) : state := fun V => if in_dec eq_id_dec V ids then match pe_lookup pe_st V with | Some n => n | None => st V end else st V. Theorem assign_removes: forall pe_st ids st, pe_override st pe_st = pe_override (assigned pe_st ids st) (pe_removes pe_st ids). Proof. intros pe_st ids st. apply functional_extensionality. intros V. rewrite !pe_override_correct. rewrite pe_removes_correct. unfold assigned. destruct (in_dec eq_id_dec V ids); destruct (pe_lookup pe_st V); reflexivity. Qed. Lemma ceval_extensionality: forall c st st1 st2, c / st || st1 -> (forall V, st1 V = st2 V) -> c / st || st2. Proof. intros c st st1 st2 H Heq. apply functional_extensionality in Heq. rewrite <- Heq. apply H. Qed. Theorem eval_assign: forall pe_st ids st, assign pe_st ids / st || assigned pe_st ids st. Proof. intros pe_st ids st. induction ids as [| V ids]; simpl. Case "[]". eapply ceval_extensionality. apply E_Skip. reflexivity. Case "V::ids". remember (pe_lookup pe_st V) as lookup. destruct lookup. SCase "Some". eapply E_Seq. apply IHids. unfold assigned. simpl. eapply ceval_extensionality. apply E_Ass. simpl. reflexivity. intros V0. unfold update. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); auto. SCase "None". eapply ceval_extensionality. apply IHids. unfold assigned. intros V0. simpl. compare V V0 SSCase. SSCase "equal". rewrite <- Heqlookup. destruct (in_dec eq_id_dec V ids); reflexivity. SSCase "not equal". destruct (in_dec eq_id_dec V0 ids); reflexivity. Qed. (** ** The Partial Evaluation Relation *) (** At long last, we can define a partial evaluator for commands without loops, as an inductive relation! The inequality conditions in [PE_AssDynamic] and [PE_If] are just to keep the partial evaluator deterministic; they are not required for correctness. *) Reserved Notation "c1 '/' st '||' c1' '/' st'" (at level 40, st at level 39, c1' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2', c1 / pe_st || c1' / pe_st' -> c2 / pe_st' || c2' / pe_st'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 -> c2 / pe_st || c2' / pe_st2 -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) where "c1 '/' st '||' c1' '/' st'" := (pe_com c1 st c1' st'). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" ]. Hint Constructors pe_com. Hint Constructors ceval. (** ** Examples *) (** Below are some examples of using the partial evaluator. To make the [pe_com] relation actually usable for automatic partial evaluation, we would need to define more automation tactics in Coq. That is not hard to do, but it is not needed here. *) Example pe_example1: (X ::= ANum 3 ;; Y ::= AMult (AId Z) (APlus (AId X) (AId X))) / [] || (SKIP;; Y ::= AMult (AId Z) (ANum 6)) / [(X,3)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_AssDynamic. reflexivity. intros n H. inversion H. Qed. Example pe_example2: (X ::= ANum 3 ;; IFB BLe (AId X) (ANum 4) THEN X ::= ANum 4 ELSE SKIP FI) / [] || (SKIP;; SKIP) / [(X,4)]. Proof. eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_IfTrue. reflexivity. eapply PE_AssStatic. reflexivity. Qed. Example pe_example3: (X ::= ANum 3;; IFB BLe (AId Y) (ANum 4) THEN Y ::= ANum 4;; IFB BEq (AId X) (AId Y) THEN Y ::= ANum 999 ELSE SKIP FI ELSE SKIP FI) / [] || (SKIP;; IFB BLe (AId Y) (ANum 4) THEN (SKIP;; SKIP);; (SKIP;; Y ::= ANum 4) ELSE SKIP;; SKIP FI) / [(X,3)]. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st). eapply PE_Seq. eapply PE_AssStatic. reflexivity. eapply PE_If; intuition eauto; try solve by inversion. econstructor. eapply PE_AssStatic. reflexivity. eapply PE_IfFalse. reflexivity. econstructor. reflexivity. reflexivity. Qed. (** ** Correctness of Partial Evaluation *) (** Finally let's prove that this partial evaluator is correct! *) Reserved Notation "c' '/' pe_st' '/' st '||' st''" (at level 40, pe_st' at level 39, st at level 39). Inductive pe_ceval (c':com) (pe_st':pe_state) (st:state) (st'':state) : Prop := | pe_ceval_intro : forall st', c' / st || st' -> pe_override st' pe_st' = st'' -> c' / pe_st' / st || st'' where "c' '/' pe_st' '/' st '||' st''" := (pe_ceval c' pe_st' st st''). Hint Constructors pe_ceval. Theorem pe_com_complete: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') -> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. reflexivity. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. reflexivity. Case "PE_Seq". edestruct IHHpe1. eassumption. subst. edestruct IHHpe2. eassumption. eauto. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c' / pe_st' / st || st'') -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' [st' Heval Heq]; try (inversion Heval; []; subst); auto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eauto. Case "PE_If". inversion Heval; subst; inversion H7; (eapply ceval_deterministic in H8; [| apply eval_assign]); subst. SCase "E_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. SCase "E_IfFalse". rewrite -> pe_compare_override. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. rewrite <- assign_removes. eauto. Qed. (** The main theorem. Thanks to David Menendez for this formulation! *) Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' -> forall st st'', (c / pe_override st pe_st || st'') <-> (c' / pe_st' / st || st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". apply pe_com_complete. apply H. Case "<-". apply pe_com_sound. apply H. Qed. (* ####################################################### *) (** * Partial Evaluation of Loops *) (** It may seem straightforward at first glance to extend the partial evaluation relation [pe_com] above to loops. Indeed, many loops are easy to deal with. Considered this repeated-squaring loop, for example: WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END If we know neither [X] nor [Y] statically, then the entire loop is dynamic and the residual command should be the same. If we know [X] but not [Y], then the loop can be unrolled all the way and the residual command should be Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y);; Y ::= AMult (AId Y) (AId Y) if [X] is initially [3] (and finally [0]). In general, a loop is easy to partially evaluate if the final partial state of the loop body is equal to the initial state, or if its guard condition is static. But there are other loops for which it is hard to express the residual program we want in Imp. For example, take this program for checking if [Y] is even or odd: X ::= ANum 0;; WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; X ::= AMinus (ANum 1) (AId X) END The value of [X] alternates between [0] and [1] during the loop. Ideally, we would like to unroll this loop, not all the way but _two-fold_, into something like WHILE BLe (ANum 1) (AId Y) DO Y ::= AMinus (AId Y) (ANum 1);; IF BLe (ANum 1) (AId Y) THEN Y ::= AMinus (AId Y) (ANum 1) ELSE X ::= ANum 1;; EXIT FI END;; X ::= ANum 0 Unfortunately, there is no [EXIT] command in Imp. Without extending the range of control structures available in our language, the best we can do is to repeat loop-guard tests or add flag variables. Neither option is terribly attractive. Still, as a digression, below is an attempt at performing partial evaluation on Imp commands. We add one more command argument [c''] to the [pe_com] relation, which keeps track of a loop to roll up. *) Module Loop. Reserved Notation "c1 '/' st '||' c1' '/' st' '/' c''" (at level 40, st at level 39, c1' at level 39, st' at level 39). Inductive pe_com : com -> pe_state -> com -> pe_state -> com -> Prop := | PE_Skip : forall pe_st, SKIP / pe_st || SKIP / pe_st / SKIP | PE_AssStatic : forall pe_st a1 n1 l, pe_aexp pe_st a1 = ANum n1 -> (l ::= a1) / pe_st || SKIP / pe_add pe_st l n1 / SKIP | PE_AssDynamic : forall pe_st a1 a1' l, pe_aexp pe_st a1 = a1' -> (forall n, a1' <> ANum n) -> (l ::= a1) / pe_st || (l ::= a1') / pe_remove pe_st l / SKIP | PE_Seq : forall pe_st pe_st' pe_st'' c1 c2 c1' c2' c'', c1 / pe_st || c1' / pe_st' / SKIP -> c2 / pe_st' || c2' / pe_st'' / c'' -> (c1 ;; c2) / pe_st || (c1' ;; c2') / pe_st'' / c'' | PE_IfTrue : forall pe_st pe_st' b1 c1 c2 c1' c'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c1' / pe_st' / c'' | PE_IfFalse : forall pe_st pe_st' b1 c1 c2 c2' c'', pe_bexp pe_st b1 = BFalse -> c2 / pe_st || c2' / pe_st' / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || c2' / pe_st' / c'' | PE_If : forall pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2' c'', pe_bexp pe_st b1 <> BTrue -> pe_bexp pe_st b1 <> BFalse -> c1 / pe_st || c1' / pe_st1 / c'' -> c2 / pe_st || c2' / pe_st2 / c'' -> (IFB b1 THEN c1 ELSE c2 FI) / pe_st || (IFB pe_bexp pe_st b1 THEN c1' ;; assign pe_st1 (pe_compare pe_st1 pe_st2) ELSE c2' ;; assign pe_st2 (pe_compare pe_st1 pe_st2) FI) / pe_removes pe_st1 (pe_compare pe_st1 pe_st2) / c'' | PE_WhileEnd : forall pe_st b1 c1, pe_bexp pe_st b1 = BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / SKIP | PE_WhileLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (WHILE b1 DO c1 END) / pe_st || (c1';;c2') / pe_st'' / c2'' | PE_While : forall pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / c2'' -> pe_compare pe_st pe_st'' <> [] -> (c2'' = SKIP \/ c2'' = WHILE b1 DO c1 END) -> (WHILE b1 DO c1 END) / pe_st || (IFB pe_bexp pe_st b1 THEN c1';; c2';; assign pe_st'' (pe_compare pe_st pe_st'') ELSE assign pe_st (pe_compare pe_st pe_st'') FI) / pe_removes pe_st (pe_compare pe_st pe_st'') / c2'' | PE_WhileFixedEnd : forall pe_st b1 c1, pe_bexp pe_st b1 <> BFalse -> (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE b1 DO c1 END) | PE_WhileFixedLoop : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 = BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE BTrue DO SKIP END) / pe_st / SKIP (* Because we have an infinite loop, we should actually start to throw away the rest of the program: (WHILE b1 DO c1 END) / pe_st || SKIP / pe_st / (WHILE BTrue DO SKIP END) *) | PE_WhileFixed : forall pe_st pe_st' pe_st'' b1 c1 c1' c2', pe_bexp pe_st b1 <> BFalse -> pe_bexp pe_st b1 <> BTrue -> c1 / pe_st || c1' / pe_st' / SKIP -> (WHILE b1 DO c1 END) / pe_st' || c2' / pe_st'' / (WHILE b1 DO c1 END) -> pe_compare pe_st pe_st'' = [] -> (WHILE b1 DO c1 END) / pe_st || (WHILE pe_bexp pe_st b1 DO c1';; c2' END) / pe_st / SKIP where "c1 '/' st '||' c1' '/' st' '/' c''" := (pe_com c1 st c1' st' c''). Tactic Notation "pe_com_cases" tactic(first) ident(c) := first; [ Case_aux c "PE_Skip" | Case_aux c "PE_AssStatic" | Case_aux c "PE_AssDynamic" | Case_aux c "PE_Seq" | Case_aux c "PE_IfTrue" | Case_aux c "PE_IfFalse" | Case_aux c "PE_If" | Case_aux c "PE_WhileEnd" | Case_aux c "PE_WhileLoop" | Case_aux c "PE_While" | Case_aux c "PE_WhileFixedEnd" | Case_aux c "PE_WhileFixedLoop" | Case_aux c "PE_WhileFixed" ]. Hint Constructors pe_com. (** ** Examples *) Ltac step i := (eapply i; intuition eauto; try solve by inversion); repeat (try eapply PE_Seq; try (eapply PE_AssStatic; simpl; reflexivity); try (eapply PE_AssDynamic; [ simpl; reflexivity | intuition eauto; solve by inversion ])). Definition square_loop: com := WHILE BLe (ANum 1) (AId X) DO Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1) END. Example pe_loop_example1: square_loop / [] || (WHILE BLe (ANum 1) (AId X) DO (Y ::= AMult (AId Y) (AId Y);; X ::= AMinus (AId X) (ANum 1));; SKIP END) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. reflexivity. reflexivity. Qed. Example pe_loop_example2: (X ::= ANum 3;; square_loop) / [] || (SKIP;; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; (Y ::= AMult (AId Y) (AId Y);; SKIP);; SKIP) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileLoop. step PE_WhileEnd. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example3: (Z ::= ANum 3;; subtract_slowly) / [] || (SKIP;; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; IFB BNot (BEq (AId X) (ANum 0)) THEN (SKIP;; X ::= AMinus (AId X) (ANum 1));; WHILE BNot (BEq (AId X) (ANum 0)) DO (SKIP;; X ::= AMinus (AId X) (ANum 1));; SKIP END;; SKIP;; Z ::= ANum 0 ELSE SKIP;; Z ::= ANum 1 FI;; SKIP ELSE SKIP;; Z ::= ANum 2 FI;; SKIP ELSE SKIP;; Z ::= ANum 3 FI) / [] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_While. step PE_While. step PE_While. step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity. inversion H. inversion H. inversion H. reflexivity. reflexivity. Qed. Example pe_loop_example4: (X ::= ANum 0;; WHILE BLe (AId X) (ANum 2) DO X ::= AMinus (ANum 1) (AId X) END) / [] || (SKIP;; WHILE BTrue DO SKIP END) / [(X,0)] / SKIP. Proof. erewrite f_equal2 with (f := fun c st => _ / _ || c / st / SKIP). eapply PE_Seq. eapply PE_AssStatic. reflexivity. step PE_WhileFixedLoop. step PE_WhileLoop. step PE_WhileFixedEnd. inversion H. reflexivity. reflexivity. reflexivity. Qed. (** ** Correctness *) (** Because this partial evaluator can unroll a loop n-fold where n is a (finite) integer greater than one, in order to show it correct we need to perform induction not structurally on dynamic evaluation but on the number of times dynamic evaluation enters a loop body. *) Reserved Notation "c1 '/' st '||' st' '#' n" (at level 40, st at level 39, st' at level 39). Inductive ceval_count : com -> state -> state -> nat -> Prop := | E'Skip : forall st, SKIP / st || st # 0 | E'Ass : forall st a1 n l, aeval st a1 = n -> (l ::= a1) / st || (update st l n) # 0 | E'Seq : forall c1 c2 st st' st'' n1 n2, c1 / st || st' # n1 -> c2 / st' || st'' # n2 -> (c1 ;; c2) / st || st'' # (n1 + n2) | E'IfTrue : forall st st' b1 c1 c2 n, beval st b1 = true -> c1 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'IfFalse : forall st st' b1 c1 c2 n, beval st b1 = false -> c2 / st || st' # n -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' # n | E'WhileEnd : forall b1 st c1, beval st b1 = false -> (WHILE b1 DO c1 END) / st || st # 0 | E'WhileLoop : forall st st' st'' b1 c1 n1 n2, beval st b1 = true -> c1 / st || st' # n1 -> (WHILE b1 DO c1 END) / st' || st'' # n2 -> (WHILE b1 DO c1 END) / st || st'' # S (n1 + n2) where "c1 '/' st '||' st' # n" := (ceval_count c1 st st' n). Tactic Notation "ceval_count_cases" tactic(first) ident(c) := first; [ Case_aux c "E'Skip" | Case_aux c "E'Ass" | Case_aux c "E'Seq" | Case_aux c "E'IfTrue" | Case_aux c "E'IfFalse" | Case_aux c "E'WhileEnd" | Case_aux c "E'WhileLoop" ]. Hint Constructors ceval_count. Theorem ceval_count_complete: forall c st st', c / st || st' -> exists n, c / st || st' # n. Proof. intros c st st' Heval. induction Heval; try inversion IHHeval1; try inversion IHHeval2; try inversion IHHeval; eauto. Qed. Theorem ceval_count_sound: forall c st st' n, c / st || st' # n -> c / st || st'. Proof. intros c st st' n Heval. induction Heval; eauto. Qed. Theorem pe_compare_nil_lookup: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall V, pe_lookup pe_st1 V = pe_lookup pe_st2 V. Proof. intros pe_st1 pe_st2 H V. apply (pe_compare_correct pe_st1 pe_st2 V). rewrite H. intro. inversion H0. Qed. Theorem pe_compare_nil_override: forall pe_st1 pe_st2, pe_compare pe_st1 pe_st2 = [] -> forall st, pe_override st pe_st1 = pe_override st pe_st2. Proof. intros pe_st1 pe_st2 H st. apply functional_extensionality. intros V. rewrite !pe_override_correct. apply pe_compare_nil_lookup with (V:=V) in H. rewrite H. reflexivity. Qed. Reserved Notation "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" (at level 40, pe_st' at level 39, c'' at level 39, st at level 39, st'' at level 39). Inductive pe_ceval_count (c':com) (pe_st':pe_state) (c'':com) (st:state) (st'':state) (n:nat) : Prop := | pe_ceval_count_intro : forall st' n', c' / st || st' -> c'' / pe_override st' pe_st' || st'' # n' -> n' <= n -> c' / pe_st' / c'' / st || st'' # n where "c' '/' pe_st' '/' c'' '/' st '||' st'' '#' n" := (pe_ceval_count c' pe_st' c'' st st'' n). Hint Constructors pe_ceval_count. Lemma pe_ceval_count_le: forall c' pe_st' c'' st st'' n n', n' <= n -> c' / pe_st' / c'' / st || st'' # n' -> c' / pe_st' / c'' / st || st'' # n. Proof. intros c' pe_st' c'' st st'' n n' Hle H. inversion H. econstructor; try eassumption. omega. Qed. Theorem pe_com_complete: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c / pe_override st pe_st || st'' # n) -> (c' / pe_st' / c'' / st || st'' # n). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n Heval; try (inversion Heval; subst; try (rewrite -> pe_bexp_correct, -> H in *; solve by inversion); []); eauto. Case "PE_AssStatic". econstructor. econstructor. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_add. rewrite -> H. apply E'Skip. auto. Case "PE_AssDynamic". econstructor. econstructor. reflexivity. rewrite -> pe_aexp_correct. rewrite <- pe_override_update_remove. apply E'Skip. auto. Case "PE_Seq". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_If". inversion Heval; subst. SCase "E'IfTrue". edestruct IHHpe1. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite <- assign_removes. eassumption. eassumption. SCase "E_IfFalse". edestruct IHHpe2. eassumption. econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. eapply E_Seq. eassumption. apply eval_assign. rewrite -> pe_compare_override. rewrite <- assign_removes. eassumption. eassumption. Case "PE_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor; eauto. omega. Case "PE_While". inversion Heval; subst. SCase "E_WhileEnd". econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption. apply eval_assign. rewrite <- assign_removes. inversion H2; subst; auto. auto. SCase "E_WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption. repeat eapply E_Seq; eauto. apply eval_assign. rewrite -> pe_compare_override, <- assign_removes. eassumption. omega. Case "PE_WhileFixedLoop". apply ex_falso_quodlibet. generalize dependent (S (n1 + n2)). intros n. clear - Case H H0 IHHpe1 IHHpe2. generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct, H in H7. inversion H7. SCase "E'WhileLoop". edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H0) in H7. apply H1 in H7; [| omega]. inversion H7. Case "PE_WhileFixed". generalize dependent st. induction n using lt_wf_ind; intros st Heval. inversion Heval; subst. SCase "E'WhileEnd". rewrite pe_bexp_correct in H8. eauto. SCase "E'WhileLoop". rewrite pe_bexp_correct in H5. edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption. inversion Hskip. subst. edestruct IHHpe2. eassumption. rewrite <- (pe_compare_nil_override _ _ H1) in H8. apply H2 in H8; [| omega]. inversion H8. econstructor; [ eapply E_WhileLoop; eauto | eassumption | omega]. Qed. Theorem pe_com_sound: forall c pe_st pe_st' c' c'', c / pe_st || c' / pe_st' / c'' -> forall st st'' n, (c' / pe_st' / c'' / st || st'' # n) -> (c / pe_override st pe_st || st''). Proof. intros c pe_st pe_st' c' c'' Hpe. pe_com_cases (induction Hpe) Case; intros st st'' n [st' n' Heval Heval' Hle]; try (inversion Heval; []; subst); try (inversion Heval'; []; subst); eauto. Case "PE_AssStatic". rewrite <- pe_override_update_add. apply E_Ass. rewrite -> pe_aexp_correct. rewrite -> H. reflexivity. Case "PE_AssDynamic". rewrite <- pe_override_update_remove. apply E_Ass. rewrite <- pe_aexp_correct. reflexivity. Case "PE_Seq". eapply E_Seq; eauto. Case "PE_IfTrue". apply E_IfTrue. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_IfFalse". apply E_IfFalse. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe. eauto. Case "PE_If". inversion Heval; subst; inversion H7; subst; clear H7. SCase "E_IfTrue". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. apply E_IfTrue. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. SCase "E_IfFalse". eapply ceval_deterministic in H8; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. apply E_IfFalse. rewrite -> pe_bexp_correct. assumption. eapply IHHpe2. eauto. Case "PE_WhileEnd". apply E_WhileEnd. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. Case "PE_WhileLoop". eapply E_WhileLoop. rewrite -> pe_bexp_correct. rewrite -> H. reflexivity. eapply IHHpe1. eauto. eapply IHHpe2. eauto. Case "PE_While". inversion Heval; subst. SCase "E_IfTrue". inversion H9. subst. clear H9. inversion H10. subst. clear H10. eapply ceval_deterministic in H11; [| apply eval_assign]. subst. rewrite -> pe_compare_override in Heval'. rewrite <- assign_removes in Heval'. eapply E_WhileLoop. rewrite -> pe_bexp_correct. assumption. eapply IHHpe1. eauto. eapply IHHpe2. eauto. SCase "E_IfFalse". apply ceval_count_sound in Heval'. eapply ceval_deterministic in H9; [| apply eval_assign]. subst. rewrite <- assign_removes in Heval'. inversion H2; subst. SSCase "c2'' = SKIP". inversion Heval'. subst. apply E_WhileEnd. rewrite -> pe_bexp_correct. assumption. SSCase "c2'' = WHILE b1 DO c1 END". assumption. Case "PE_WhileFixedEnd". eapply ceval_count_sound. apply Heval'. Case "PE_WhileFixedLoop". apply loop_never_stops in Heval. inversion Heval. Case "PE_WhileFixed". clear - Case H1 IHHpe1 IHHpe2 Heval. remember (WHILE pe_bexp pe_st b1 DO c1';; c2' END) as c'. ceval_cases (induction Heval) SCase; inversion Heqc'; subst; clear Heqc'. SCase "E_WhileEnd". apply E_WhileEnd. rewrite pe_bexp_correct. assumption. SCase "E_WhileLoop". assert (IHHeval2' := IHHeval2 (refl_equal _)). apply ceval_count_complete in IHHeval2'. inversion IHHeval2'. clear IHHeval1 IHHeval2 IHHeval2'. inversion Heval1. subst. eapply E_WhileLoop. rewrite pe_bexp_correct. assumption. eauto. eapply IHHpe2. econstructor. eassumption. rewrite <- (pe_compare_nil_override _ _ H1). eassumption. apply le_n. Qed. Corollary pe_com_correct: forall c pe_st pe_st' c', c / pe_st || c' / pe_st' / SKIP -> forall st st'', (c / pe_override st pe_st || st'') <-> (exists st', c' / st || st' /\ pe_override st' pe_st' = st''). Proof. intros c pe_st pe_st' c' H st st''. split. Case "->". intros Heval. apply ceval_count_complete in Heval. inversion Heval as [n Heval']. apply pe_com_complete with (st:=st) (st'':=st'') (n:=n) in H. inversion H as [? ? ? Hskip ?]. inversion Hskip. subst. eauto. assumption. Case "<-". intros [st' [Heval Heq]]. subst st''. eapply pe_com_sound in H. apply H. econstructor. apply Heval. apply E'Skip. apply le_n. Qed. End Loop. (* ####################################################### *) (** * Partial Evaluation of Flowchart Programs *) (** Instead of partially evaluating [WHILE] loops directly, the standard approach to partially evaluating imperative programs is to convert them into _flowcharts_. In other words, it turns out that adding labels and jumps to our language makes it much easier to partially evaluate. The result of partially evaluating a flowchart is a residual flowchart. If we are lucky, the jumps in the residual flowchart can be converted back to [WHILE] loops, but that is not possible in general; we do not pursue it here. *) (** ** Basic blocks *) (** A flowchart is made of _basic blocks_, which we represent with the inductive type [block]. A basic block is a sequence of assignments (the constructor [Assign]), concluding with a conditional jump (the constructor [If]) or an unconditional jump (the constructor [Goto]). The destinations of the jumps are specified by _labels_, which can be of any type. Therefore, we parameterize the [block] type by the type of labels. *) Inductive block (Label:Type) : Type := | Goto : Label -> block Label | If : bexp -> Label -> Label -> block Label | Assign : id -> aexp -> block Label -> block Label. Tactic Notation "block_cases" tactic(first) ident(c) := first; [ Case_aux c "Goto" | Case_aux c "If" | Case_aux c "Assign" ]. Arguments Goto {Label} _. Arguments If {Label} _ _ _. Arguments Assign {Label} _ _ _. (** We use the "even or odd" program, expressed above in Imp, as our running example. Converting this program into a flowchart turns out to require 4 labels, so we define the following type. *) Inductive parity_label : Type := | entry : parity_label | loop : parity_label | body : parity_label | done : parity_label. (** The following [block] is the basic block found at the [body] label of the example program. *) Definition parity_body : block parity_label := Assign Y (AMinus (AId Y) (ANum 1)) (Assign X (AMinus (ANum 1) (AId X)) (Goto loop)). (** To evaluate a basic block, given an initial state, is to compute the final state and the label to jump to next. Because basic blocks do not _contain_ loops or other control structures, evaluation of basic blocks is a total function -- we don't need to worry about non-termination. *) Fixpoint keval {L:Type} (st:state) (k : block L) : state * L := match k with | Goto l => (st, l) | If b l1 l2 => (st, if beval st b then l1 else l2) | Assign i a k => keval (update st i (aeval st a)) k end. Example keval_example: keval empty_state parity_body = (update (update empty_state Y 0) X 1, loop). Proof. reflexivity. Qed. (** ** Flowchart programs *) (** A flowchart program is simply a lookup function that maps labels to basic blocks. Actually, some labels are _halting states_ and do not map to any basic block. So, more precisely, a flowchart [program] whose labels are of type [L] is a function from [L] to [option (block L)]. *) Definition program (L:Type) : Type := L -> option (block L). Definition parity : program parity_label := fun l => match l with | entry => Some (Assign X (ANum 0) (Goto loop)) | loop => Some (If (BLe (ANum 1) (AId Y)) body done) | body => Some parity_body | done => None (* halt *) end. (** Unlike a basic block, a program may not terminate, so we model the evaluation of programs by an inductive relation [peval] rather than a recursive function. *) Inductive peval {L:Type} (p : program L) : state -> L -> state -> L -> Prop := | E_None: forall st l, p l = None -> peval p st l st l | E_Some: forall st l k st' l' st'' l'', p l = Some k -> keval st k = (st', l') -> peval p st' l' st'' l'' -> peval p st l st'' l''. Example parity_eval: peval parity empty_state entry empty_state done. Proof. erewrite f_equal with (f := fun st => peval _ _ _ st _). eapply E_Some. reflexivity. reflexivity. eapply E_Some. reflexivity. reflexivity. apply E_None. reflexivity. apply functional_extensionality. intros i. rewrite update_same; auto. Qed. Tactic Notation "peval_cases" tactic(first) ident(c) := first; [ Case_aux c "E_None" | Case_aux c "E_Some" ]. (** ** Partial evaluation of basic blocks and flowchart programs *) (** Partial evaluation changes the label type in a systematic way: if the label type used to be [L], it becomes [pe_state * L]. So the same label in the original program may be unfolded, or blown up, into multiple labels by being paired with different partial states. For example, the label [loop] in the [parity] program will become two labels: [([(X,0)], loop)] and [([(X,1)], loop)]. This change of label type is reflected in the types of [pe_block] and [pe_program] defined presently. *) Fixpoint pe_block {L:Type} (pe_st:pe_state) (k : block L) : block (pe_state * L) := match k with | Goto l => Goto (pe_st, l) | If b l1 l2 => match pe_bexp pe_st b with | BTrue => Goto (pe_st, l1) | BFalse => Goto (pe_st, l2) | b' => If b' (pe_st, l1) (pe_st, l2) end | Assign i a k => match pe_aexp pe_st a with | ANum n => pe_block (pe_add pe_st i n) k | a' => Assign i a' (pe_block (pe_remove pe_st i) k) end end. Example pe_block_example: pe_block [(X,0)] parity_body = Assign Y (AMinus (AId Y) (ANum 1)) (Goto ([(X,1)], loop)). Proof. reflexivity. Qed. Theorem pe_block_correct: forall (L:Type) st pe_st k st' pe_st' (l':L), keval st (pe_block pe_st k) = (st', (pe_st', l')) -> keval (pe_override st pe_st) k = (pe_override st' pe_st', l'). Proof. intros. generalize dependent pe_st. generalize dependent st. block_cases (induction k as [l | b l1 l2 | i a k]) Case; intros st pe_st H. Case "Goto". inversion H; reflexivity. Case "If". replace (keval st (pe_block pe_st (If b l1 l2))) with (keval st (If (pe_bexp pe_st b) (pe_st, l1) (pe_st, l2))) in H by (simpl; destruct (pe_bexp pe_st b); reflexivity). simpl in *. rewrite pe_bexp_correct. destruct (beval st (pe_bexp pe_st b)); inversion H; reflexivity. Case "Assign". simpl in *. rewrite pe_aexp_correct. destruct (pe_aexp pe_st a); simpl; try solve [rewrite pe_override_update_add; apply IHk; apply H]; solve [rewrite pe_override_update_remove; apply IHk; apply H]. Qed. Definition pe_program {L:Type} (p : program L) : program (pe_state * L) := fun pe_l => match pe_l with (pe_st, l) => option_map (pe_block pe_st) (p l) end. Inductive pe_peval {L:Type} (p : program L) (st:state) (pe_st:pe_state) (l:L) (st'o:state) (l':L) : Prop := | pe_peval_intro : forall st' pe_st', peval (pe_program p) st (pe_st, l) st' (pe_st', l') -> pe_override st' pe_st' = st'o -> pe_peval p st pe_st l st'o l'. Theorem pe_program_correct: forall (L:Type) (p : program L) st pe_st l st'o l', peval p (pe_override st pe_st) l st'o l' <-> pe_peval p st pe_st l st'o l'. Proof. intros. split; [Case "->" | Case "<-"]. Case "->". intros Heval. remember (pe_override st pe_st) as sto. generalize dependent pe_st. generalize dependent st. peval_cases (induction Heval as [ sto l Hlookup | sto l k st'o l' st''o l'' Hlookup Hkeval Heval ]) SCase; intros st pe_st Heqsto; subst sto. SCase "E_None". eapply pe_peval_intro. apply E_None. simpl. rewrite Hlookup. reflexivity. reflexivity. SCase "E_Some". remember (keval st (pe_block pe_st k)) as x. destruct x as [st' [pe_st' l'_]]. symmetry in Heqx. erewrite pe_block_correct in Hkeval by apply Heqx. inversion Hkeval. subst st'o l'_. clear Hkeval. edestruct IHHeval. reflexivity. subst st''o. clear IHHeval. eapply pe_peval_intro; [| reflexivity]. eapply E_Some; eauto. simpl. rewrite Hlookup. reflexivity. Case "<-". intros [st' pe_st' Heval Heqst'o]. remember (pe_st, l) as pe_st_l. remember (pe_st', l') as pe_st'_l'. generalize dependent pe_st. generalize dependent l. peval_cases (induction Heval as [ st [pe_st_ l_] Hlookup | st [pe_st_ l_] pe_k st' [pe_st'_ l'_] st'' [pe_st'' l''] Hlookup Hkeval Heval ]) SCase; intros l pe_st Heqpe_st_l; inversion Heqpe_st_l; inversion Heqpe_st'_l'; repeat subst. SCase "E_None". apply E_None. simpl in Hlookup. destruct (p l'); [ solve [ inversion Hlookup ] | reflexivity ]. SCase "E_Some". simpl in Hlookup. remember (p l) as k. destruct k as [k|]; inversion Hlookup; subst. eapply E_Some; eauto. apply pe_block_correct. apply Hkeval. Qed. (** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
/* ---------------------------------------------------------------------------------- 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_dma_cmd_gen # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, output pcie_cmd_rd_en, input [33:0] pcie_cmd_rd_data, input pcie_cmd_empty_n, output prp_fifo_rd_en, input [C_PCIE_DATA_WIDTH-1:0] prp_fifo_rd_data, output prp_fifo_free_en, output [5:4] prp_fifo_free_len, input prp_fifo_empty_n, output pcie_rx_cmd_wr_en, output [33:0] pcie_rx_cmd_wr_data, input pcie_rx_cmd_full_n, output pcie_tx_cmd_wr_en, output [33:0] pcie_tx_cmd_wr_data, input pcie_tx_cmd_full_n ); localparam S_IDLE = 15'b000000000000001; localparam S_CMD0 = 15'b000000000000010; localparam S_CMD1 = 15'b000000000000100; localparam S_CMD2 = 15'b000000000001000; localparam S_CMD3 = 15'b000000000010000; localparam S_CHECK_PRP_FIFO = 15'b000000000100000; localparam S_RD_PRP0 = 15'b000000001000000; localparam S_RD_PRP1 = 15'b000000010000000; localparam S_PCIE_PRP = 15'b000000100000000; localparam S_CHECK_PCIE_CMD_FIFO0 = 15'b000001000000000; localparam S_PCIE_CMD0 = 15'b000010000000000; localparam S_PCIE_CMD1 = 15'b000100000000000; localparam S_CHECK_PCIE_CMD_FIFO1 = 15'b001000000000000; localparam S_PCIE_CMD2 = 15'b010000000000000; localparam S_PCIE_CMD3 = 15'b100000000000000; reg [14:0] cur_state; reg [14:0] next_state; reg r_dma_cmd_type; reg r_dma_cmd_dir; reg r_2st_valid; reg r_1st_mrd_need; reg r_2st_mrd_need; reg [6:0] r_hcmd_slot_tag; reg r_pcie_rcb_cross; reg [12:2] r_1st_4b_len; reg [12:2] r_2st_4b_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_hcmd_prp_1; reg [C_PCIE_ADDR_WIDTH-1:2] r_hcmd_prp_2; reg [63:2] r_prp_1; reg [63:2] r_prp_2; reg r_pcie_cmd_rd_en; reg r_prp_fifo_rd_en; reg r_prp_fifo_free_en; reg r_pcie_rx_cmd_wr_en; reg r_pcie_tx_cmd_wr_en; reg [3:0] r_pcie_cmd_wr_data_sel; reg [33:0] r_pcie_cmd_wr_data; wire w_pcie_cmd_full_n; assign pcie_cmd_rd_en = r_pcie_cmd_rd_en; assign prp_fifo_rd_en = r_prp_fifo_rd_en; assign prp_fifo_free_en = r_prp_fifo_free_en; assign prp_fifo_free_len = (r_pcie_rcb_cross == 0) ? 2'b01 : 2'b10; assign pcie_rx_cmd_wr_en = r_pcie_rx_cmd_wr_en; assign pcie_rx_cmd_wr_data = r_pcie_cmd_wr_data; assign pcie_tx_cmd_wr_en = r_pcie_tx_cmd_wr_en; assign pcie_tx_cmd_wr_data = r_pcie_cmd_wr_data; 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 assign w_pcie_cmd_full_n = (r_dma_cmd_dir == 1'b1) ? pcie_tx_cmd_full_n : pcie_rx_cmd_full_n; always @ (*) begin case(cur_state) S_IDLE: begin if(pcie_cmd_empty_n == 1'b1) next_state <= S_CMD0; else next_state <= S_IDLE; end S_CMD0: begin next_state <= S_CMD1; end S_CMD1: begin next_state <= S_CMD2; end S_CMD2: begin next_state <= S_CMD3; end S_CMD3: begin if((r_1st_mrd_need | (r_2st_valid & r_2st_mrd_need)) == 1'b1) next_state <= S_CHECK_PRP_FIFO; else next_state <= S_CHECK_PCIE_CMD_FIFO0; end S_CHECK_PRP_FIFO: begin if(prp_fifo_empty_n == 1) next_state <= S_RD_PRP0; else next_state <= S_CHECK_PRP_FIFO; end S_RD_PRP0: begin if(r_pcie_rcb_cross == 1) next_state <= S_RD_PRP1; else next_state <= S_PCIE_PRP; end S_RD_PRP1: begin next_state <= S_PCIE_PRP; end S_PCIE_PRP: begin next_state <= S_CHECK_PCIE_CMD_FIFO0; end S_CHECK_PCIE_CMD_FIFO0: begin if(w_pcie_cmd_full_n == 1'b1) next_state <= S_PCIE_CMD0; else next_state <= S_CHECK_PCIE_CMD_FIFO0; end S_PCIE_CMD0: begin next_state <= S_PCIE_CMD1; end S_PCIE_CMD1: begin if(r_2st_valid == 1'b1) next_state <= S_CHECK_PCIE_CMD_FIFO1; else next_state <= S_IDLE; end S_CHECK_PCIE_CMD_FIFO1: begin if(w_pcie_cmd_full_n == 1'b1) next_state <= S_PCIE_CMD2; else next_state <= S_CHECK_PCIE_CMD_FIFO1; end S_PCIE_CMD2: begin next_state <= S_PCIE_CMD3; end S_PCIE_CMD3: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_CMD0: begin r_dma_cmd_type <= pcie_cmd_rd_data[11]; r_dma_cmd_dir <= pcie_cmd_rd_data[10]; r_2st_valid <= pcie_cmd_rd_data[9]; r_1st_mrd_need <= pcie_cmd_rd_data[8]; r_2st_mrd_need <= pcie_cmd_rd_data[7]; r_hcmd_slot_tag <= pcie_cmd_rd_data[6:0]; end S_CMD1: begin r_pcie_rcb_cross <= pcie_cmd_rd_data[22]; r_1st_4b_len <= pcie_cmd_rd_data[21:11]; r_2st_4b_len <= pcie_cmd_rd_data[10:0]; end S_CMD2: begin r_hcmd_prp_1 <= pcie_cmd_rd_data[33:0]; end S_CMD3: begin r_hcmd_prp_2 <= {pcie_cmd_rd_data[33:10], 10'b0}; end S_CHECK_PRP_FIFO: begin end S_RD_PRP0: begin r_prp_1 <= prp_fifo_rd_data[63:2]; r_prp_2 <= prp_fifo_rd_data[127:66]; end S_RD_PRP1: begin r_prp_2 <= prp_fifo_rd_data[63:2]; end S_PCIE_PRP: begin if(r_1st_mrd_need == 1) begin r_hcmd_prp_1[C_PCIE_ADDR_WIDTH-1:12] <= r_prp_1[C_PCIE_ADDR_WIDTH-1:12]; r_hcmd_prp_2[C_PCIE_ADDR_WIDTH-1:12] <= r_prp_2[C_PCIE_ADDR_WIDTH-1:12]; end else begin r_hcmd_prp_2[C_PCIE_ADDR_WIDTH-1:12] <= r_prp_1[C_PCIE_ADDR_WIDTH-1:12]; end end S_CHECK_PCIE_CMD_FIFO0: begin end S_PCIE_CMD0: begin end S_PCIE_CMD1: begin end S_CHECK_PCIE_CMD_FIFO1: begin end S_PCIE_CMD2: begin end S_PCIE_CMD3: begin end default: begin end endcase end always @ (*) begin case(r_pcie_cmd_wr_data_sel) // synthesis parallel_case full_case 4'b0001: r_pcie_cmd_wr_data <= {14'b0, r_dma_cmd_type, ~r_2st_valid, r_hcmd_slot_tag, r_1st_4b_len}; 4'b0010: r_pcie_cmd_wr_data <= r_hcmd_prp_1; 4'b0100: r_pcie_cmd_wr_data <= {14'b0, r_dma_cmd_type, 1'b1, r_hcmd_slot_tag, r_2st_4b_len}; 4'b1000: r_pcie_cmd_wr_data <= {r_hcmd_prp_2[C_PCIE_ADDR_WIDTH-1:12], 10'b0}; endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CMD0: begin r_pcie_cmd_rd_en <= 1; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CMD1: begin r_pcie_cmd_rd_en <= 1; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CMD2: begin r_pcie_cmd_rd_en <= 1; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CMD3: begin r_pcie_cmd_rd_en <= 1; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CHECK_PRP_FIFO: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_RD_PRP0: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 1; r_prp_fifo_free_en <= 1; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_RD_PRP1: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 1; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_PCIE_PRP: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_CHECK_PCIE_CMD_FIFO0: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_PCIE_CMD0: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= ~r_dma_cmd_dir; r_pcie_tx_cmd_wr_en <= r_dma_cmd_dir; r_pcie_cmd_wr_data_sel <= 4'b0001; end S_PCIE_CMD1: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= ~r_dma_cmd_dir; r_pcie_tx_cmd_wr_en <= r_dma_cmd_dir; r_pcie_cmd_wr_data_sel <= 4'b0010; end S_CHECK_PCIE_CMD_FIFO1: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end S_PCIE_CMD2: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= ~r_dma_cmd_dir; r_pcie_tx_cmd_wr_en <= r_dma_cmd_dir; r_pcie_cmd_wr_data_sel <= 4'b0100; end S_PCIE_CMD3: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= ~r_dma_cmd_dir; r_pcie_tx_cmd_wr_en <= r_dma_cmd_dir; r_pcie_cmd_wr_data_sel <= 4'b1000; end default: begin r_pcie_cmd_rd_en <= 0; r_prp_fifo_rd_en <= 0; r_prp_fifo_free_en <= 0; r_pcie_rx_cmd_wr_en <= 0; r_pcie_tx_cmd_wr_en <= 0; r_pcie_cmd_wr_data_sel <= 4'b0000; end endcase end 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 module tx_buffer ( input usbclk, input bus_reset, // Used here for the 257-Hack to fix the FX2 bug input reset, // standard DSP-side reset input [15:0] usbdata, input wire WR, output wire have_space, output reg tx_underrun, input wire [3:0] channels, output reg [15:0] tx_i_0, output reg [15:0] tx_q_0, output reg [15:0] tx_i_1, output reg [15:0] tx_q_1, output reg [15:0] tx_i_2, output reg [15:0] tx_q_2, output reg [15:0] tx_i_3, output reg [15:0] tx_q_3, input txclk, input txstrobe, input clear_status, output wire tx_empty, output [11:0] debugbus ); wire [11:0] txfifolevel; reg [8:0] write_count; wire tx_full; wire [15:0] fifodata; wire rdreq; reg [3:0] load_next; // DAC Side of FIFO assign rdreq = ((load_next != channels) & !tx_empty); always @(posedge txclk) if(reset) begin {tx_i_0,tx_q_0,tx_i_1,tx_q_1,tx_i_2,tx_q_2,tx_i_3,tx_q_3} <= #1 128'h0; load_next <= #1 4'd0; end else if(load_next != channels) begin load_next <= #1 load_next + 4'd1; case(load_next) 4'd0 : tx_i_0 <= #1 tx_empty ? 16'd0 : fifodata; 4'd1 : tx_q_0 <= #1 tx_empty ? 16'd0 : fifodata; 4'd2 : tx_i_1 <= #1 tx_empty ? 16'd0 : fifodata; 4'd3 : tx_q_1 <= #1 tx_empty ? 16'd0 : fifodata; 4'd4 : tx_i_2 <= #1 tx_empty ? 16'd0 : fifodata; 4'd5 : tx_q_2 <= #1 tx_empty ? 16'd0 : fifodata; 4'd6 : tx_i_3 <= #1 tx_empty ? 16'd0 : fifodata; 4'd7 : tx_q_3 <= #1 tx_empty ? 16'd0 : fifodata; endcase // case(load_next) end // if (load_next != channels) else if(txstrobe & (load_next == channels)) begin load_next <= #1 4'd0; end // USB Side of FIFO assign have_space = (txfifolevel <= (4095-256)); always @(posedge usbclk) if(bus_reset) // Use bus reset because this is on usbclk write_count <= #1 0; else if(WR & ~write_count[8]) write_count <= #1 write_count + 9'd1; else write_count <= #1 WR ? write_count : 9'b0; // Detect Underruns always @(posedge txclk) if(reset) tx_underrun <= 1'b0; else if(txstrobe & (load_next != channels)) tx_underrun <= 1'b1; else if(clear_status) tx_underrun <= 1'b0; // FIFO fifo_4k txfifo ( .data ( usbdata ), .wrreq ( WR & ~write_count[8] ), .wrclk ( usbclk ), .q ( fifodata ), .rdreq ( rdreq ), .rdclk ( txclk ), .aclr ( reset ), // asynch, so we can use either .rdempty ( tx_empty ), .rdusedw ( ), .wrfull ( tx_full ), .wrusedw ( txfifolevel ) ); // Debugging Aids assign debugbus[0] = WR; assign debugbus[1] = have_space; assign debugbus[2] = tx_empty; assign debugbus[3] = tx_full; assign debugbus[4] = tx_underrun; assign debugbus[5] = write_count[8]; assign debugbus[6] = txstrobe; assign debugbus[7] = rdreq; assign debugbus[11:8] = load_next; endmodule // tx_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_cpld_sel# ( parameter C_PCIE_DATA_WIDTH = 128 ) ( input pcie_user_clk, input cpld_fifo_wr_en, input [C_PCIE_DATA_WIDTH-1:0] cpld_fifo_wr_data, input [7:0] cpld_fifo_tag, input cpld_fifo_tag_last, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data ); reg [7:0] r_cpld_fifo_tag; reg [C_PCIE_DATA_WIDTH-1:0] r_cpld_fifo_wr_data; reg r_cpld0_fifo_tag_last; reg r_cpld0_fifo_wr_en; reg r_cpld1_fifo_tag_last; reg r_cpld1_fifo_wr_en; reg r_cpld2_fifo_tag_last; reg r_cpld2_fifo_wr_en; wire [2:0] w_cpld_prefix_tag_hit; assign w_cpld_prefix_tag_hit[0] = (cpld_fifo_tag[7:3] == 5'b00000); assign w_cpld_prefix_tag_hit[1] = (cpld_fifo_tag[7:3] == 5'b00001); assign w_cpld_prefix_tag_hit[2] = (cpld_fifo_tag[7:4] == 4'b0001); assign cpld0_fifo_tag = r_cpld_fifo_tag; assign cpld0_fifo_tag_last = r_cpld0_fifo_tag_last; assign cpld0_fifo_wr_en = r_cpld0_fifo_wr_en; assign cpld0_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld1_fifo_tag = r_cpld_fifo_tag; assign cpld1_fifo_tag_last = r_cpld1_fifo_tag_last; assign cpld1_fifo_wr_en = r_cpld1_fifo_wr_en; assign cpld1_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld2_fifo_tag = r_cpld_fifo_tag; assign cpld2_fifo_tag_last = r_cpld2_fifo_tag_last; assign cpld2_fifo_wr_en = r_cpld2_fifo_wr_en; assign cpld2_fifo_wr_data = r_cpld_fifo_wr_data; always @(posedge pcie_user_clk) begin r_cpld_fifo_tag <= cpld_fifo_tag; r_cpld_fifo_wr_data <= cpld_fifo_wr_data; r_cpld0_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[0]; r_cpld0_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[0]; r_cpld1_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[1]; r_cpld1_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[1]; r_cpld2_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[2]; r_cpld2_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[2]; 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_cpld_sel# ( parameter C_PCIE_DATA_WIDTH = 128 ) ( input pcie_user_clk, input cpld_fifo_wr_en, input [C_PCIE_DATA_WIDTH-1:0] cpld_fifo_wr_data, input [7:0] cpld_fifo_tag, input cpld_fifo_tag_last, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data ); reg [7:0] r_cpld_fifo_tag; reg [C_PCIE_DATA_WIDTH-1:0] r_cpld_fifo_wr_data; reg r_cpld0_fifo_tag_last; reg r_cpld0_fifo_wr_en; reg r_cpld1_fifo_tag_last; reg r_cpld1_fifo_wr_en; reg r_cpld2_fifo_tag_last; reg r_cpld2_fifo_wr_en; wire [2:0] w_cpld_prefix_tag_hit; assign w_cpld_prefix_tag_hit[0] = (cpld_fifo_tag[7:3] == 5'b00000); assign w_cpld_prefix_tag_hit[1] = (cpld_fifo_tag[7:3] == 5'b00001); assign w_cpld_prefix_tag_hit[2] = (cpld_fifo_tag[7:4] == 4'b0001); assign cpld0_fifo_tag = r_cpld_fifo_tag; assign cpld0_fifo_tag_last = r_cpld0_fifo_tag_last; assign cpld0_fifo_wr_en = r_cpld0_fifo_wr_en; assign cpld0_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld1_fifo_tag = r_cpld_fifo_tag; assign cpld1_fifo_tag_last = r_cpld1_fifo_tag_last; assign cpld1_fifo_wr_en = r_cpld1_fifo_wr_en; assign cpld1_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld2_fifo_tag = r_cpld_fifo_tag; assign cpld2_fifo_tag_last = r_cpld2_fifo_tag_last; assign cpld2_fifo_wr_en = r_cpld2_fifo_wr_en; assign cpld2_fifo_wr_data = r_cpld_fifo_wr_data; always @(posedge pcie_user_clk) begin r_cpld_fifo_tag <= cpld_fifo_tag; r_cpld_fifo_wr_data <= cpld_fifo_wr_data; r_cpld0_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[0]; r_cpld0_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[0]; r_cpld1_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[1]; r_cpld1_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[1]; r_cpld2_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[2]; r_cpld2_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[2]; 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_cpld_sel# ( parameter C_PCIE_DATA_WIDTH = 128 ) ( input pcie_user_clk, input cpld_fifo_wr_en, input [C_PCIE_DATA_WIDTH-1:0] cpld_fifo_wr_data, input [7:0] cpld_fifo_tag, input cpld_fifo_tag_last, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data ); reg [7:0] r_cpld_fifo_tag; reg [C_PCIE_DATA_WIDTH-1:0] r_cpld_fifo_wr_data; reg r_cpld0_fifo_tag_last; reg r_cpld0_fifo_wr_en; reg r_cpld1_fifo_tag_last; reg r_cpld1_fifo_wr_en; reg r_cpld2_fifo_tag_last; reg r_cpld2_fifo_wr_en; wire [2:0] w_cpld_prefix_tag_hit; assign w_cpld_prefix_tag_hit[0] = (cpld_fifo_tag[7:3] == 5'b00000); assign w_cpld_prefix_tag_hit[1] = (cpld_fifo_tag[7:3] == 5'b00001); assign w_cpld_prefix_tag_hit[2] = (cpld_fifo_tag[7:4] == 4'b0001); assign cpld0_fifo_tag = r_cpld_fifo_tag; assign cpld0_fifo_tag_last = r_cpld0_fifo_tag_last; assign cpld0_fifo_wr_en = r_cpld0_fifo_wr_en; assign cpld0_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld1_fifo_tag = r_cpld_fifo_tag; assign cpld1_fifo_tag_last = r_cpld1_fifo_tag_last; assign cpld1_fifo_wr_en = r_cpld1_fifo_wr_en; assign cpld1_fifo_wr_data = r_cpld_fifo_wr_data; assign cpld2_fifo_tag = r_cpld_fifo_tag; assign cpld2_fifo_tag_last = r_cpld2_fifo_tag_last; assign cpld2_fifo_wr_en = r_cpld2_fifo_wr_en; assign cpld2_fifo_wr_data = r_cpld_fifo_wr_data; always @(posedge pcie_user_clk) begin r_cpld_fifo_tag <= cpld_fifo_tag; r_cpld_fifo_wr_data <= cpld_fifo_wr_data; r_cpld0_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[0]; r_cpld0_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[0]; r_cpld1_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[1]; r_cpld1_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[1]; r_cpld2_fifo_tag_last = cpld_fifo_tag_last & w_cpld_prefix_tag_hit[2]; r_cpld2_fifo_wr_en <= cpld_fifo_wr_en & w_cpld_prefix_tag_hit[2]; end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2005 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=0; reg [7:0] crc; reg [223:0] sum; wire [255:0] mglehy = {32{~crc}}; wire [215:0] drricx = {27{crc}}; wire [15:0] apqrli = {2{~crc}}; wire [2:0] szlfpf = crc[2:0]; wire [15:0] dzosui = {2{crc}}; wire [31:0] zndrba = {16{crc[1:0]}}; wire [223:0] bxiouf; vliw vliw ( // Outputs .bxiouf (bxiouf), // Inputs .mglehy (mglehy[255:0]), .drricx (drricx[215:0]), .apqrli (apqrli[15:0]), .szlfpf (szlfpf[2:0]), .dzosui (dzosui[15:0]), .zndrba (zndrba[31:0])); always @ (posedge clk) begin cyc <= cyc + 1; crc <= {crc[6:0], ~^ {crc[7],crc[5],crc[4],crc[3]}}; if (cyc==0) begin // Setup crc <= 8'hed; sum <= 224'h0; end else if (cyc<90) begin //$write("[%0t] cyc==%0d BXI=%x\n",$time, cyc, bxiouf); sum <= {sum[222:0],sum[223]} ^ bxiouf; end else if (cyc==99) begin $write("[%0t] cyc==%0d crc=%b %x\n",$time, cyc, crc, sum); if (crc !== 8'b01110000) $stop; if (sum !== 224'h1fdff998855c3c38d467e28124847831f9ad6d4a09f2801098f032a8) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module vliw ( input[255:0] mglehy, input[215:0] drricx, input[15:0] apqrli, input[2:0] szlfpf, input[15:0] dzosui, input[31:0] zndrba, output [223:0] bxiouf ); wire [463:0] zhknfc = ({29{~apqrli}} & {mglehy, drricx[215:8]}) | ({29{apqrli}} & {mglehy[247:0], drricx}); wire [335:0] umntwz = ({21{~dzosui}} & zhknfc[463:128]) | ({21{dzosui}} & zhknfc[335:0]); wire [335:0] viuvoc = umntwz << {szlfpf, 4'b0000}; wire [223:0] rzyeut = viuvoc[335:112]; wire [223:0] bxiouf = {rzyeut[7:0], rzyeut[15:8], rzyeut[23:16], rzyeut[31:24], rzyeut[39:32], rzyeut[47:40], rzyeut[55:48], rzyeut[63:56], rzyeut[71:64], rzyeut[79:72], rzyeut[87:80], rzyeut[95:88], rzyeut[103:96], rzyeut[111:104], rzyeut[119:112], rzyeut[127:120], rzyeut[135:128], rzyeut[143:136], rzyeut[151:144], rzyeut[159:152], rzyeut[167:160], rzyeut[175:168], rzyeut[183:176], rzyeut[191:184], rzyeut[199:192], rzyeut[207:200], rzyeut[215:208], rzyeut[223:216]}; 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 # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [15:0] pcie_dev_id, output tx_err_drop, input tx_cpld_gnt, input tx_mrd_gnt, input tx_mwr_gnt, //pcie tx signal input m_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] m_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_tx_tkeep, output [3:0] m_axis_tx_tuser, output m_axis_tx_tlast, output m_axis_tx_tvalid, input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last ); wire w_tx_arb_valid; wire [5:0] w_tx_arb_gnt; wire [2:0] w_tx_arb_type; wire [11:2] w_tx_pcie_len; wire [127:0] w_tx_pcie_head; wire [31:0] w_tx_cpld_udata; wire w_tx_arb_rdy; pcie_tx_arb # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_arb_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (pcie_dev_id), .tx_cpld_gnt (tx_cpld_gnt), .tx_mrd_gnt (tx_mrd_gnt), .tx_mwr_gnt (tx_mwr_gnt), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy) ); pcie_tx_tran # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_tran_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .tx_err_drop (tx_err_drop), //pcie tx signal .m_axis_tx_tready (m_axis_tx_tready), .m_axis_tx_tdata (m_axis_tx_tdata), .m_axis_tx_tkeep (m_axis_tx_tkeep), .m_axis_tx_tuser (m_axis_tx_tuser), .m_axis_tx_tlast (m_axis_tx_tlast), .m_axis_tx_tvalid (m_axis_tx_tvalid), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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 # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [15:0] pcie_dev_id, output tx_err_drop, input tx_cpld_gnt, input tx_mrd_gnt, input tx_mwr_gnt, //pcie tx signal input m_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] m_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_tx_tkeep, output [3:0] m_axis_tx_tuser, output m_axis_tx_tlast, output m_axis_tx_tvalid, input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last ); wire w_tx_arb_valid; wire [5:0] w_tx_arb_gnt; wire [2:0] w_tx_arb_type; wire [11:2] w_tx_pcie_len; wire [127:0] w_tx_pcie_head; wire [31:0] w_tx_cpld_udata; wire w_tx_arb_rdy; pcie_tx_arb # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_arb_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (pcie_dev_id), .tx_cpld_gnt (tx_cpld_gnt), .tx_mrd_gnt (tx_mrd_gnt), .tx_mwr_gnt (tx_mwr_gnt), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy) ); pcie_tx_tran # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_tran_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .tx_err_drop (tx_err_drop), //pcie tx signal .m_axis_tx_tready (m_axis_tx_tready), .m_axis_tx_tdata (m_axis_tx_tdata), .m_axis_tx_tkeep (m_axis_tx_tkeep), .m_axis_tx_tuser (m_axis_tx_tuser), .m_axis_tx_tlast (m_axis_tx_tlast), .m_axis_tx_tvalid (m_axis_tx_tvalid), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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 # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [15:0] pcie_dev_id, output tx_err_drop, input tx_cpld_gnt, input tx_mrd_gnt, input tx_mwr_gnt, //pcie tx signal input m_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] m_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_tx_tkeep, output [3:0] m_axis_tx_tuser, output m_axis_tx_tlast, output m_axis_tx_tvalid, input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last ); wire w_tx_arb_valid; wire [5:0] w_tx_arb_gnt; wire [2:0] w_tx_arb_type; wire [11:2] w_tx_pcie_len; wire [127:0] w_tx_pcie_head; wire [31:0] w_tx_cpld_udata; wire w_tx_arb_rdy; pcie_tx_arb # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_arb_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (pcie_dev_id), .tx_cpld_gnt (tx_cpld_gnt), .tx_mrd_gnt (tx_mrd_gnt), .tx_mwr_gnt (tx_mwr_gnt), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy) ); pcie_tx_tran # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_tran_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .tx_err_drop (tx_err_drop), //pcie tx signal .m_axis_tx_tready (m_axis_tx_tready), .m_axis_tx_tdata (m_axis_tx_tdata), .m_axis_tx_tkeep (m_axis_tx_tkeep), .m_axis_tx_tuser (m_axis_tx_tuser), .m_axis_tx_tlast (m_axis_tx_tlast), .m_axis_tx_tvalid (m_axis_tx_tvalid), .tx_arb_valid (w_tx_arb_valid), .tx_arb_gnt (w_tx_arb_gnt), .tx_arb_type (w_tx_arb_type), .tx_pcie_len (w_tx_pcie_len), .tx_pcie_head (w_tx_pcie_head), .tx_cpld_udata (w_tx_cpld_udata), .tx_arb_rdy (w_tx_arb_rdy), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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_tans_if # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( //PCIe user clock input pcie_user_clk, input pcie_user_rst_n, //PCIe rx interface output mreq_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] mreq_fifo_wr_data, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data, //PCIe tx interface input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last, output pcie_mreq_err, output pcie_cpld_err, output pcie_cpld_len_err, //PCIe Integrated Block Interface input [5:0] tx_buf_av, input tx_err_drop, input tx_cfg_req, input s_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] s_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] s_axis_tx_tkeep, output [3:0] s_axis_tx_tuser, output s_axis_tx_tlast, output s_axis_tx_tvalid, output tx_cfg_gnt, input [C_PCIE_DATA_WIDTH-1:0] m_axis_rx_tdata, input [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_rx_tkeep, input m_axis_rx_tlast, input m_axis_rx_tvalid, output m_axis_rx_tready, input [21:0] m_axis_rx_tuser, input [11:0] fc_cpld, input [7:0] fc_cplh, input [11:0] fc_npd, input [7:0] fc_nph, input [11:0] fc_pd, input [7:0] fc_ph, output [2:0] fc_sel, input [7:0] cfg_bus_number, input [4:0] cfg_device_number, input [2:0] cfg_function_number ); wire w_tx_cpld_gnt; wire w_tx_mrd_gnt; wire w_tx_mwr_gnt; reg [15:0] r_pcie_dev_id; always @(posedge pcie_user_clk) begin r_pcie_dev_id <= {cfg_bus_number, cfg_device_number, cfg_function_number}; end pcie_fc_cntl pcie_fc_cntl_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .fc_cpld (fc_cpld), .fc_cplh (fc_cplh), .fc_npd (fc_npd), .fc_nph (fc_nph), .fc_pd (fc_pd), .fc_ph (fc_ph), .fc_sel (fc_sel), .tx_buf_av (tx_buf_av), .tx_cfg_req (tx_cfg_req), .tx_cfg_gnt (tx_cfg_gnt), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt) ); pcie_rx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_rx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), //pcie rx signal .s_axis_rx_tdata (m_axis_rx_tdata), .s_axis_rx_tkeep (m_axis_rx_tkeep), .s_axis_rx_tlast (m_axis_rx_tlast), .s_axis_rx_tvalid (m_axis_rx_tvalid), .s_axis_rx_tready (m_axis_rx_tready), .s_axis_rx_tuser (m_axis_rx_tuser), .pcie_mreq_err (pcie_mreq_err), .pcie_cpld_err (pcie_cpld_err), .pcie_cpld_len_err (pcie_cpld_len_err), .mreq_fifo_wr_en (mreq_fifo_wr_en), .mreq_fifo_wr_data (mreq_fifo_wr_data), .cpld0_fifo_tag (cpld0_fifo_tag), .cpld0_fifo_tag_last (cpld0_fifo_tag_last), .cpld0_fifo_wr_en (cpld0_fifo_wr_en), .cpld0_fifo_wr_data (cpld0_fifo_wr_data), .cpld1_fifo_tag (cpld1_fifo_tag), .cpld1_fifo_tag_last (cpld1_fifo_tag_last), .cpld1_fifo_wr_en (cpld1_fifo_wr_en), .cpld1_fifo_wr_data (cpld1_fifo_wr_data), .cpld2_fifo_tag (cpld2_fifo_tag), .cpld2_fifo_tag_last (cpld2_fifo_tag_last), .cpld2_fifo_wr_en (cpld2_fifo_wr_en), .cpld2_fifo_wr_data (cpld2_fifo_wr_data) ); pcie_tx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (r_pcie_dev_id), .tx_err_drop (tx_err_drop), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt), //pcie tx signal .m_axis_tx_tready (s_axis_tx_tready), .m_axis_tx_tdata (s_axis_tx_tdata), .m_axis_tx_tkeep (s_axis_tx_tkeep), .m_axis_tx_tuser (s_axis_tx_tuser), .m_axis_tx_tlast (s_axis_tx_tlast), .m_axis_tx_tvalid (s_axis_tx_tvalid), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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_tans_if # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( //PCIe user clock input pcie_user_clk, input pcie_user_rst_n, //PCIe rx interface output mreq_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] mreq_fifo_wr_data, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data, //PCIe tx interface input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last, output pcie_mreq_err, output pcie_cpld_err, output pcie_cpld_len_err, //PCIe Integrated Block Interface input [5:0] tx_buf_av, input tx_err_drop, input tx_cfg_req, input s_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] s_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] s_axis_tx_tkeep, output [3:0] s_axis_tx_tuser, output s_axis_tx_tlast, output s_axis_tx_tvalid, output tx_cfg_gnt, input [C_PCIE_DATA_WIDTH-1:0] m_axis_rx_tdata, input [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_rx_tkeep, input m_axis_rx_tlast, input m_axis_rx_tvalid, output m_axis_rx_tready, input [21:0] m_axis_rx_tuser, input [11:0] fc_cpld, input [7:0] fc_cplh, input [11:0] fc_npd, input [7:0] fc_nph, input [11:0] fc_pd, input [7:0] fc_ph, output [2:0] fc_sel, input [7:0] cfg_bus_number, input [4:0] cfg_device_number, input [2:0] cfg_function_number ); wire w_tx_cpld_gnt; wire w_tx_mrd_gnt; wire w_tx_mwr_gnt; reg [15:0] r_pcie_dev_id; always @(posedge pcie_user_clk) begin r_pcie_dev_id <= {cfg_bus_number, cfg_device_number, cfg_function_number}; end pcie_fc_cntl pcie_fc_cntl_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .fc_cpld (fc_cpld), .fc_cplh (fc_cplh), .fc_npd (fc_npd), .fc_nph (fc_nph), .fc_pd (fc_pd), .fc_ph (fc_ph), .fc_sel (fc_sel), .tx_buf_av (tx_buf_av), .tx_cfg_req (tx_cfg_req), .tx_cfg_gnt (tx_cfg_gnt), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt) ); pcie_rx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_rx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), //pcie rx signal .s_axis_rx_tdata (m_axis_rx_tdata), .s_axis_rx_tkeep (m_axis_rx_tkeep), .s_axis_rx_tlast (m_axis_rx_tlast), .s_axis_rx_tvalid (m_axis_rx_tvalid), .s_axis_rx_tready (m_axis_rx_tready), .s_axis_rx_tuser (m_axis_rx_tuser), .pcie_mreq_err (pcie_mreq_err), .pcie_cpld_err (pcie_cpld_err), .pcie_cpld_len_err (pcie_cpld_len_err), .mreq_fifo_wr_en (mreq_fifo_wr_en), .mreq_fifo_wr_data (mreq_fifo_wr_data), .cpld0_fifo_tag (cpld0_fifo_tag), .cpld0_fifo_tag_last (cpld0_fifo_tag_last), .cpld0_fifo_wr_en (cpld0_fifo_wr_en), .cpld0_fifo_wr_data (cpld0_fifo_wr_data), .cpld1_fifo_tag (cpld1_fifo_tag), .cpld1_fifo_tag_last (cpld1_fifo_tag_last), .cpld1_fifo_wr_en (cpld1_fifo_wr_en), .cpld1_fifo_wr_data (cpld1_fifo_wr_data), .cpld2_fifo_tag (cpld2_fifo_tag), .cpld2_fifo_tag_last (cpld2_fifo_tag_last), .cpld2_fifo_wr_en (cpld2_fifo_wr_en), .cpld2_fifo_wr_data (cpld2_fifo_wr_data) ); pcie_tx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (r_pcie_dev_id), .tx_err_drop (tx_err_drop), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt), //pcie tx signal .m_axis_tx_tready (s_axis_tx_tready), .m_axis_tx_tdata (s_axis_tx_tdata), .m_axis_tx_tkeep (s_axis_tx_tkeep), .m_axis_tx_tuser (s_axis_tx_tuser), .m_axis_tx_tlast (s_axis_tx_tlast), .m_axis_tx_tvalid (s_axis_tx_tvalid), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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_tans_if # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( //PCIe user clock input pcie_user_clk, input pcie_user_rst_n, //PCIe rx interface output mreq_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] mreq_fifo_wr_data, output [7:0] cpld0_fifo_tag, output cpld0_fifo_tag_last, output cpld0_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld0_fifo_wr_data, output [7:0] cpld1_fifo_tag, output cpld1_fifo_tag_last, output cpld1_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld1_fifo_wr_data, output [7:0] cpld2_fifo_tag, output cpld2_fifo_tag_last, output cpld2_fifo_wr_en, output [C_PCIE_DATA_WIDTH-1:0] cpld2_fifo_wr_data, //PCIe tx interface input tx_cpld_req, input [7:0] tx_cpld_tag, input [15:0] tx_cpld_req_id, input [11:2] tx_cpld_len, input [11:0] tx_cpld_bc, input [6:0] tx_cpld_laddr, input [63:0] tx_cpld_data, output tx_cpld_req_ack, input tx_mrd0_req, input [7:0] tx_mrd0_tag, input [11:2] tx_mrd0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd0_addr, output tx_mrd0_req_ack, input tx_mrd1_req, input [7:0] tx_mrd1_tag, input [11:2] tx_mrd1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd1_addr, output tx_mrd1_req_ack, input tx_mrd2_req, input [7:0] tx_mrd2_tag, input [11:2] tx_mrd2_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mrd2_addr, output tx_mrd2_req_ack, input tx_mwr0_req, input [7:0] tx_mwr0_tag, input [11:2] tx_mwr0_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr0_addr, output tx_mwr0_req_ack, output tx_mwr0_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr0_rd_data, output tx_mwr0_data_last, input tx_mwr1_req, input [7:0] tx_mwr1_tag, input [11:2] tx_mwr1_len, input [C_PCIE_ADDR_WIDTH-1:2] tx_mwr1_addr, output tx_mwr1_req_ack, output tx_mwr1_rd_en, input [C_PCIE_DATA_WIDTH-1:0] tx_mwr1_rd_data, output tx_mwr1_data_last, output pcie_mreq_err, output pcie_cpld_err, output pcie_cpld_len_err, //PCIe Integrated Block Interface input [5:0] tx_buf_av, input tx_err_drop, input tx_cfg_req, input s_axis_tx_tready, output [C_PCIE_DATA_WIDTH-1:0] s_axis_tx_tdata, output [(C_PCIE_DATA_WIDTH/8)-1:0] s_axis_tx_tkeep, output [3:0] s_axis_tx_tuser, output s_axis_tx_tlast, output s_axis_tx_tvalid, output tx_cfg_gnt, input [C_PCIE_DATA_WIDTH-1:0] m_axis_rx_tdata, input [(C_PCIE_DATA_WIDTH/8)-1:0] m_axis_rx_tkeep, input m_axis_rx_tlast, input m_axis_rx_tvalid, output m_axis_rx_tready, input [21:0] m_axis_rx_tuser, input [11:0] fc_cpld, input [7:0] fc_cplh, input [11:0] fc_npd, input [7:0] fc_nph, input [11:0] fc_pd, input [7:0] fc_ph, output [2:0] fc_sel, input [7:0] cfg_bus_number, input [4:0] cfg_device_number, input [2:0] cfg_function_number ); wire w_tx_cpld_gnt; wire w_tx_mrd_gnt; wire w_tx_mwr_gnt; reg [15:0] r_pcie_dev_id; always @(posedge pcie_user_clk) begin r_pcie_dev_id <= {cfg_bus_number, cfg_device_number, cfg_function_number}; end pcie_fc_cntl pcie_fc_cntl_inst0 ( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .fc_cpld (fc_cpld), .fc_cplh (fc_cplh), .fc_npd (fc_npd), .fc_nph (fc_nph), .fc_pd (fc_pd), .fc_ph (fc_ph), .fc_sel (fc_sel), .tx_buf_av (tx_buf_av), .tx_cfg_req (tx_cfg_req), .tx_cfg_gnt (tx_cfg_gnt), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt) ); pcie_rx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_rx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), //pcie rx signal .s_axis_rx_tdata (m_axis_rx_tdata), .s_axis_rx_tkeep (m_axis_rx_tkeep), .s_axis_rx_tlast (m_axis_rx_tlast), .s_axis_rx_tvalid (m_axis_rx_tvalid), .s_axis_rx_tready (m_axis_rx_tready), .s_axis_rx_tuser (m_axis_rx_tuser), .pcie_mreq_err (pcie_mreq_err), .pcie_cpld_err (pcie_cpld_err), .pcie_cpld_len_err (pcie_cpld_len_err), .mreq_fifo_wr_en (mreq_fifo_wr_en), .mreq_fifo_wr_data (mreq_fifo_wr_data), .cpld0_fifo_tag (cpld0_fifo_tag), .cpld0_fifo_tag_last (cpld0_fifo_tag_last), .cpld0_fifo_wr_en (cpld0_fifo_wr_en), .cpld0_fifo_wr_data (cpld0_fifo_wr_data), .cpld1_fifo_tag (cpld1_fifo_tag), .cpld1_fifo_tag_last (cpld1_fifo_tag_last), .cpld1_fifo_wr_en (cpld1_fifo_wr_en), .cpld1_fifo_wr_data (cpld1_fifo_wr_data), .cpld2_fifo_tag (cpld2_fifo_tag), .cpld2_fifo_tag_last (cpld2_fifo_tag_last), .cpld2_fifo_wr_en (cpld2_fifo_wr_en), .cpld2_fifo_wr_data (cpld2_fifo_wr_data) ); pcie_tx # ( .C_PCIE_DATA_WIDTH (C_PCIE_DATA_WIDTH) ) pcie_tx_inst0( .pcie_user_clk (pcie_user_clk), .pcie_user_rst_n (pcie_user_rst_n), .pcie_dev_id (r_pcie_dev_id), .tx_err_drop (tx_err_drop), .tx_cpld_gnt (w_tx_cpld_gnt), .tx_mrd_gnt (w_tx_mrd_gnt), .tx_mwr_gnt (w_tx_mwr_gnt), //pcie tx signal .m_axis_tx_tready (s_axis_tx_tready), .m_axis_tx_tdata (s_axis_tx_tdata), .m_axis_tx_tkeep (s_axis_tx_tkeep), .m_axis_tx_tuser (s_axis_tx_tuser), .m_axis_tx_tlast (s_axis_tx_tlast), .m_axis_tx_tvalid (s_axis_tx_tvalid), .tx_cpld_req (tx_cpld_req), .tx_cpld_tag (tx_cpld_tag), .tx_cpld_req_id (tx_cpld_req_id), .tx_cpld_len (tx_cpld_len), .tx_cpld_bc (tx_cpld_bc), .tx_cpld_laddr (tx_cpld_laddr), .tx_cpld_data (tx_cpld_data), .tx_cpld_req_ack (tx_cpld_req_ack), .tx_mrd0_req (tx_mrd0_req), .tx_mrd0_tag (tx_mrd0_tag), .tx_mrd0_len (tx_mrd0_len), .tx_mrd0_addr (tx_mrd0_addr), .tx_mrd0_req_ack (tx_mrd0_req_ack), .tx_mrd1_req (tx_mrd1_req), .tx_mrd1_tag (tx_mrd1_tag), .tx_mrd1_len (tx_mrd1_len), .tx_mrd1_addr (tx_mrd1_addr), .tx_mrd1_req_ack (tx_mrd1_req_ack), .tx_mrd2_req (tx_mrd2_req), .tx_mrd2_tag (tx_mrd2_tag), .tx_mrd2_len (tx_mrd2_len), .tx_mrd2_addr (tx_mrd2_addr), .tx_mrd2_req_ack (tx_mrd2_req_ack), .tx_mwr0_req (tx_mwr0_req), .tx_mwr0_tag (tx_mwr0_tag), .tx_mwr0_len (tx_mwr0_len), .tx_mwr0_addr (tx_mwr0_addr), .tx_mwr0_req_ack (tx_mwr0_req_ack), .tx_mwr0_rd_en (tx_mwr0_rd_en), .tx_mwr0_rd_data (tx_mwr0_rd_data), .tx_mwr0_data_last (tx_mwr0_data_last), .tx_mwr1_req (tx_mwr1_req), .tx_mwr1_tag (tx_mwr1_tag), .tx_mwr1_len (tx_mwr1_len), .tx_mwr1_addr (tx_mwr1_addr), .tx_mwr1_req_ack (tx_mwr1_req_ack), .tx_mwr1_rd_en (tx_mwr1_rd_en), .tx_mwr1_rd_data (tx_mwr1_rd_data), .tx_mwr1_data_last (tx_mwr1_data_last) ); 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_cmd_fifo # ( parameter P_FIFO_DATA_WIDTH = 34, parameter P_FIFO_DEPTH_WIDTH = 5 ) ( input clk, input rst_n, input wr_en, input [P_FIFO_DATA_WIDTH-1:0] wr_data, output full_n, input rd_en, output [P_FIFO_DATA_WIDTH-1:0] rd_data, output empty_n ); localparam P_FIFO_ALLOC_WIDTH = 1; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_front_addr_p1; wire [P_FIFO_DEPTH_WIDTH-1:0] w_front_addr; reg [P_FIFO_DEPTH_WIDTH:0] r_rear_addr; assign full_n = ~((r_rear_addr[P_FIFO_DEPTH_WIDTH] ^ r_front_addr[P_FIFO_DEPTH_WIDTH]) & (r_rear_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH] == r_front_addr[P_FIFO_DEPTH_WIDTH-1:P_FIFO_ALLOC_WIDTH])); assign empty_n = ~(r_front_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH] == r_rear_addr[P_FIFO_DEPTH_WIDTH:P_FIFO_ALLOC_WIDTH]); always @(posedge clk or negedge rst_n) begin if (rst_n == 0) begin r_front_addr <= 0; r_front_addr_p1 <= 1; r_rear_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 (wr_en == 1) begin r_rear_addr <= r_rear_addr + 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]; localparam LP_DEVICE = "7SERIES"; localparam LP_BRAM_SIZE = "18Kb"; 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 = "READ_FIRST"; localparam LP_WE_WIDTH = 4; 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 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], 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) ) ramb18sdp_0( .DO (rd_data[LP_READ_WIDTH-1:0]), .DI (wr_data[LP_WRITE_WIDTH-1:0]), .RDADDR (rdaddr), .RDCLK (clk), .RDEN (1'b1), .REGCE (1'b1), .RST (1'b0), .WE ({LP_WE_WIDTH{1'b1}}), .WRADDR (wraddr), .WRCLK (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_tx_req # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_payload_size, output pcie_tx_cmd_rd_en, input [33:0] pcie_tx_cmd_rd_data, input pcie_tx_cmd_empty_n, output pcie_tx_fifo_free_en, output [9:4] pcie_tx_fifo_free_len, input pcie_tx_fifo_empty_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, output dma_tx_done_wr_en, output [20:0] dma_tx_done_wr_data, input dma_tx_done_wr_rdy_n ); localparam S_IDLE = 10'b0000000001; localparam S_PCIE_TX_CMD_0 = 10'b0000000010; localparam S_PCIE_TX_CMD_1 = 10'b0000000100; localparam S_PCIE_CHK_FIFO = 10'b0000001000; localparam S_PCIE_MWR_REQ = 10'b0000010000; localparam S_PCIE_MWR_ACK = 10'b0000100000; localparam S_PCIE_MWR_DONE = 10'b0001000000; localparam S_PCIE_MWR_NEXT = 10'b0010000000; localparam S_PCIE_DMA_DONE_WR_WAIT = 10'b0100000000; localparam S_PCIE_DMA_DONE_WR = 10'b1000000000; reg [9:0] cur_state; reg [9:0] next_state; reg [2:0] r_pcie_max_payload_size; reg r_pcie_tx_cmd_rd_en; reg r_pcie_tx_fifo_free_en; reg r_tx_dma_mwr_req; reg r_dma_cmd_type; reg r_dma_done_check; reg [6:0] r_hcmd_slot_tag; reg [12:2] r_pcie_tx_len; reg [12:2] r_pcie_orig_len; reg [9:2] r_pcie_tx_cur_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_pcie_addr; reg r_dma_tx_done_wr_en; assign pcie_tx_cmd_rd_en = r_pcie_tx_cmd_rd_en; assign pcie_tx_fifo_free_en = r_pcie_tx_fifo_free_en; assign pcie_tx_fifo_free_len = r_pcie_tx_cur_len[9:4]; assign tx_dma_mwr_req = r_tx_dma_mwr_req; assign tx_dma_mwr_tag = 8'b0; assign tx_dma_mwr_len = {2'b0, r_pcie_tx_cur_len}; assign tx_dma_mwr_addr = r_pcie_addr; assign dma_tx_done_wr_en = r_dma_tx_done_wr_en; assign dma_tx_done_wr_data = {r_dma_cmd_type, r_dma_done_check, 1'b1, r_hcmd_slot_tag, r_pcie_orig_len}; 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_tx_cmd_empty_n == 1) next_state <= S_PCIE_TX_CMD_0; else next_state <= S_IDLE; end S_PCIE_TX_CMD_0: begin next_state <= S_PCIE_TX_CMD_1; end S_PCIE_TX_CMD_1: begin next_state <= S_PCIE_CHK_FIFO; end S_PCIE_CHK_FIFO: begin if(pcie_tx_fifo_empty_n == 1) next_state <= S_PCIE_MWR_REQ; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_MWR_REQ: begin next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_ACK: begin if(tx_dma_mwr_req_ack == 1) next_state <= S_PCIE_MWR_DONE; else next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_DONE: begin next_state <= S_PCIE_MWR_NEXT; end S_PCIE_MWR_NEXT: begin if(r_pcie_tx_len == 0) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_DMA_DONE_WR_WAIT: begin if(dma_tx_done_wr_rdy_n == 1) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_DMA_DONE_WR; end S_PCIE_DMA_DONE_WR: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin r_pcie_max_payload_size <= pcie_max_payload_size; end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_TX_CMD_0: begin r_dma_cmd_type <= pcie_tx_cmd_rd_data[19]; r_dma_done_check <= pcie_tx_cmd_rd_data[18]; r_hcmd_slot_tag <= pcie_tx_cmd_rd_data[17:11]; r_pcie_tx_len <= {pcie_tx_cmd_rd_data[10:2], 2'b0}; end S_PCIE_TX_CMD_1: begin r_pcie_orig_len <= r_pcie_tx_len; case(r_pcie_max_payload_size) 3'b010: begin if(r_pcie_tx_len[8:7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b100; else r_pcie_tx_cur_len[9:7] <= {1'b0, r_pcie_tx_len[8:7]}; end 3'b001: begin if(r_pcie_tx_len[7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b010; else r_pcie_tx_cur_len[9:7] <= {2'b0, r_pcie_tx_len[7]}; end default: begin if(r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b001; else r_pcie_tx_cur_len[9:7] <= 3'b000; end endcase r_pcie_tx_cur_len[6:2] <= r_pcie_tx_len[6:2]; r_pcie_addr <= {pcie_tx_cmd_rd_data[33:2], 2'b0}; end S_PCIE_CHK_FIFO: begin end S_PCIE_MWR_REQ: begin end S_PCIE_MWR_ACK: begin end S_PCIE_MWR_DONE: begin r_pcie_addr <= r_pcie_addr + r_pcie_tx_cur_len; r_pcie_tx_len <= r_pcie_tx_len - r_pcie_tx_cur_len; case(r_pcie_max_payload_size) 3'b010: r_pcie_tx_cur_len <= 8'h80; 3'b001: r_pcie_tx_cur_len <= 8'h40; default: r_pcie_tx_cur_len <= 8'h20; endcase end S_PCIE_MWR_NEXT: begin end S_PCIE_DMA_DONE_WR_WAIT: begin end S_PCIE_DMA_DONE_WR: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_0: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_1: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_CHK_FIFO: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_REQ: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 1; r_tx_dma_mwr_req <= 1; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_ACK: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_DONE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_NEXT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR_WAIT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 1; end default: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 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_req # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_payload_size, output pcie_tx_cmd_rd_en, input [33:0] pcie_tx_cmd_rd_data, input pcie_tx_cmd_empty_n, output pcie_tx_fifo_free_en, output [9:4] pcie_tx_fifo_free_len, input pcie_tx_fifo_empty_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, output dma_tx_done_wr_en, output [20:0] dma_tx_done_wr_data, input dma_tx_done_wr_rdy_n ); localparam S_IDLE = 10'b0000000001; localparam S_PCIE_TX_CMD_0 = 10'b0000000010; localparam S_PCIE_TX_CMD_1 = 10'b0000000100; localparam S_PCIE_CHK_FIFO = 10'b0000001000; localparam S_PCIE_MWR_REQ = 10'b0000010000; localparam S_PCIE_MWR_ACK = 10'b0000100000; localparam S_PCIE_MWR_DONE = 10'b0001000000; localparam S_PCIE_MWR_NEXT = 10'b0010000000; localparam S_PCIE_DMA_DONE_WR_WAIT = 10'b0100000000; localparam S_PCIE_DMA_DONE_WR = 10'b1000000000; reg [9:0] cur_state; reg [9:0] next_state; reg [2:0] r_pcie_max_payload_size; reg r_pcie_tx_cmd_rd_en; reg r_pcie_tx_fifo_free_en; reg r_tx_dma_mwr_req; reg r_dma_cmd_type; reg r_dma_done_check; reg [6:0] r_hcmd_slot_tag; reg [12:2] r_pcie_tx_len; reg [12:2] r_pcie_orig_len; reg [9:2] r_pcie_tx_cur_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_pcie_addr; reg r_dma_tx_done_wr_en; assign pcie_tx_cmd_rd_en = r_pcie_tx_cmd_rd_en; assign pcie_tx_fifo_free_en = r_pcie_tx_fifo_free_en; assign pcie_tx_fifo_free_len = r_pcie_tx_cur_len[9:4]; assign tx_dma_mwr_req = r_tx_dma_mwr_req; assign tx_dma_mwr_tag = 8'b0; assign tx_dma_mwr_len = {2'b0, r_pcie_tx_cur_len}; assign tx_dma_mwr_addr = r_pcie_addr; assign dma_tx_done_wr_en = r_dma_tx_done_wr_en; assign dma_tx_done_wr_data = {r_dma_cmd_type, r_dma_done_check, 1'b1, r_hcmd_slot_tag, r_pcie_orig_len}; 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_tx_cmd_empty_n == 1) next_state <= S_PCIE_TX_CMD_0; else next_state <= S_IDLE; end S_PCIE_TX_CMD_0: begin next_state <= S_PCIE_TX_CMD_1; end S_PCIE_TX_CMD_1: begin next_state <= S_PCIE_CHK_FIFO; end S_PCIE_CHK_FIFO: begin if(pcie_tx_fifo_empty_n == 1) next_state <= S_PCIE_MWR_REQ; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_MWR_REQ: begin next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_ACK: begin if(tx_dma_mwr_req_ack == 1) next_state <= S_PCIE_MWR_DONE; else next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_DONE: begin next_state <= S_PCIE_MWR_NEXT; end S_PCIE_MWR_NEXT: begin if(r_pcie_tx_len == 0) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_DMA_DONE_WR_WAIT: begin if(dma_tx_done_wr_rdy_n == 1) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_DMA_DONE_WR; end S_PCIE_DMA_DONE_WR: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin r_pcie_max_payload_size <= pcie_max_payload_size; end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_TX_CMD_0: begin r_dma_cmd_type <= pcie_tx_cmd_rd_data[19]; r_dma_done_check <= pcie_tx_cmd_rd_data[18]; r_hcmd_slot_tag <= pcie_tx_cmd_rd_data[17:11]; r_pcie_tx_len <= {pcie_tx_cmd_rd_data[10:2], 2'b0}; end S_PCIE_TX_CMD_1: begin r_pcie_orig_len <= r_pcie_tx_len; case(r_pcie_max_payload_size) 3'b010: begin if(r_pcie_tx_len[8:7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b100; else r_pcie_tx_cur_len[9:7] <= {1'b0, r_pcie_tx_len[8:7]}; end 3'b001: begin if(r_pcie_tx_len[7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b010; else r_pcie_tx_cur_len[9:7] <= {2'b0, r_pcie_tx_len[7]}; end default: begin if(r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b001; else r_pcie_tx_cur_len[9:7] <= 3'b000; end endcase r_pcie_tx_cur_len[6:2] <= r_pcie_tx_len[6:2]; r_pcie_addr <= {pcie_tx_cmd_rd_data[33:2], 2'b0}; end S_PCIE_CHK_FIFO: begin end S_PCIE_MWR_REQ: begin end S_PCIE_MWR_ACK: begin end S_PCIE_MWR_DONE: begin r_pcie_addr <= r_pcie_addr + r_pcie_tx_cur_len; r_pcie_tx_len <= r_pcie_tx_len - r_pcie_tx_cur_len; case(r_pcie_max_payload_size) 3'b010: r_pcie_tx_cur_len <= 8'h80; 3'b001: r_pcie_tx_cur_len <= 8'h40; default: r_pcie_tx_cur_len <= 8'h20; endcase end S_PCIE_MWR_NEXT: begin end S_PCIE_DMA_DONE_WR_WAIT: begin end S_PCIE_DMA_DONE_WR: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_0: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_1: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_CHK_FIFO: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_REQ: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 1; r_tx_dma_mwr_req <= 1; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_ACK: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_DONE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_NEXT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR_WAIT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 1; end default: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 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_req # ( parameter C_PCIE_DATA_WIDTH = 128, parameter C_PCIE_ADDR_WIDTH = 36 ) ( input pcie_user_clk, input pcie_user_rst_n, input [2:0] pcie_max_payload_size, output pcie_tx_cmd_rd_en, input [33:0] pcie_tx_cmd_rd_data, input pcie_tx_cmd_empty_n, output pcie_tx_fifo_free_en, output [9:4] pcie_tx_fifo_free_len, input pcie_tx_fifo_empty_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, output dma_tx_done_wr_en, output [20:0] dma_tx_done_wr_data, input dma_tx_done_wr_rdy_n ); localparam S_IDLE = 10'b0000000001; localparam S_PCIE_TX_CMD_0 = 10'b0000000010; localparam S_PCIE_TX_CMD_1 = 10'b0000000100; localparam S_PCIE_CHK_FIFO = 10'b0000001000; localparam S_PCIE_MWR_REQ = 10'b0000010000; localparam S_PCIE_MWR_ACK = 10'b0000100000; localparam S_PCIE_MWR_DONE = 10'b0001000000; localparam S_PCIE_MWR_NEXT = 10'b0010000000; localparam S_PCIE_DMA_DONE_WR_WAIT = 10'b0100000000; localparam S_PCIE_DMA_DONE_WR = 10'b1000000000; reg [9:0] cur_state; reg [9:0] next_state; reg [2:0] r_pcie_max_payload_size; reg r_pcie_tx_cmd_rd_en; reg r_pcie_tx_fifo_free_en; reg r_tx_dma_mwr_req; reg r_dma_cmd_type; reg r_dma_done_check; reg [6:0] r_hcmd_slot_tag; reg [12:2] r_pcie_tx_len; reg [12:2] r_pcie_orig_len; reg [9:2] r_pcie_tx_cur_len; reg [C_PCIE_ADDR_WIDTH-1:2] r_pcie_addr; reg r_dma_tx_done_wr_en; assign pcie_tx_cmd_rd_en = r_pcie_tx_cmd_rd_en; assign pcie_tx_fifo_free_en = r_pcie_tx_fifo_free_en; assign pcie_tx_fifo_free_len = r_pcie_tx_cur_len[9:4]; assign tx_dma_mwr_req = r_tx_dma_mwr_req; assign tx_dma_mwr_tag = 8'b0; assign tx_dma_mwr_len = {2'b0, r_pcie_tx_cur_len}; assign tx_dma_mwr_addr = r_pcie_addr; assign dma_tx_done_wr_en = r_dma_tx_done_wr_en; assign dma_tx_done_wr_data = {r_dma_cmd_type, r_dma_done_check, 1'b1, r_hcmd_slot_tag, r_pcie_orig_len}; 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_tx_cmd_empty_n == 1) next_state <= S_PCIE_TX_CMD_0; else next_state <= S_IDLE; end S_PCIE_TX_CMD_0: begin next_state <= S_PCIE_TX_CMD_1; end S_PCIE_TX_CMD_1: begin next_state <= S_PCIE_CHK_FIFO; end S_PCIE_CHK_FIFO: begin if(pcie_tx_fifo_empty_n == 1) next_state <= S_PCIE_MWR_REQ; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_MWR_REQ: begin next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_ACK: begin if(tx_dma_mwr_req_ack == 1) next_state <= S_PCIE_MWR_DONE; else next_state <= S_PCIE_MWR_ACK; end S_PCIE_MWR_DONE: begin next_state <= S_PCIE_MWR_NEXT; end S_PCIE_MWR_NEXT: begin if(r_pcie_tx_len == 0) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_CHK_FIFO; end S_PCIE_DMA_DONE_WR_WAIT: begin if(dma_tx_done_wr_rdy_n == 1) next_state <= S_PCIE_DMA_DONE_WR_WAIT; else next_state <= S_PCIE_DMA_DONE_WR; end S_PCIE_DMA_DONE_WR: begin next_state <= S_IDLE; end default: begin next_state <= S_IDLE; end endcase end always @ (posedge pcie_user_clk) begin r_pcie_max_payload_size <= pcie_max_payload_size; end always @ (posedge pcie_user_clk) begin case(cur_state) S_IDLE: begin end S_PCIE_TX_CMD_0: begin r_dma_cmd_type <= pcie_tx_cmd_rd_data[19]; r_dma_done_check <= pcie_tx_cmd_rd_data[18]; r_hcmd_slot_tag <= pcie_tx_cmd_rd_data[17:11]; r_pcie_tx_len <= {pcie_tx_cmd_rd_data[10:2], 2'b0}; end S_PCIE_TX_CMD_1: begin r_pcie_orig_len <= r_pcie_tx_len; case(r_pcie_max_payload_size) 3'b010: begin if(r_pcie_tx_len[8:7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b100; else r_pcie_tx_cur_len[9:7] <= {1'b0, r_pcie_tx_len[8:7]}; end 3'b001: begin if(r_pcie_tx_len[7] == 0 && r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b010; else r_pcie_tx_cur_len[9:7] <= {2'b0, r_pcie_tx_len[7]}; end default: begin if(r_pcie_tx_len[6:2] == 0) r_pcie_tx_cur_len[9:7] <= 3'b001; else r_pcie_tx_cur_len[9:7] <= 3'b000; end endcase r_pcie_tx_cur_len[6:2] <= r_pcie_tx_len[6:2]; r_pcie_addr <= {pcie_tx_cmd_rd_data[33:2], 2'b0}; end S_PCIE_CHK_FIFO: begin end S_PCIE_MWR_REQ: begin end S_PCIE_MWR_ACK: begin end S_PCIE_MWR_DONE: begin r_pcie_addr <= r_pcie_addr + r_pcie_tx_cur_len; r_pcie_tx_len <= r_pcie_tx_len - r_pcie_tx_cur_len; case(r_pcie_max_payload_size) 3'b010: r_pcie_tx_cur_len <= 8'h80; 3'b001: r_pcie_tx_cur_len <= 8'h40; default: r_pcie_tx_cur_len <= 8'h20; endcase end S_PCIE_MWR_NEXT: begin end S_PCIE_DMA_DONE_WR_WAIT: begin end S_PCIE_DMA_DONE_WR: begin end default: begin end endcase end always @ (*) begin case(cur_state) S_IDLE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_0: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_TX_CMD_1: begin r_pcie_tx_cmd_rd_en <= 1; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_CHK_FIFO: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_REQ: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 1; r_tx_dma_mwr_req <= 1; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_ACK: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_DONE: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_MWR_NEXT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR_WAIT: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end S_PCIE_DMA_DONE_WR: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 1; end default: begin r_pcie_tx_cmd_rd_en <= 0; r_pcie_tx_fifo_free_en <= 0; r_tx_dma_mwr_req <= 0; r_dma_tx_done_wr_en <= 0; end endcase end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; // verilator lint_off COMBDLY // verilator lint_off UNOPT // verilator lint_off UNOPTFLAT reg c1_start; initial c1_start = 0; wire [31:0] c1_count; comb_loop c1 (.count(c1_count), .start(c1_start)); wire s2_start = (c1_count==0 && c1_start); wire [31:0] s2_count; seq_loop s2 (.count(s2_count), .start(s2_start)); wire c3_start = (s2_count[0]); wire [31:0] c3_count; comb_loop c3 (.count(c3_count), .start(c3_start)); reg [7:0] cyc; initial cyc=0; always @ (posedge clk) begin //$write("[%0t] %x counts %x %x %x\n",$time,cyc,c1_count,s2_count,c3_count); cyc <= cyc + 8'd1; case (cyc) 8'd00: begin c1_start <= 1'b0; end 8'd01: begin c1_start <= 1'b1; end default: ; endcase case (cyc) 8'd02: begin if (c1_count!=32'h3) $stop; if (s2_count!=32'h3) $stop; if (c3_count!=32'h6) $stop; end 8'd03: begin $write("*-* All Finished *-*\n"); $finish; end default: ; endcase end endmodule module comb_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner = 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner = runnerm1; $write ("%m count=%d runner =%x\n",count, runnerm1); end end endmodule module seq_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner <= 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner <= runnerm1; $write ("%m count=%d runner<=%x\n",count, runnerm1); end end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; // verilator lint_off COMBDLY // verilator lint_off UNOPT // verilator lint_off UNOPTFLAT reg c1_start; initial c1_start = 0; wire [31:0] c1_count; comb_loop c1 (.count(c1_count), .start(c1_start)); wire s2_start = (c1_count==0 && c1_start); wire [31:0] s2_count; seq_loop s2 (.count(s2_count), .start(s2_start)); wire c3_start = (s2_count[0]); wire [31:0] c3_count; comb_loop c3 (.count(c3_count), .start(c3_start)); reg [7:0] cyc; initial cyc=0; always @ (posedge clk) begin //$write("[%0t] %x counts %x %x %x\n",$time,cyc,c1_count,s2_count,c3_count); cyc <= cyc + 8'd1; case (cyc) 8'd00: begin c1_start <= 1'b0; end 8'd01: begin c1_start <= 1'b1; end default: ; endcase case (cyc) 8'd02: begin if (c1_count!=32'h3) $stop; if (s2_count!=32'h3) $stop; if (c3_count!=32'h6) $stop; end 8'd03: begin $write("*-* All Finished *-*\n"); $finish; end default: ; endcase end endmodule module comb_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner = 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner = runnerm1; $write ("%m count=%d runner =%x\n",count, runnerm1); end end endmodule module seq_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner <= 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner <= runnerm1; $write ("%m count=%d runner<=%x\n",count, runnerm1); end end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; // verilator lint_off COMBDLY // verilator lint_off UNOPT // verilator lint_off UNOPTFLAT reg c1_start; initial c1_start = 0; wire [31:0] c1_count; comb_loop c1 (.count(c1_count), .start(c1_start)); wire s2_start = (c1_count==0 && c1_start); wire [31:0] s2_count; seq_loop s2 (.count(s2_count), .start(s2_start)); wire c3_start = (s2_count[0]); wire [31:0] c3_count; comb_loop c3 (.count(c3_count), .start(c3_start)); reg [7:0] cyc; initial cyc=0; always @ (posedge clk) begin //$write("[%0t] %x counts %x %x %x\n",$time,cyc,c1_count,s2_count,c3_count); cyc <= cyc + 8'd1; case (cyc) 8'd00: begin c1_start <= 1'b0; end 8'd01: begin c1_start <= 1'b1; end default: ; endcase case (cyc) 8'd02: begin if (c1_count!=32'h3) $stop; if (s2_count!=32'h3) $stop; if (c3_count!=32'h6) $stop; end 8'd03: begin $write("*-* All Finished *-*\n"); $finish; end default: ; endcase end endmodule module comb_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner = 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner = runnerm1; $write ("%m count=%d runner =%x\n",count, runnerm1); end end endmodule module seq_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner <= 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner <= runnerm1; $write ("%m count=%d runner<=%x\n",count, runnerm1); end end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; // verilator lint_off COMBDLY // verilator lint_off UNOPT // verilator lint_off UNOPTFLAT reg c1_start; initial c1_start = 0; wire [31:0] c1_count; comb_loop c1 (.count(c1_count), .start(c1_start)); wire s2_start = (c1_count==0 && c1_start); wire [31:0] s2_count; seq_loop s2 (.count(s2_count), .start(s2_start)); wire c3_start = (s2_count[0]); wire [31:0] c3_count; comb_loop c3 (.count(c3_count), .start(c3_start)); reg [7:0] cyc; initial cyc=0; always @ (posedge clk) begin //$write("[%0t] %x counts %x %x %x\n",$time,cyc,c1_count,s2_count,c3_count); cyc <= cyc + 8'd1; case (cyc) 8'd00: begin c1_start <= 1'b0; end 8'd01: begin c1_start <= 1'b1; end default: ; endcase case (cyc) 8'd02: begin if (c1_count!=32'h3) $stop; if (s2_count!=32'h3) $stop; if (c3_count!=32'h6) $stop; end 8'd03: begin $write("*-* All Finished *-*\n"); $finish; end default: ; endcase end endmodule module comb_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner = 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner = runnerm1; $write ("%m count=%d runner =%x\n",count, runnerm1); end end endmodule module seq_loop (/*AUTOARG*/ // Outputs count, // Inputs start ); input start; output reg [31:0] count; initial count = 0; reg [31:0] runnerm1, runner; initial runner = 0; always @ (start) begin if (start) begin runner <= 3; end end always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin count = count + 1; runner <= runnerm1; $write ("%m count=%d runner<=%x\n",count, runnerm1); end end endmodule
module serial_tx #( parameter CLK_PER_BIT = 50 )( input clk, input rst, output tx, input block, output busy, input [7:0] data, input new_data ); // clog2 is 'ceiling of log base 2' which gives you the number of bits needed to store a value parameter CTR_SIZE = $clog2(CLK_PER_BIT); localparam STATE_SIZE = 2; localparam IDLE = 2'd0, START_BIT = 2'd1, DATA = 2'd2, STOP_BIT = 2'd3; reg [CTR_SIZE-1:0] ctr_d, ctr_q; reg [2:0] bit_ctr_d, bit_ctr_q; reg [7:0] data_d, data_q; reg [STATE_SIZE-1:0] state_d, state_q = IDLE; reg tx_d, tx_q; reg busy_d, busy_q; reg block_d, block_q; assign tx = tx_q; assign busy = busy_q; always @(*) begin block_d = block; ctr_d = ctr_q; bit_ctr_d = bit_ctr_q; data_d = data_q; state_d = state_q; busy_d = busy_q; case (state_q) IDLE: begin if (block_q) begin busy_d = 1'b1; tx_d = 1'b1; end else begin busy_d = 1'b0; tx_d = 1'b1; bit_ctr_d = 3'b0; ctr_d = 1'b0; if (new_data) begin data_d = data; state_d = START_BIT; busy_d = 1'b1; end end end START_BIT: begin busy_d = 1'b1; ctr_d = ctr_q + 1'b1; tx_d = 1'b0; if (ctr_q == CLK_PER_BIT - 1) begin ctr_d = 1'b0; state_d = DATA; end end DATA: begin busy_d = 1'b1; tx_d = data_q[bit_ctr_q]; ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin ctr_d = 1'b0; bit_ctr_d = bit_ctr_q + 1'b1; if (bit_ctr_q == 7) begin state_d = STOP_BIT; end end end STOP_BIT: begin busy_d = 1'b1; tx_d = 1'b1; ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin state_d = IDLE; end end default: begin state_d = IDLE; end endcase end always @(posedge clk) begin if (rst) begin state_q <= IDLE; tx_q <= 1'b1; end else begin state_q <= state_d; tx_q <= tx_d; end block_q <= block_d; data_q <= data_d; bit_ctr_q <= bit_ctr_d; ctr_q <= ctr_d; busy_q <= busy_d; end endmodule
module serial_tx #( parameter CLK_PER_BIT = 50 )( input clk, input rst, output tx, input block, output busy, input [7:0] data, input new_data ); // clog2 is 'ceiling of log base 2' which gives you the number of bits needed to store a value parameter CTR_SIZE = $clog2(CLK_PER_BIT); localparam STATE_SIZE = 2; localparam IDLE = 2'd0, START_BIT = 2'd1, DATA = 2'd2, STOP_BIT = 2'd3; reg [CTR_SIZE-1:0] ctr_d, ctr_q; reg [2:0] bit_ctr_d, bit_ctr_q; reg [7:0] data_d, data_q; reg [STATE_SIZE-1:0] state_d, state_q = IDLE; reg tx_d, tx_q; reg busy_d, busy_q; reg block_d, block_q; assign tx = tx_q; assign busy = busy_q; always @(*) begin block_d = block; ctr_d = ctr_q; bit_ctr_d = bit_ctr_q; data_d = data_q; state_d = state_q; busy_d = busy_q; case (state_q) IDLE: begin if (block_q) begin busy_d = 1'b1; tx_d = 1'b1; end else begin busy_d = 1'b0; tx_d = 1'b1; bit_ctr_d = 3'b0; ctr_d = 1'b0; if (new_data) begin data_d = data; state_d = START_BIT; busy_d = 1'b1; end end end START_BIT: begin busy_d = 1'b1; ctr_d = ctr_q + 1'b1; tx_d = 1'b0; if (ctr_q == CLK_PER_BIT - 1) begin ctr_d = 1'b0; state_d = DATA; end end DATA: begin busy_d = 1'b1; tx_d = data_q[bit_ctr_q]; ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin ctr_d = 1'b0; bit_ctr_d = bit_ctr_q + 1'b1; if (bit_ctr_q == 7) begin state_d = STOP_BIT; end end end STOP_BIT: begin busy_d = 1'b1; tx_d = 1'b1; ctr_d = ctr_q + 1'b1; if (ctr_q == CLK_PER_BIT - 1) begin state_d = IDLE; end end default: begin state_d = IDLE; end endcase end always @(posedge clk) begin if (rst) begin state_q <= IDLE; tx_q <= 1'b1; end else begin state_q <= state_d; tx_q <= tx_d; end block_q <= block_d; data_q <= data_d; bit_ctr_q <= bit_ctr_d; ctr_q <= ctr_d; busy_q <= busy_d; end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=1; // verilator lint_off UNOPT // verilator lint_off UNOPTFLAT reg [31:0] runner; initial runner = 5; reg [31:0] runnerm1; reg [59:0] runnerq; reg [89:0] runnerw; always @ (posedge clk) begin if (cyc!=0) begin cyc <= cyc + 1; if (cyc==1) begin `ifdef verilator if (runner != 0) $stop; // Initial settlement failed `endif end if (cyc==2) begin runner = 20; runnerq = 60'h0; runnerw = 90'h0; end if (cyc==3) begin if (runner != 0) $stop; $write("*-* All Finished *-*\n"); $finish; end end end // This forms a "loop" where we keep going through the always till runner=0 // This isn't "regular" beh code, but insures our change detection is working properly always @ (/*AS*/runner) begin runnerm1 = runner - 32'd1; end always @ (/*AS*/runnerm1) begin if (runner > 0) begin runner = runnerm1; runnerq = runnerq - 60'd1; runnerw = runnerw - 90'd1; $write ("[%0t] runner=%d\n", $time, runner); end end endmodule
//Legal Notice: (C)2016 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 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. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module niosii_pio_0 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, readdata ) ; output [ 7: 0] out_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; wire clk_en; reg [ 7: 0] data_out; wire [ 7: 0] out_port; wire [ 7: 0] read_mux_out; wire [ 31: 0] readdata; assign clk_en = 1; //s1, which is an e_avalon_slave assign read_mux_out = {8 {(address == 0)}} & data_out; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) data_out <= 0; else if (chipselect && ~write_n && (address == 0)) data_out <= writedata[7 : 0]; end assign readdata = {32'b0 | read_mux_out}; assign out_port = data_out; endmodule
//Legal Notice: (C)2016 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 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. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module niosii_pio_0 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, readdata ) ; output [ 7: 0] out_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; wire clk_en; reg [ 7: 0] data_out; wire [ 7: 0] out_port; wire [ 7: 0] read_mux_out; wire [ 31: 0] readdata; assign clk_en = 1; //s1, which is an e_avalon_slave assign read_mux_out = {8 {(address == 0)}} & data_out; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) data_out <= 0; else if (chipselect && ~write_n && (address == 0)) data_out <= writedata[7 : 0]; end assign readdata = {32'b0 | read_mux_out}; assign out_port = data_out; endmodule
//Legal Notice: (C)2016 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 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. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module niosii_pio_0 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, readdata ) ; output [ 7: 0] out_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; wire clk_en; reg [ 7: 0] data_out; wire [ 7: 0] out_port; wire [ 7: 0] read_mux_out; wire [ 31: 0] readdata; assign clk_en = 1; //s1, which is an e_avalon_slave assign read_mux_out = {8 {(address == 0)}} & data_out; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) data_out <= 0; else if (chipselect && ~write_n && (address == 0)) data_out <= writedata[7 : 0]; end assign readdata = {32'b0 | read_mux_out}; assign out_port = data_out; endmodule
//Legal Notice: (C)2016 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 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. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module niosii_pio_0 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, readdata ) ; output [ 7: 0] out_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; wire clk_en; reg [ 7: 0] data_out; wire [ 7: 0] out_port; wire [ 7: 0] read_mux_out; wire [ 31: 0] readdata; assign clk_en = 1; //s1, which is an e_avalon_slave assign read_mux_out = {8 {(address == 0)}} & data_out; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) data_out <= 0; else if (chipselect && ~write_n && (address == 0)) data_out <= writedata[7 : 0]; end assign readdata = {32'b0 | read_mux_out}; assign out_port = data_out; endmodule
//Legal Notice: (C)2016 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 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. // synthesis translate_off `timescale 1ns / 1ps // synthesis translate_on // turn off superfluous verilog processor warnings // altera message_level Level1 // altera message_off 10034 10035 10036 10037 10230 10240 10030 module niosii_pio_0 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, readdata ) ; output [ 7: 0] out_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; wire clk_en; reg [ 7: 0] data_out; wire [ 7: 0] out_port; wire [ 7: 0] read_mux_out; wire [ 31: 0] readdata; assign clk_en = 1; //s1, which is an e_avalon_slave assign read_mux_out = {8 {(address == 0)}} & data_out; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) data_out <= 0; else if (chipselect && ~write_n && (address == 0)) data_out <= writedata[7 : 0]; end assign readdata = {32'b0 | read_mux_out}; assign out_port = data_out; endmodule
/* salsaengine.v * * Copyright (c) 2013 kramble * Parts copyright (c) 2011 [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // NB HALFRAM no longer applies, configure via parameters ADDRBITS, THREADS // Bracket this config option in SIM so we don't accidentally leave it set in a live build `ifdef SIM //`define ONETHREAD // Start one thread only (for SIMULATION less confusing and faster startup) `endif `timescale 1ns/1ps module salsaengine (hash_clk, reset, din, dout, shift, start, busy, result ); input hash_clk; input reset; // NB pbkdf_clk domain (need a long reset (at least THREADS+4) to initialize correctly, this is done in pbkdfengine (15 cycles) input shift; input start; // NB pbkdf_clk domain output busy; output reg result = 1'b0; parameter SBITS = 8; // Shift data path width input [SBITS-1:0] din; output [SBITS-1:0] dout; // Configure ADDRBITS to allocate RAM for core (automatically sets LOOKAHEAD_GAP) // NB do not use ADDRBITS > 13 for THREADS=8 since this corresponds to more than a full scratchpad // These settings are now overriden in ltcminer_icarus.v determined by LOCAL_MINERS ... // parameter ADDRBITS = 13; // 8MBit RAM allocated to core, full scratchpad (will not fit LX150) parameter ADDRBITS = 12; // 4MBit RAM allocated to core, half scratchpad // parameter ADDRBITS = 11; // 2MBit RAM allocated to core, quarter scratchpad // parameter ADDRBITS = 10; // 1MBit RAM allocated to core, eighth scratchpad // Do not change THREADS - this must match the salsa pipeline (code is untested for other values) parameter THREADS = 16; // NB Phase has THREADS+1 cycles function integer clog2; // Courtesy of razorfishsl, replaces $clog2() input integer value; begin value = value-1; for (clog2=0; value>0; clog2=clog2+1) value = value>>1; end endfunction parameter THREADS_BITS = clog2(THREADS); // Workaround for range-reversal error in inactive code when ADDRBITS=13 parameter ADDRBITSX = (ADDRBITS == 13) ? ADDRBITS-1 : ADDRBITS; reg [THREADS_BITS:0]phase = 0; reg [THREADS_BITS:0]phase_d = THREADS+1; reg reset_d=0, fsmreset=0, start_d=0, fsmstart=0; always @ (posedge hash_clk) // Phase control and sync begin phase <= (phase == THREADS) ? 0 : phase + 1; phase_d <= phase; reset_d <= reset; // Synchronise to hash_clk domain fsmreset <= reset_d; start_d <= start; fsmstart <= start_d; end // Salsa Mix FSM (handles both loading of the scratchpad ROM and the subsequent processing) parameter XSnull = 0, XSload = 1, XSmix = 2, XSram = 4; // One-hot since these map directly to mux contrls reg [2:0] XCtl = XSnull; parameter R_IDLE=0, R_START=1, R_WRITE=2, R_MIX=3, R_INT=4, R_WAIT=5; reg [2:0] mstate = R_IDLE; reg [10:0] cycle = 11'd0; reg doneROM = 1'd0; // Yes ROM, as its referred thus in the salsa docs reg addrsourceMix = 1'b0; reg datasourceLoad = 1'b0; reg addrsourceSave = 1'b0; reg resultsourceRam = 1'b0; reg xoren = 1'b1; reg [THREADS_BITS+1:0] intcycles = 0; // Number of interpolation cycles required ... How many do we need? Say THREADS_BITS+1 wire [511:0] Xmix; reg [511:0] X0; reg [511:0] X1; wire [511:0] X0in; wire [511:0] X1in; wire [511:0] X0out; reg [1023:0] salsaShiftReg; reg [31:0] nonce_sr; // In series with salsaShiftReg assign dout = salsaShiftReg[1023:1024-SBITS]; // sstate is implemented in ram (alternatively could use a rotating shift register) reg [THREADS_BITS+30:0] sstate [THREADS-1:0]; // NB initialized via a long reset (see pbkdfengine) // List components of sstate here for ease of maintenance ... wire [2:0] mstate_in; wire [10:0] cycle_in; wire [9:0] writeaddr_in; wire doneROM_in; wire addrsourceMix_in; wire addrsourceSave_in; wire [THREADS_BITS+1:0] intcycles_in; // How many do we need? Say THREADS_BITS+1 wire [9:0] writeaddr_next = writeaddr_in + 10'd1; reg [31:0] snonce [THREADS-1:0]; // Nonce store. Note bidirectional loading below, this will either implement // as registers or dual-port ram, so do NOT integrate with sstate. // NB no busy_in or result_in as these flag are NOT saved on a per-thread basis // Convert salsaShiftReg to little-endian word format to match scrypt.c as its easier to debug it // this way rather than recoding the SMix salsa to work with original buffer wire [1023:0] X; `define IDX(x) (((x)+1)*(32)-1):((x)*(32)) genvar i; generate for (i = 0; i < 32; i = i + 1) begin : Xrewire wire [31:0] tmp; assign tmp = salsaShiftReg[`IDX(i)]; assign X[`IDX(i)] = { tmp[7:0], tmp[15:8], tmp[23:16], tmp[31:24] }; end endgenerate // NB writeaddr is cycle counter in R_WRITE so use full size regardless of RAM size (* S = "TRUE" *) reg [9:0] writeaddr = 10'd0; // ALTRAM Max is 256 bit width, so use four // Ram is registered on inputs vis ram_addr, ram_din and ram_wren // Output is unregistered, OLD data on write (less delay than NEW??) wire [9:0] Xaddr; wire [ADDRBITS-1:0]rd_addr; wire [ADDRBITS-1:0]wr_addr1; wire [ADDRBITS-1:0]wr_addr2; wire [ADDRBITS-1:0]wr_addr3; wire [ADDRBITS-1:0]wr_addr4; wire [255:0]ram1_din; wire [255:0]ram1_dout; wire [255:0]ram2_din; wire [255:0]ram2_dout; wire [255:0]ram3_din; wire [255:0]ram3_dout; wire [255:0]ram4_din; wire [255:0]ram4_dout; wire [1023:0]ramout; (* S = "TRUE" *) reg ram_wren = 1'b0; wire ram_clk; assign ram_clk = hash_clk; // Uses same clock as hasher for now // Top ram address is reserved for X0Save/X1save, so adjust wire [15:0] memtop = 16'hfffe; // One less than the top memory location (per THREAD bank) wire [ADDRBITS-THREADS_BITS-1:0] adj_addr; if (ADDRBITS < 13) assign adj_addr = (Xaddr[9:THREADS_BITS+10-ADDRBITS] == memtop[9:THREADS_BITS+10-ADDRBITS]) ? memtop[ADDRBITS-THREADS_BITS-1:0] : Xaddr[9:THREADS_BITS+10-ADDRBITS]; else assign adj_addr = Xaddr; wire [THREADS_BITS-1:0] phase_addr; assign phase_addr = phase[THREADS_BITS-1:0]; // TODO can we remove the +1 and adjust the wr_addr to use the same prefix via phase_d? assign rd_addr = { phase_addr+1, addrsourceSave_in ? memtop[ADDRBITS-THREADS_BITS:1] : adj_addr }; // LSB are ignored wire [9:0] writeaddr_adj = addrsourceMix ? memtop[10:1] : writeaddr; assign wr_addr1 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr2 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr3 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr4 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; // Duplicate address to reduce fanout (its a ridiculous kludge, but seems to be the approved method) (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_1 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_2 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_3 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_4 = 0; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr1 = rd_addr | rd_addr_z_1; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr2 = rd_addr | rd_addr_z_2; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr3 = rd_addr | rd_addr_z_3; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr4 = rd_addr | rd_addr_z_4; ram # (.ADDRBITS(ADDRBITS)) ram1_blk (rd_addr1, wr_addr1, ram_clk, ram1_din, ram_wren, ram1_dout); ram # (.ADDRBITS(ADDRBITS)) ram2_blk (rd_addr2, wr_addr2, ram_clk, ram2_din, ram_wren, ram2_dout); ram # (.ADDRBITS(ADDRBITS)) ram3_blk (rd_addr3, wr_addr3, ram_clk, ram3_din, ram_wren, ram3_dout); ram # (.ADDRBITS(ADDRBITS)) ram4_blk (rd_addr4, wr_addr4, ram_clk, ram4_din, ram_wren, ram4_dout); assign ramout = { ram4_dout, ram3_dout, ram2_dout, ram1_dout }; // Unregistered output assign { ram4_din, ram3_din, ram2_din, ram1_din } = datasourceLoad ? X : { Xmix, X0out}; // Registered input // Salsa unit salsa salsa_blk (hash_clk, X0, X1, Xmix, X0out, Xaddr); // Main multiplexer wire [511:0] Zbits; assign Zbits = {512{xoren}}; // xoren enables xor from ram (else we load from ram) // With luck the synthesizer will interpret this correctly as one-hot control ... // DEBUG using default state of 0 for XSnull so as to show up issues with preserved values (previously held value X0/X1) // assign X0in = (XCtl==XSmix) ? X0out : (XCtl==XSram) ? (X0out & Zbits) ^ ramout[511:0] : (XCtl==XSload) ? X[511:0] : 0; // assign X1in = (XCtl==XSmix) ? Xmix : (XCtl==XSram) ? (Xmix & Zbits) ^ ramout[1023:512] : (XCtl==XSload) ? X[1023:512] : 0; // Now using explicit control signals (rather than relying on synthesizer to map correctly) // XSMix is now the default (XSnull is unused as this mapped onto zero in the DEBUG version above) - TODO amend FSM accordingly assign X0in = XCtl[2] ? (X0out & Zbits) ^ ramout[511:0] : XCtl[0] ? X[511:0] : X0out; assign X1in = XCtl[2] ? (Xmix & Zbits) ^ ramout[1023:512] : XCtl[0] ? X[1023:512] : Xmix; // Salsa FSM - TODO may want to move this into a separate function (for floorplanning), see hashvariant-C // Hold separate state for each thread (a bit of a kludge to avoid rewriting FSM from scratch) // NB must ensure shift and result do NOT overlap by carefully controlling timing of start signal // NB Phase has THREADS+1 cycles, but we do not save the state for (phase==THREADS) as it is never active assign { mstate_in, writeaddr_in, cycle_in, doneROM_in, addrsourceMix_in, addrsourceSave_in, intcycles_in} = (phase == THREADS ) ? 0 : sstate[phase]; // Interface FSM ensures threads start evenly (required for correct salsa FSM operation) reg busy_flag = 1'b0; `ifdef ONETHREAD // TEST CONTROLLER ... just allow a single thread to run (busy is currently a common flag) // NB the thread automatically restarts after it completes, so its a slight misnomer to say it starts once. reg start_once = 1'b0; wire start_flag; assign start_flag = fsmstart & ~start_once; assign busy = busy_flag; // Ack to pbkdfengine `else // NB start_flag only has effect when a thread is at R_IDLE, ie after reset, normally a thread will automatically // restart on completion. We need to spread the R_IDLE starts evenly to ensure proper ooperation. NB the pbkdf // engine requires busy and result, but this looks alter itself in the salsa FSM, even though these are global // flags. Reset periodically (on loadnonce in pbkdfengine) to ensure it stays in sync. reg [15:0] start_count = 0; // TODO automatic configuration (currently assumes THREADS 8 or 16, and ADDRBITS 12,11,10 calculated as follows...) // For THREADS=8, lookup_gap=2 salsa takes on average 9*(1024+(1024*1.5)) = 23040 clocks, generically 9*1024*(lookup_gap/2+1.5) // For THREADS=16, use 17*1024*(lookup_gap/2+1.5), where lookupgap is double that for THREADS=8 parameter START_INTERVAL = (THREADS==16) ? ((ADDRBITS==12) ? 60928 : (ADDRBITS==11) ? 95744 : 165376) / THREADS : // 16 threads ((ADDRBITS==12) ? 23040 : (ADDRBITS==11) ? 36864 : 50688) / THREADS ; // 8 threads reg start_flag = 1'b0; assign busy = busy_flag; // Ack to pbkdfengine - this will toggle on transtion through R_START `endif always @ (posedge hash_clk) begin X0 <= X0in; X1 <= X1in; if (phase_d != THREADS) sstate[phase_d] <= fsmreset ? 0 : { mstate, writeaddr, cycle, doneROM, addrsourceMix, addrsourceSave, intcycles }; mstate <= mstate_in; // Set defaults (overridden below as necessary) writeaddr <= writeaddr_in; cycle <= cycle_in; intcycles <= intcycles_in; doneROM <= doneROM_in; addrsourceMix <= addrsourceMix_in; addrsourceSave <= addrsourceSave_in; // Overwritten below, but addrsourceSave_in is used above // Duplicate address to reduce fanout (its a ridiculous kludge, but seems to be the approved method) rd_addr_z_1 <= {ADDRBITS{fsmreset}}; rd_addr_z_2 <= {ADDRBITS{fsmreset}}; rd_addr_z_3 <= {ADDRBITS{fsmreset}}; rd_addr_z_4 <= {ADDRBITS{fsmreset}}; XCtl <= XSnull; // Default states addrsourceSave <= 0; // NB addrsourceSave_in is the active control so this DOES need to be in sstate datasourceLoad <= 0; // Does not need to be saved in sstate resultsourceRam <= 0; // Does not need to be saved in sstate ram_wren <= 0; xoren <= 1; // Interface FSM ensures threads start evenly (required for correct salsa FSM operation) `ifdef ONETHREAD if (fsmstart && phase!=THREADS) start_once <= 1'b1; if (fsmreset) start_once <= 1'b0; `else start_count <= start_count + 1; // start_flag <= 1'b0; // Done below when we transition out of R_IDLE if (fsmreset || start_count == START_INTERVAL) begin start_count <= 0; if (~fsmreset && fsmstart) start_flag <= 1'b1; end `endif // Could use explicit mux for this ... if (shift) begin salsaShiftReg <= { salsaShiftReg[1023-SBITS:0], nonce_sr[31:32-SBITS] }; nonce_sr <= { nonce_sr[31-SBITS:0], din}; end else if (XCtl==XSload && phase_d != THREADS) // Set at end of previous hash - this is executed regardless of phase begin salsaShiftReg <= resultsourceRam ? ramout : { Xmix, X0out }; // Simultaneously with XSload nonce_sr <= snonce[phase_d]; // NB bidirectional load snonce[phase_d] <= nonce_sr; end if (fsmreset == 1'b1) begin mstate <= R_IDLE; // This will propagate to all sstate slots as we hold reset for 10 cycles busy_flag <= 1'b0; result <= 1'b0; end else begin case (mstate_in) R_IDLE: begin // R_IDLE only applies after reset. Normally each thread will reenter at S_START and // assumes that input data is waiting (this relies on the threads being started evenly, // hence the interface FSM at the top of this file) if (phase!=THREADS && start_flag) // Ensure (phase==THREADS) slot is never active begin XCtl <= XSload; // First time only (normally done at end of previous salsa cycle=1023) `ifndef ONETHREAD start_flag <= 1'b0; `endif busy_flag <= 1'b0; // Toggle the busy flag low to ack pbkdfengine (its usually already set // since other threads are running) writeaddr <= 0; // Preset to write X on next cycle addrsourceMix <= 1'b0; datasourceLoad <= 1'b1; ram_wren <= 1'b1; mstate <= R_START; end end R_START: begin // Reentry point after thread completion. ASSUMES new data is ready. XCtl <= XSmix; writeaddr <= writeaddr_next; cycle <= 0; if (ADDRBITS == 13) ram_wren <= 1'b1; // Full scratchpad needs to write to addr=001 next cycle doneROM <= 1'b0; busy_flag <= 1'b1; result <= 1'b0; mstate <= R_WRITE; end R_WRITE: begin XCtl <= XSmix; writeaddr <= writeaddr_next; if (writeaddr_in==1022) doneROM <= 1'b1; // Need to do one more cycle to update X0,X1 else if (~doneROM_in) begin if (ADDRBITS < 13) ram_wren <= ~|writeaddr_next[THREADS_BITS+9-ADDRBITSX:0]; // Only write non-interpolated addresses else ram_wren <= 1'b1; end if (doneROM_in) begin addrsourceMix <= 1'b1; // Remains set for duration of R_MIX mstate <= R_MIX; XCtl <= XSram; // Load from ram next cycle // Need this to cover the case of the initial read being interpolated // NB CODE IS REPLICATED IN R_MIX if (ADDRBITS < 13) begin intcycles <= { {THREADS_BITS+12-ADDRBITSX{1'b0}}, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; // Interpolated addresses if ( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) // Highest address reserved intcycles <= { {THREADS_BITS+11-ADDRBITSX{1'b0}}, 1'b1, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; if ( (Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1]) || |Xaddr[THREADS_BITS+9-ADDRBITSX:0] ) begin ram_wren <= 1'b1; xoren <= 0; // Will do direct load from ram, not xor mstate <= R_INT; // Interpolate end // If intcycles will be set to 1, need to preset for readback if ( ( Xaddr[THREADS_BITS+9-ADDRBITSX:0] == 1 ) && !( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) ) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end // END REPLICATED BLOCK end end R_MIX: begin // NB There is an extra step here cf R_WRITE above to read ram data hence 9 not 8 stages. XCtl <= XSmix; cycle <= cycle_in + 11'd1; if (cycle_in==1023) begin busy_flag <= 1'b0; // Will hold at 0 for 9 clocks until set at R_START if (fsmstart) // Check data input is ready begin XCtl <= XSload; // Initial load else we overwrite input NB This is // executed on the next cycle, regardless of phase // Flag the SHA256 FSM to start final PBKDF2_SHA256_80_128_32 result <= 1'b1; mstate <= R_START; // Restart immediately writeaddr <= 0; // Preset to write X on next cycle datasourceLoad <= 1'b1; addrsourceMix <= 1'b0; ram_wren <= 1'b1; end else begin // mstate <= R_IDLE; // Wait for start_flag mstate <= R_WAIT; addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) ram_wren <= 1'b1; // Save result end end else begin XCtl <= XSram; // Load from ram next cycle // NB CODE IS REPLICATED IN R_WRITE if (ADDRBITS < 13) begin intcycles <= { {THREADS_BITS+12-ADDRBITSX{1'b0}}, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; // Interpolated addresses if ( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) // Highest address reserved intcycles <= { {THREADS_BITS+11-ADDRBITSX{1'b0}}, 1'b1, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; if ( (Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1]) || |Xaddr[THREADS_BITS+9-ADDRBITSX:0] ) begin ram_wren <= 1'b1; xoren <= 0; // Will do direct load from ram, not xor mstate <= R_INT; // Interpolate end // If intcycles will be set to 1, need to preset for readback if ( ( Xaddr[THREADS_BITS+9-ADDRBITSX:0] == 1 ) && !( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) ) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end // END REPLICATED BLOCK end end R_WAIT: begin if (fsmstart) // Check data input is ready begin XCtl <= XSload; // Initial load else we overwrite input NB This is // executed on the next cycle, regardless of phase // Flag the SHA256 FSM to start final PBKDF2_SHA256_80_128_32 result <= 1'b1; mstate <= R_START; // Restart immediately writeaddr <= 0; // Preset to write X on next cycle datasourceLoad <= 1'b1; resultsourceRam <= 1'b1; addrsourceMix <= 1'b0; ram_wren <= 1'b1; end else addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end R_INT: begin // Interpolate scratchpad for odd addresses XCtl <= XSmix; intcycles <= intcycles_in - 1; if (intcycles_in==2) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) if (intcycles_in==1) begin XCtl <= XSram; // Setup to XOR from saved X0/X1 in ram at next cycle mstate <= R_MIX; end // Else mstate remains at R_INT so we continue interpolating end endcase end `ifdef SIM // Print the final Xmix for each cycle to compare with scrypt.c (debugging) if (mstate==R_MIX) $display ("phase %d cycle %d Xmix %08x\n", phase, cycle-1, Xmix[511:480]); `endif end // always @(posedge hash_clk) endmodule
/* salsaengine.v * * Copyright (c) 2013 kramble * Parts copyright (c) 2011 [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // NB HALFRAM no longer applies, configure via parameters ADDRBITS, THREADS // Bracket this config option in SIM so we don't accidentally leave it set in a live build `ifdef SIM //`define ONETHREAD // Start one thread only (for SIMULATION less confusing and faster startup) `endif `timescale 1ns/1ps module salsaengine (hash_clk, reset, din, dout, shift, start, busy, result ); input hash_clk; input reset; // NB pbkdf_clk domain (need a long reset (at least THREADS+4) to initialize correctly, this is done in pbkdfengine (15 cycles) input shift; input start; // NB pbkdf_clk domain output busy; output reg result = 1'b0; parameter SBITS = 8; // Shift data path width input [SBITS-1:0] din; output [SBITS-1:0] dout; // Configure ADDRBITS to allocate RAM for core (automatically sets LOOKAHEAD_GAP) // NB do not use ADDRBITS > 13 for THREADS=8 since this corresponds to more than a full scratchpad // These settings are now overriden in ltcminer_icarus.v determined by LOCAL_MINERS ... // parameter ADDRBITS = 13; // 8MBit RAM allocated to core, full scratchpad (will not fit LX150) parameter ADDRBITS = 12; // 4MBit RAM allocated to core, half scratchpad // parameter ADDRBITS = 11; // 2MBit RAM allocated to core, quarter scratchpad // parameter ADDRBITS = 10; // 1MBit RAM allocated to core, eighth scratchpad // Do not change THREADS - this must match the salsa pipeline (code is untested for other values) parameter THREADS = 16; // NB Phase has THREADS+1 cycles function integer clog2; // Courtesy of razorfishsl, replaces $clog2() input integer value; begin value = value-1; for (clog2=0; value>0; clog2=clog2+1) value = value>>1; end endfunction parameter THREADS_BITS = clog2(THREADS); // Workaround for range-reversal error in inactive code when ADDRBITS=13 parameter ADDRBITSX = (ADDRBITS == 13) ? ADDRBITS-1 : ADDRBITS; reg [THREADS_BITS:0]phase = 0; reg [THREADS_BITS:0]phase_d = THREADS+1; reg reset_d=0, fsmreset=0, start_d=0, fsmstart=0; always @ (posedge hash_clk) // Phase control and sync begin phase <= (phase == THREADS) ? 0 : phase + 1; phase_d <= phase; reset_d <= reset; // Synchronise to hash_clk domain fsmreset <= reset_d; start_d <= start; fsmstart <= start_d; end // Salsa Mix FSM (handles both loading of the scratchpad ROM and the subsequent processing) parameter XSnull = 0, XSload = 1, XSmix = 2, XSram = 4; // One-hot since these map directly to mux contrls reg [2:0] XCtl = XSnull; parameter R_IDLE=0, R_START=1, R_WRITE=2, R_MIX=3, R_INT=4, R_WAIT=5; reg [2:0] mstate = R_IDLE; reg [10:0] cycle = 11'd0; reg doneROM = 1'd0; // Yes ROM, as its referred thus in the salsa docs reg addrsourceMix = 1'b0; reg datasourceLoad = 1'b0; reg addrsourceSave = 1'b0; reg resultsourceRam = 1'b0; reg xoren = 1'b1; reg [THREADS_BITS+1:0] intcycles = 0; // Number of interpolation cycles required ... How many do we need? Say THREADS_BITS+1 wire [511:0] Xmix; reg [511:0] X0; reg [511:0] X1; wire [511:0] X0in; wire [511:0] X1in; wire [511:0] X0out; reg [1023:0] salsaShiftReg; reg [31:0] nonce_sr; // In series with salsaShiftReg assign dout = salsaShiftReg[1023:1024-SBITS]; // sstate is implemented in ram (alternatively could use a rotating shift register) reg [THREADS_BITS+30:0] sstate [THREADS-1:0]; // NB initialized via a long reset (see pbkdfengine) // List components of sstate here for ease of maintenance ... wire [2:0] mstate_in; wire [10:0] cycle_in; wire [9:0] writeaddr_in; wire doneROM_in; wire addrsourceMix_in; wire addrsourceSave_in; wire [THREADS_BITS+1:0] intcycles_in; // How many do we need? Say THREADS_BITS+1 wire [9:0] writeaddr_next = writeaddr_in + 10'd1; reg [31:0] snonce [THREADS-1:0]; // Nonce store. Note bidirectional loading below, this will either implement // as registers or dual-port ram, so do NOT integrate with sstate. // NB no busy_in or result_in as these flag are NOT saved on a per-thread basis // Convert salsaShiftReg to little-endian word format to match scrypt.c as its easier to debug it // this way rather than recoding the SMix salsa to work with original buffer wire [1023:0] X; `define IDX(x) (((x)+1)*(32)-1):((x)*(32)) genvar i; generate for (i = 0; i < 32; i = i + 1) begin : Xrewire wire [31:0] tmp; assign tmp = salsaShiftReg[`IDX(i)]; assign X[`IDX(i)] = { tmp[7:0], tmp[15:8], tmp[23:16], tmp[31:24] }; end endgenerate // NB writeaddr is cycle counter in R_WRITE so use full size regardless of RAM size (* S = "TRUE" *) reg [9:0] writeaddr = 10'd0; // ALTRAM Max is 256 bit width, so use four // Ram is registered on inputs vis ram_addr, ram_din and ram_wren // Output is unregistered, OLD data on write (less delay than NEW??) wire [9:0] Xaddr; wire [ADDRBITS-1:0]rd_addr; wire [ADDRBITS-1:0]wr_addr1; wire [ADDRBITS-1:0]wr_addr2; wire [ADDRBITS-1:0]wr_addr3; wire [ADDRBITS-1:0]wr_addr4; wire [255:0]ram1_din; wire [255:0]ram1_dout; wire [255:0]ram2_din; wire [255:0]ram2_dout; wire [255:0]ram3_din; wire [255:0]ram3_dout; wire [255:0]ram4_din; wire [255:0]ram4_dout; wire [1023:0]ramout; (* S = "TRUE" *) reg ram_wren = 1'b0; wire ram_clk; assign ram_clk = hash_clk; // Uses same clock as hasher for now // Top ram address is reserved for X0Save/X1save, so adjust wire [15:0] memtop = 16'hfffe; // One less than the top memory location (per THREAD bank) wire [ADDRBITS-THREADS_BITS-1:0] adj_addr; if (ADDRBITS < 13) assign adj_addr = (Xaddr[9:THREADS_BITS+10-ADDRBITS] == memtop[9:THREADS_BITS+10-ADDRBITS]) ? memtop[ADDRBITS-THREADS_BITS-1:0] : Xaddr[9:THREADS_BITS+10-ADDRBITS]; else assign adj_addr = Xaddr; wire [THREADS_BITS-1:0] phase_addr; assign phase_addr = phase[THREADS_BITS-1:0]; // TODO can we remove the +1 and adjust the wr_addr to use the same prefix via phase_d? assign rd_addr = { phase_addr+1, addrsourceSave_in ? memtop[ADDRBITS-THREADS_BITS:1] : adj_addr }; // LSB are ignored wire [9:0] writeaddr_adj = addrsourceMix ? memtop[10:1] : writeaddr; assign wr_addr1 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr2 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr3 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; assign wr_addr4 = { phase_addr, writeaddr_adj[9:THREADS_BITS+10-ADDRBITS] }; // Duplicate address to reduce fanout (its a ridiculous kludge, but seems to be the approved method) (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_1 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_2 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_3 = 0; (* S = "TRUE" *) reg [ADDRBITS-1:0] rd_addr_z_4 = 0; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr1 = rd_addr | rd_addr_z_1; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr2 = rd_addr | rd_addr_z_2; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr3 = rd_addr | rd_addr_z_3; (* S = "TRUE" *) wire [ADDRBITS-1:0] rd_addr4 = rd_addr | rd_addr_z_4; ram # (.ADDRBITS(ADDRBITS)) ram1_blk (rd_addr1, wr_addr1, ram_clk, ram1_din, ram_wren, ram1_dout); ram # (.ADDRBITS(ADDRBITS)) ram2_blk (rd_addr2, wr_addr2, ram_clk, ram2_din, ram_wren, ram2_dout); ram # (.ADDRBITS(ADDRBITS)) ram3_blk (rd_addr3, wr_addr3, ram_clk, ram3_din, ram_wren, ram3_dout); ram # (.ADDRBITS(ADDRBITS)) ram4_blk (rd_addr4, wr_addr4, ram_clk, ram4_din, ram_wren, ram4_dout); assign ramout = { ram4_dout, ram3_dout, ram2_dout, ram1_dout }; // Unregistered output assign { ram4_din, ram3_din, ram2_din, ram1_din } = datasourceLoad ? X : { Xmix, X0out}; // Registered input // Salsa unit salsa salsa_blk (hash_clk, X0, X1, Xmix, X0out, Xaddr); // Main multiplexer wire [511:0] Zbits; assign Zbits = {512{xoren}}; // xoren enables xor from ram (else we load from ram) // With luck the synthesizer will interpret this correctly as one-hot control ... // DEBUG using default state of 0 for XSnull so as to show up issues with preserved values (previously held value X0/X1) // assign X0in = (XCtl==XSmix) ? X0out : (XCtl==XSram) ? (X0out & Zbits) ^ ramout[511:0] : (XCtl==XSload) ? X[511:0] : 0; // assign X1in = (XCtl==XSmix) ? Xmix : (XCtl==XSram) ? (Xmix & Zbits) ^ ramout[1023:512] : (XCtl==XSload) ? X[1023:512] : 0; // Now using explicit control signals (rather than relying on synthesizer to map correctly) // XSMix is now the default (XSnull is unused as this mapped onto zero in the DEBUG version above) - TODO amend FSM accordingly assign X0in = XCtl[2] ? (X0out & Zbits) ^ ramout[511:0] : XCtl[0] ? X[511:0] : X0out; assign X1in = XCtl[2] ? (Xmix & Zbits) ^ ramout[1023:512] : XCtl[0] ? X[1023:512] : Xmix; // Salsa FSM - TODO may want to move this into a separate function (for floorplanning), see hashvariant-C // Hold separate state for each thread (a bit of a kludge to avoid rewriting FSM from scratch) // NB must ensure shift and result do NOT overlap by carefully controlling timing of start signal // NB Phase has THREADS+1 cycles, but we do not save the state for (phase==THREADS) as it is never active assign { mstate_in, writeaddr_in, cycle_in, doneROM_in, addrsourceMix_in, addrsourceSave_in, intcycles_in} = (phase == THREADS ) ? 0 : sstate[phase]; // Interface FSM ensures threads start evenly (required for correct salsa FSM operation) reg busy_flag = 1'b0; `ifdef ONETHREAD // TEST CONTROLLER ... just allow a single thread to run (busy is currently a common flag) // NB the thread automatically restarts after it completes, so its a slight misnomer to say it starts once. reg start_once = 1'b0; wire start_flag; assign start_flag = fsmstart & ~start_once; assign busy = busy_flag; // Ack to pbkdfengine `else // NB start_flag only has effect when a thread is at R_IDLE, ie after reset, normally a thread will automatically // restart on completion. We need to spread the R_IDLE starts evenly to ensure proper ooperation. NB the pbkdf // engine requires busy and result, but this looks alter itself in the salsa FSM, even though these are global // flags. Reset periodically (on loadnonce in pbkdfengine) to ensure it stays in sync. reg [15:0] start_count = 0; // TODO automatic configuration (currently assumes THREADS 8 or 16, and ADDRBITS 12,11,10 calculated as follows...) // For THREADS=8, lookup_gap=2 salsa takes on average 9*(1024+(1024*1.5)) = 23040 clocks, generically 9*1024*(lookup_gap/2+1.5) // For THREADS=16, use 17*1024*(lookup_gap/2+1.5), where lookupgap is double that for THREADS=8 parameter START_INTERVAL = (THREADS==16) ? ((ADDRBITS==12) ? 60928 : (ADDRBITS==11) ? 95744 : 165376) / THREADS : // 16 threads ((ADDRBITS==12) ? 23040 : (ADDRBITS==11) ? 36864 : 50688) / THREADS ; // 8 threads reg start_flag = 1'b0; assign busy = busy_flag; // Ack to pbkdfengine - this will toggle on transtion through R_START `endif always @ (posedge hash_clk) begin X0 <= X0in; X1 <= X1in; if (phase_d != THREADS) sstate[phase_d] <= fsmreset ? 0 : { mstate, writeaddr, cycle, doneROM, addrsourceMix, addrsourceSave, intcycles }; mstate <= mstate_in; // Set defaults (overridden below as necessary) writeaddr <= writeaddr_in; cycle <= cycle_in; intcycles <= intcycles_in; doneROM <= doneROM_in; addrsourceMix <= addrsourceMix_in; addrsourceSave <= addrsourceSave_in; // Overwritten below, but addrsourceSave_in is used above // Duplicate address to reduce fanout (its a ridiculous kludge, but seems to be the approved method) rd_addr_z_1 <= {ADDRBITS{fsmreset}}; rd_addr_z_2 <= {ADDRBITS{fsmreset}}; rd_addr_z_3 <= {ADDRBITS{fsmreset}}; rd_addr_z_4 <= {ADDRBITS{fsmreset}}; XCtl <= XSnull; // Default states addrsourceSave <= 0; // NB addrsourceSave_in is the active control so this DOES need to be in sstate datasourceLoad <= 0; // Does not need to be saved in sstate resultsourceRam <= 0; // Does not need to be saved in sstate ram_wren <= 0; xoren <= 1; // Interface FSM ensures threads start evenly (required for correct salsa FSM operation) `ifdef ONETHREAD if (fsmstart && phase!=THREADS) start_once <= 1'b1; if (fsmreset) start_once <= 1'b0; `else start_count <= start_count + 1; // start_flag <= 1'b0; // Done below when we transition out of R_IDLE if (fsmreset || start_count == START_INTERVAL) begin start_count <= 0; if (~fsmreset && fsmstart) start_flag <= 1'b1; end `endif // Could use explicit mux for this ... if (shift) begin salsaShiftReg <= { salsaShiftReg[1023-SBITS:0], nonce_sr[31:32-SBITS] }; nonce_sr <= { nonce_sr[31-SBITS:0], din}; end else if (XCtl==XSload && phase_d != THREADS) // Set at end of previous hash - this is executed regardless of phase begin salsaShiftReg <= resultsourceRam ? ramout : { Xmix, X0out }; // Simultaneously with XSload nonce_sr <= snonce[phase_d]; // NB bidirectional load snonce[phase_d] <= nonce_sr; end if (fsmreset == 1'b1) begin mstate <= R_IDLE; // This will propagate to all sstate slots as we hold reset for 10 cycles busy_flag <= 1'b0; result <= 1'b0; end else begin case (mstate_in) R_IDLE: begin // R_IDLE only applies after reset. Normally each thread will reenter at S_START and // assumes that input data is waiting (this relies on the threads being started evenly, // hence the interface FSM at the top of this file) if (phase!=THREADS && start_flag) // Ensure (phase==THREADS) slot is never active begin XCtl <= XSload; // First time only (normally done at end of previous salsa cycle=1023) `ifndef ONETHREAD start_flag <= 1'b0; `endif busy_flag <= 1'b0; // Toggle the busy flag low to ack pbkdfengine (its usually already set // since other threads are running) writeaddr <= 0; // Preset to write X on next cycle addrsourceMix <= 1'b0; datasourceLoad <= 1'b1; ram_wren <= 1'b1; mstate <= R_START; end end R_START: begin // Reentry point after thread completion. ASSUMES new data is ready. XCtl <= XSmix; writeaddr <= writeaddr_next; cycle <= 0; if (ADDRBITS == 13) ram_wren <= 1'b1; // Full scratchpad needs to write to addr=001 next cycle doneROM <= 1'b0; busy_flag <= 1'b1; result <= 1'b0; mstate <= R_WRITE; end R_WRITE: begin XCtl <= XSmix; writeaddr <= writeaddr_next; if (writeaddr_in==1022) doneROM <= 1'b1; // Need to do one more cycle to update X0,X1 else if (~doneROM_in) begin if (ADDRBITS < 13) ram_wren <= ~|writeaddr_next[THREADS_BITS+9-ADDRBITSX:0]; // Only write non-interpolated addresses else ram_wren <= 1'b1; end if (doneROM_in) begin addrsourceMix <= 1'b1; // Remains set for duration of R_MIX mstate <= R_MIX; XCtl <= XSram; // Load from ram next cycle // Need this to cover the case of the initial read being interpolated // NB CODE IS REPLICATED IN R_MIX if (ADDRBITS < 13) begin intcycles <= { {THREADS_BITS+12-ADDRBITSX{1'b0}}, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; // Interpolated addresses if ( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) // Highest address reserved intcycles <= { {THREADS_BITS+11-ADDRBITSX{1'b0}}, 1'b1, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; if ( (Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1]) || |Xaddr[THREADS_BITS+9-ADDRBITSX:0] ) begin ram_wren <= 1'b1; xoren <= 0; // Will do direct load from ram, not xor mstate <= R_INT; // Interpolate end // If intcycles will be set to 1, need to preset for readback if ( ( Xaddr[THREADS_BITS+9-ADDRBITSX:0] == 1 ) && !( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) ) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end // END REPLICATED BLOCK end end R_MIX: begin // NB There is an extra step here cf R_WRITE above to read ram data hence 9 not 8 stages. XCtl <= XSmix; cycle <= cycle_in + 11'd1; if (cycle_in==1023) begin busy_flag <= 1'b0; // Will hold at 0 for 9 clocks until set at R_START if (fsmstart) // Check data input is ready begin XCtl <= XSload; // Initial load else we overwrite input NB This is // executed on the next cycle, regardless of phase // Flag the SHA256 FSM to start final PBKDF2_SHA256_80_128_32 result <= 1'b1; mstate <= R_START; // Restart immediately writeaddr <= 0; // Preset to write X on next cycle datasourceLoad <= 1'b1; addrsourceMix <= 1'b0; ram_wren <= 1'b1; end else begin // mstate <= R_IDLE; // Wait for start_flag mstate <= R_WAIT; addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) ram_wren <= 1'b1; // Save result end end else begin XCtl <= XSram; // Load from ram next cycle // NB CODE IS REPLICATED IN R_WRITE if (ADDRBITS < 13) begin intcycles <= { {THREADS_BITS+12-ADDRBITSX{1'b0}}, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; // Interpolated addresses if ( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) // Highest address reserved intcycles <= { {THREADS_BITS+11-ADDRBITSX{1'b0}}, 1'b1, Xaddr[THREADS_BITS+9-ADDRBITSX:0] }; if ( (Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1]) || |Xaddr[THREADS_BITS+9-ADDRBITSX:0] ) begin ram_wren <= 1'b1; xoren <= 0; // Will do direct load from ram, not xor mstate <= R_INT; // Interpolate end // If intcycles will be set to 1, need to preset for readback if ( ( Xaddr[THREADS_BITS+9-ADDRBITSX:0] == 1 ) && !( Xaddr[9:THREADS_BITS+10-ADDRBITSX] == memtop[ADDRBITSX-THREADS_BITS:1] ) ) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end // END REPLICATED BLOCK end end R_WAIT: begin if (fsmstart) // Check data input is ready begin XCtl <= XSload; // Initial load else we overwrite input NB This is // executed on the next cycle, regardless of phase // Flag the SHA256 FSM to start final PBKDF2_SHA256_80_128_32 result <= 1'b1; mstate <= R_START; // Restart immediately writeaddr <= 0; // Preset to write X on next cycle datasourceLoad <= 1'b1; resultsourceRam <= 1'b1; addrsourceMix <= 1'b0; ram_wren <= 1'b1; end else addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) end R_INT: begin // Interpolate scratchpad for odd addresses XCtl <= XSmix; intcycles <= intcycles_in - 1; if (intcycles_in==2) addrsourceSave <= 1'b1; // Preset to read saved data (9 clocks later) if (intcycles_in==1) begin XCtl <= XSram; // Setup to XOR from saved X0/X1 in ram at next cycle mstate <= R_MIX; end // Else mstate remains at R_INT so we continue interpolating end endcase end `ifdef SIM // Print the final Xmix for each cycle to compare with scrypt.c (debugging) if (mstate==R_MIX) $display ("phase %d cycle %d Xmix %08x\n", phase, cycle-1, Xmix[511:480]); `endif end // always @(posedge hash_clk) endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2008 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc=0; reg [63:0] crc; reg [63:0] sum; // Take CRC data and apply to testblock inputs wire [1:0] in = crc[1:0]; /*AUTOWIRE*/ // Beginning of automatic wires (for undeclared instantiated-module outputs) wire [1:0] out; // From test of Test.v // End of automatics Test test (/*AUTOINST*/ // Outputs .out (out[1:0]), // Inputs .in (in[1:0])); // Aggregate outputs into a single result vector wire [63:0] result = {62'h0, out}; // What checksum will we end up with `define EXPECTED_SUM 64'hbb2d9709592f64bd // 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; 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; if (sum !== `EXPECTED_SUM) $stop; $write("*-* All Finished *-*\n"); $finish; end end endmodule module Test (/*AUTOARG*/ // Outputs out, // Inputs in ); input [1:0] in; output reg [1:0] out; always @* begin // bug99: Internal Error: ../V3Ast.cpp:495: New node already linked? case (in[1:0]) 2'd0, 2'd1, 2'd2, 2'd3: begin out = in; end endcase end endmodule
//Legal Notice: (C)2013 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 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 debounce ( clk, reset_n, data_in, data_out ); parameter WIDTH = 32; // set to be the width of the bus being debounced parameter POLARITY = "HIGH"; // set to be "HIGH" for active high debounce or "LOW" for active low debounce parameter TIMEOUT = 50000; // number of input clock cycles the input signal needs to be in the active state parameter TIMEOUT_WIDTH = 16; // set to be ceil(log2(TIMEOUT)) input wire clk; input wire reset_n; input wire [WIDTH-1:0] data_in; output wire [WIDTH-1:0] data_out; reg [TIMEOUT_WIDTH-1:0] counter [0:WIDTH-1]; wire counter_reset [0:WIDTH-1]; wire counter_enable [0:WIDTH-1]; // need one counter per input to debounce genvar i; generate for (i = 0; i < WIDTH; i = i+1) begin: debounce_counter_loop always @ (posedge clk or negedge reset_n) begin if (reset_n == 0) begin counter[i] <= 0; end else begin if (counter_reset[i] == 1) // resetting the counter needs to win begin counter[i] <= 0; end else if (counter_enable[i] == 1) begin counter[i] <= counter[i] + 1'b1; end end end if (POLARITY == "HIGH") begin assign counter_reset[i] = (data_in[i] == 0); assign counter_enable[i] = (data_in[i] == 1) & (counter[i] < TIMEOUT); assign data_out[i] = (counter[i] == TIMEOUT) ? 1'b1 : 1'b0; end else begin assign counter_reset[i] = (data_in[i] == 1); assign counter_enable[i] = (data_in[i] == 0) & (counter[i] < TIMEOUT); assign data_out[i] = (counter[i] == TIMEOUT) ? 1'b0 : 1'b1; end end endgenerate endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=1; reg [15:0] m_din; // OK reg [15:0] a_split_1, a_split_2; always @ (/*AS*/m_din) begin a_split_1 = m_din; a_split_2 = m_din; end // OK reg [15:0] b_split_1, b_split_2; always @ (/*AS*/m_din) begin b_split_1 = m_din; b_split_2 = b_split_1; end // Not OK reg [15:0] c_split_1, c_split_2; always @ (/*AS*/m_din) begin c_split_1 = m_din; c_split_2 = c_split_1; c_split_1 = ~m_din; end // OK reg [15:0] d_split_1, d_split_2; always @ (posedge clk) begin d_split_1 <= m_din; d_split_2 <= d_split_1; d_split_1 <= ~m_din; end // Not OK always @ (posedge clk) begin $write(" foo %x", m_din); $write(" bar %x\n", m_din); end // Not OK reg [15:0] e_split_1, e_split_2; always @ (posedge clk) begin e_split_1 = m_din; e_split_2 = e_split_1; end // Not OK reg [15:0] f_split_1, f_split_2; always @ (posedge clk) begin f_split_2 = f_split_1; f_split_1 = m_din; end // Not Ok reg [15:0] l_split_1, l_split_2; always @ (posedge clk) begin l_split_2 <= l_split_1; l_split_1 <= l_split_2 | m_din; end // OK reg [15:0] z_split_1, z_split_2; always @ (posedge clk) begin z_split_1 <= 0; z_split_1 <= ~m_din; end always @ (posedge clk) begin z_split_2 <= 0; z_split_2 <= z_split_1; end always @ (posedge clk) begin if (cyc!=0) begin cyc<=cyc+1; if (cyc==1) begin m_din <= 16'hfeed; end if (cyc==3) begin end if (cyc==4) begin m_din <= 16'he11e; //$write(" A %x %x\n", a_split_1, a_split_2); if (!(a_split_1==16'hfeed && a_split_2==16'hfeed)) $stop; if (!(b_split_1==16'hfeed && b_split_2==16'hfeed)) $stop; if (!(c_split_1==16'h0112 && c_split_2==16'hfeed)) $stop; if (!(d_split_1==16'h0112 && d_split_2==16'h0112)) $stop; if (!(e_split_1==16'hfeed && e_split_2==16'hfeed)) $stop; if (!(f_split_1==16'hfeed && f_split_2==16'hfeed)) $stop; if (!(z_split_1==16'h0112 && z_split_2==16'h0112)) $stop; end if (cyc==5) begin m_din <= 16'he22e; if (!(a_split_1==16'he11e && a_split_2==16'he11e)) $stop; if (!(b_split_1==16'he11e && b_split_2==16'he11e)) $stop; if (!(c_split_1==16'h1ee1 && c_split_2==16'he11e)) $stop; if (!(d_split_1==16'h0112 && d_split_2==16'h0112)) $stop; if (!(z_split_1==16'h0112 && z_split_2==16'h0112)) $stop; // Two valid orderings, as we don't know which posedge clk gets evaled first if (!(e_split_1==16'hfeed && e_split_2==16'hfeed) && !(e_split_1==16'he11e && e_split_2==16'he11e)) $stop; if (!(f_split_1==16'hfeed && f_split_2==16'hfeed) && !(f_split_1==16'he11e && f_split_2==16'hfeed)) $stop; end if (cyc==6) begin m_din <= 16'he33e; if (!(a_split_1==16'he22e && a_split_2==16'he22e)) $stop; if (!(b_split_1==16'he22e && b_split_2==16'he22e)) $stop; if (!(c_split_1==16'h1dd1 && c_split_2==16'he22e)) $stop; if (!(d_split_1==16'h1ee1 && d_split_2==16'h0112)) $stop; if (!(z_split_1==16'h1ee1 && d_split_2==16'h0112)) $stop; // Two valid orderings, as we don't know which posedge clk gets evaled first if (!(e_split_1==16'he11e && e_split_2==16'he11e) && !(e_split_1==16'he22e && e_split_2==16'he22e)) $stop; if (!(f_split_1==16'he11e && f_split_2==16'hfeed) && !(f_split_1==16'he22e && f_split_2==16'he11e)) $stop; end if (cyc==7) begin $write("*-* All Finished *-*\n"); $finish; end end end endmodule
// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed into the Public Domain, for any use, // without warranty, 2003 by Wilson Snyder. module t (/*AUTOARG*/ // Inputs clk ); input clk; integer cyc; initial cyc=1; reg [15:0] m_din; // OK reg [15:0] a_split_1, a_split_2; always @ (/*AS*/m_din) begin a_split_1 = m_din; a_split_2 = m_din; end // OK reg [15:0] b_split_1, b_split_2; always @ (/*AS*/m_din) begin b_split_1 = m_din; b_split_2 = b_split_1; end // Not OK reg [15:0] c_split_1, c_split_2; always @ (/*AS*/m_din) begin c_split_1 = m_din; c_split_2 = c_split_1; c_split_1 = ~m_din; end // OK reg [15:0] d_split_1, d_split_2; always @ (posedge clk) begin d_split_1 <= m_din; d_split_2 <= d_split_1; d_split_1 <= ~m_din; end // Not OK always @ (posedge clk) begin $write(" foo %x", m_din); $write(" bar %x\n", m_din); end // Not OK reg [15:0] e_split_1, e_split_2; always @ (posedge clk) begin e_split_1 = m_din; e_split_2 = e_split_1; end // Not OK reg [15:0] f_split_1, f_split_2; always @ (posedge clk) begin f_split_2 = f_split_1; f_split_1 = m_din; end // Not Ok reg [15:0] l_split_1, l_split_2; always @ (posedge clk) begin l_split_2 <= l_split_1; l_split_1 <= l_split_2 | m_din; end // OK reg [15:0] z_split_1, z_split_2; always @ (posedge clk) begin z_split_1 <= 0; z_split_1 <= ~m_din; end always @ (posedge clk) begin z_split_2 <= 0; z_split_2 <= z_split_1; end always @ (posedge clk) begin if (cyc!=0) begin cyc<=cyc+1; if (cyc==1) begin m_din <= 16'hfeed; end if (cyc==3) begin end if (cyc==4) begin m_din <= 16'he11e; //$write(" A %x %x\n", a_split_1, a_split_2); if (!(a_split_1==16'hfeed && a_split_2==16'hfeed)) $stop; if (!(b_split_1==16'hfeed && b_split_2==16'hfeed)) $stop; if (!(c_split_1==16'h0112 && c_split_2==16'hfeed)) $stop; if (!(d_split_1==16'h0112 && d_split_2==16'h0112)) $stop; if (!(e_split_1==16'hfeed && e_split_2==16'hfeed)) $stop; if (!(f_split_1==16'hfeed && f_split_2==16'hfeed)) $stop; if (!(z_split_1==16'h0112 && z_split_2==16'h0112)) $stop; end if (cyc==5) begin m_din <= 16'he22e; if (!(a_split_1==16'he11e && a_split_2==16'he11e)) $stop; if (!(b_split_1==16'he11e && b_split_2==16'he11e)) $stop; if (!(c_split_1==16'h1ee1 && c_split_2==16'he11e)) $stop; if (!(d_split_1==16'h0112 && d_split_2==16'h0112)) $stop; if (!(z_split_1==16'h0112 && z_split_2==16'h0112)) $stop; // Two valid orderings, as we don't know which posedge clk gets evaled first if (!(e_split_1==16'hfeed && e_split_2==16'hfeed) && !(e_split_1==16'he11e && e_split_2==16'he11e)) $stop; if (!(f_split_1==16'hfeed && f_split_2==16'hfeed) && !(f_split_1==16'he11e && f_split_2==16'hfeed)) $stop; end if (cyc==6) begin m_din <= 16'he33e; if (!(a_split_1==16'he22e && a_split_2==16'he22e)) $stop; if (!(b_split_1==16'he22e && b_split_2==16'he22e)) $stop; if (!(c_split_1==16'h1dd1 && c_split_2==16'he22e)) $stop; if (!(d_split_1==16'h1ee1 && d_split_2==16'h0112)) $stop; if (!(z_split_1==16'h1ee1 && d_split_2==16'h0112)) $stop; // Two valid orderings, as we don't know which posedge clk gets evaled first if (!(e_split_1==16'he11e && e_split_2==16'he11e) && !(e_split_1==16'he22e && e_split_2==16'he22e)) $stop; if (!(f_split_1==16'he11e && f_split_2==16'hfeed) && !(f_split_1==16'he22e && f_split_2==16'he11e)) $stop; end if (cyc==7) begin $write("*-* All Finished *-*\n"); $finish; end end 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 m_axi_dma # ( parameter C_M_AXI_ADDR_WIDTH = 32, parameter C_M_AXI_DATA_WIDTH = 64, parameter C_M_AXI_ID_WIDTH = 1, parameter C_M_AXI_AWUSER_WIDTH = 1, parameter C_M_AXI_WUSER_WIDTH = 1, parameter C_M_AXI_BUSER_WIDTH = 1, parameter C_M_AXI_ARUSER_WIDTH = 1, parameter C_M_AXI_RUSER_WIDTH = 1 ) ( //////////////////////////////////////////////////////////////// //AXI4 master interface signals input m_axi_aclk, input m_axi_aresetn, // Write address channel output [C_M_AXI_ID_WIDTH-1:0] m_axi_awid, output [C_M_AXI_ADDR_WIDTH-1:0] m_axi_awaddr, output [7:0] m_axi_awlen, output [2:0] m_axi_awsize, output [1:0] m_axi_awburst, output [1:0] m_axi_awlock, output [3:0] m_axi_awcache, output [2:0] m_axi_awprot, output [3:0] m_axi_awregion, output [3:0] m_axi_awqos, output [C_M_AXI_AWUSER_WIDTH-1:0] m_axi_awuser, output m_axi_awvalid, input m_axi_awready, // Write data channel output [C_M_AXI_ID_WIDTH-1:0] m_axi_wid, output [C_M_AXI_DATA_WIDTH-1:0] m_axi_wdata, output [(C_M_AXI_DATA_WIDTH/8)-1:0] m_axi_wstrb, output m_axi_wlast, output [C_M_AXI_WUSER_WIDTH-1:0] m_axi_wuser, output m_axi_wvalid, input m_axi_wready, // Write response channel input [C_M_AXI_ID_WIDTH-1:0] m_axi_bid, input [1:0] m_axi_bresp, input m_axi_bvalid, input [C_M_AXI_BUSER_WIDTH-1:0] m_axi_buser, output m_axi_bready, // Read address channel output [C_M_AXI_ID_WIDTH-1:0] m_axi_arid, output [C_M_AXI_ADDR_WIDTH-1:0] m_axi_araddr, output [7:0] m_axi_arlen, output [2:0] m_axi_arsize, output [1:0] m_axi_arburst, output [1:0] m_axi_arlock, output [3:0] m_axi_arcache, output [2:0] m_axi_arprot, output [3:0] m_axi_arregion, output [3:0] m_axi_arqos, output [C_M_AXI_ARUSER_WIDTH-1:0] m_axi_aruser, output m_axi_arvalid, input m_axi_arready, // Read data channel input [C_M_AXI_ID_WIDTH-1:0] m_axi_rid, input [C_M_AXI_DATA_WIDTH-1:0] m_axi_rdata, input [1:0] m_axi_rresp, input m_axi_rlast, input [C_M_AXI_RUSER_WIDTH-1:0] m_axi_ruser, input m_axi_rvalid, output m_axi_rready, output m_axi_bresp_err, output m_axi_rresp_err, output pcie_rx_fifo_rd_en, input [C_M_AXI_DATA_WIDTH-1:0] pcie_rx_fifo_rd_data, output pcie_rx_fifo_free_en, output [9:4] pcie_rx_fifo_free_len, input pcie_rx_fifo_empty_n, output pcie_tx_fifo_alloc_en, output [9:4] pcie_tx_fifo_alloc_len, output pcie_tx_fifo_wr_en, output [C_M_AXI_DATA_WIDTH-1:0] pcie_tx_fifo_wr_data, input pcie_tx_fifo_full_n, input pcie_user_clk, input pcie_user_rst_n, input dev_rx_cmd_wr_en, input [29:0] dev_rx_cmd_wr_data, output dev_rx_cmd_full_n, input dev_tx_cmd_wr_en, input [29:0] dev_tx_cmd_wr_data, output dev_tx_cmd_full_n, output dma_rx_done_wr_en, output [20:0] dma_rx_done_wr_data, input dma_rx_done_wr_rdy_n ); wire w_dev_rx_cmd_rd_en; wire [29:0] w_dev_rx_cmd_rd_data; wire w_dev_rx_cmd_empty_n; wire w_dev_tx_cmd_rd_en; wire [29:0] w_dev_tx_cmd_rd_data; wire w_dev_tx_cmd_empty_n; dev_rx_cmd_fifo dev_rx_cmd_fifo_inst0 ( .wr_clk (pcie_user_clk), .wr_rst_n (pcie_user_rst_n), .wr_en (dev_rx_cmd_wr_en), .wr_data (dev_rx_cmd_wr_data), .full_n (dev_rx_cmd_full_n), .rd_clk (m_axi_aclk), .rd_rst_n (m_axi_aresetn & pcie_user_rst_n), .rd_en (w_dev_rx_cmd_rd_en), .rd_data (w_dev_rx_cmd_rd_data), .empty_n (w_dev_rx_cmd_empty_n) ); dev_tx_cmd_fifo dev_tx_cmd_fifo_inst0 ( .wr_clk (pcie_user_clk), .wr_rst_n (pcie_user_rst_n), .wr_en (dev_tx_cmd_wr_en), .wr_data (dev_tx_cmd_wr_data), .full_n (dev_tx_cmd_full_n), .rd_clk (m_axi_aclk), .rd_rst_n (m_axi_aresetn & pcie_user_rst_n), .rd_en (w_dev_tx_cmd_rd_en), .rd_data (w_dev_tx_cmd_rd_data), .empty_n (w_dev_tx_cmd_empty_n) ); m_axi_write # ( .C_M_AXI_ADDR_WIDTH (C_M_AXI_ADDR_WIDTH), .C_M_AXI_DATA_WIDTH (C_M_AXI_DATA_WIDTH), .C_M_AXI_ID_WIDTH (C_M_AXI_ID_WIDTH), .C_M_AXI_AWUSER_WIDTH (C_M_AXI_AWUSER_WIDTH), .C_M_AXI_WUSER_WIDTH (C_M_AXI_WUSER_WIDTH), .C_M_AXI_BUSER_WIDTH (C_M_AXI_BUSER_WIDTH) ) m_axi_write_inst0( //////////////////////////////////////////////////////////////// //AXI4 master write channel signal .m_axi_aclk (m_axi_aclk), .m_axi_aresetn (m_axi_aresetn), // Write address channel .m_axi_awid (m_axi_awid), .m_axi_awaddr (m_axi_awaddr), .m_axi_awlen (m_axi_awlen), .m_axi_awsize (m_axi_awsize), .m_axi_awburst (m_axi_awburst), .m_axi_awlock (m_axi_awlock), .m_axi_awcache (m_axi_awcache), .m_axi_awprot (m_axi_awprot), .m_axi_awregion (m_axi_awregion), .m_axi_awqos (m_axi_awqos), .m_axi_awuser (m_axi_awuser), .m_axi_awvalid (m_axi_awvalid), .m_axi_awready (m_axi_awready), // Write data channel .m_axi_wid (m_axi_wid), .m_axi_wdata (m_axi_wdata), .m_axi_wstrb (m_axi_wstrb), .m_axi_wlast (m_axi_wlast), .m_axi_wuser (m_axi_wuser), .m_axi_wvalid (m_axi_wvalid), .m_axi_wready (m_axi_wready), // Write response channel .m_axi_bid (m_axi_bid), .m_axi_bresp (m_axi_bresp), .m_axi_bvalid (m_axi_bvalid), .m_axi_buser (m_axi_buser), .m_axi_bready (m_axi_bready), .m_axi_bresp_err (m_axi_bresp_err), .dev_rx_cmd_rd_en (w_dev_rx_cmd_rd_en), .dev_rx_cmd_rd_data (w_dev_rx_cmd_rd_data), .dev_rx_cmd_empty_n (w_dev_rx_cmd_empty_n), .pcie_rx_fifo_rd_en (pcie_rx_fifo_rd_en), .pcie_rx_fifo_rd_data (pcie_rx_fifo_rd_data), .pcie_rx_fifo_free_en (pcie_rx_fifo_free_en), .pcie_rx_fifo_free_len (pcie_rx_fifo_free_len), .pcie_rx_fifo_empty_n (pcie_rx_fifo_empty_n), .dma_rx_done_wr_en (dma_rx_done_wr_en), .dma_rx_done_wr_data (dma_rx_done_wr_data), .dma_rx_done_wr_rdy_n (dma_rx_done_wr_rdy_n) ); m_axi_read # ( .C_M_AXI_ADDR_WIDTH (C_M_AXI_ADDR_WIDTH), .C_M_AXI_DATA_WIDTH (C_M_AXI_DATA_WIDTH), .C_M_AXI_ID_WIDTH (C_M_AXI_ID_WIDTH), .C_M_AXI_ARUSER_WIDTH (C_M_AXI_ARUSER_WIDTH), .C_M_AXI_RUSER_WIDTH (C_M_AXI_RUSER_WIDTH) ) m_axi_read_inst0( //////////////////////////////////////////////////////////////// //AXI4 master read channel signals .m_axi_aclk (m_axi_aclk), .m_axi_aresetn (m_axi_aresetn), // Read address channel .m_axi_arid (m_axi_arid), .m_axi_araddr (m_axi_araddr), .m_axi_arlen (m_axi_arlen), .m_axi_arsize (m_axi_arsize), .m_axi_arburst (m_axi_arburst), .m_axi_arlock (m_axi_arlock), .m_axi_arcache (m_axi_arcache), .m_axi_arprot (m_axi_arprot), .m_axi_arregion (m_axi_arregion), .m_axi_arqos (m_axi_arqos), .m_axi_aruser (m_axi_aruser), .m_axi_arvalid (m_axi_arvalid), .m_axi_arready (m_axi_arready), // Read data channel .m_axi_rid (m_axi_rid), .m_axi_rdata (m_axi_rdata), .m_axi_rresp (m_axi_rresp), .m_axi_rlast (m_axi_rlast), .m_axi_ruser (m_axi_ruser), .m_axi_rvalid (m_axi_rvalid), .m_axi_rready (m_axi_rready), .m_axi_rresp_err (m_axi_rresp_err), .dev_tx_cmd_rd_en (w_dev_tx_cmd_rd_en), .dev_tx_cmd_rd_data (w_dev_tx_cmd_rd_data), .dev_tx_cmd_empty_n (w_dev_tx_cmd_empty_n), .pcie_tx_fifo_alloc_en (pcie_tx_fifo_alloc_en), .pcie_tx_fifo_alloc_len (pcie_tx_fifo_alloc_len), .pcie_tx_fifo_wr_en (pcie_tx_fifo_wr_en), .pcie_tx_fifo_wr_data (pcie_tx_fifo_wr_data), .pcie_tx_fifo_full_n (pcie_tx_fifo_full_n) ); endmodule