'Is $clog2 task supported in Verilog HDL?
When I used it in a program an error was generated ($clog2 is not supported). But I see our StackOverflowers using $clog2 task in their program. Please tell me how to use that.
Solution 1:[1]
$clog2 is not supported by Verilog. It is a SystemVerilog system task. Moreover, system tasks are not synthesizable.
However, you can make a function/macro which outputs the log bsae 2 value of a given number. Here are some of the examples of user defined implementation:
Using macro:
`define CLOG2(x) \
(x <= 2) ? 1 : \
(x <= 4) ? 2 : \
(x <= 8) ? 3 : \
(x <= 16) ? 4 : \
(x <= 32) ? 5 : \
(x <= 64) ? 6 : \
..etc, ..
(x <= 4294967296) ? 32 : \
-1
parameter MAX_VALUE = 42;
parameter MAX_WIDTH = `CLOG2(MAX_VALUE);
Using function:
function [31:0] log2;
input [31:0] value;
integer i;
reg [31:0] j;
begin
j = value - 1;
log2 = 0;
for (i = 0; i < 31; i = i + 1)
if (j[i]) log2 = i+1;
end
endfunction
initial
begin
$display("10 = %d", log2(10));
end
Both the above examples leads to synthesizable code. The user can extend this code as per the maximum bit width requirement.
So, you can either change the compiler to compile SystemVerilog code or implement the above function to make a user-defined log code.
Solution 2:[2]
$clog2is supported by Verilog, but only Verilog-2005 (IEEE Std 1364-2005). Since Verilog-2005 was released at the same time as IEEE's SystemVerilog, it is generally considered a SystemVerilog enhancement. Here are two source documenting $clog2 as a Verilog-2005 feature:
- Sutherland HDL - Busting the Myth that SystemVerilog is only for Verification ยง 9.6 Expression size functions
- Xilinx - Verilog $clog2 function implemented improperly
The Verilog-2005 was mostly an intermediate release for eventual merger of Verilog and SystemVerilog (which happened in IEEE Std 1800-2009). Some simulators may have not implanted Verilog-2005 as everything in it is included in SystemVerilog. If your simulator does not run Verilog-2005 by default, then refer to your manual which may included a option to enable it. Enabling SystemVerilog is another option, or user methods as described in sharvil111's solution.
Solution 3:[3]
Just wanted to point out that $clog2 is a synthesizable construct and can be handled by most tools. It does not become unsynthesizable simply because it is a system task.
For example, the following is a synthesizable statement:
logic [$clog2(WIDTH) - 1 : 0] addr;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sharvil111 |
| Solution 2 | Greg |
| Solution 3 | Nimish Shah |
