Logical, Equality and Set Operators

Tell a true/false test from a bit operation, know what a comparison does with an unknown, and write address sets with inside.

You Will Be Able To

  • Predict the result of ! and ~, and of && and &, on a vector.
  • Explain why a function behind && can run in the gates and not in simulation.
  • Predict what ==, === and ==? return when a bit is unknown.
  • Write a set of addresses with inside, and predict the comparators it builds.
Lesson
R10.2
Time
30 min
Runs on
Your browser
Check
5 questions

An operator masked the alarms on one channel. The alarm still fired. The design tested "no mask bit is set" with if (~mask). That test is true for every mask except 1111.

mask!mask~maskif (!mask) runsif (~mask) runs
000011111yesyes
010101010noyes
100000111noyes
111100000nono

Measured on Icarus 12 and Verilator 5.052. ! asks one question about the whole value. ~ flips four bits.

Negate the Value, or Invert the Bits

! is the logical negate. It asks "is this value zero?" and answers with one bit. ~ is the bitwise invert. It flips each bit and returns a vector of the same width.

For a 1-bit signal the two agree. For a vector they do not. An if treats any non-zero vector as true, so if (~mask) asks "is at least one bit of mask 0?".

Two Operators, Two CircuitsArrows show the 4-bit mask moving through each test. Both end in one true/false bit.
  • I/O
  • Datapath
  • Result
  • Data
Two operators, two circuitsArrows show the 4-bit `mask` moving through each test. Both end in one true/false bit. io mask[3:0] 4 bits datapath Any bit 1? ! reduces first datapath Invert 1 bit the answer datapath Invert 4 bits ~ keeps the width datapath Any bit 1? the if reduces result True for 0000only no mask bit set result False for 1111only not every bit set !mask~mask
  1. io mask[3:0]4 bits
    • !mask → Any bit 1?
    • ~mask → Invert 4 bits
  2. datapath Any bit 1?! reduces first
    • Invert 1 bit
  3. datapath Invert 1 bitthe answer
    • True for 0000 only
  4. result True for 0000 onlyno mask bit set
  5. datapath Invert 4 bits~ keeps the width
    • Any bit 1?
  6. datapath Any bit 1?the if reduces
    • False for 1111 only
  7. result False for 1111 onlynot every bit set
  1. Negate

    !mask ORs the four bits into one, then inverts that bit. It is 1 only for 0000.

  2. Invert

    ~mask flips each bit. The if then asks whether any flipped bit is 1. Only 1111 gives 0000.

Read the diagram as text
  • mask[3:0]: 4 bits
  • Any bit 1?: ! reduces first
  • Invert 1 bit: the answer
  • Invert 4 bits: ~ keeps the width
  • Any bit 1?: the if reduces
  • True for 0000 only: no mask bit set
  • False for 1111 only: not every bit set
  • mask[3:0] → Any bit 1?: !mask
  • Any bit 1? → Invert 1 bit
  • Invert 1 bit → True for 0000 only
  • mask[3:0] → Invert 4 bits: ~mask
  • Invert 4 bits → Any bit 1?
  • Any bit 1? → False for 1111 only

On this flow each test is 3 cells and 2 levels. The cost is the same; the function is not.

Lint reports both spellings on a vector. For if (~mask) it says the if "expects 1 bit" where the invert "generates 4 bits". For !mask it says the same about the operand of !. A compare with zero, mask == '0, states the question and is silent in Lint.

Logical Operators Return One Bit

&& and || are logical operators. Each operand becomes one true/false bit first: true when any bit is 1. The result is one bit.

a = 0101, b = 1010ResultMeaning
a & b0000no bit position is 1 in both
a && b1both values are non-zero
a | b1111each position is 1 in at least one
a || b1at least one value is non-zero

Measured on Icarus 12. On this flow a && b and if (a & b) each build 7 cells and 3 levels, for two different functions.

Simulation also short-circuits these operators. In a && b, when a is false the answer is already known, so b is not evaluated. In a || b the same happens when a is true.

Simulation: the call can be skipped

function automatic logic in_range(input logic [3:0] v);
  seen = seen + 1;       // changes a variable outside
  return v < 4'd10;
endfunction

ok = 1'b0 && in_range(4'd3);   // not called
ok = 1'b1 || in_range(4'd3);   // not called
ok = 1'b0 &  in_range(4'd3);   // called

Icarus 12 and Verilator 5.052: after five such lines, two with &&, two with || and one with &, seen is 3. Two calls never ran.

Gates: both sides always exist

// The synthesizer builds the logic of in_range
// once per call site. Its gates are always there
// and always switching.
//
// If the function also updates other state,
// the gates update it on every cycle.

A function that only computes its return value is safe. One that changes outside variables can differ between simulation and gates.

SystemVerilog also has -> (implication) and <-> (equivalence). a -> b means !a || b. On this flow both simulate and both synthesize: 2 cells for the pair. Other synthesis tools may refuse them, so write the !a || b form in a design.

Equality and an Unknown

== and != compare 0s and 1s. If a bit is x or z and the answer depends on it, the result is x. === and !== compare all four values exactly, so their result is always 0 or 1.

v = 4'b10x1Icarus 12Why
v == 4'b1001xthe answer depends on the unknown bit
v != 4'b1001xthe same question, inverted
v == 4'b00010a known bit already differs
v < 4'd3, v > 4'd3xa relational operator with an unknown bit
v === 4'b10010x is not the same as 0
v === 4'b10x11every bit is identical, the x too
v ==? 4'b10x11an x or ? on the right is a wildcard
v ==? 4'b1?01xthe unknown is on the left, where it counts

Verilator 5.052 has no x: it prints 1 for the first row and 0 for the second.

An x result is neither true nor false, and an if takes its else branch for it. Lesson R10.5 shows how that hides an unknown.

8-bit operandsCellsLevels
a == b154
a === b154
a < b299
d ==? 8'b??1010??32

Measured on this flow. === builds the same gates as ==. A wildcard compare tests only the four named bits.

So === in a design buys nothing in the gates. In simulation it turns an unknown into a clean 0 or 1. Use == in RTL and keep === for the testbench.

Sets: inside and Wildcards

inside asks whether a value is in a set. The set can hold single values, ranges in square brackets, and patterns with ? for bits that do not matter.

Two sets on a 4-bit address.
assign hit  = addr inside {[3:7], 12};      // 3, 4, 5, 6, 7 or 12
assign page = addr inside {4'b1?0?};        // 8, 9, 12 or 13
addr0123456789101112131415
hit0001111100001000
page0000000011001100

Measured on Verilator 5.052 for every address. A range is a stretch of the number line; a wildcard pattern is a set of scattered points.

In gates a set is a few comparators with an OR behind them. On this flow addr inside {[3:7], 12} is 5 cells and 3 levels. The hand-written (addr >= 3 && addr <= 7) || addr == 12 is the same 5 cells.

The Lab: The Alarm That Ignored Its Mask

Design brief
PortDirectionWidthMeaning
maskinput[3:0]any bit set turns the alarms off
levelinput[3:0]the sensor level, 0 to 15
armedoutput11 when no bit of mask is set
alarmoutput11 when armed and level is 12 or more, or exactly 9
Latency
combinational: no clock and no reset
Corner cases
a mask with some bits set and some clear. Done when: Run shows armed=0 on the last three lines, and Lint is silent
  1. Run as shipped

    Lines 3 and 4 have a mask set and still show armed=1 alarm=1. Only the mask 1111 disarms the gate.

  2. Ask Lint

    Lint warns WIDTHTRUNC on the if: it "expects 1 bit" and the invert "generates 4 bits".

  3. Negate, then look again

    Write if (!mask) and Run. The three masked lines now show armed=0. Lint still warns, now about a 4-bit operand of !.

  4. State the question

    Write if (mask == 4'b0000). Run gives the same lines and Lint is silent.

  5. Check the gates

    Synthesize each version. All are 7 cells and 4 levels. The bug cost nothing and saved nothing; only the function changed.

Asked in interviews
  1. What is the difference between ! and ~?

    ! is a logical negate: it gives one bit, 1 when the whole value is zero. ~ inverts each bit and keeps the width. On a vector, if (~v) is true unless every bit of v is 1.

  2. What is the difference between == and ===?

    == returns x when an unknown bit decides the answer. === compares x and z as values and always returns 0 or 1. Synthesis builds the same comparator for both, so === belongs in testbenches.

  3. Does && short-circuit in hardware?

    No. Simulation skips the second operand when the first one settles the result. The gates for both operands always exist. The two differ only if the second operand is a function with side effects.

Try It

The bench applies five input sets. The first two have no mask, and both lines are right. Lines 3 and 4 have a mask bit set, yet the gate stays armed and the alarm fires.

~mask is 1010 for the mask 0101. That value is not zero, so the if runs. Only the mask 1111 inverts to 0000.

Synthesize reports 7 cells and 4 levels, with 0 flops and 0 latches.

RTLIcarus Verilog · in your browser · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: mask=0000 level=13 | armed=1 alarm=1 mask=0000 level=5 | armed=1 alarm=0 mask=0101 level=13 | armed=1 alarm=1 mask=1000 level=9 | armed=1 alarm=1 mask=1111 level=13 | armed=0 alarm=0

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

Read included file: tb.sv
`timescale 1ns/1ps
module tb;
  logic [3:0] mask = 0, level = 0;
  logic       armed, alarm;
  alarm_gate dut (.*);

  // Apply one input set, wait for the logic to settle, print the two outputs.
  task automatic show(input logic [3:0] m, input logic [3:0] l);
    mask = m; level = l;
    #1 $display("mask=%b level=%0d | armed=%b alarm=%b", mask, level, armed, alarm);
  endtask
  initial begin
    show(4'b0000, 4'd13);    // no mask, dangerous level
    show(4'b0000, 4'd5);     // no mask, safe level
    show(4'b0101, 4'd13);    // masked
    show(4'b1000, 4'd9);     // masked
    show(4'b1111, 4'd13);    // masked
    $finish(0);
  end
endmodule

Check Yourself

Predict the outputen is 4'b0110. The loop tests en[i] && tally(i) for i from 0 to 3, and tally counts its own calls. What does the bench print?
module tb;
  logic [3:0] en = 4'b0110;
  int         seen = 0;
  function automatic logic tally(input int i);
    seen = seen + 1;               // changes a variable outside the function
    return 1'b1;
  endfunction
  initial begin
    for (int i = 0; i < 4; i++)
      if (en[i] && tally(i)) ;     // nothing to do
    $display("seen=%0d", seen);
    $finish(0);
  end
endmodule
Spot the bugEach option is a testbench check: bad must be 1 when state is not one of the legal codes 01 and 10. The bench tries all four codes, then x1, which is not legal either. Which option fails?
ConceptA designer replaces a == b with a === b on two 8-bit buses "so the compare is never x". What does this flow build for the new line?
Predict the outputThe loop tries all 256 byte values against one set: a range, a wildcard pattern and a single value. This item runs on Verilator. What does it print?
module tb;
  logic [7:0] d;
  int         n = 0;
  initial begin
    for (int i = 0; i < 256; i++) begin
      d = i[7:0];
      if (d inside {[8'h10:8'h1f], 8'hf?, 8'h80}) n++;
    end
    $display("n=%0d", n);
    $finish(0);
  end
endmodule
ConceptA block holds if (valid && pop_fifo()), where the function pop_fifo also moves a read pointer. What can go wrong?

Common Mistakes

Wrong Join two vectors with && to test whether they share a set bit.

&& first reduces each vector to one true/false bit, so it is true whenever both are non-zero.

Fix AND the vectors bit by bit, then test the result: (a & b) != '0.

Before
if (pending && enabled)          // both non-zero
  irq = 1'b1;
After
if ((pending & enabled) != '0)   // a shared bit
  irq = 1'b1;

Wrong Compare a signal with a literal that holds an x, to mean "this bit does not matter".

In simulation == with an x bit is never true, while this flow built gates that ignore the bit.

Fix Use the wildcard equality ==? with a ? in the literal. Simulation and gates then agree.

Before
assign hit = (op == 4'b1x01);    // never 1 in simulation
After
assign hit = (op ==? 4'b1?01);   // bit 2 is not compared

Wrong Use === in a design so that the compare can never return x.

The gates compare 0 and 1 only, so the x-proof compare exists in simulation alone and hides unknowns.

Fix Use == and != in RTL. Keep === and !== for testbench checks.

Remember

  • ! asks whether the whole value is zero. ~ flips each bit. On a vector, if (~v) is true unless every bit is 1.
  • Test a vector with a comparison such as v == '0. Lint reports both if (~v) and !v on a vector.
  • && and || return one bit and skip their second operand in simulation when the first decides. Gates never skip.
  • == returns x when an unknown bit decides the answer. === never returns x, and builds the same gates as ==.
  • ==? and inside compare against wildcards, values and ranges, and build plain comparators.

Practice

Report a problem with this page