Your First SystemVerilog Module and Testbench

Write a gate-level module, wrap it in a testbench that checks every input row, and read a compile error.

You Will Be Able To

  • Write a module with ports, gate primitives and assign.
  • Connect an instance by name.
  • Read a testbench built from initial, # and $display.
  • Make a bench check every row by itself.
Lesson
G2.3
Time
25 min
Runs on
Your browser
Check
5 questions

A selector circuit passed its code review and failed on the board. The module was correct. The line that placed it listed the wires in the wrong order, and the compiler said nothing.

One Selector, Connected by Name and by PositionOne input row per step. The selector gives a when sel is 0 and b when sel is 1. The second copy has its wires in the order a, b, sel.
01234567sel a b000001010011100101110111y, connected by namey, wrong position orderfirst wrong row
Scroll horizontally ↔
  1. Cycle 0

    All inputs are 0. Both copies give 0, so this row shows nothing.

  2. Cycle 1

    The row 001: sel is 0, so y must follow a, which is 0. The second copy gives 1.

  3. Cycle 7

    Four of the eight rows are wrong. A test of the rows 000 and 111 alone would pass.

Measured on the simulator. Both copies compile without a warning.

A Module Is a Box with Ports

A module is one block of hardware with a name. Its ports are the wires that cross its border. Each port is an input or an output.

The majority circuit as a module
module maj3 (            // the name of the block
  input  logic a,        // three 1-bit inputs
  input  logic b,
  input  logic c,
  output logic y         // one 1-bit output
);
  assign y = (a & b) | (a & c) | (b & c);
endmodule                // the end of the block
WordMeaning
module … endmodulethe start and the end of one block
input, outputthe direction of a port, seen from inside the block
logica 4-state signal: 0, 1, x or z; without a range it is 1 bit wide
assigndrives a signal from an expression, all the time
;ends a declaration or a statement

Five words are enough for a first module.

The module describes hardware. Nothing in it runs once or runs first. The output y follows the inputs for as long as the circuit has power.

Two Ways to Write the Gates

You can place each gate yourself with a gate primitive. Or you can write one expression with the operators & (AND), | (OR), ^ (XOR) and ~ (NOT).

Gate by gate

module maj3 (
  input  logic a, b, c,
  output wire  y
);
  wire ab, ac, bc;
  and g1 (ab, a, b);
  and g2 (ac, a, c);
  and g3 (bc, b, c);
  or  g4 (y, ab, ac, bc);
endmodule

Synthesized on this site: 4 cells, 3 logic levels.

One expression

module maj3 (
  input  logic a, b, c,
  output logic y
);
  assign y = (a & b) | (a & c) | (b & c);
endmodule

The same result: 4 cells, 3 logic levels.

In a primitive, the output comes first: and g1 (ab, a, b) drives ab. A wire between two gates needs a declaration, here wire ab, ac, bc;.

Both forms describe the same function, and the synthesis tool builds the same cells from both. Use primitives to show a structure. Use assign for everything else.

The Testbench Around the Module

A module does nothing until something drives its inputs. A testbench is a module with no ports. It holds a copy of your design, drives the inputs and prints the outputs.

From a Circuit to a Text to a TestArrows show what goes into what. The circuit becomes the text of a module. The testbench holds one copy of that module and drives it.
  • Design
  • Driver
  • DUT
  • Scoreboard
  • Structure
  • Data
CallValueReturnWaiting
From a circuit to a text to a testArrows show what goes into what. The circuit becomes the text of a module. The testbench holds one copy of that module and drives it. design Circuit three ANDs, one OR design module maj3 ports a, b, c, y driver initial block drives a, b, c dut maj3 dut a copy inside tb scoreboard Check and print compares y, $display written as textplaced in tba, b, cy
  1. design Circuitthree ANDs, one OR
    • written as text → module maj3
  2. design module maj3ports a, b, c, y
    • placed in tb → maj3 dut
  3. dut maj3 duta copy inside tb
    • y → Check and print
  4. driver initial blockdrives a, b, c
    • a, b, c → maj3 dut
  5. scoreboard Check and printcompares y, $display
  1. The circuit

    The majority circuit of the last lesson: three AND gates and one OR gate.

  2. The same circuit as text

    The module maj3 describes it. Its ports are the wires that leave the drawing.

    Follow the calls, values and waits
    1. data maj3: Circuit → module maj3
  3. The text inside a bench

    The bench places one copy, named dut. Its initial block sets a, b and c, waits, and reads y.

    Follow the calls, values and waits
    1. data 110: initial block → maj3 dut
    2. data y = 1: maj3 dut → Check and print
Read the diagram as text
  • Circuit: three ANDs, one OR
  • module maj3: ports a, b, c, y
  • initial block: drives a, b, c
  • maj3 dut: a copy inside tb
  • Check and print: compares y, $display
  • Circuit → module maj3: written as text
  • module maj3 → maj3 dut: placed in tb
  • initial block → maj3 dut: a, b, c
  • maj3 dut → Check and print: y

The design is hardware. The bench is a program that runs in the simulator only.

Line in the benchWhat it doesHardware?
maj3 dut (.a(a), .b(b), .c(c), .y(y));places a copy of maj3 and connects each port by nameyes
initial begin … endruns its statements once, in order, from time 0no
{a, b, c} = 3'b110;sets the three inputsno
#1;waits one time unit of simulated timeno
$display("y=%b", y);prints one line; %b shows a value in binaryno

Only the instance is hardware. The rest tells the simulator what to do.

Connect by name. .a(a) means: port a of the module gets the wire a of the bench. A connection by position depends on the order, as the trace at the top shows.

A Bench That Checks Itself

Three inputs have only eight rows. So the bench can try them all: an exhaustive test. A for loop counts from 0 to 7, and the three bits of the counter are the inputs.

The bench also knows the right answer. It computes it another way than the design does: it counts the 1s. Then it compares with !== and counts the wrong rows.

The loop of the bench in the lab below
for (int i = 0; i < 8; i++) begin
  {a, b, c} = i[2:0];                  // row i of the truth table
  #1;                                  // wait for the gates
  if (y !== (a + b + c >= 2)) wrong++; // compare with the expected value
end
$display("%0d of 8 rows wrong", wrong);
DesignWhat the bench prints last
(a & b) | (a & c): one pair missing1 of 8 rows wrong
(a & b) | (a & c) | (b & c)0 of 8 rows wrong
a & b & c: all three needed3 of 8 rows wrong

Measured with the bench of the lab. The last line is the verdict: you do not need to read the eight rows.

Use !== in a check. It also sees x and z. The plain != gives x when a value is unknown, and an if treats x as false.

Reading a Compile Error

The compiler stops at the first thing it cannot read. Its message starts with the file and the line number. Fix the first message and run again: later messages often follow from the first one.

MistakeMessage of the simulatorHow to read it
a missing ; at the end of the assign line, line 9 of the labmain.sv:10: syntax errorthe error is noticed on the next line: look one line up
an unknown name d in an assign`error: Unable to bind wire/reg/memory d' in tb.dut'`the name was never declared
a port .d(c) that the module does not have`error: port d'' is not a port of dut.`check the port names of the module
the module name maj for maj3error: Unknown module type: majno module has that name
a missing endmodulesyntax error on the last line of the file, then I give up.a block was never closed: match each module with its endmodule

Measured with Icarus Verilog 12 on the bench of this lesson. Other simulators use other words for the same mistakes.

Asked in interviews
  1. What is the difference between a design module and a testbench?

    The design describes hardware and can be synthesized. The testbench has no ports. It places the design, drives its inputs and checks its outputs. Delays and $display belong in the bench only.

  2. Why connect ports by name?

    A connection by position depends on the order of the port list. A wrong order of same-size wires compiles without a warning. By name, each wire is tied to its port, and the order is free.

  3. What makes a testbench self-checking?

    It compares each output with an expected value and reports pass or fail by itself. The expected value comes from an independent model. Nobody has to read a waveform or a log to know the result.

In Plain Verilog

Older code is written in Verilog-2001. It has no logic type. A signal driven by assign or by a gate is a wire. A signal set inside initial is a reg.

SystemVerilog

module maj3 (
  input  logic a, b, c,
  output logic y
);
  assign y = (a & b) | (a & c) | (b & c);
endmodule

// in the bench
logic a, b, c, y;
for (int i = 0; i < 8; i++) ...

One type, logic, for every signal. The loop counter is declared in the loop.

Verilog-2001

module maj3 (
  input  wire a, b, c,
  output wire y
);
  assign y = (a & b) | (a & c) | (b & c);
endmodule

// in the bench
reg  a, b, c;  wire y;
integer i;
for (i = 0; i < 8; i = i + 1) ...

The same hardware. Here reg does not mean a register: it is a signal that a block assigns.

This course writes SystemVerilog from the start. The SystemVerilog track teaches the language in full. Lesson R1.1 in the RTL Design track shows what synthesis does with it.

Try It

The design tests two pairs of inputs and forgets the pair b, c. The bench finds the row where only that pair is 1 and marks it.

Add | (b & c) to the expression and run again. The last line becomes 0 of 8 rows wrong.

Press Synthesize and open the Gates tab. The fixed design is 4 cells in 3 logic levels. The tool picked its own gates for the same truth table.

Now break it on purpose: delete the ; at the end of the assign line and run. Read the first message and its line number.

RTLIcarus Verilog · in your browser · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: a=0 b=0 c=0 y=0 a=0 b=0 c=1 y=0 a=0 b=1 c=0 y=0 a=0 b=1 c=1 y=0 wrong a=1 b=0 c=0 y=0 a=1 b=0 c=1 y=1 a=1 b=1 c=0 y=1 a=1 b=1 c=1 y=1 1 of 8 rows wrong

Original design · 2 cells · 0 flip-flops · 0 latches · 2 logic levels. Synthesis uses Yosys; counts depend on the toolchain.

Read included file: tb.sv
// tb.sv: the testbench (read-only). It tries every input row and checks the output.
module tb;
  logic a, b, c;      // the bench drives these
  logic y;            // the design drives this
  int   wrong = 0;

  maj3 dut (.a(a), .b(b), .c(c), .y(y));   // the design under test, connected by name

  initial begin
    for (int i = 0; i < 8; i++) begin
      {a, b, c} = i[2:0];                  // row i of the truth table
      #1;                                  // wait one time unit for the gates to settle
      if (y !== (a + b + c >= 2)) wrong++; // the expected value, computed another way
      $display("a=%b b=%b c=%b  y=%b%s", a, b, c, y, y === (a + b + c >= 2) ? "" : "  wrong");
    end
    $display("%0d of 8 rows wrong", wrong);
  end
endmodule

Check Yourself

Spot the bugEach option places the selector pick, whose ports are sel, a, b, y in that order. The bench checks all eight rows. Which instance fails?
ConceptWhich of these lines does not describe hardware?
ConceptA design has four 1-bit inputs. How many rows must an exhaustive bench try?
ConceptThe simulator reports main.sv:6: syntax error. Line 6 looks correct. Where do you look next?
Predict the outputThree assign lines appear with the last step first. Predict the exact line the program prints for a = 1, b = 1, c = 1.
module three (input logic a, b, c, output logic y);
  logic t, u;
  assign y = u & c;      // the last step comes first in the file
  assign u = ~t;
  assign t = a ^ b;
endmodule
module tb;
  logic a, b, c, y;
  three dut (.a(a), .b(b), .c(c), .y(y));
  initial begin
    {a, b, c} = 3'b111;
    #1 $display("%b", y);
  end
endmodule

Common Mistakes

Wrong Connect an instance by position and get the order wrong.

The compiler accepts any order of 1-bit wires. The circuit is then simply a different circuit.

Fix Connect by name: .sel(sel), .a(a), .b(b), .y(y). The order no longer matters.

Before
pick u (a, b, sel, y);
After
pick u (.sel(sel), .a(a), .b(b), .y(y));

Wrong Mistype a wire name in a gate primitive.

A new name in a gate line makes a new 1-bit wire with no driver. No error appears, and the output becomes x.

Fix Declare every wire, and read the output of the first run for x and z.

Wrong Read the lines of a module as steps that run from top to bottom.

Each assign and each gate is a piece of hardware. All of them work at the same time, in any order.

Fix Read a module as a drawing of wires. Only the lines inside initial run in order.

Wrong Print the outputs and check them by eye.

Nobody reads the eighth row as carefully as the first. A wrong row slips through.

Fix Let the bench compare each output with the expected value and count the wrong rows.

Remember

  • A module is a block with ports. assign and gate primitives describe its hardware.
  • In a gate primitive the output comes first. Declare every wire.
  • Place a module with an instance and connect it by name: .port(wire).
  • A testbench drives the inputs in an initial block, waits with #1 and prints with $display.
  • Try every row and let the bench count the wrong ones.

Practice

Report a problem with this page