The ALU, the arithmetic logic unit, is the block of the core that computes: it takes two 32-bit operands and an operation code and produces one 32-bit result. Almost every instruction passes through it, including many that do not look like arithmetic, such as loads, stores and jumps, which use it to add an address. This article specifies the ALU you write in exercises E01 and E02: its ports, the ten operations and their codes, the two details that catch most people (shift amounts and signed comparisons), and how the hidden tests check your work.

13 min read | Beginner to Intermediate

What You'll Learn

  • List the ten ALU operations of RV32I and the code of each
  • Explain how one adder computes both addition and subtraction
  • Explain why shifts use only five bits of the second operand and how arithmetic and logical right shifts differ
  • Distinguish signed from unsigned comparison and write an ALU that passes E01 and E02

Before You Start

You write this block in Verilog, so you need the basics: modules, ports, case statements and combinational always blocks. If they are new, the Verilog Tutorial comes first.

Read The Core's Specification for the coding rules and the fixed ALU codes. Two articles from the first half of the tutorial explain the ideas used here: Numbers in Hardware (two's complement, sign extension and overflow) and Arithmetic, Logic and Immediates (the RV32I instructions that use the ALU). This is the first exercise, so nothing needs to be passed before it.

What the ALU Does in the Core

An ALU is pure combinational logic: its output depends only on its current inputs, with no clock and no memory. Change an operand, and the result changes a moment later, after the delay of the gates in between. That makes it simple to specify: for every combination of inputs, there is exactly one right output.

In the core, the decoder decides what the ALU computes for each instruction, and the multiplexers in front of it decide which two values it computes with. Many instructions use it for addition, which is why ADD is the most common operation by far:

Instruction kindOperand aOperand bOperationThe result is
add, sub, and, or, ... (register-register)rs1rs2from funct3 and funct7the value for rd
addi, andi, slli, ... (register-immediate)rs1immediatefrom funct3the value for rd
lw, sb and the other loads and storesrs1immediateADDthe memory address
jalrrs1immediateADDthe jump target
auipcPCimmediateADDPC plus the upper immediate
luizeroimmediateADDthe upper immediate itself

Branches do not use the ALU in this core: they have their own comparator, Branches and Jumps, so that a branch can compare two registers while the ALU is free. The ALU does not know any of this. It sees op, a and b, and produces y.

The Ports and the Operations

The module name and ports are fixed. This is the starter's header:

module cvr32_alu (
    input  logic [3:0]  op,      // operation code, see the table
    input  logic [31:0] a,       // first operand
    input  logic [31:0] b,       // second operand
    output logic [31:0] y        // result
);

And the ten operations, with the codes the decoder uses:

opNamey
0ADDa + b
1SUBa - b
2SLLa shifted left by b[4:0], zeros shifted in
3SLT1 if a is less than b as signed numbers, else 0
4SLTU1 if a is less than b as unsigned numbers, else 0
5XORa XOR b, bit by bit
6SRLa shifted right by b[4:0], zeros shifted in
7SRAa shifted right by b[4:0], copies of bit 31 shifted in
8ORa OR b, bit by bit
9ANDa AND b, bit by bit

The codes 10 to 15 are never sent. The tests do not check them, but your ALU must still give y some value for them, as the next section explains. E01 covers the five operations that need no special care (ADD, SUB, XOR, OR, AND); E02 adds the shifts and comparisons.

How the ALU Is Built

A useful way to think about an ALU is as several small function units that all compute at once, with a multiplexer at the end that picks the result the operation code asks for:

Illustration: operands a and b feed four function units, an adder that also subtracts, a shifter, a comparator and a logic unit, and a multiplexer controlled by the operation code op selects one of their results as y.

In Verilog you rarely build it unit by unit. A case statement on op inside a combinational block, with one line per operation that computes the result with Verilog's own operators, describes the same thing, and the synthesis tool turns it into adders, shifters and multiplexers. What matters is that the description is complete: every op value, including the unused ones, must assign y. If some value of op leaves y unassigned, the tools assume y should keep its previous value and build a latch, a storage element that has no place in an ALU. A default branch in the case, or a default assignment before it, prevents that.

Two of the units deserve a closer look, because they show how hardware saves work.

One adder for two operations. In two's complement, -b equals NOT b plus 1. So a - b is a + (NOT b) + 1: the same adder, with b inverted and a carry of 1 into the lowest bit. Hardware ALUs are often built this way, with one adder and a few XOR gates in front of it. You do not have to build it like that; writing a - b lets the tool choose. But it explains why subtraction costs almost nothing extra, and why the result of both wraps around in the same way: 0x0000_0000 - 1 is 0xFFFF_FFFF, and 0xFFFF_FFFF + 1 is 0x0000_0000. RISC-V has no carry or overflow flags; a program that needs to detect overflow checks the result with other instructions (Arithmetic, Logic and Immediates shows how).

Logic operations are 32 copies of one gate. AND, OR and XOR work on each bit position independently: bit 7 of the result depends only on bit 7 of a and bit 7 of b. They are the cheapest part of the ALU.

Quick Check

Q: What does your ALU return for SUB with a = 0x0000_0005 and b = 0x0000_0007, and for ADD with a = 0x7FFF_FFFF and b = 0x0000_0001?

Show Answer

5 - 7 = -2, which in 32-bit two's complement is 0xFFFF_FFFE. 0x7FFF_FFFF + 1 = 0x8000_0000: the largest positive signed number plus one wraps to the most negative one. The ALU reports nothing about it; there are no flags.

Shifts

A shift moves every bit of a left or right by some number of positions. Shifting left by n multiplies by 2 to the power n (as long as nothing falls off the top), which is why compilers use it for multiplying by constants and for computing array addresses.

The number of positions comes from b, but only its low 5 bits count. A 32-bit value can be shifted by 0 to 31 positions, and 5 bits hold exactly that range, so RV32I defines the shift amount as b[4:0] and ignores the other 27 bits. A shift by 37 is a shift by 5, because 37 is 100101 in binary and its low 5 bits are 00101. This matters for the register forms sll, srl and sra, where the amount comes from a register that can hold any value; for the immediate forms the decoder sends an immediate whose low 5 bits are the shift amount. Verilog's shift operators shift by the whole value of their right operand, so a shift by 37 in plain Verilog gives 0. Use the low 5 bits explicitly.

Right shifts come in two kinds. A logical shift right (SRL) fills the vacated top bits with zeros: it treats the value as unsigned. An arithmetic shift right (SRA) fills them with copies of bit 31, the sign bit, so a negative number stays negative. 0x8000_0000 shifted right by 4 is 0x0800_0000 with SRL, but 0xF800_0000 with SRA. Arithmetic shift right by n divides a signed number by 2 to the power n, rounding toward minus infinity, which is what compilers use it for. In Verilog, the arithmetic shift operator >>> copies the sign bit only when its left operand is signed; on a plain logic vector it behaves like >>. Marking the operand with $signed(...) is the usual way to make it arithmetic.

Signed and Unsigned Comparison

SLT and SLTU both answer "is a less than b?" with 1 or 0 in bit 0 and zeros in the other 31 bits. They differ in how they read the bits. Take a = 0xFFFF_FFFB and b = 0x0000_0005. Read as signed numbers, a is -5 and b is 5, so a is less: SLT gives 1. Read as unsigned numbers, a is 4,294,967,291 and b is 5, so a is not less: SLTU gives 0. The same 32 bits, two different answers, and both are right for their instruction.

C compilers choose between the two by the type of the variables: int comparisons use the signed forms, unsigned comparisons and pointer comparisons the unsigned ones. An ALU that mixes them up runs most programs correctly and fails on the first comparison that involves a negative number, which is the kind of bug that is hard to find later. In Verilog, a comparison of two logic vectors is unsigned; $signed(a) < $signed(b) makes it signed.

Quick Check

Q: a = 0x8000_0000 and b = 0x0000_0001. What do SLT and SLTU return, and what does SRA with this b return?

Show Answer

As a signed number, a is the most negative 32-bit value, so a is less than 1: SLT returns 1. As an unsigned number, a is 2,147,483,648, larger than 1: SLTU returns 0. SRA by 1 keeps the sign bit and gives 0xC000_0000.

How It Is Tested

The ALU is tested on its own, with a testbench that drives op, a and b, waits a moment for the combinational logic to settle and compares y with a model of the correct result. For every operation it tries every pair of ten corner values (0, 1, -1, the largest and smallest signed numbers, the shift amounts 31, 32 and 37, and a few others) and then several hundred random pairs, a third of them with small values of b so that shifts by every amount are covered. That is 2,000 checks for E01, and 2,000 more for the shifts and comparisons in E02, where the E01 checks are run again so a change to your shifts cannot quietly break your adder.

When a check fails, the test prints the operation, the operands, the expected and the actual result, for up to ten failures. This is the message a common mistake produces:

Output
FAIL: sra a=0xffffffff b=0x00000001: expected 0xffffffff, got 0x7fffffff

The ALU shifted a zero into bit 31 instead of a copy of the sign bit: it computed SRL where SRA was asked. The test suite was checked against that mistake and others like it (an unsigned SLT, a signed SLTU, a shift that uses all 32 bits of b, SUB computed as ADD, XOR or AND computed as OR): every one of them fails at least one check.

Where Does This Matter?

The 32-bit adder inside the ALU is often on the longest path of a simple core: the slowest chain of logic between two registers, which sets the clock frequency. Clocks, Cycles and Time measures how its delay grows with its width. Real designs spend a lot of effort on fast adders for that reason, and the synthesis tool picks a fast adder structure for you from the same a + b you write.

Common Mistakes

Mistake #1: An arithmetic shift that is really logical

a >>> n on an unsigned vector shifts in zeros. Unless the left operand is signed, SRA silently becomes SRL, and only negative values show the difference.

Mistake #2: Comparing signed values as unsigned (or the other way)

Plain a < b on logic vectors is an unsigned comparison: right for SLTU, wrong for SLT. Check both instructions with one negative operand before you submit.

Mistake #3: Shifting by the whole of b

Writing the shift with all 32 bits of b gives 0 for every shift amount of 32 or more, but RV32I shifts by b[4:0]. A shift by 37 must give the same result as a shift by 5.

Your Turn in the Lab

Both exercises open with a visible test, testbench.v, next to your design: a short list of directed checks that prints ok or FAIL for each. Simulate it as you work and add your own checks to it. When you submit, it runs together with the hidden tests, and your edits to it do not change the grading.

Write cvr32_alu in two steps.

  1. E01: ADD, SUB, XOR, OR and AND, with a default for every other code. Submit, and fix anything the messages point at.
  2. E02: start from your E01 solution and add SLL, SLT, SLTU, SRL and SRA. The E01 operations are tested again.

Keep the passed version in your project as cvr32_alu.sv; the core exercises need it from E07 on.

Open exercise E01 in ChipVerify Lab Open exercise E02 in ChipVerify Lab

Summary

  • The ALU is combinational: from op, a and b it produces one 32-bit result y, with ten operations coded 0 to 9 and a defined value for every other code.
  • The core uses ADD not only for add instructions but for every load and store address, the jalr target, auipc and lui.
  • Subtraction is addition of the inverted operand plus one; results wrap around in 32 bits and there are no flags.
  • Shifts use only b[4:0]; SRL shifts in zeros and SRA copies the sign bit, which in Verilog needs a signed left operand.
  • SLT compares as signed numbers and SLTU as unsigned; the same bits can give opposite answers, so both are tested with negative values.
Did you find what you were looking for?

Quiz

No quiz questions available for this article.