TDEB Top Bar

Trending
Semiconductor Industry News — The Digital Electronics Blog
Follow Us

TDEB Masthead

The Semiconductor Hub

Semiconductors.  Chips and Systems.  Innovation.

Indexed by leading Search Engines, AI and referenced by Engineers worldwide 500+ Articles 10M+ Pageviews 30+ Reports 50+ Citations

Verilog Rules for Synthesis That Can Save Your Breath

The Editor's Desk
by
1
Share Facebook X LinkedIn WhatsApp Email

This article contains some thoughts of mine about how an engineer should write Verilog code for synthesis, general rules that will save you headaches if you follow them, and how a Verilog file should be laid out.

The rules

  • If you don't know what hardware the code you just wrote is, neither will the synthesizer.
  • Remember that Verilog is a Hardware Description Language (HDL), and as such it describes hardware, not magical circuits that you can never actually build.
  • You should be able to draw a schematic for everything that you write Verilog for.
  • Be sure to know which parts of your circuit are combinational logic and which are sequential elements. If you do not know, or the code is too hard to read to figure this out, the synthesizer will probably not be able to figure it out either. I recommend keeping the combinational logic clearly separate from the sequential logic. This prevents errors later. It also prevents level-sensitive latches from being synthesized where you meant to have flip-flops.
  • I also recommend a naming convention that lets you tell what is a state-holding element at all times. I use "_f" appended to all registers that are flip-flops.
  • I recommend having a style for your inputs and outputs. I list them in this order: outputs, inouts, special inputs such as clk and reset, then inputs.
  • When instantiating a module, always connect signals by name, using the notation period, port name of the module, then in parentheses the signal you are connecting. This prevents errors when you change underlying modules or someone reorders the ports.
  • Unlike a strongly typed language, Verilog is loosely typed: a port is just a wire of some width, so it is easy to reorder connections and get no error at all, only a circuit that does the wrong thing. (The original version of this post called Verilog strongly typed; that was wrong, and the point of the rule is exactly that the language will not catch the mistake for you.)
  • Example of a risky, positional module instantiation: nand2 my_nand(C, A, B);
  • Example of a correct, named module instantiation: nand2 my_nand(.out(C), .in1(A), .in2(B));
  • Make your circuit synchronous whenever possible. Synchronous design is much easier than asynchronous design.
  • Also reduce the number of clock domains and clock-domain crossings whenever possible.
  • Remember that FPGA look-up tables (LUTs) can glitch when their inputs change, in ways that are hard to predict. Never use a LUT output as a clock or an asynchronous reset, and never send a combinational signal across a clock domain: register it first, then pass it through a synchronizer in the receiving domain.

Verilog files should be laid out like this

  • define constants
  • declare outputs (these are _out)
  • declare inouts, if any (these are _inout)
  • declare special inputs such as clk and reset
  • declare inputs (these are _in)
  • declare all state (these are _f)
  • declare the inputs to state (these have the same name as the state but end in _temp)
  • declare wires (naming is not restricted, except that connections between two instantiated modules are usually of the form A_to_B_connection)
  • declare "wire regs" (naming is not restricted, except that connections are usually of the form A_to_B_connection, and variables that are outputs but still need to be read inside the module, and that you don't want to make inouts, get _internal appended)
  • do assigns
  • do assigns to outputs
  • instantiate other modules
  • combinational logic always blocks come next
  • then the always @(posedge clk ...) block: put reset values here and assign the _temps to the _fs (that is, state <= next_state). I think there should be no combinational logic inside an always @(posedge clk) block, with the exception of conditional assignment (write enables), because all Verilog synthesizers understand write enables on flip-flops.

Why these rules matter

A synthesizer does not read your intent; it pattern-matches your code against templates it knows: a flip-flop, a latch, a multiplexer, an adder. Code that matches a template cleanly becomes the hardware you expect. Code that sits between templates becomes something you did not ask for, most often a latch, or logic that simulates one way and synthesizes another. Every rule above is a way of staying on the known templates.

The separation of combinational and sequential logic, together with the _f and _temp naming, makes the hardware visible in the text: every _f is a flip-flop, every _temp is the input to one, and everything else is gates. A reviewer can then sketch the schematic, which is the real test of the first three rules.

Deep dive: the numbers and details

This part holds code templates, the assignment rules that go with them, and the checks that catch mistakes. Skip it if the overview is all you need.

A module written to the layout above

module counter_en (
  output wire [7:0] count_out,   // outputs first
  input  wire       clk,         // special inputs
  input  wire       rst,
  input  wire       en_in        // ordinary inputs
);
  // state (_f) and the inputs to state (_temp)
  reg [7:0] count_f;
  reg [7:0] count_temp;

  // assigns to outputs
  assign count_out = count_f;

  // combinational logic: blocking assignments, every path assigns
  always @(*) begin
    count_temp = count_f;
    if (en_in)
      count_temp = count_f + 8'd1;
  end

  // sequential logic: nonblocking assignments, reset value, no other logic
  always @(posedge clk) begin
    if (rst)
      count_f <= 8'd0;
    else
      count_f <= count_temp;
  end
endmodule

The default assignment count_temp = count_f; at the top of the combinational block is what keeps it combinational: the variable is assigned on every path through the block.

How an unintended latch appears

// Latch inferred: y keeps its old value when sel is 0
always @(*) begin
  if (sel)
    y = a;
end

// Fixed: y is assigned on every path
always @(*) begin
  y = 1'b0;
  if (sel)
    y = a;
end

In the first block, when sel is 0 nothing assigns y, so the hardware must remember the old value. That memory is a level-sensitive latch, which is exactly what the "keep combinational and sequential separate" rule is meant to prevent. Incomplete case statements without a default cause the same problem.

Blocking and nonblocking assignments

The layout above works because each kind of block uses one kind of assignment. Clifford Cummings' widely used SNUG 2000 paper, "Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill!", sets out eight guidelines. The ones that match this post's rules are:

  1. When modeling sequential logic, use nonblocking assignments (<=).
  2. When modeling latches, use nonblocking assignments.
  3. When modeling combinational logic with an always block, use blocking assignments (=).
  4. When modeling both sequential and combinational logic in the same always block, use nonblocking assignments.
  5. Do not mix blocking and nonblocking assignments in the same always block.
  6. Do not make assignments to the same variable from more than one always block.

The paper's remaining two guidelines are about simulation only (use $strobe to display values set by nonblocking assignments, and do not make assignments with #0 delays). The paper concludes that following the eight guidelines removes 90 to 100 percent of the most common Verilog simulation race conditions.

Why positional port lists go wrong

Suppose the nand2 module is later edited so its port list reads (in1, in2, out) instead of (out, in1, in2). The positional instance nand2 my_nand(C, A, B); now drives the gate's inputs from C and A, and connects its output to B. All three are 1-bit wires, so the code still compiles. At best a lint tool reports a signal with two drivers; at worst the bug reaches simulation. The named instance .out(C), .in1(A), .in2(B) is unaffected by the reorder, and a misspelled port name becomes a compile error.

Crossing clock domains safely

A flip-flop that samples a signal changing near its clock edge can go metastable: its output hovers between 0 and 1 for an unpredictable time before settling. The standard defense for a single control bit is a two-flop synchronizer in the receiving domain:

// a_sig_f is registered in clock domain A (no logic after the flop)
reg sync1_f, sync2_f;
always @(posedge clk_b) begin
  sync1_f <= a_sig_f;   // may go metastable
  sync2_f <= sync1_f;   // has a full clk_b period to settle
end
// use only sync2_f in domain B

The source signal must come straight from a flip-flop, because a glitch from combinational logic, such as a LUT whose inputs change at slightly different times, can be captured as a false pulse. Multi-bit values need more than this: a handshake, a Gray-coded pointer or an asynchronous FIFO, because the bits of a bus will not all be synchronized on the same cycle. Fewer clock domains means fewer of these crossings to design and verify, which is the reason behind the rule above.

More on this blog: clock domain synchronizers and metastability, causes and MTBF.

Let a lint tool enforce the rules

Many of these rules can be checked automatically. The free Verilator simulator, run with --lint-only -Wall, reports for example:

Verilator warningWhat it catchesRule it enforces
LATCHA signal not assigned on all paths of a combinational blockNo unintended latches
CASEINCOMPLETEA case statement with uncovered input patternsNo unintended latches
BLKSEQA blocking assignment in a clocked block (style warning)Nonblocking for sequential logic
COMBDLYA nonblocking (delayed) assignment in a combinational blockBlocking for combinational logic
MULTIDRIVENA signal driven from more than one always blockOne block per variable
WIDTHOperands or connections of mismatched widthsCatches many connection mistakes

The full list and the options are in the Verilator --lint-only documentation. For more on lint in general, see Linting tools for HDL design verification on this blog.

Interview angle

  • "What hardware does this code produce?" Expect to be shown a short always block and asked to draw it. Spot the missing else, the missing default, or the blocking assignment in a clocked block.
  • "Why named port connections?" Because Verilog will not catch a reordered positional list.
  • "How do you pass a signal between clock domains?" Register it at the source, synchronize it with two flops at the destination, and use a handshake or FIFO for buses.

Further reading

The Editor's Desk
About the Author
The Editor's Desk
Share Facebook X LinkedIn WhatsApp Email

Post a Comment

1 Comments

Your comments will be moderated before it appears here.

Post a Comment

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!