Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: An ALU and Exercises

Design a parameterized ALU with flags in VHDL using numeric_std, check it against a C reference model, then work through twelve practice exercises with hints.

This closing lesson has two parts. First, a small project, an arithmetic logic unit (ALU) with status flags, shows how a complete combinational block is written, checked and extended. Second, a set of exercises lets you practice everything in the chapters on finite state machines, testbenches, synthesis and design patterns, with hints for each.

VHDL listings are read-only on this site (no simulator available); the C programs are runnable reference models, which is exactly how many real teams check hardware: a "golden model" in software and a testbench that compares the two.

The ALU specification

An 8-bit ALU with two operands a and b, a 3-bit operation code op, a result y and four flags:

op Operation Result
000 ADD a + b
001 SUB a - b
010 AND a and b
011 OR a or b
100 XOR a xor b
101 SHL a shifted left by 1
110 SHR a shifted right by 1 (logical)
111 SLT 1 if a < b (signed), else 0

Flags: Z (result is zero), N (result negative, MSB set), C (carry or no-borrow out of the top bit for add/sub, last bit shifted out for shifts), V (signed overflow for add/sub).

The VHDL

VHDL
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity alu is
  generic (W : positive := 8);
  port (a, b : in  std_logic_vector(W-1 downto 0);
        op   : in  std_logic_vector(2 downto 0);
        y    : out std_logic_vector(W-1 downto 0);
        z, n, c, v : out std_logic);
end entity;

architecture rtl of alu is
begin
  process (a, b, op)
    variable ua, ub : unsigned(W-1 downto 0);
    variable wide   : unsigned(W downto 0);     -- one extra bit for carry
    variable r      : unsigned(W-1 downto 0);
    variable cf, vf : std_logic;
  begin
    ua := unsigned(a);  ub := unsigned(b);
    wide := (others => '0');
    cf := '0';  vf := '0';
    case op is
      when "000" =>                                   -- ADD
        wide := ('0' & ua) + ('0' & ub);
        r := wide(W-1 downto 0);  cf := wide(W);
        vf := (ua(W-1) xnor ub(W-1)) and (ua(W-1) xor r(W-1));
      when "001" =>                                   -- SUB
        wide := ('0' & ua) + ('0' & (not ub)) + 1;
        r := wide(W-1 downto 0);  cf := wide(W);      -- C = 1 means no borrow
        vf := (ua(W-1) xor ub(W-1)) and (ua(W-1) xor r(W-1));
      when "010" => r := ua and ub;
      when "011" => r := ua or ub;
      when "100" => r := ua xor ub;
      when "101" => r := shift_left(ua, 1);   cf := ua(W-1);
      when "110" => r := shift_right(ua, 1);  cf := ua(0);
      when others =>                                  -- SLT (signed)
        r := (others => '0');
        if signed(a) < signed(b) then r(0) := '1'; end if;
    end case;
    y <= std_logic_vector(r);
    z <= '1' when r = 0 else '0';
    n <= r(W-1);
    c <= cf;
    v <= vf;
  end process;
end architecture;

Why it is written this way:

  • Variables inside the process hold intermediate values; they are assigned and read in order. They do not create flip-flops because the process has no clock, and every output is assigned on every path (defaults for cf, vf, and the others branch), so there are no latches (inferred hardware).
  • A carry bit from a wider vector: extending the operands by one bit makes the top bit of the sum the carry.
  • Subtraction as addition: a - b = a + (not b) + 1, the same circuit a real adder uses. The carry then means no borrow.
  • Signed overflow rule: for addition, overflow happens when both operands have the same sign and the result has a different sign. For subtraction, when the operands have different signs and the result's sign differs from a.
  • The generic W makes the ALU any width without code changes.

The golden model in C

This C program implements the same table independently and prints the flags for a handful of operations, including the classic traps: 127 + 1 overflowing in signed arithmetic and 0 - 1 borrowing.

C C stand-in: ALU reference model with flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check by hand: 127 + 1 = 128 sets N and V (signed overflow) but not C; 255 + 1 = 0 sets Z and C but not V (as unsigned it carried, as signed it is -1 + 1 = 0, no overflow); 0 - 1 clears C (a borrow occurred); 0xFF < 1 is true when both are signed (-1 < 1).

Exhaustive testing

An 8-bit ALU has 2^8 x 2^8 x 8 = 524,288 input combinations: small enough to test all of them. A testbench can loop through all combinations and compare each output with a golden model. The same idea in C, comparing two independent implementations of an operation, shows how little code it takes:

C C stand-in: exhaustive check of two implementations of SUB

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

For wider datapaths exhaustive testing is impossible; you switch to directed corner cases plus random vectors, as in the testbench lessons.

Practice exercises

Work through these on your own tools (GHDL is free), then compare ideas with the hints.

Finite state machines

  1. Vending machine. Accepts 5 and 10 cent coins, dispenses at 15 cents, no change returned. Hint: states are the amount so far (0, 5, 10); Mealy output on the transition that reaches 15.
  2. Detect 110 with overlap. Hint: build the table the way the 1011 detector was built: states record the longest matching prefix.
  3. One-hot recoding. Take the traffic light FSM and give states as one-hot constants. Hint: declare std_logic_vector(5 downto 0) constants and add when others to return to ALL_RED_1.

Testbenches

  1. Self-checking ALU test. Loop through all operand pairs for ADD and compare with a behavioral reference using +. Hint: use a nested for loop with to_unsigned.
  2. Count protocol violations. A FIFO testbench that counts "write while full" and "read while empty" attempts and asserts the FIFO ignores them.

Synthesis and timing

  1. Find the critical path. A design computes y = a*b + c*d. Rewrite it with two pipeline stages. Hint: register the products, then the sum.
  2. Remove the latch. A combinational process contains if en = '1' then q <= d; end if; and the synthesis report warns about an inferred latch. Fix it two ways: (a) it was meant to be combinational, so give q a default value or an else branch; (b) it was meant to hold a value, so move it into a clocked process (rising_edge(clk)).
  3. Counter size. How many bits does a counter need for a 250 ms delay at 48 MHz? Compute and write the generic. (Answer below.)

Design patterns

  1. Debouncer. Input must be stable for 20 ms at 100 MHz. Choose the counter width.
  2. Handshake adapter. Insert a one-word register slice that follows ready/valid rules without losing throughput. Hint: decide when the slice is "full", and let it accept a new word while sending the old one if the consumer is ready.
  3. Gray counter. Convert a binary counter to Gray code with one XOR per bit: gray = bin xor (bin shifted right by 1).
  4. PWM. A counter compared with a duty-cycle register produces a PWM output; make duty updates take effect only at the start of a period to avoid glitches.
C C stand-in: answers to exercises 8, 9 and 11

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The answers: 12,000,000 cycles need a 24-bit counter (2^24 = 16,777,216), 2,000,000 cycles need 21 bits, and the 3-bit Gray sequence is 000 001 011 010 110 111 101 100, one bit changing per step.

Where to go next

You now know the whole VHDL flow: describe the hardware, check it in simulation, synthesize it and make it fast and robust. Good next steps are a real board (a $30-100 FPGA kit), the open-source GHDL + Yosys + nextpnr toolchain, a soft CPU core, a VGA or HDMI video generator and the VHDL-2008 features such as process (all), generic types and to_string. Return to the VHDL track page at any time to review a chapter.

When you start your own designs, begin with a golden model and a testbench, then add the VHDL. A design that has a trustworthy testbench is nearly always finished sooner than one written first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the ALU, why is subtraction implemented as a + (not b) + 1?

    Two's complement negation is invert and add one, so one adder handles both operations.
  2. 2. When does signed overflow happen on an addition?

    Adding two positives that gives a negative (or two negatives that give a positive) means the signed result does not fit.
  3. 3. Why can the 8-bit ALU be tested exhaustively?

    524,288 combinations run in a moment in simulation, so every case can be compared with the golden model.
  4. 4. Why are the intermediate values in the ALU process variables?

    Variables inside a combinational process are scratch values; every output signal is still assigned on every path.

Summary

  • An ALU is a combinational block: a case on op, a carry bit from a one-bit-wider sum, and flags Z, N, C, V.
  • Subtraction reuses the adder as a + not b + 1; overflow follows the sign rules.
  • A software golden model lets a testbench compare results; small datapaths can be tested exhaustively.
  • The exercises cover FSMs, testbenches, timing, latches, debouncing, handshakes, Gray code and PWM.
  • Next steps: a real board, GHDL and an open-source flow, then VHDL-2008 features.

Next: Back to the VHDL track