Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 40 ยท Tools and Toolchain

Inline Assembly in C

Embed assembly in C with GCC extended asm: operands, constraints, clobbers, volatile, rdtsc and cpuid examples, and why intrinsics are usually safer.

Sometimes you need one specific instruction that C has no way to express: read the CPU's cycle counter, ask which features it supports, issue a memory barrier, or make a system call. The compiler offers a back door for this: inline assembly, where you write assembly text inside a C function and tell the compiler how it connects to your C variables.

Inline assembly is powerful and easy to get wrong, because the compiler does not understand your assembly; it only trusts what you say about it. In this lesson you learn the GCC and Clang extended asm syntax, how constraints and clobbers describe the instruction's effects, a few classic examples, and why compiler intrinsics and built-ins are usually the better tool. Two of the examples run on the site's real x86-64 compiler.

Basic asm and extended asm

The simplest form is a string:

C
__asm__("nop");

That works when the instruction touches nothing the compiler cares about. As soon as the assembly reads or writes a C variable, you need extended asm, which has four parts separated by colons:

C
__asm__ volatile (
    "template"          /* the assembly text */
    : outputs           /* C variables the asm writes */
    : inputs            /* C values the asm reads */
    : clobbers          /* registers or state the asm changes behind your back */
);

You do not name registers for your variables. Instead you give each operand a constraint that tells the compiler what kind of place it may use, and the compiler picks the actual register. In the template, %0 is the first operand listed (counting outputs first, then inputs), %1 the second, and so on. GCC defaults to AT&T syntax (source first, see Assemblers and Syntax), and a literal register in the template is written %%rax because a single % introduces an operand.

Here is the smallest useful example, adding two integers:

C
int add_asm(int a, int b) {
    __asm__("addl %1, %0"      /* %0 = %0 + %1 */
            : "+r"(a)          /* operand 0: a, read and written, any register */
            : "r"(b));         /* operand 1: b, read only, any register */
    return a;
}

The +r in the output list says "this operand is both input and output, and it must live in a general register." After the asm, a holds the sum. The compiler might emit mov eax, edi / add eax, esi around it; you never see which registers were chosen, and you do not need to.

Constraints

Constraints are short letter codes. The ones you will use most on x86-64:

Constraint Meaning
r any general-purpose register
m a memory operand
i an immediate constant known at compile time
a, b, c, d specifically rax, rbx, rcx, rdx (or their 32-bit forms)
S, D rsi and rdi
0, 1... the same place as operand number 0, 1...

Modifiers in front of the letter describe direction:

  • = means write-only output: the old value does not matter.
  • + means read-write: the old value is used and a new one produced.
  • & (early clobber) means this output is written before all inputs are consumed, so it must not share a register with any input.

Using the wrong modifier is a classic bug: if you write "=r"(a) but your assembly also reads a, the compiler may hand you a register holding garbage, because you promised not to read it.

The next demo does not run any machine code. It is a tiny model of what the compiler does with your template and constraints: it assigns registers and wraps the template with the loads and stores needed to connect it to your variables. It makes the otherwise hidden step visible.

JS What the compiler does with an asm statement

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real compilers keep variables in registers already, so the loads and stores often disappear. The structure, though, is exactly this.

Clobbers and volatile

The compiler does not parse your assembly text, so it does not know what else the instruction changes. The clobber list is where you tell it:

  • A register name ("rcx", "r11") says "this register is overwritten; do not keep a live value in it across my asm."
  • "cc" says the asm modifies the flags register.
  • "memory" says the asm may read or write memory in ways not described by the operands, so the compiler must flush values it was holding in registers and cannot move memory accesses across it.

asm volatile("" ::: "memory") (an empty template with a memory clobber) is the classic compiler barrier: it emits no instruction, but stops the compiler from reordering memory accesses across it. It does not stop the CPU from reordering them, which needs a real fence instruction (mfence on x86, dmb on ARM).

volatile tells the compiler the asm has side effects beyond its outputs, so it must not delete it, even if the outputs are unused, nor move it out of loops or duplicate it. Without volatile, an asm that has outputs is treated like a pure function of its inputs: if you call it twice with the same inputs, the compiler may compute it once. That is fine for bswap, and disastrous for a cycle counter.

Classic example: reading the cycle counter

rdtsc reads the time-stamp counter into edx:eax (high half in edx, low half in eax). The a and d constraints bind outputs to exactly those registers:

C
static inline unsigned long long read_tsc(void) {
    unsigned lo, hi;
    __asm__ volatile ("rdtsc" : "=a"(lo), "=d"(hi));
    return ((unsigned long long)hi << 32) | lo;
}

rdtsc is not a serializing instruction: the CPU may execute neighbouring instructions out of order around it, so careful benchmarks add a fence such as lfence or use rdtscp. Counter ticks are also not guaranteed to equal core clock cycles on modern CPUs (they usually tick at a constant reference rate). Treat the number as a relative timer, not an exact cycle count.

Another classic is cpuid, which reports CPU features. It takes the "leaf" number in eax and returns four values in eax, ebx, ecx and edx:

C
unsigned eax, ebx, ecx, edx;
__asm__ volatile ("cpuid"
                  : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
                  : "a"(0), "c"(0));
/* leaf 0: eax = highest supported leaf; ebx, edx, ecx spell the vendor string */

Note that "a"(0) appears as an input while "=a"(eax) is an output: the same register serves both roles, which is legal because inputs are read before outputs are written.

Running real inline asm

This program uses two real inline-assembly statements: addl, and lea computing 5 * x as x + x*4. It is guarded with #if defined(__x86_64__), because inline assembly is specific to one architecture; on any other CPU the plain C fallback runs. The site's runner is a real x86-64 GCC, so the assembly versions run.

C Inline asm on x86-64 GCC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The lea trick is the same idea that compilers use for x * 5: LEA does address arithmetic without touching flags, and the scaled-index form computes x + x*4 in one step.

Prefer intrinsics and built-ins

Inline assembly has real costs. It is not portable to other architectures, the compiler cannot optimize across it (it treats it as a black box), and a wrong constraint produces bugs that appear only at certain optimization levels. For most needs there is a safer tool:

  • Built-in functions such as __builtin_popcount, __builtin_clz, __builtin_bswap32 and __builtin_expect compile to the best instruction on each target, or to a fallback sequence when none exists.
  • Intrinsics (from headers like <immintrin.h> and <arm_neon.h>) expose vector and special instructions as ordinary C functions with typed arguments. The compiler still schedules registers and optimizes around them. SIMD uses these.
  • Atomics (<stdatomic.h>, C++ std::atomic) replace hand-written lock prefixes and barriers.
  • A separate .s file or a function defined in a .S file avoids the inline machinery when you want a whole function in assembly.

The demo compares a hand-written bswap (reverse byte order) with the built-in. Both give the same result on x86-64, but the built-in also works elsewhere and the compiler can fold it into a constant.

C Inline asm vs the built-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Working with the compiler: the gcc -c workflow

A good habit is to look at what the compiler did with your asm. Compile to an object file or to assembly and read the result:

Terminal
gcc -O2 -S -masm=intel tsc.c -o tsc.s    # emit assembly in Intel syntax
gcc -O2 -c tsc.c -o tsc.o                # compile only, no linking
objdump -d -M intel tsc.o                # see the machine code

In the output you will find your template's text between the instructions the compiler generated to feed it, often marked with #APP and #NO_APP comments. If a value is being shuffled through extra registers, that is usually a sign that a constraint is too restrictive or a clobber too broad.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In __asm__("addl %1, %0" : "+r"(a) : "r"(b)); what does %0 refer to?

    Operands are numbered in the order they appear, outputs first. The compiler picks the real register and substitutes it for %0.
  2. 2. What is the difference between the = and + constraint modifiers?

    = promises the old value is not read; + says the old value is used and a new one is produced.
  3. 3. Why is volatile important for an rdtsc asm statement?

    Without volatile, an asm with only register outputs may be treated as computable once from its inputs, so two timer reads could collapse into one.
  4. 4. What does the "memory" clobber do?

    It is a compiler-level barrier only. It does not emit any instruction and does not order accesses between CPU cores.
  5. 5. Which is generally the better choice when a built-in or intrinsic exists?

    The compiler understands intrinsics and built-ins, so it can allocate registers, schedule and fold them, and often falls back on other CPUs.

Summary

  • Extended asm has a template, outputs, inputs and clobbers; constraints let the compiler choose registers.
  • %0, %1... name operands in order; use %%reg for a literal register in the template.
  • =, + and & describe whether an operand is written, read-written, or must not share a register with inputs.
  • Clobbers ("cc", "memory", register names) are promises you make about side effects; wrong ones cause bugs that appear only when optimization changes.
  • volatile stops the compiler from removing or merging an asm statement whose effects are not in its outputs.
  • Prefer built-ins, intrinsics and atomics; keep inline assembly for the rare instruction nothing else can express.

Next: Debugging at the Instruction Level, where you step through code one instruction at a time.