Registers & Data Movement
Registers Overview
x86-64 has 16 general-purpose 64-bit registers. Writing to a 32-bit sub-register (e.g. eax) zero-extends the upper 32 bits of the full register; writing to 16/8-bit sub-registers leaves the upper bits unchanged.
; General-purpose 64-bit registers (x86-64)
; rax, rbx, rcx, rdx — main accumulators / scratch
; rsi, rdi — source/destination index (string ops)
; rbp, rsp — base pointer / stack pointer
; r8 .. r15 — extended registers
; 32-bit: eax, 32-bit: ecx, 16-bit: ax, 8-bit: al/ah
mov rax, 42 ; load immediate into 64-bit register
mov eax, 0x1F ; 32-bit move (zero-extends to rax)mov — Move Data
mov copies data between registers, memory, and immediates. Memory-to-memory moves are not allowed — go through a register. Always specify the size (byte/word/dword/qword) when the operand size is ambiguous, e.g. mov dword [rsp], 1.
mov rax, 60 ; immediate -> register
mov rbx, rax ; register -> register
mov qword [rsp-8], 7 ; immediate -> memory (qword = 8 bytes)
mov rcx, [rsp-8] ; memory -> register
; INVALID: mov [rsp-8], [rsp-16] (memory-to-memory not allowed)
; Use two steps: mov rax, [src]; mov [dst], raxlea — Load Effective Address
lea computes the address of a memory operand without accessing memory. It is frequently used as a fast arithmetic instruction (multiplication by 5/3/9 etc. via scale+index) and to take the address of stack variables or data labels.
; Compute address without dereferencing
lea rax, [rbx + rcx*8 + 16] ; rax = rbx + rcx*8 + 16
; Common idiom: fast arithmetic (no memory access)
lea rax, [rax + rax*4] ; rax *= 5 (rax = rax + rax*4)
; Pointer into a buffer
lea rsi, [buffer] ; rsi = address of buffer
lea rdi, [rsp + 32] ; rdi = address of stack slotpush / pop — Stack Operations
push decrements rsp by 8 (64-bit mode) then stores the value; pop loads then increments rsp. In the System V AMD64 ABI, the first 6 integer args go in rdi, rsi, rdx, rcx, r8, r9 — push is mainly used to save callee-saved registers (rbx, rbp, r12-r15) and to spill temporaries.
push rax ; rsp -= 8; [rsp] = rax
push qword 42 ; push immediate
pop rbx ; rbx = [rsp]; rsp += 8
; Save/restore callee-saved registers
push rbx
push r12
; ... function body ...
pop r12
pop rbx
ret
; Push arguments in reverse (C calling convention)
push 3
push 2
push 1xchg / xadd — Atomic Exchange
xchg with a memory operand is always atomic (implicit lock). xadd combines exchange and add. Together with lock cmpxchg (compare-and-swap) these form the foundation of lock-free synchronization primitives.
; xchg swaps two operands (implicitly LOCKed with memory)
xchg rax, rbx ; swap register/register
xchg [counter], rcx ; swap memory/register (atomic)
; xadd: swap then add (returns old value in src)
; lock xadd [counter], rax ; atomic fetch-and-add
; Spinlock idiom
spin:
xor eax, eax
lock cmpxchg [lock_var], 1 ; if [lock_var]==0, set to 1
jnz spin ; retry if not acquiredmovzx / movsx — Zero/Sign Extend
movzx zero-extends a smaller value into a larger register (unsigned load). movsx sign-extends (signed load). Use movsxd to load a 32-bit signed value into a 64-bit register; movsx on 32->64 is encoded as movsxd in 64-bit mode.
; movzx: zero-extend (unsigned)
movzx rax, byte [rsi] ; load byte, zero-extend to 64-bit
movzx eax, word [rdi] ; load word, zero-extend to 32-bit
; movsx: sign-extend (signed)
movsx rax, byte [rsi] ; sign-extend byte to 64-bit
movsx rax, dword [rdi] ; sign-extend 32-bit to 64-bit (movsxd)Arithmetic & Logic
add / sub — Integer Arithmetic
add/sub set CF (unsigned carry/borrow), OF (signed overflow), SF (sign), ZF (zero), PF (parity), and AF (auxiliary carry). Use jc/jo to detect unsigned/signed overflow. Subtracting from rsp allocates stack space — keep rsp 16-byte aligned before calls per the ABI.
add rax, rbx ; rax = rax + rbx
add rax, 10 ; rax = rax + 10
sub rcx, rdx ; rcx = rcx - rdx
sub rsp, 32 ; allocate 32 bytes of stack (align!)
; 64-bit addition with carry check
add rax, rbx
jc .overflow ; jump if unsigned overflow (CF=1)imul / idiv — Multiply & Divide
Two-operand imul is the common form — it keeps only the low 64 bits and is what compilers emit for a*b. For full-width multiplication use one-operand mul/imul (result in rdx:rax). Before idiv, sign-extend the dividend with cqo (or cdq for 32-bit); for unsigned div, zero rdx with xor rdx,rdx.
; Two-operand imul (most common): dst = dst * src
imul rax, rbx ; rax = rax * rbx (lower 64 bits)
imul rcx, 10 ; rcx = rcx * 10
; One-operand: rdx:rax = rax * src (full 128-bit)
mul rbx ; unsigned: rdx:rax = rax * rbx
imul rbx ; signed: rdx:rax = rax * rbx
; idiv: signed divide rdx:rax by src
; Must sign-extend rax into rdx:rax first!
cqo ; sign-extend rax -> rdx:rax
idiv rcx ; rax = rdx:rax / rcx, rdx = remainder
; Unsigned: use div (zero rdx first)
xor rdx, rdx
div rcx ; rax = rdx:rax / rcx, rdx = remainderinc / dec / neg
inc and dec do NOT update the carry flag (CF) — this lets you use them inside multi-precision add/sub chains that rely on CF. They do update ZF/SF/OF. neg computes two's complement negation (0 - dst) and sets CF=1 unless the operand was 0.
inc rax ; rax++ (does NOT affect CF!)
dec rcx ; rcx-- (does NOT affect CF!)
neg rdx ; rdx = -rdx (two's complement negate)
; Common loop pattern
mov rcx, 10
.loop:
; ... loop body ...
dec rcx
jnz .loop ; repeat until rcx == 0and / or / xor / not / test
xor reg,reg is the idiomatic way to zero a register (shorter encoding than mov reg,0). test a,a is equivalent to and a,a but discards the result — commonly used to check sign/zero without modifying the operand. and/or/xor clear CF and OF.
and rax, 0xFF ; mask low byte (rax &= 0xFF)
or rcx, 0x10 ; set bit 4
xor rdx, rdx ; rdx = 0 (idiomatic zeroing)
xor rax, rax ; clear rax (shorter than mov rax,0)
not r8 ; bitwise NOT (one's complement)
test rax, rax ; set flags from rax & rax (checks zero/sign)
test rcx, 0x1 ; test if low bit set (odd/even check)shl / shr / sar — Shifts
shl/shr are logical shifts (zero-fill); sar preserves the sign bit (arithmetic shift). Multiplying/dividing by powers of two via shifts is much faster than imul/idiv. The shift count is masked to 5 bits (32-bit operand) or 6 bits (64-bit operand).
shl rax, 4 ; logical left shift (rax *= 16)
shr rax, 3 ; logical right shift (unsigned rax /= 8)
sar rax, 3 ; arithmetic right shift (signed rax /= 8)
; Rotate (carry not involved)
rol rax, 4 ; rotate left
ror rax, 4 ; rotate right
; Shift by CL (only low 5 bits used in 64-bit mode)
mov cl, 4
shl rax, cl ; shift left by 4Control Flow & Branching
cmp / test — Compare
cmp sets flags as if subtracting without storing. For signed comparisons use je/jne/jl/jg/jle/jge; for unsigned use jb/ja/jbe/jae (below/above). Mixing them is a classic bug — jl checks SF!=OF while jb just checks CF.
cmp rax, rbx ; compute rax - rbx, set flags (discard result)
cmp rax, 10 ; compare with immediate
; Signed comparisons
cmp rax, rbx
je .equal ; jump if rax == rbx (ZF=1)
jl .less ; jump if rax < rbx signed (SF!=OF)
jg .greater ; jump if rax > rbx signed (ZF=0 and SF==OF)
jle .le ; jump if rax <= rbx signed
jge .ge ; jump if rax >= rbx signed
; Unsigned comparisons (use 'below'/'above' mnemonics)
cmp rax, rbx
jb .below ; rax < rbx unsigned (CF=1)
ja .above ; rax > rbx unsigned (CF=0 and ZF=0)
jbe .be ; rax <= rbx unsigned
jae .ae ; rax >= rbx unsignedjmp — Unconditional Jump
jmp performs an unconditional jump. Conditional jumps (jcc) test flags set by cmp/test/arithmetic. In 64-bit mode near conditional jumps can reach ±2GB, so the 'short jump too far' problem is largely gone. Indirect jumps via register/memory enable switch/case jump tables.
; Direct jump to a label
jmp .end
; Conditional jumps (short/near, 64-bit allows near)
.loop:
dec rcx
jnz .loop ; jump if ZF=0 (rcx != 0)
; Indirect jump through register/memory (jump table)
lea rax, [table]
mov rdi, [rax + rbx*8]
jmp rdi ; jump to address in rdi
; Jump table example (switch statement)
table: dq .case0, .case1, .case2, .case3Common Conditional Jumps
There are many synonyms (je==jz, jb==jc==jnae). The signed (l/g) vs unsigned (b/a) distinction is critical: jl/jg test SF and OF; jb/ja test CF. Use signed forms after comparing signed ints, unsigned forms after comparing pointers/unsigned ints.
; After cmp/test:
je / jz ; jump if equal / zero (ZF=1)
jne / jnz ; jump if not equal / nonzero (ZF=0)
; Signed
jl / jnge ; less (SF!=OF)
jge / jnl ; greater-or-equal (SF==OF)
jle / jng ; less-or-equal (ZF=1 or SF!=OF)
jg / jnle ; greater (ZF=0 and SF==OF)
; Unsigned
jb / jnae / jc ; below / carry (CF=1)
jae / jnb / jnc ; above-or-equal (CF=0)
jbe / jna ; below-or-equal (CF=1 or ZF=1)
ja / jnbe ; above (CF=0 and ZF=0)
; Special
js ; jump if sign (SF=1)
jns ; jump if not sign (SF=0)
jo ; jump if overflow (OF=1)
jno ; jump if no overflow (OF=0)Loop with cx
loop decrements rcx and jumps if rcx!=0. Although convenient, it is slower on modern CPUs than a dec/jnz pair, so compilers emit dec/jnz instead. loope/loopz additionally require ZF=1; loopne/loopnz require ZF=0.
; loop: dec rcx then jump if rcx != 0
mov rcx, 5
.loop:
; ... body executes 5 times ...
loop .loop
; loope/loopz: loop while equal/zero
; loopne/loopnz: loop while not equal/not zero
; Modern compilers prefer dec + jnz (loop is slower on many CPUs)
mov rcx, 5
.loop:
; ...
dec rcx
jnz .loopcmov — Conditional Move
cmovcc performs a conditional move — branchless code that avoids branch misprediction penalties. The destination must be a register (not memory). Be aware cmov always evaluates both source operands, so avoid it when one path has side effects or when the source memory access could fault.
; cmovcc: move only if condition is true (branchless)
cmp rax, rbx
cmovl rax, rbx ; if rax < rbx (signed), rax = rbx -> rax = min(a,b)
; max(a, b)
cmp rax, rbx
cmovl rax, rbx ; rax = max(rax, rbx)? No: if rax<rbx, set rax=rbx -> max
; Branchless abs:
; abs(x): mask = x >> 63; result = (x ^ mask) - mask
mov rax, rdi
sar rdi, 63 ; all 1s if negative, 0 if positive
xor rax, rdi
sub rax, rdi ; rax = |original rdi|Stack, Functions & Calling Convention
Function Prologue & Epilogue
The standard prologue saves rbp, sets rbp as frame pointer, and allocates locals by subtracting from rsp. leave is a one-byte epilogue equivalent to mov rsp,rbp; pop rbp. The System V AMD64 ABI requires rsp to be 16-byte aligned at the point of a call (so 8 bytes off after the return address is pushed).
; System V AMD64 calling convention (Linux/macOS)
; Args: rdi, rsi, rdx, rcx, r8, r9 (then stack)
; Return: rax. Callee-saved: rbx, rbp, r12-r15
my_func:
push rbp
mov rbp, rsp ; standard prologue
sub rsp, 32 ; allocate locals (keep 16-byte aligned)
; ... function body ...
mov rsp, rbp ; or: leave
pop rbp ; standard epilogue
ret
; Compact form using leave
my_func2:
push rbp
mov rbp, rsp
sub rsp, 16
; ...
leave ; mov rsp,rbp; pop rbp
retcall / ret — Call & Return
call pushes the return address (8 bytes in 64-bit) onto the stack and jumps to the target; ret pops it back into rip. For tail calls use jmp so the callee returns directly to your caller — this preserves the stack and enables tail-call optimization.
; call pushes return address, then jumps
call my_func
; ret pops return address into rip
my_func:
; ...
ret
; Call with arguments (System V AMD64)
mov rdi, 1 ; 1st arg
mov rsi, 2 ; 2nd arg
mov rdx, 3 ; 3rd arg
call add_three ; result in rax
; Tail call: jmp instead of call+ret
my_wrapper:
jmp target_func ; reuses our return addressLeaf Functions & Red Zone
The System V AMD64 ABI reserves a 128-byte 'red zone' below rsp that leaf functions (functions that make no calls) can use without adjusting rsp. Windows x64 does NOT have a red zone. Leaf functions often need no prologue at all.
; Leaf function (no calls) can use the red zone:
; 128 bytes below rsp that won't be clobbered by signals/interrupts
leaf_sqrt_sum:
; rdi, rsi = args, rax = result
mov rax, rdi
add rax, rsi
ret ; no prologue needed!
; Non-leaf functions MUST save rsp properly because
; a call would write into the red zone.
; Red zone is NOT honored on Windows x64.Local Variables & Stack Frame
With a frame pointer (rbp), locals are accessed at [rbp - offset] and incoming stack arguments at [rbp + offset]. Compilers often omit the frame pointer (-fomit-frame-pointer) and reference locals directly from rsp, freeing up rbp as a general register.
my_func:
push rbp
mov rbp, rsp
sub rsp, 32 ; 32 bytes for locals
; Local variables accessed via [rbp - offset]
mov qword [rbp-8], 10 ; local1
mov qword [rbp-16], 20 ; local2
; Read arguments (also via rbp once saved on stack,
; or directly from registers)
mov rax, [rbp-8]
add rax, [rbp-16]
leave
retPreserving Callee-Saved Registers
Callee-saved registers (rbx, rbp, r12-r15) must be preserved across your function — push them on entry, pop in reverse order on exit. Caller-saved registers (rax, rcx, rdx, rsi, rdi, r8-r11) may be freely clobbered, but if you need their values across a call you must save them yourself.
; rbx, rbp, r12, r13, r14, r15 are callee-saved
; rax, rcx, rdx, rsi, rdi, r8-r11 are caller-saved
my_func:
push rbx ; we want to use rbx
push r12 ; and r12
mov rbx, rdi ; use them
mov r12, rsi
; ... do work, may call other functions ...
; (those calls will preserve rbx/r12 for us)
mov rax, rbx ; prepare return value
pop r12 ; restore in REVERSE order
pop rbx
retSystem Calls & Hello World
syscall — Linux System Call
On Linux x86-64, syscalls use the syscall instruction with the number in rax and up to 6 args in rdi, rsi, rdx, r10, r8, r9 (note r10, not rcx, for the 4th arg). Common numbers: write=1, read=0, exit=60, mmap=9. syscall clobbers rcx and r11. macOS uses different numbers (e.g. write=0x2000004).
; Linux x86-64 syscall convention:
; rax = syscall number
; rdi, rsi, rdx, r10, r8, r9 = args (NOTE: r10 not rcx!)
; return value in rax; clobbers rcx and r11
; write(1, msg, 12)
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd = stdout
lea rsi, [msg] ; buf
mov rdx, 12 ; count
syscall
; exit(0)
mov rax, 60 ; syscall: exit
xor rdi, rdi ; status = 0
syscall
section .data
msg: db "hello world", 10 ; 12 bytes with newlineComplete Hello World (NASM, Linux)
A freestanding hello world links against no libc — it calls the kernel directly via syscall. $ - msg computes the length at assembly time (the $ symbol is the current address). _start is the default entry point for ld. The program ends with the exit syscall; returning from _start is undefined.
; nasm -f elf64 hello.asm && ld hello.o -o hello && ./hello
section .data
msg: db "Hello, World!", 10
msg_len: equ $ - msg ; length computed at assemble time
section .text
global _start
_start:
; write(1, msg, msg_len)
mov rax, 1 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg_len
syscall
; exit(0)
mov rax, 60
xor rdi, rdi
syscallReading Command-Line argc / argv
On entry to _start (Linux, no libc), the kernel sets up the stack with argc at [rsp], then argv pointers, then envp, then NULL. If you link against libc and use main, the C runtime parses these for you — main receives argc and argv in rdi/rsi instead.
; At _start the stack looks like:
; [rsp] = argc
; [rsp+8] = argv[0]
; [rsp+16] = argv[1]
; ...
; [rsp + 8*(argc+1)] = NULL
_start:
mov rdi, [rsp] ; argc
mov rsi, [rsp+8] ; argv[0] (program name)
mov rdx, [rsp+16] ; argv[1] (first user arg)
; Loop over argv
mov rbx, rsp
add rbx, 8 ; skip argc, point at argv[0]
.loop:
mov rax, [rbx]
test rax, rax
jz .done ; NULL terminator
; rax -> one argv string
add rbx, 8
jmp .loop
.done:
; exit
mov rax, 60
xor rdi, rdi
syscallCalling C Library Functions
When calling C functions, align rsp to 16 bytes before the call (the call pushes 8 bytes, leaving it 8 off). For variadic functions like printf, rax must hold the number of vector (XMM) register arguments — set it to 0 for integer-only calls. Use main as the entry point so the C runtime sets up libc and libc can call your destructors on exit.
; Link with gcc: nasm -f elf64 demo.asm && gcc demo.o -o demo -no-pie
extern printf
section .data
fmt: db "sum = %d", 10, 0
section .text
global main
main:
push rbp
mov rbp, rsp
sub rsp, 16 ; keep stack 16-byte aligned
; printf("sum = %d\n", 42)
; Variadic: rdi=fmt, rsi=arg, rax=#vector regs (0)
lea rdi, [fmt]
mov rsi, 42
xor rax, rax ; 0 floating-point args
call printf
xor rax, rax ; return 0
leave
retRelated Assembly snippets
Copy-paste ready code for common tasks.
Hello World via Linux syscall
A freestanding x86-64 program that prints and exits using only kernel syscalls.
Function Call Convention (System V AMD64)
Pass args in registers, preserve callee-saved regs, keep rsp 16-byte aligned.
Loop Summation (1..N)
Sum integers 1..N with a counted loop using dec/jnz.
strlen — Scan Until NUL
Compute C-string length by scanning memory until a zero byte.
memcpy — Copy with rep movsb
Use the rep movsb string instruction for a tight memory copy.
Bit Manipulation: popcount, ctz, abs
Use BMI/ABM instructions for branchless bit operations.
Read a File via syscalls
open/read/write/close a file using only Linux syscalls.
Recursive factorial
Implement factorial(n) recursively with a proper stack frame.
Was this helpful?