Sometimes we have to write a MUX to choose over couple logic like this:
assign y = sel[0] ? 2'd0 :
sel[1] ? 2'd1 :
sel[2] ? 2'd2 :
sel[3] ? 2'd3 : 2'd0;
We call this the serial (slow) priority encoder. This code, in theory,should be synthesized to four levels of logic.
Now we optimze this to 1 level of logic:
localparam ENCODE_MAX_WIDTH = 4;
function [$clog2(ENCODE_MAX_WIDTH)-1:0] priority_encode(input [ENCODE_MAX_WIDTH-1:0] sel);
integer i;
priority_encode= 0;
for(i=0; i<4; i=i+1)
priority_encode |= (sel & ((1<<i+1)-1)) == (1<<i) ? i : '0;
endfunction
y = priority_encode(sel);
Explaination:
// 3. Unroll loop up to small value of i. Use pseudocode to simplify
// understanding.
priority_encode = or_reduce(
if((sel & 0001) =