Case statement in verilog

aditya3524 picture aditya3524 · Mar 14, 2013 · Viewed 19.9k times · Source

I came across priority encoder design and found out a new way to do it using a case statement. The only thing that is confusing is, does a case statement give priority to cases? Example:

case(1'b1)                                
  A[3]: Y<=4'b1000;             
  A[2]: Y<=4'b0100;  
  A[1]: Y<=4'b0010;  
  A[0]: Y<=4'b0001;  
  default:Y<=4'b0000;
endcase

Here if I give A as 1111 Y gets 1000 i.e it gives priority to the first case statement. Why is this so?

Answer

Morgan picture Morgan · Mar 14, 2013

I would refactor this to :

casez(A)                                
  4'b1???: Y<=4'b1000;             
  4'b01??: Y<=4'b0100;  
  4'b001?: Y<=4'b0010;  
  4'b0001: Y<=4'b0001;  
  default: Y<=4'b0000;
endcase

Then there is no need to worry about priority, each match is unique.

From IEEE Std 1800-2009 (IEEE STANDARD FOR SYSTEMVERILOG)

12.5.2 Constant expression in case statement
A constant expression can be used for the case_expression. The value of the constant expression shall be compared against the case_item_expressions.

The following example demonstrates the usage by modeling a 3-bit priority encoder:

logic [2:0] encode ;

case (1)
  encode[2] : $display("Select Line 2") ;
  encode[1] : $display("Select Line 1") ;
  encode[0] : $display("Select Line 0") ;
  default $display("Error: One of the bits expected ON");
endcase

12.5.3 unique-case, unique0-case, and priority-case
The case, casez, and casex keywords can be qualified by priority, unique, or unique0 keywords to perform certain violation checks. These are collectively referred to as a priority-case, unique-case or unique0-case. A priority-case shall act on the first match only. Unique-case and unique0-case assert that there are no overlapping case_items and hence that it is safe for the case_items to be evaluated in parallel.

...

priority casez(a) // values 4,5,6,7 cause a violation report 
  3’b00?: $display("0 or 1");
  3’b0??: $display("2 or 3");
endcase

I am not sure how well supported the priority case statements are supported by synthesis tools though.