Zig Inline Assembly
Inline assembly lets you write CPU instructions by hand, right inside a Zig function. Let’s be honest up front: most Zig programmers never need it. The compiler writes better machine code than most of us for normal work, and Zig already has builtins for many special instructions. But when you’re writing an operating system kernel, a bootloader, or code that talks straight to the hardware, there are a few things only assembly can do. This page shows what it looks like, so you can read it when you meet it and write a little when you have to.
When you’d actually need it
Section titled “When you’d actually need it”Reach for inline assembly only when there’s no other way:
- Special instructions the language has no word for: reading a CPU’s tick counter,
cpuid, enabling or disabling interrupts, switching page tables. - System calls without a C library, in a tiny static program or your own runtime.
- Kernels, bootloaders and embedded startup code, where you set up the stack or jump to an address yourself.
And here’s what you don’t need it for, because Zig has builtins that compile to the right instruction on every CPU:
| You want | Use this instead |
|---|---|
| Count set bits, leading/trailing zeros | @popCount, @clz, @ctz |
| Byte swapping | @byteSwap |
| Fused multiply-add, square root | @mulAdd, @sqrt |
| SIMD (several numbers per instruction) | @Vector, see Zig Vectors |
| Atomic operations between threads | @atomicLoad, @atomicRmw, std.atomic |
const std = @import("std");
pub fn main() void { const x: u32 = 0b1011_0110; std.debug.print("{d} bits set\n", .{@popCount(x)}); std.debug.print("{d} trailing zeros\n", .{@ctz(x)});}Output:
5 bits set1 trailing zerosOn an x86-64 CPU with the right features, @popCount becomes the popcnt instruction. On a CPU without it, Zig writes a fallback for you. With assembly, that fallback would be your job. Zig Builtins lists more of these.
Your first asm: adding two numbers
Section titled “Your first asm: adding two numbers”Here’s a function that adds two numbers with the x86-64 addq instruction. It’s pointless in real code (a + b does the same), but it’s small enough to see every part:
const std = @import("std");
fn add(a: u64, b: u64) u64 { return asm ("addq %[b], %[result]" : [result] "=r" (-> u64), : [a] "0" (a), [b] "r" (b), );}
pub fn main() void { std.debug.print("2 + 3 = {d}\n", .{add(2, 3)}); std.debug.print("40 + 2 = {d}\n", .{add(40, 2)});}Output:
2 + 3 = 540 + 2 = 42An asm expression has up to four parts, separated by colons:
- The template, a string with the instructions:
"addq %[b], %[result]".%[name]is replaced with whatever register Zig picked for that name. On x86, Zig uses AT&T syntax, where the destination comes last:addq src, dstmeansdst = dst + src. If you learned Intel syntax (add dst, src), this is backwards from what you’re used to. - The output:
[result] "=r" (-> u64)."=r"means “the result ends up in some general register”, and-> u64makes that the value of the wholeasmexpression. - The inputs:
[a] "0" (a)and[b] "r" (b)."r"means “putbin any register”."0"means “putain the same register as output number 0”, soaddqaddsbstraight into it. - Clobbers (optional, not used here): registers or memory the code changes without saying so in the outputs.
The letters inside the quotes are constraints, and they come from LLVM and GCC. The language reference on assembly says this part is still considered unstable, and points you to the LLVM and GCC docs for what each letter means.
volatile and clobbers: a raw system call
Section titled “volatile and clobbers: a raw system call”On Linux, a program asks the kernel to do things (write to a file, exit) with the syscall instruction. Normally std.Io does this for you, but here’s the raw version, writing to stdout with no library in between:
const std = @import("std");
fn write(fd: usize, bytes: []const u8) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize), : [number] "{rax}" (@as(usize, 1)), // 1 is `write` on x86-64 Linux [fd] "{rdi}" (fd), [ptr] "{rsi}" (@intFromPtr(bytes.ptr)), [len] "{rdx}" (bytes.len), : .{ .rcx = true, .r11 = true, .memory = true });}
pub fn main() void { const n = write(1, "Hello from a raw syscall!\n"); std.debug.print("the kernel says it wrote {d} bytes\n", .{n});}Output:
Hello from a raw syscall!the kernel says it wrote 26 bytesThree new things:
"{rax}"with curly braces asks for one exact register. The Linux kernel expects the system call number inrax, the arguments inrdi,rsiandrdx, and puts the result back inrax.volatiletells Zig “this has side effects, keep it even if nobody uses the result”. Without it, the optimizer is allowed to delete anasmwhose output is unused, and a syscall that prints something must never be deleted.- The clobber list
.{ .rcx = true, .r11 = true, .memory = true }is a struct literal of what the code destroys. Thesyscallinstruction overwritesrcxandr11, so Zig must not keep anything there..memory = truesays the code may read or write memory Zig doesn’t know about (here, the kernel reads our string).
Reading the CPU’s tick counter
Section titled “Reading the CPU’s tick counter”A more realistic use: x86 CPUs have a time-stamp counter that ticks very fast, and the rdtsc instruction reads it. No builtin does this, so assembly it is. rdtsc puts the low 32 bits in eax and the high 32 bits in edx:
const std = @import("std");
fn rdtsc() u64 { var low: u32 = undefined; var high: u32 = undefined; asm volatile ("rdtsc" : [low] "={eax}" (low), [high] "={edx}" (high), ); return (@as(u64, high) << 32) | low;}
pub fn main() void { const before = rdtsc(); var sum: u64 = 0; for (0..1000) |i| sum += i; const after = rdtsc(); std.debug.print("sum = {d}, took about {d} CPU ticks\n", .{ sum, after - before });}You’ll see something like:
sum = 499500, took about 2908 CPU ticksThe tick count changes every run. Here the outputs are bound to variables ((low), (high)) instead of using -> type, which is how you get more than one value out. For timing real code, prefer the portable clocks from Zig Performance; rdtsc is for when you need the raw counter.
It only works on one kind of CPU
Section titled “It only works on one kind of CPU”Assembly is written for one CPU family. Everything on this page is x86-64. Try to build the add example for a 64-bit ARM Linux machine:
zig build-exe add.zig -target aarch64-linuxerror: <inline asm>:1:2: unrecognized instruction mnemonic, did you mean: add, addp, adds, addv, fadd, madd? addq x2, x0 ^ARM has no addq. The syscall example fails even earlier, because the clobber struct for ARM has no rcx field: error: no field named 'rcx' in struct 'lang.assembly.Clobbers__struct_32'. Even on the same CPU, system call numbers differ between operating systems, so write above is x86-64 Linux only.
The usual fix is to check the target at compile time and keep a plain Zig version for everything else:
const std = @import("std");const builtin = @import("builtin");
fn add(a: u64, b: u64) u64 { if (builtin.target.cpu.arch == .x86_64) { return asm ("addq %[b], %[result]" : [result] "=r" (-> u64), : [a] "0" (a), [b] "r" (b), ); } else { return a + b; // plain Zig everywhere else }}
pub fn main() void { std.debug.print("2 + 3 = {d}\n", .{add(2, 3)});}Output:
2 + 3 = 5builtin.target.cpu.arch is known at compile time, so only one branch is compiled. This version builds for aarch64-linux and riscv64-linux too (we checked). That’s exactly how the standard library handles it: per-CPU assembly where it must, with a separate file or branch for each architecture. Zig Cross-Compilation shows how to build for other targets.
Practice
Section titled “Practice”1. Subtract with subq
Section titled “1. Subtract with subq”Write sub(a, b) that returns a - b using the x86-64 subq instruction, and print sub(10, 3).
Hint: copy add and change only the instruction. In AT&T order, subq %[b], %[result] means result = result - b.
Show solution
const std = @import("std");
fn sub(a: u64, b: u64) u64 { return asm ("subq %[b], %[result]" : [result] "=r" (-> u64), : [a] "0" (a), [b] "r" (b), );}
pub fn main() void { std.debug.print("10 - 3 = {d}\n", .{sub(10, 3)});}Output:
10 - 3 = 7The "0" constraint puts a in the result register first, and subq takes b away from it. Swap the operands in the template and you’d get b - a, a typical AT&T mix-up.
2. Exit without the standard library
Section titled “2. Exit without the standard library”Write exit(code) that calls the Linux exit system call (number 60 on x86-64) with the code in rdi. Call exit(0) at the end of main, after printing a line.
Hint: it never returns, so make the function return noreturn, use asm volatile with no outputs, and put unreachable; after it. The output section is then empty, so the line starts with : straight away.
Show solution
const std = @import("std");
fn exit(code: usize) noreturn { asm volatile ("syscall" : : [number] "{rax}" (@as(usize, 60)), // 60 is `exit` on x86-64 Linux [code] "{rdi}" (code), : .{ .rcx = true, .r11 = true }); unreachable;}
pub fn main() void { std.debug.print("about to exit\n", .{}); exit(0);}Output:
about to exitThe empty output section is the lone : line. In real programs use std.process.exit, which does this for every operating system Zig supports.
- You rarely need inline assembly. Builtins like
@popCount,@byteSwap,@Vectorand atomics cover most special instructions portably. - An
asmexpression has a template, outputs, inputs and clobbers, separated by colons.%[name]refers to an operand. - On x86, Zig uses AT&T syntax: the destination comes last.
volatilekeeps assembly with side effects from being optimized away. Clobbers list what the code destroys.- Constraint mistakes don’t cause compile errors, they cause silent bugs. Keep
asmblocks tiny. - Assembly is not portable: check
builtin.target.cpu.archat compile time and keep a plain Zig fallback.
Next up: Zig & WebAssembly, building Zig code that runs in a browser or in Node.js.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Assembly: the full syntax, with every part of a syscall example explained in comments.
- Zig language reference: Global Assembly: assembly outside of functions.
- LLVM inline assembly constraint codes: what letters like
r,0and{rax}mean. - GCC Extended Asm: the C version of the same idea, with good explanations of clobbers and
volatile.