Search code examples
verilogsystem-verilog

How to write a part select expression using shift operator in system verilog?


How to write a part select expression using shift operator in system Verilog?
Given a memory word

logic [0:8] memword;

How to write the part select expression memword[i:j] in shift operator? If not shift operator, can you please suggest other expressions?

i and j can be any indexing expression. We will assign this memory word to another memory word with |i-j| width.

Consider both left to right and right to left indexing.

use case: writing an alternative statement for the part select for compiler related optimization

The memory could be used anywhere in the program

always @(posedge clk) begin
   if (memword[i:j]) begin
      mem2 = memword[i:j];
   end
end

The main usage is to eliminate part select.


Solution

  • For the code shown, you could write a function to mask the part select, and shift it into the lsb.

    logic [8:0] memword;
    
    
    class vector#(int WIDTH);
        typedef logic [WIDTH-1:0] w_t;
        
        static function w_t slice(w_t vector, int L,R);
          int slice_width = L-R+1;
          w_t mask = (1'b1 << slice_width) -1;
          return vector >> R  & mask;
        endfunction
      endclass
    
    always @(posedge clk) begin
       if (vector#(9)::slice(memword,i,j) begin
          mem2 = vector#(9)::slice(memword,i,j)
       end
    end
    

    Although you could write this function to deal with both big and little endian indexing, It might be easier to write two seperate functions.