Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 40 ยท ARM Assembly

ARM Load/Store, Conditions and Branches

Learn ARM64 addressing modes (offset, pre-index, post-index), flags with cmp and b.cond, cbz, csel and cset, and how bl and ret use the link register.

The previous lesson introduced ARM64's registers and fixed-width instructions. Now we make programs do real work: reach memory in several ways, compare numbers, branch, and call functions. Three ideas stand out compared with x86: only loads and stores touch memory, flags are set only when you ask, and a call does not push anything on the stack at all.

The runnable examples use an ARM-flavored toy interpreter in JavaScript, so you can run real-looking ARM syntax and check every result; the instructions it implements follow the architecture's semantics, but it is a model and not an emulator.

Load-store architecture

On x86 you can write add DWORD PTR [rdi], 1, which reads memory, adds and writes back in one instruction. ARM64 is a load-store architecture: arithmetic instructions work only on registers, and memory is accessed only by dedicated load and store instructions. Incrementing a counter in memory takes three steps:

ASM
ldr  w1, [x0]          // load the 4-byte value
add  w1, w1, #1        // work in a register
str  w1, [x0]          // store it back

The instruction names encode the size. ldr and str move a 64-bit x register or a 32-bit w register, and b and h variants handle bytes and halfwords:

Instruction Moves Upper bits of the register
ldr x0, [..] / str x0, [..] 8 bytes all used
ldr w0, [..] / str w0, [..] 4 bytes loads clear bits 63..32
ldrh / strh 2 bytes loads zero-extend
ldrb / strb 1 byte loads zero-extend
ldrsb, ldrsh, ldrsw 1, 2, 4 bytes loads sign-extend (to x or w)

The family of paired instructions ldp and stp moves two registers at once, 16 bytes with x registers, which is why function prologues use them.

Addressing modes

A memory operand is written in square brackets. ARM64 offers a small, regular set of forms:

Form Address used Base register changes?
[x1] x1 no
[x1, #16] x1 + 16 no (offset)
[x1, x2] x1 + x2 no
[x1, x2, lsl #3] x1 + (x2 << 3) no (scaled register offset)
[x1, #16]! x1 + 16 yes, first (pre-index)
[x1], #16 x1 yes, afterwards (post-index)

The scaled form is the counterpart of x86's [base + index*scale] from Arrays and Addressing Modes: ldr x0, [x1, x2, lsl #3] loads element x2 from an array of 8-byte values. The shift is limited to the access size (for x registers, lsl #3).

Pre-index and post-index modes update the base register as part of the access, which makes the pointer-walking loop from the arrays lesson very compact:

ASM
ldr  x3, [x0], #8      // x3 = *x0; then x0 = x0 + 8   (post-index: "walk the array")
str  x3, [sp, #-16]!   // sp = sp - 16; then *sp = x3   (pre-index: this is a "push")
ldr  x3, [sp], #16     // x3 = *sp; then sp = sp + 16   (post-index: this is a "pop")

ARM64 has no push and pop instructions. A push is a store with pre-decrement, a pop a load with post-increment, always in multiples of 16 so sp stays aligned. Constant offsets are limited by the instruction word: in practice a few thousand bytes, scaled by the access size, for the plain offset form, and roughly -256 to 255 for pre/post-index. If a constant does not fit, the compiler first builds the address in a register.

Flags and conditions

Conditional branches need flags. ARM64 keeps four of them in nzcv: N (result negative), Z (result zero), C (carry, meaning no borrow after a subtraction) and V (signed overflow). Unlike x86, ordinary arithmetic does not change them. Only instructions that end in s do (adds, subs, ands), plus the comparison aliases:

ASM
cmp  x0, x1       // alias of: subs xzr, x0, x1   (subtract, keep only the flags)
cmn  x0, x1       // alias of: adds xzr, x0, x1
tst  x0, x1       // alias of: ands xzr, x0, x1

A conditional branch is written b. followed by a condition code. They are the same as x86's, with different names:

Condition Meaning after cmp a, b Flags tested
eq / ne a == b / a != b Z
lt / ge signed a < b / a >= b N != V / N == V
gt / le signed a > b / a <= b Z == 0 and N == V / Z == 1 or N != V
lo / hs unsigned a < b / a >= b C == 0 / C == 1
hi / ls unsigned a > b / a <= b C == 1 and Z == 0 / C == 0 or Z == 1
mi / pl negative / positive or zero N
vs / vc overflow / no overflow V

The signed and unsigned families differ exactly as on x86; Flags: ZF, SF, CF, OF explains why, and the interactive table below proves it with a few numbers.

Two extra instructions branch without flags. cbz x0, label jumps if the register is zero and cbnz if it is not; tbz and tbnz test a single bit. They replace the usual compare-with-zero plus branch pair, and they leave the flags untouched. Their reach is limited: b can jump about ยฑ128 MiB, while b.cond, cbz and cbnz reach about ยฑ1 MiB and tbz/tbnz about ยฑ32 KiB. The assembler and linker deal with that, so you rarely notice.

Avoiding branches: csel and cset

ARM64 has conditional select instructions that pick a value based on the flags, without any jump:

ASM
csel  x0, x1, x2, gt     // x0 = (flags say gt) ? x1 : x2
cset  w0, eq             // w0 = (eq) ? 1 : 0
csinc, csinv, csneg      // variants that increment, invert or negate the "else" value

This is the ARM spelling of x86's cmov from How if, switch and Ternaries Compile. The C function int max(int a, int b) { return a > b ? a : b; } compiles at -O2 to just this, with no branch at all:

ASM
max:
    cmp   w0, w1
    csel  w0, w0, w1, gt     // keep a if a > b, otherwise take b
    ret

The model below implements exactly the flag formulas from the tables: it subtracts like cmp, derives N, Z, C and V, evaluates every condition code, and then uses csel and cset to compute maximum and a clamp. Each row shows a case where the answers deliberately disagree.

JS cmp, condition codes, csel and cset

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

No output.

Look at the INT_MIN, 1 row. Subtracting 1 from the smallest signed 64-bit number wraps around to the largest positive one, so N is clear, but V is set. Because lt tests N != V, it still reports the correct signed answer (INT_MIN is less than 1), while hi and hs report the unsigned view, in which 0x8000... is a huge number. That is the job of V: it corrects the sign when the subtraction wraps. The -1, 1 row shows the other classic disagreement: signed lt is true, unsigned hi is also true.

How does ARM64 call a function with no stack push? It uses a register. The instruction bl label ("branch with link") puts the address of the next instruction into x30 (the link register) and jumps. ret is simply an indirect branch to x30.

flowchart LR
  M["caller: bl f"] -->|"x30 = address after bl, jump to f"| F["callee f: runs its code"]
  F -->|"ret = branch to x30"| R["caller continues after bl"]

A leaf function needs nothing more than bl and ret; the return address travels in a register.

For a leaf function (one that calls nobody) this is all you need, and the call and return cost no memory traffic. But a function that calls another function would overwrite x30 with its own bl, losing its way home. So non-leaf functions save the link register in their prologue, together with the frame pointer x29, in one paired store, and restore both before returning:

ASM
stp  x29, x30, [sp, #-16]!    // push frame pointer and link register (pre-index)
mov  x29, sp                  // frame pointer = current stack top
...                           // body, may contain bl
ldp  x29, x30, [sp], #16      // pop them (post-index)
ret

It is the same idea as the push rbp / mov rbp, rsp prologue in Stack Frames, Prologues and Epilogues, except that the return address is saved by the callee's own instruction instead of being pushed by call. Arguments and results follow the AAPCS64 convention from the last lesson: x0 to x7 in, x0 out.

The next demo is a complete ARM-style program. It keeps five 64-bit numbers in memory at address 512 (the toy has 8-byte memory cells and no flags register, so conditions are evaluated directly from the last cmp, a simplification of what you saw above). The leaf function sum walks the array with a post-index load and loops with cbz. The function total is a non-leaf function: it calls sum twice, so it saves x29 and x30 with stp, keeps its arguments and an intermediate result on the stack with pre-index stores, and unwinds everything with post-index loads. The stack pointer starts at 4096, and the program prints it at the end to prove the pushes and pops balanced.

JS A leaf function and a non-leaf function with bl and ret

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

No output.

The result is 250: the sum of all five numbers (150) plus the sum of the first four (100). The stack pointer prints 4096 again at the end, because each stp/str with a negative pre-index is matched by an ldp/ldr with a positive post-index. Try deleting the stp x29, x30 / ldp x29, x30 pair: the second bl overwrites x30 with its own return address, so the final ret jumps back into total instead of to _start, and the program goes wrong (on real hardware that is a crash or worse). That is why every function that makes a call must preserve x30.

Loops and function calls in real code must follow the whole calling convention: callee-saved registers x19 to x28 have to be restored, and sp must stay 16-byte aligned at every memory access. The toy leaves out alignment checks and register-saving rules to keep the code short.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ldr x3, [x0], #8 do?

    In the post-index form the access uses the unmodified base register, and the base is updated afterwards. It is the compact way to walk an array of 8-byte elements.
  2. 2. Which pair of instructions pushes x0 onto the stack in ARM64?

    ARM64 has no push instruction. A pre-indexed store with a negative offset decrements sp and writes in one step; 16 is used to keep sp 16-byte aligned.
  3. 3. After bl helper, where is the return address?

    bl stores the address of the following instruction in x30 and branches. ret later branches to x30. Nothing is pushed on the stack, which is why non-leaf functions must save x30 themselves.
  4. 4. What is true about the flags on ARM64?

    ARM64 updates nzcv only for the flag-setting forms (adds, subs, ands and the aliases cmp, cmn, tst). Plain add and sub leave the flags alone, so a comparison result survives other arithmetic.
  5. 5. Why does a non-leaf function begin with stp x29, x30, [sp, #-16]!?

    Each bl overwrites x30 with its own return address, so a function that makes calls must first save its caller's return address (and normally the frame pointer) on the stack.

Summary

  • ARM64 is a load-store architecture: only ldr/str (and variants such as ldrb, ldrsw, ldp, stp) access memory.
  • Addressing modes are offset, register (optionally shifted), pre-index [x1, #n]! and post-index [x1], #n; push and pop are a pre-decrement store and a post-increment load.
  • Flags are set only by cmp, cmn, tst and the s-suffixed instructions; b.cond branches on them with the same eq/ne/lt/ge/gt/le and lo/hs/hi/ls families as x86.
  • cbz, cbnz, tbz and tbnz branch without flags; csel and cset select values without branching.
  • bl puts the return address in x30 and ret branches to it; non-leaf functions save x29 and x30 with stp and restore them with ldp.

Next: x86-64 vs ARM64: Side by Side, where we put the same C function through both instruction sets and compare the results.