Skip to content
LumenaryAcademy
Foundations 55 min

Registers and arithmetic

The sixteen general-purpose registers, their 32-, 16- and 8-bit names, and the instructions that add, multiply, divide and shift.

Code tested · 4AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

A handful of very fast boxes

High-level languages let you create as many variables as you like. A processor does not work that way. Inside the chip there are a few small storage slots called registers, each holding one number, and almost every instruction reads its inputs from registers and writes its result to one. Memory is enormous by comparison (billions of bytes), but reaching it takes far longer than reaching a register, often a few nanoseconds when the data is in a cache and around a hundred when it is not, against well under a nanosecond for a register.

So the central skill of assembly programming, and the central job of a compiler's back end, is register allocation: deciding which values live in registers at each moment, and which must wait in memory. In this lesson you learn the registers of x86-64, the rules for using parts of them, and the arithmetic instructions that work on them. By the end you will compute a number and print it in decimal, digit by digit, because no print function is coming to help.

DefinitionsH

The x86-64 registers

Definition— general-purpose register

A general-purpose register is a 64-bit storage slot inside the processor that instructions can use for any integer or address. x86-64 has sixteen of them.

Their names are a museum of x86 history. The first eight come from the 16-bit 8086 of 1978, where each had a special job; AMD added eight more, simply numbered, when it created x86-64:

64-bitTraditional meaning of the nameConventional use on Linux today
raxaccumulatorreturn value; system-call number
rbxbaseany value that must survive function calls
rcxcounter4th function argument; shift counts go in its low byte cl
rdxdata3rd argument; high half of multiply and divide
rsisource index2nd argument
rdidestination index1st argument
rbpbase pointeroptional frame pointer, otherwise a general register
rspstack pointerthe top of the stack: never use it for anything else
r8–r15(new in x86-64)r8, r9: 5th and 6th arguments; the rest general

The "conventional use" column is not enforced by the processor (apart from rsp and a few instructions such as div and shifts by cl). It comes from the calling convention, the agreement that lets separately written functions cooperate, which lesson 5 covers in full. For now, treat the registers as sixteen boxes and leave rsp alone.

Smaller views of the same register

Each register can also be used at smaller widths. These are not separate registers: they are names for the low part of the same 64 bits.

64 bitslow 32low 16low 8
raxeaxaxal (and ah, bits 8–15)
rbxebxbxbl
rcxecxcxcl
rdxedxdxdl
rsiesisisil
rdiedididil
rbpebpbpbpl
rspespspspl
r8 … r15r8d … r15dr8w … r15wr8b … r15b

The rule for writing to a smaller part is the most important detail on this page:

Definition— zero extension on 32-bit writes

Writing a 32-bit register (such as eax) sets the upper 32 bits of the full register to zero. Writing a 16-bit or 8-bit register (such as ax or al) changes only those bits and leaves the rest unchanged.

The 32-bit rule exists for speed: if a write to eax kept the old upper half, every such instruction would depend on whatever wrote rax before, which would slow down the processor's out-of-order machinery. It is also why compilers write mov eax, 1 rather than mov rax, 1 for small constants: same effect, one byte shorter.

Besides these sixteen there are rip, the address of the next instruction, which you cannot write directly but can use for addressing (as in [rip + msg]); rflags, a register of single-bit flags set by arithmetic (lesson 4); and the vector registers xmm0–xmm15 (wider ymm and zmm versions on processors with AVX), used for floating-point numbers and for processing several values at once.

How instructions are written

An Intel-syntax instruction is a mnemonic followed by operands, destination first:

asm
        mov     ecx, 10          # ecx = 10           (register, immediate)
        add     eax, ecx         # eax = eax + ecx    (register, register)
        add     eax, [rip + n]   # eax = eax + the 4 bytes at n   (register, memory)
        imul    eax, ecx, 3      # eax = ecx * 3      (three-operand form)

An operand is a register, an immediate (a constant written in the instruction), or a memory location in square brackets. At most one operand may be in memory. Most immediates are at most 32 bits, sign-extended to 64; the one exception is mov into a 64-bit register, which accepts a full 64-bit constant. Both operands must have the same width: add rax, ecx is an error.

ComputationC

Arithmetic, and printing the answer

The basic arithmetic instructions are:

InstructionEffect
add a, b / sub a, ba = a + b / a = a - b
inc a / dec aa = a + 1 / a = a - 1
neg aa = -a (two's complement)
imul a, b / imul a, b, imma = a * b / a = b * imm (signed; low half of the product)
mul brdx:rax = rax * b (unsigned, full double-width product)
div b / idiv bdivide rdx:rax by b: quotient to rax, remainder to rdx (unsigned / signed)

With 32-bit operands, the same instructions use eax and edx instead.

Notice that div is unusual. It does not take two operands: it always divides the double-width number formed by rdx (high half) and rax (low half), written rdx:rax. So before dividing an ordinary number you must make the high half correct: xor edx, edx (zero) for unsigned division, or cqo (copy the sign of rax into every bit of rdx) before idiv for signed division.

Division is how we print. A number like 42 must become two characters, '4' (code 52) and '2' (code 50). Dividing by 10 gives the tens digit as the quotient and the units digit as the remainder, and adding the code of '0' (48) to a digit gives its character. This program computes 7 × 6 and prints the answer:

asm
        .intel_syntax noprefix

        .section .bss
out:    .skip 3                     # room for two digits and a newline

        .text
        .globl _start
_start:
        mov     eax, 7
        mov     ecx, 6
        imul    eax, ecx            # eax = 7 * 6

        # Split eax into tens and units: divide the 64-bit number edx:eax by ecx.
        xor     edx, edx            # the high half of the dividend must be 0
        mov     ecx, 10
        div     ecx                 # eax = quotient (tens), edx = remainder (units)

        add     eax, '0'            # 4 -> the character '4'
        add     edx, '0'            # 2 -> the character '2'
        mov     [rip + out], al     # store the low byte of eax
        mov     [rip + out + 1], dl # store the low byte of edx
        mov     BYTE PTR [rip + out + 2], 10

        mov     eax, 1              # write(1, out, 3)
        mov     edi, 1
        lea     rsi, [rip + out]
        mov     edx, 3
        syscall

        mov     eax, 60             # exit(0)
        xor     edi, edi
        syscall

It prints:

text
42

Three new things appear. .section .bss with .skip 3 reserves three zero-filled bytes that the program may change; .bss costs nothing in the executable file, because the system just hands over zeroed memory. mov [rip + out], al stores a byte from a register into memory; lesson 3 explains memory operands properly. And BYTE PTR tells the assembler the size of the store, which it cannot guess when the source is the bare number 10.

A worked example: minutes and seconds

A music player shows a track of 245 seconds as 4:05. That is two divisions: by 60 to get minutes and leftover seconds, then by 10 to split the seconds into two digits. Because div overwrites both eax and edx, we park the seconds in ebx between the two divisions.

asm
        .intel_syntax noprefix

        .section .bss
clock:  .skip 5                     # "m:ss" and a newline

        .text
        .globl _start
_start:
        mov     eax, 245            # a song lasting 245 seconds
        xor     edx, edx
        mov     ecx, 60
        div     ecx                 # eax = 4 minutes, edx = 5 seconds
        mov     ebx, edx            # keep the seconds safe in ebx

        add     eax, '0'
        mov     [rip + clock], al
        mov     BYTE PTR [rip + clock + 1], ':'

        mov     eax, ebx            # now split the seconds into two digits
        xor     edx, edx
        mov     ecx, 10
        div     ecx                 # eax = tens of seconds, edx = units
        add     eax, '0'
        add     edx, '0'
        mov     [rip + clock + 2], al
        mov     [rip + clock + 3], dl
        mov     BYTE PTR [rip + clock + 4], 10

        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + clock]
        mov     edx, 5
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

It prints:

text
4:05

The leading zero in 05 comes for free: 5 divided by 10 is 0 remainder 5, and '0' + 0 is the character 0. The program only works for tracks shorter than 10 minutes, since it prints one minute digit. Lesson 4 replaces these fixed digit counts with a loop that handles any number.

Overflow wraps around

Registers have fixed widths, and arithmetic wraps around silently. al holds 8 bits, so after mov al, 250 and add al, 10 it holds 4 (260 − 256), and nothing stops the program. The processor does record that something unusual happened, in the carry and overflow flags, and lesson 4 shows how to test them. Signed numbers use two's complement: −1 is all ones (0xFFFFFFFFFFFFFFFF in 64 bits), and the same add instruction works for signed and unsigned values. Only some instructions, such as imul versus mul, idiv versus div, and sar versus shr, care about the difference.

Worked examplesH

Bits, shifts and partial registers

The bitwise instructions treat a register as a row of bits:

InstructionEffect
and a, b / or a, b / xor a, bbit by bit AND, OR, exclusive OR
not aflip every bit
shl a, n / shr a, nshift left / right by n, filling with zeros
sar a, nshift right, copying the sign bit in (signed division by 2ⁿ, rounding down)
rol a, n / ror a, nrotate: bits pushed out of one end come back in the other

The shift count n is either a constant or the register cl. Shifting left by n multiplies by 2ⁿ, and shifting right with shr divides an unsigned number by 2ⁿ, which is why compilers use shifts wherever they can.

Example— Packing and unpacking Unix permissions

Unix file permissions are three groups of three bits: read, write and execute for the owner, the group and everyone else. rwxr-xr-- is 7, 5 and 4, packed as the octal number 754. This program packs the three digits with shifts and or, then unpacks the group's digit with a shift and a mask.

asm
        .intel_syntax noprefix

        .section .bss
out:    .skip 2

        .text
        .globl _start
_start:
        # Unix permissions rwxr-xr-- : owner 7, group 5, others 4, three bits each.
        mov     eax, 7
        shl     eax, 3              # make room for the group's three bits
        or      eax, 5
        shl     eax, 3              # and for the others' three bits
        or      eax, 4              # eax = 0b111_101_100 = 492 = octal 754

        # Read the group's permissions back out.
        mov     ecx, eax
        shr     ecx, 3              # move the group bits to the bottom
        and     ecx, 7              # keep only three bits (7 = 0b111)

        add     ecx, '0'
        mov     [rip + out], cl
        mov     BYTE PTR [rip + out + 1], 10
        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + out]
        mov     edx, 2
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

It prints 5. The pattern "shift the field down, then AND with a mask of ones" is how every bit field is read, from network packet headers to the flags inside a file system.

Example— Seeing the partial-register rule

This program fills rax with ones, writes 7 into one of its smaller parts, and then prints the value of the top four bits (shifting right by 60 leaves bits 60–63 at the bottom).

asm
        .intel_syntax noprefix

        .section .bss
out:    .skip 6                     # "dd\ndd\n"

        .text
        .globl _start
_start:
        # Case 1: write a 32-bit register.
        mov     rax, -1             # all 64 bits set to 1
        mov     eax, 7              # writes the low 32 bits ... and clears the high 32
        shr     rax, 60             # keep only the top 4 bits
        xor     edx, edx
        mov     ecx, 10
        div     ecx
        add     eax, '0'
        add     edx, '0'
        mov     [rip + out], al
        mov     [rip + out + 1], dl
        mov     BYTE PTR [rip + out + 2], 10

        # Case 2: write an 8-bit register.
        mov     rax, -1
        mov     al, 7               # writes the low 8 bits and leaves the other 56 alone
        shr     rax, 60
        xor     edx, edx
        mov     ecx, 10
        div     ecx
        add     eax, '0'
        add     edx, '0'
        mov     [rip + out + 3], al
        mov     [rip + out + 4], dl
        mov     BYTE PTR [rip + out + 5], 10

        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + out]
        mov     edx, 6
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

It prints:

text
00
15

After mov eax, 7 the top bits are all zero; after mov al, 7 they are still all ones (binary 1111 is 15). Forgetting this rule is a classic source of bugs: you load a byte into al, then use rax as an index, and the leftover upper bits send you to a wild address. When you want a small value in a full register, load it with movzx (zero-extend, next lesson) or with a 32-bit mov.

Common misconceptionsH

Common mistakes

Misconception

Forgetting to clear rdx before div. div ecx divides the 64-bit value edx:eax, not just eax. If edx holds leftover junk, the quotient may not fit in 32 bits, and the processor raises a divide error. Linux reports it, confusingly, as Floating point exception; our test program that set edx to 100 before dividing 42 by 10 died that way. The same happens when you divide by zero. Always write xor edx, edx before div, or cqo / cdq before idiv.

Misconception

Thinking mov can copy memory to memory. x86-64 instructions allow at most one memory operand. To copy a value from one variable to another you load it into a register and store it again. (Some special string instructions, such as movsb, do move memory to memory, but they use fixed registers and are rarely the simplest choice.)

Misconception

Using the register names as if they were variable names. It is tempting to think "rcx is the counter" and "rsi is the source", because the names say so. On modern processors any general register works for any job, apart from the few instructions that hard-wire one (such as div, mul and shifts by cl). What really decides how registers are used is the calling convention, and comments: write down which value lives in which register, because nothing else will.

Misconception

Using rsp as a spare register. rsp is the stack pointer. Even a program that never pushes anything may be interrupted by a signal handler that uses the stack below rsp. Changing it to a random value is asking for a crash. The other fifteen registers are yours.

ExplanationH

How professionals think about registers

Experienced assembly programmers rarely think "I need rcx". They think about live ranges: from the moment a value is computed to its last use, it needs a home. When there are more live values than registers, some must be spilled to memory and reloaded later. Sixteen registers sounds generous until you write a real loop with several pointers, counters and temporaries.

Compilers solve this problem automatically with register allocation algorithms, often based on graph colouring: values that are live at the same time "interfere" and must get different registers. Their output is the best place to learn idioms. You will see xor eax, eax to set a register to zero (shorter than mov eax, 0, and recognised by the processor as not depending on the old value), lea eax, [rdi + rdi*4] to multiply by five without imul, and 32-bit operations wherever 32 bits are enough. Lesson 7 is devoted to reading such output.

A final professional habit: comment the meaning, not the mechanics. add eax, ecx # add ecx to eax tells the reader nothing new; add eax, ecx # total += price tells them what the registers hold.

Exercises

Exercises

Every register value and output below was checked by running the code.

1. Registers and arithmetic

Warm-upComputational

What value is in eax after these instructions?

        mov     eax, 20
        sub     eax, 3
        imul    eax, eax, 2

2. Registers and arithmetic

CoreComputational

After these instructions, what are the values of eax and edx? Give both numbers.

        mov     eax, 47
        xor     edx, edx
        mov     ecx, 5
        div     ecx

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

3. Registers and arithmetic

CoreComputational

What is in rax after these two instructions?

        mov     rax, -1
        mov     ax, 0
Choose one

4. Registers and arithmetic

CoreComputational

What value does al hold after these instructions?

        xor     eax, eax
        mov     al, 250
        add     al, 10

5. Registers and arithmetic

CoreComputational

rax holds −16. What signed value does it hold after sar rax, 2?

6. Registers and arithmetic

CoreHuman

Why do the lesson's programs write xor edx, edx right before div ecx?

Choose one

7. Registers and arithmetic

StretchComputational

In the minutes-and-seconds program, the first instruction is changed to mov eax, 200. What does the program print now?

Further reading and resources