Skip to content

2.23. Assembly Functions

An assembly function lets you write machine instructions and call them like a DQ function. Use one when you need a specific processor instruction that DQ expressions or library functions do not provide. You will need to know the assembly language for your target processor.

Here is a complete x86-64 example that adds two numbers:

use print

func Add(left : int, right : int) -> int [[inline, asm]]:
    lea $result, [$left + $right]
endfunc

func *Main():
    PrintLn("{}", [Add(19, 23)])
endfunc

This prints 42. $left and $right stand for the function arguments, and $result stands for its return value. The compiler chooses the actual registers. For ordinary addition, use a DQ expression; this small example shows how an assembly operation connects to a normal function call.

There are two forms:

Attributes What you write
[[inline, asm]] Instructions inserted at each direct call; the compiler connects arguments and results.
[[asm]] A complete native function, including argument handling and return instructions.

Both use a colon body closed by endfunc. They do not accept a bodyless declaration or a brace body. Instructions and register names depend on the target; the x86-64 examples do not work unchanged on ARM or RISC-V.

2.23.1 Inline Assembly Functions

[[inline, asm]] is useful for a small operation that should become part of the caller's code. Declare its input and result types just as for an ordinary function, then use named operands in the instructions.

On x86-64, use Intel syntax. ARM, AArch64, and RISC-V use their native syntax. DQ does not translate instructions or reorder their operands.

2.23.1.1 Named Operands

Use $result for the return value and $parameter for a function parameter. The compiler replaces these names with the target assembly operands allocated for the call.

For example, ARM targets with the rbit instruction can reverse the bits of a 32-bit value:

func ReverseBits(value : uint32) -> uint32 [[inline, asm]]:
    rbit    $result, $value
endfunc

$result is valid only when the function has a return type. An unknown name is a compile error. A literal dollar sign in assembly text must be written as $$ because the underlying assembly template syntax reserves $.

By default, parameters are register inputs and the result is a register output. Use the hints below for constant operands, memory access, or additional effects. The input and output registers may overlap. Write instructions that remain correct if $result uses the same register as an input, and do not modify an input register unless that change is represented by an output or clobber.

2.23.1.2 Operand Hints

The compiler must know what your instructions read or change. Put one hint list immediately before endfunc to describe those effects. For example, this x86-64 function multiplies by a compile-time constant:

func MulImmediate(value : int32, factor : int32) -> int32 [[inline, asm]]:
    imul    $result, $value, $factor
    [[immediate(factor), clobber(flags)]]
endfunc

The hint list tells the compiler about the instructions; it is not assembly text. It supports these clauses:

Hint Meaning
immediate(parameter, ...) Require compile-time integer-like arguments and use them as immediate operands
memread(parameter, ...) Describe memory read through typed pointer or readable reference arguments
memwrite(parameter, ...) Describe memory written through typed pointer or writable reference arguments
memreadwrite(parameter, ...) Describe memory both read and written through typed pointer or read/write reference arguments
clobber(resource, ...) Declare registers or other target resources modified by the assembly

A clause can name multiple operands. Clause and argument order do not affect the meaning. Each parameter may occur in at most one hint; parameters omitted from the list remain register inputs.

An immediate argument must be a compile-time constant at every call site. Its type must be an integer, Boolean, character, or enumeration type.

Memory operands must be typed pointers or references so that the compiler knows the accessed element type. The reference mode must permit the described access: refin can be read but not written, refout can be written but not read, and ref supports all three memory hints. The programmer remains responsible for passing a valid address.

A clobber names a register or other resource changed by the instructions. clobber(memory) is supported on every inline-assembly target. It acts as a compiler barrier, preventing memory operations from being moved across it:

func CompilerBarrier() [[inline, asm]]:
    [[clobber(memory)]]
endfunc

This does not emit a processor memory-barrier instruction.

clobber(flags) declares the condition-code state on x86, ARM, and AArch64 targets. It is not available on RISC-V. A physical register can also be named as a clobber, using its lowercase target name or a recognized conventional alias:

func AddOneThroughRax(value : int) -> int [[inline, asm]]:
    mov     rax, $value
    lea     $result, [rax + 1]
    [[clobber(rax)]]
endfunc

Declare every memory access and every modified resource that is not already an output. The optimizer can only account for effects described by the signature, memory hints, and clobbers.

2.23.2 Reading and Writing Memory

Use memory hints for instructions that access a pointed-to value. With these hints, $address means the memory at that address, rather than a register containing the pointer. These examples use x86-64 Intel syntax:

func Load32(address : ^int32) -> int32 [[inline, asm]]:
    mov     $result, $address
    [[memread(address)]]
endfunc

func Store32(address : ^int32, value : int32) [[inline, asm]]:
    mov     $address, $value
    [[memwrite(address)]]
endfunc

func AddTo32(address : ^int32, value : int32) [[inline, asm]]:
    add     $address, $value
    [[memreadwrite(address), clobber(flags)]]
endfunc

To try these three functions, place use print before them and add:

func *Main():
    var value : int32 = 10
    Store32(%value, 20)
    AddTo32(%value, 3)
    PrintLn("{}", [Load32(%value)])
endfunc

This prints 23. %value supplies the address of the local variable. memwrite describes the store, memreadwrite describes the addition, and memread describes the load. These hints tell the optimizer how the assembly interacts with the surrounding DQ code; the instructions perform the actual reads and writes.

An instruction may still require an explicit size qualifier when its other operands do not determine the access width:

func Inc32(address : ^int32) [[inline, asm]]:
    inc     dword ptr $address
    [[memreadwrite(address), clobber(flags)]]
endfunc

2.23.3 Complete Assembly Functions

Use [[asm]] when you need to control the whole native function. Unlike the inline form, its body must include the instruction that returns to the caller.

use print

func Return42() -> int [[asm]]:
    mov     eax, 42
    ret
endfunc

func *Main():
    PrintLn("{}", [Return42()])
endfunc

This prints 42 on x86-64 and uses Intel syntax. DQ uses the unified instruction destination, source operand order and does not support AT&T syntax.

The DQ signature determines the calling convention: the rules for passing arguments and returning values. The assembly implementation must read arguments from the correct registers or stack locations, place a return value in the correct location, preserve all required registers, and return to the caller. Parameter names and result are not available as operands in a complete assembly function.

The compiler emits an [[asm]] function as naked and non-inline. Consequently, it does not generate a prologue or epilogue (the instructions that normally set up and restore a function's stack and registers), or a DQ return operation. [[asm]] cannot be combined with [[external]], [[abstract]], or [[always_inline]].

2.23.4 Inline Assembly Restrictions

An inline assembly function does not produce a separately callable function. Every direct call emits the assembly template at the call site. It therefore cannot be converted to a function reference or have its address taken.

Inline assembly functions must be ordinary module-level functions. Methods and special functions such as *Main and *ModuleInit are not supported. They also cannot use [[external]], [[noinline]], [[weak]], [[section]], or native export attributes. [[overload]] is allowed, and inline assembly definitions in a module's public interface remain available to importing modules.

2.23.4.1 Operand Types and Registers

Without an operand hint, each parameter is a register input. Integer, Boolean, character, enumeration, pointer, and floating-point scalar operands are supported. The result is always a register output and must also have a supported scalar type. Integer and pointer values use the target's general-purpose register class; floating-point values use its native floating-point register class. Availability of a particular floating-point register class may depend on the selected CPU features.

2.23.5 Source Processing

Assembly bodies participate in normal DQ source processing:

  • // and /* ... */ comments are removed;
  • compiler directives are processed, and inactive conditional branches are omitted;
  • endfunc closes the body only when it is active and outside a comment;
  • comments and skipped branches preserve the separation between assembly tokens and instructions.

This permits target-specific implementations selected with conditional compilation. This x86-64 example uses a build-supplied TARGET_HAS_PAUSE definition to choose the instruction:

func Pause() [[inline, asm]]:
    #ifdef TARGET_HAS_PAUSE
        pause
    #else
        nop
    #endif
endfunc

Inside an assembly body, # starts a DQ directive only when it is the first non-whitespace, non-comment character on a physical source line. After assembly text has started on the line, # remains target assembly syntax. For example, the immediate in mov r0, #1 is preserved. Keep an instruction and any line-leading immediate operand on the same physical line; a continuation line starting with # would be parsed as a directive.

Because DQ comments are removed before assembly is parsed, do not use // or /* ... */ when those characters are intended as target assembler syntax. A line-leading # likewise cannot be used as a target assembler comment. In a complete [[asm]] body, [[...]] has no special meaning. In an [[inline, asm]] body, a line beginning with [[ is parsed as the single trailing operand-hint list, after which only comments, whitespace, and endfunc may follow.

2.23.6 Supported Inline-Assembly Targets

Typed inline assembly is supported for these target identifiers:

  • x86-64: x86_64;
  • ARM: arm_m0, arm_m3, arm_m4, arm_m4f, arm_m33, arm_m7f, arm_m7fd, arm, and ARM-A identifiers beginning with arm_a;
  • AArch64: aarch64, arm64;
  • RISC-V 32-bit: riscv32, rv32i, rv32imac;
  • RISC-V 64-bit: riscv64, rv64g.

Complete [[asm]] functions are not restricted to this list. In either form, instructions must match the selected target and CPU features.