Functions and Tasks in RTL
Write functions that synthesize to the logic you expect, and find the two ways a function makes simulation differ from the gates.
You Will Be Able To
- Predict how many copies of its logic a function builds.
- Choose between
automaticand static storage, and between a task and avoidfunction. - Find a stale output caused by a function that reads a signal it does not take as an argument.
- Write a constant function that sizes a port at elaboration.
- Lesson
- R11.3
- Time
- 25 min
- Runs on
- Your browser
- Check
- 5 questions
A gain block limits its output to a ceiling that software can lower. Software lowered it, and the simulation kept showing the old, larger output. The synthesized block had no such fault. The limiter was a function, and the function read the ceiling without anyone passing it in.
y (Icarus) is the shipped design in simulation. y (gates) is what the synthesized block computes: twice the sample, limited to the ceiling.- Cycle 0
Edge 2: the sample is 60 and the ceiling 200. Both rows show 120.
- Cycle 1
Edge 3: only the ceiling changed, to 100. The gates give 100. Simulation still shows 120.
- Cycle 3
Edge 5: the sample changed, so the block ran again and caught up.
- Cycle 4
Edge 6: the ceiling rose alone to 250. The gates give 140. Simulation still shows 100.
Measured on Icarus 12. Verilator 5.052 printed the gates row for the same file.
A Function Is Logic, Copied at Every Call
A function takes inputs, runs in zero time and returns a value. In RTL it is a named piece of combinational logic. The synthesizer pastes that logic in at every place you call it.
- Neutral
- Step
- Datapath
- Structure
- One definition
The package holds the text of
sat_addonce. - Two calls
The module calls it for
yand again forz. - Two copies
Synthesize reports 89 cells for the module. One call alone is 44.
Read the diagram as text
- sat_add: one definition in a package
- sat_add(a, b): call site 1
- sat_add(c, d): call site 2
- adder + limiter: its own gates, drives y
- adder + limiter: its own gates, drives z
- sat_add → sat_add(a, b): used by
- sat_add → sat_add(c, d): used by
- sat_add(a, b) → adder + limiter: builds
- sat_add(c, d) → adder + limiter: builds
A function saves typing and review time. It does not save gates.
package sat_pkg;
// The sum of two bytes, held at 255.
function automatic logic [7:0] sat_add(input logic [7:0] a, b);
logic [8:0] s;
s = a + b;
return s[8] ? 8'hff : s[7:0];
endfunction
endpackage
module two_calls
import sat_pkg::*;
(
input logic [7:0] a, b, c, d,
output logic [7:0] y, z
);
assign y = sat_add(a, b); // one copy of the adder and the limiter
assign z = sat_add(c, d); // a second copy
endmoduleHow the module calls sat_add | Cells | Levels |
|---|---|---|
once: y = sat_add(a, b) | 44 | 16 |
twice, two results: y and z | 89 | 16 |
twice, nested: sat_add(sat_add(a, b), c) | 88 | 32 |
once, arguments chosen by sel | 62 | 17 |
Measured on this flow. Nesting puts the copies in series, so the levels double.
automatic, and What Static Storage Does
A function declared in a module or a package is static unless you write automatic. Static means its arguments and local variables exist once, and every call shares them. They keep their values after the call returns.
Hardware has no such memory inside a block of gates. So a static function can simulate one way and synthesize another.
Static, and the variable is never cleared
function logic [2:0] ones(input logic [3:0] d);
logic [2:0] n;
for (int i = 0; i < 4; i++)
n = n + 3'(d[i]);
return n;
endfunction
Icarus 12 prints x: n starts unknown. With n cleared once, the count keeps growing: 3, then 4 for inputs 0111 and 0001. Synthesize refuses the module: found logic loop. Lint warns UNOPTFLAT.
Automatic, and the variable starts at 0
function automatic logic [2:0] ones(input logic [3:0] d);
logic [2:0] n = 0;
for (int i = 0; i < 4; i++)
n = n + 3'(d[i]);
return n;
endfunction
Icarus 12: 3 and then 1. Synthesize builds 9 cells and 4 levels of logic.
| Rule for an RTL function | Reason |
|---|---|
Declare it automatic | each call gets fresh variables, as each copy of the logic does |
| Assign every local variable before reading it | an automatic variable starts unknown at each call |
Use input arguments, and output ones in a void function | every synthesis tool accepts these two directions |
Return with return value; on every path | a path that returns nothing gives an unknown or an old value |
Tasks and void Functions
A task is a subroutine with no return value. It passes results out through output arguments. Unlike a function, a task may wait for time or for a clock edge.
That freedom is the problem in RTL. A void function does the same job and cannot wait, so the compiler enforces the rule for you.
| Subroutine | This flow | Tool message |
|---|---|---|
| task with no wait: reverses 8 bits | builds, 0 cells (wiring) | none |
void function with two outputs: reversed byte and parity | builds, 7 cells | none |
task that waits: @(posedge clk); inside | refused | unsynthesizable timing control |
function with a delay: #1 inside | refused | Yosys: statements that pass time are not allowed in this context. Lint: Delays are not legal in functions |
Measured on the pinned Yosys and the Lint button.
Constant Functions: Run by the Tool
A function called with only parameters and literals is a constant function. The tool runs it during elaboration, before any hardware exists. Its result can size a port or a counter.
DEPTH at 12 the function returns 4. Synthesize reports 13 cells and 4 flops: a 4-bit pointer and its wrap logic. The loop inside the function built nothing.module fifo_ptr #(parameter int DEPTH = 12) (
input logic clk, rst_n, inc,
output logic [width_for(DEPTH)-1:0] ptr
);
// How many bits a pointer into n entries needs.
function automatic int width_for(input int n);
int w = 1;
while ((1 << w) < n) w++;
return w;
endfunction
localparam int W = width_for(DEPTH); // called with a parameter: it runs in the tool
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) ptr <= '0;
else if (inc) ptr <= (ptr == W'(DEPTH - 1)) ? '0 : ptr + 1'b1;
endmodulePass it a signal and the same call is refused: reference to non-constant variable 'd' is not allowed in a constant expression.
What always @* Cannot See
always @* builds its wake-up list from the signals that its own statements read. It does not look inside a function. always_comb does.
How y is driven | Changes with gain alone on Icarus 12? |
|---|---|
always_comb y = mul(d); | yes |
always @* y = mul(d); | no: stale |
assign y = mul(d); | no: stale |
always @* y = mul2(d, gain); | yes: gain is an argument |
always @(d or gain) y = mul(d); | yes, as long as the list is kept complete by hand |
mul reads gain from the module. mul2 takes it as an argument. A continuous assign missed the change too.
Two habits remove the problem. Use always_comb for combinational logic. And pass a function everything it reads, so the call shows its inputs.
The Lab: The Limiter That Missed Its Ceiling
| Port | Direction | Width | Meaning |
|---|---|---|---|
| clk | input | 1 | clock |
| rst_n | input | 1 | reset, asynchronous, active-low |
| sample | input | [7:0] | the input sample |
| ceiling | input | [7:0] | the largest value y may take |
| y | output | [7:0] | twice the sample, limited to the ceiling |
| y_q | output | [7:0] | y registered |
- Clock
- rising edge
- Reset
rst_nasynchronous, active-low- Corner cases
ceilingchanging whilesamplestays still. Done when: Run showsy=100at edge 3 andy=140at edge 6, and Synthesize still reports 43 cells
Run as shipped
At edges 3, 4 and 6
yignores the new ceiling, andy_qstores the stale value. Lint prints nothing.Find what the block reads
The statement reads
sample. The function also readsceiling, which the statement never names.Fix it
Change
always @*toalways_comband Run.yfollows the ceiling at once.Make the input visible
Give
clipa second argument for the ceiling and pass it in the call. Now evenalways @*would work, and a reader sees the dependency.Check the gates
Synthesize each version: 43 cells, 8 flops, 11 levels every time. Only the simulation changed.
Asked in interviews
Why should RTL functions be
automatic?A static function shares its variables between calls and keeps their values. Hardware built from the function has no such memory, so simulation and gates can differ. An automatic function gets fresh variables at each call.
Does calling a function twice share its logic?
No. Each call builds a copy. On this flow one saturating add was 44 cells and two calls were 89. To share, mux the arguments into a single call.
What is the difference between
always @*andalways_combwith functions?always @*is sensitive only to signals its own statements read.always_combalso includes signals read inside the functions it calls, and it runs once at time 0.
Try It
The bench changes its inputs 1 ns after an edge and prints 1 ns after the next one. At edges 3 and 4 the ceiling is 100, yet y shows 120. At edge 6 the ceiling is 250, yet y shows 100.
The block reran only when sample changed, at edges 2, 5 and 7. With always_comb the six lines read 120, 100, 100, 100, 140 and 150.
Synthesize reports 43 cells: 8 $_DFF_PN0_ flops and 35 gates, 0 latches and 11 levels of logic. The count is the same for the fixed design.
Synthesize the design to measure its cells and inspect the mapped gates.
e2 sample=60 ceiling=200 y=120 y_q=120 e3 sample=60 ceiling=100 y=120 y_q=120 e4 sample=60 ceiling=100 y=120 y_q=120 e5 sample=70 ceiling=100 y=100 y_q=100 e6 sample=70 ceiling=250 y=100 y_q=100 e7 sample=90 ceiling=150 y=150 y_q=150Original design · 43 cells · 8 flip-flops · 0 latches · 11 logic levels. Synthesis uses Yosys; counts depend on the toolchain.
Read included file: tb.sv
`timescale 1ns/1ps
module tb;
logic clk = 0;
always #5 clk = ~clk; // rising edges at 5, 15, 25, ...
logic rst_n = 1; // falls at 1 ns, rises 1 ns after edge 1
int edge_n = -1;
always @(posedge clk) edge_n = edge_n + 1;
logic [7:0] sample = 0, ceiling = 8'd200;
logic [7:0] y, y_q;
clip_gain dut (.*);
task automatic tick();
@(posedge clk); #1;
if (rst_n) $display("e%0d sample=%0d ceiling=%0d y=%0d y_q=%0d", edge_n, sample, ceiling, y, y_q);
endtask
initial begin
#1 rst_n = 0; tick(); tick(); rst_n = 1;
sample = 8'd60; tick();
ceiling = 8'd100; tick(); // the ceiling changes alone
tick();
sample = 8'd70; tick();
ceiling = 8'd250; tick(); // the ceiling changes alone
sample = 8'd90; ceiling = 8'd150; tick();
$finish(0);
end
endmodule
Check Yourself
Common Mistakes
Wrong Call one function in ten places and expect one shared block of logic.
Each call builds its own copy of the function body.
Fix Share on purpose: mux the arguments into one call, and check the cell count.
assign y = sat_add(a, b);
assign z = sat_add(c, d); // two adders: 89 cells// one adder, when only one result is needed at a time
assign y = sat_add(sel ? c : a,
sel ? d : b); // 62 cellsWrong Leave out automatic on a function in a module or a package.
The function is then static, so its variables are shared by every call and keep their last values.
Fix Write function automatic for every RTL function, and give each local variable a value before you read it.
Wrong Put a wait such as @(posedge clk) inside a task that RTL calls.
This flow refuses it: unsynthesizable timing control.
Fix Keep time in the always_ff block. Use a void function for the zero-time work, so the compiler rejects any wait.
Wrong Size a port with a function call whose argument is a signal.
A size must be known at elaboration, and a signal has no value then.
Fix Call the function with parameters and literals only, as localparam int W = width_for(DEPTH); does.
Remember
- A function is combinational logic. Every call builds its own copy: 44 cells for one saturating add, 89 for two.
- Declare RTL functions
automaticand assign each local variable before reading it. - A subroutine in RTL runs in zero time. Use a
voidfunction where you would write a task. - A function called with parameters only runs in the tool and can size a port.
always @*does not look inside functions andalways_combdoes. Pass a function everything it reads.