The idea: a datapath that computes and a controller that decides

A circuit that runs an algorithm over many clock cycles is built from two parts. The datapath holds the numbers and does the arithmetic: registers, muxes, adders, comparators. The controller is a finite state machine that says, in every cycle, which register loads and which mux input is chosen. The controller sends control signals down to the datapath and gets status signals back. It never sees the numbers themselves, only bits like "A is bigger than B".

The page builds one such design for the greatest common divisor and runs it one clock at a time. The ASMD chart on the left is the controller's plan, the datapath on the right does the work, and the Verilog at the bottom is the same design as code. In each cycle the page lights the current state, the path through the chart, the signals that are 1, the wires in use and the lines of code that act.

The controller FSM on the left with states IDLE, CMP, SUBA, SUBB, DONE sends ldA, ldB, selA and selB to the datapath on the right and gets a_gt_b and a_eq_b back. The datapath holds registers A and B, two muxes, the subtractors and a comparator. start goes into the controller, a_in and b_in into the datapath; done comes out of the controller and gcd out of the datapath
Control signals go down, status signals come back up: the controller only knows "greater" and "equal", never the numbers.

Euclid by subtraction

If A > B, every number that divides both A and B also divides A − B. So you can replace the bigger number by the difference and the GCD does not change. Repeat until the two are equal; that value is the GCD:

while (A != B)
    if (A > B) A = A - B;
    else       B = B - A;
gcd = A;

For 48 and 18 the pairs are 48, 18 → 30, 18 → 12, 18 → 12, 6 → 6, 6. Software would use the remainder % instead, but a divider is big in hardware and a subtractor is small. Euclidean Algorithm page has the mathematics; this page is about the hardware.

The ASMD chart

An ASM chart (algorithmic state machine) is a flowchart for an FSM. An ASMD chart (ASM with datapath) also writes the register transfers into it. It has three kinds of box:

  • A state box (rectangle) is one state, so one clock cycle. Its name is beside it. Inside go the transfers and signals of that state, like A ← A − B in SUBA or done = 1 in DONE. They are Moore outputs: they depend only on the state.
  • A decision box (diamond) tests one input or status bit and has a 0 exit and a 1 exit. CMP has two in a row: first a_eq_b, then a_gt_b.
  • A conditional output box (rounded, here green) sits on one exit of a decision. Its transfers happen only on that path, so they are Mealy outputs. Under IDLE, A ← a_in, B ← b_in happens only when start = 1.

One state box with all the decisions and conditional boxes under it, down to the next state boxes, is an ASM block. All of a block happens in the same clock cycle: the decisions are wires, not steps. That is why CMP takes one cycle although it holds two diamonds.

The three ASMD symbols: a state box CMP, a decision diamond with 0 and 1 exits, and a rounded conditional output box. On the right, the IDLE ASM block: the state box, the start diamond, the conditional box A gets a_in and B gets b_in on the 1 exit, and the loop back to IDLE on the 0 exit, all inside one dashed frame labelled one clock cycle; the transfers land at the rising edge at the bottom of the block
An ASM block is one clock cycle: the decisions happen at once, and the transfers land at the edge that leaves the block.

When a register transfer happens

A ← A − B in SUBA does not change A at the start of SUBA. During the cycle the subtractor computes A − B, the mux passes it, and it waits at the register's input. A takes the new value at the rising edge that ends the cycle, at the same moment the state register goes to CMP. So CMP is the first cycle that sees the new A. (Demo: one SUBB cycle up close: in cycle 7 the box says B ← B − A, the subtractor already shows 6, and B is still 18; B becomes 6 only at the edge.)

This also explains why the chart needs CMP at all. The decisions about A and B must look at values that have already landed. If SUBA tested a_gt_b itself, it would test the old A, from before its own subtraction.

The datapath, signal by signal

  • muxA: selA = 0 passes a_in, selA = 1 passes A − B. muxB does the same with b_in and B − A.
  • Registers A and B load their mux output at the rising edge when ldA (or ldB) is 1, and hold otherwise.
  • Two subtractors, A − B and B − A, always compute, even when nobody uses the result. In SUBB the page shows A − B = 250 for 12 − 18: in 8 bits the negative result wraps around. It does no harm, because ldA = 0. A design with one shared subtractor would need two more muxes to swap its inputs.
  • The comparator gives the status bits a_gt_b = (A > B) and a_eq_b = (A == B). The output is gcd = A, valid while done = 1.

Each state box becomes one row of a control table. This table is the whole controller:

StateTransferSignals that are 1Next state
IDLEif start: A ← a_in, B ← b_inldA, ldB when start = 1start ? CMP : IDLE
CMPnonenonea_eq_b ? DONE : a_gt_b ? SUBA : SUBB
SUBAA ← A − BldA, selACMP
SUBBB ← B − AldB, selBCMP
DONEgcd = AdoneIDLE

How a state register and next-state logic turn such a table into gates is on Finite State Machines. A processor's control unit is the same idea with more states and signals; see The Multicycle MIPS Processor.

Cycle by cycle: gcd(48, 18)

The values are the ones A and B hold during the cycle. (Demo: gcd(48, 18) to done.)

CycleStateABSignals = 1At the edge
1IDLExxldA, ldBA = 48, B = 18
2CMP4818none (a_gt_b = 1)→ SUBA
3SUBA4818ldA, selAA = 30
4CMP3018none (a_gt_b = 1)→ SUBA
5SUBA3018ldA, selAA = 12
6CMP1218none (a_gt_b = 0)→ SUBB
7SUBB1218ldB, selBB = 6
8CMP126none (a_gt_b = 1)→ SUBA
9SUBA126ldA, selAA = 6
10CMP66none (a_eq_b = 1)→ DONE
11DONE66done→ IDLE

A is x in cycle 1: the registers have never loaded. The first four clocks end in SUBA with A = 30, B = 18 (Demo: gcd(48, 18), the first 4 clocks).

How many cycles?

With k subtractions the run takes one load cycle, a CMP and a SUB cycle per subtraction, a last CMP and DONE: 2k + 3 cycles until done = 1. The time depends on the data, not only on the size of the numbers:

InputsSubtractionsdone = 1 in cyclegcd
7, 7037
48, 184116
13, 85131
36, 48194
0, 5never endsnevernone

13 and 8 are neighbouring Fibonacci numbers, so every step takes away little and the result is 1 (Demo: gcd(13, 8), coprime, result 1). 36 and 4 are worse: 36 − 4 − 4 … takes 8 subtractions where one remainder would do (Demo: gcd(36, 4), lopsided and slow). Equal inputs finish at once, in cycle 3 (Demo: gcd(7, 7), equal inputs).

A zero input is a real bug. With A = 0, CMP finds a_gt_b = 0 and a_eq_b = 0 every time, and SUBB does B ← B − 0, so B stays 5 and the loop never ends (Demo: gcd(0, 5) never finishes, which stops after 20 cycles). The fix belongs in the chart: one more decision box under IDLE that sends a zero input straight to DONE.

You can also save cycles by moving the subtraction into CMP as conditional boxes: under a_gt_b = 1 put A ← A − B and stay in CMP. Then each subtraction costs one cycle, not two, and gcd(48, 18) is done in cycle 7 (k + 3). The price is a Mealy controller: its outputs now depend on the status bits within the same cycle, so the path from the registers through the comparator and the controller back to the load enables gets longer.

Two charts side by side. Left, the page's chart: CMP, then SUBA or SUBB, then back to CMP, 2 cycles per subtraction, done in cycle 11 for 48 and 18. Right, a three-state chart: IDLE, CMP with conditional boxes A gets A minus B and B gets B minus A under the a_gt_b exits that loop back to CMP, and DONE: 1 cycle per subtraction, done in cycle 7
Conditional boxes let one state test and subtract in the same cycle: 7 cycles instead of 11 for gcd(48, 18).

The same design in Verilog

The datapath is one always_ff for the two registers plus three assign lines. Each if (ldA) A <= selA ? A - B : a_in; is a mux and a register with a load enable. The controller is a state register in always_ff and an always_comb that sets every output to 0 first and then switches on the state. Each case arm is one ASM block: the state box's signals, then the decisions as ifs that set next.

module gcd(input  logic clk, reset, start,
           input  logic [7:0] a_in, b_in,
           output logic done,
           output logic [7:0] gcd);
  logic ldA, ldB, selA, selB, a_gt_b, a_eq_b;
  gcd_dp   dp(.*);
  gcd_ctrl ctrl(.*);
endmodule

The top module wires the two together: .* connects every port to the signal with the same name. Setting every output to 0 at the top of always_comb matters: a signal not assigned in some arm would otherwise turn into a latch, as From Verilog to Hardware shows. The three-block style for the controller itself is on An FSM in SystemVerilog, and a testbench that would run this design is on A Self-Checking Verilog Testbench.

See also Multiply and Divide Hardware for a shift-and-add multiplier, another datapath driven by a small controller.

What the page leaves out

The page runs one fixed design with a hand-written model of it; it does not parse or simulate the Verilog. No Verilog tool was available while the page was built, so the cycle trace comes from a separate small Python model of the same chart. Left out: the handshake that holds done until the user takes the result, checking inputs for zero, the remainder-based and binary (Stein's) GCD datapaths, sharing one subtractor between A and B, timing of the comparator path and the clock period, reset of the datapath registers, and the gate-level synthesis of the controller.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OLatches and flip-flopsLatches and flip-flopslatch is level, flip-flop is edgeFlip-flops and counter designFlip-flops and counter designexcitation = characteristic backwardsLatch from transistorsLatch from transistorstransmission gates plus inverter loopCMOS layout, DRC, LVSCMOS layout, DRC, LVSDRC: can it be built? LVS: right circuit?Timing analysisTiming analysissetup limits clock, hold limits short pathsAsync FIFO (CDC)Async FIFO (CDC)Gray pointers cross; flags clear lateStuck-at fault testingStuck-at fault testingActivate, propagate, justify: D-algorithmStatic Timing AnalysisStatic Timing AnalysisSlack = required − arrival, every nodeLogical effort sizingLogical effort sizingd = gh + p; equal effort F^(1/N)Scan chainsScan chainsShift in, capture once, shift outFinite state machinesFinite state machinesMoore: output from state; Mealy: +inputsASMD chart and datapathTransfers land at the edge leaving the state1011 Sequence Detector1011 Sequence DetectorA wrong bit keeps the longest prefixFSM in SystemVerilogFSM in SystemVerilogenum, always_ff, always_comb; default!Shift registers and countersShift registers and countersChained flip-flops shift or count each clockOpen the Computer Architecture mind mapComputer Architecturestate held by a clockSequential logicLatches and flip-flopsLatches and flip-flopslatch is level, flip-flop is edgeFlip-flops and counter designFlip-flops and counter designexcitation = characteristic backwardsLatch from transistorsLatch from transistorstransmission gates plus inverter loopCMOS layout, DRC, LVSCMOS layout, DRC, LVSDRC: can it be built? LVS: right circuit?Timing analysisTiming analysissetup limits clock, hold limits short pathsAsync FIFO (CDC)Async FIFO (CDC)Gray pointers cross; flags clear lateStuck-at fault testingStuck-at fault testingActivate, propagate, justify: D-algorithmStatic Timing AnalysisStatic Timing AnalysisSlack = required − arrival, every nodeLogical effort sizingLogical effort sizingd = gh + p; equal effort F^(1/N)Scan chainsScan chainsShift in, capture once, shift outFinite state machinesFinite state machinesMoore: output from state; Mealy: +inputsASMD chart and datapathTransfers land at the edge leaving the state1011 Sequence Detector1011 Sequence DetectorA wrong bit keeps the longest prefixFSM in SystemVerilogFSM in SystemVerilogenum, always_ff, always_comb; default!Shift registers and countersShift registers and countersChained flip-flops shift or count each clock
This page on the Computer Architecture mind map · 76 pages in 7 branches · open it to see the whole map and test yourself in recall mode.