liveBook · Manning

Assembly operand constraint

As explained in Embedded Software with Rust

A register operand constraint directs inline assembly to bind an operand to a compiler-selected register for input, output, or read-modify-write access.

An assembly operand constraint describes how inline assembly exchanges values with Rust. The constraint tells the compiler whether an operand is an input, output, or read-modify-write value, and whether it should use a compiler-selected register. Because asm!() bypasses Rust’s usual safety guarantees, the surrounding unsafe block must also state accurate memory, stack, and flag behavior. section 5.5.3

Use the register constraints according to the instruction’s data flow:

  • in(reg) expr supplies an input value in a compiler-selected general-purpose register. section 5.5.3
  • out(reg) var allocates a register for an assembly result and writes that result back to Rust. section 5.5.3
  • inout(reg) var represents an operand that is read and then overwritten in place. section 5.5.3
  • options(nomem, nostack, preserves_flags) makes explicit promises about memory access, stack-pointer changes, and condition flags; retain each option only when it is true. section 5.5.3

Byte reversal with separate input and output

The Arm REV instruction reverses the bytes of a 32-bit value. Binding x with in(reg) and y with out(reg) lets the compiler choose the registers while Rust receives the result. An in-place version can use inout(reg) when the instruction reads and overwrites the same register. section 5.5.3

use core::arch::asm;

let x: u32 = 0x1234_5678;
let y: u32;

unsafe {
    asm!(
        "rev {dst}, {src}",
        src = in(reg) x,
        dst = out(reg) y,
        options(nomem, nostack, preserves_flags),
    );
}

Inspect the complete input/output binding, including the assembly placeholders and compiler-contract options. section 5.5.3

use core::arch::asm;

let mut x: u32 = 0x1234_5678;

unsafe {
    asm!(
        "rev {x}, {x}",
        x = inout(reg) x,
        options(nomem, nostack, preserves_flags),
    );
}

Compare the in-place form, where one Rust variable is both the input and the output. section 5.5.3

How Embedded Software with Rust covers it

How deep it goes
Explains input, output, and read-modify-write bindings plus memory, stack, and flag promises, without detailing register-allocation internals.
Examples
Demonstrates Arm REV, an in-place byte reversal, a GPIO register toggle, and PRIMASK interrupt masking.
What you can do after
Builds inline assembly bindings that accurately communicate operand flow and compiler-visible side effects.
How it connects
Connects inline assembly with memory-mapped I/O, compiler clobbers, volatile access, and low-level Cortex-M control.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.