Control Flow: CMP, Jumps, Calls & Syscalls

From MediaWiki
Jump to navigation Jump to search

Control Flow: CMP, Jumps, Calls & Syscalls

This page explains how the CPU executes instructions conditionally, how it branches to other code locations, and how it calls functions or system routines.

Why control flow is needed

So far, we’ve seen how to move data and perform arithmetic. However, programs must make decisions — for example, execute one piece of code if a value is positive and another if it’s negative. To do this, the CPU must compare values and decide where to go next.

Comparison instructions

The **CMP** instruction compares two operands by internally performing a subtraction. It updates the flags register but does not store the result anywhere. Subsequent instructions can check these flags to decide what to do next.

Example:

MOV RAX, 5
MOV RBX, 10
CMP RAX, RBX       ; Compare 5 with 10
; ZF = 0, SF = 1, CF = 1, OF = 0

After CMP, flags such as ZF (zero flag) or SF (sign flag) indicate the result of the comparison.

Conditional jumps

Conditional jumps alter the flow of execution based on the state of flags. They implement structures like `if`, `while`, and `for` in high-level languages.

Common conditional jumps: Instruction | Condition | Description


| ---------- | ------------

JE / JZ | ZF = 1 | Jump if equal / zero JNE / JNZ | ZF = 0 | Jump if not equal JG / JNLE | ZF = 0, SF = OF | Jump if greater (signed) JL / JNGE | SF ≠ OF | Jump if less (signed) JGE | SF = OF | Jump if greater or equal (signed) JLE | ZF = 1 or SF ≠ OF | Jump if less or equal (signed) JC | CF = 1 | Jump if carry JNC | CF = 0 | Jump if no carry

Example:

MOV RAX, 5
MOV RBX, 10
CMP RAX, RBX
JL  smaller_label    ; Jump if RAX < RBX
; otherwise continue
smaller_label:

Unconditional jumps

An unconditional jump always transfers control to a new address:

JMP target_label

This is used for loops, branching, or skipping code.

Function calls and returns

Functions (or subroutines) allow code reuse. They are implemented using the **CALL** and **RET** instructions.

  • `CALL label` pushes the return address (next instruction) onto the stack and jumps to `label`.
  • `RET` pops that address from the stack and resumes execution there.

Example:

CALL print_hello
; Execution resumes here after RET
print_hello:
  ; function body
  RET

System calls

User programs request operating system services through **syscalls**. In Linux on x86-64, arguments are placed in registers, and the syscall instruction is used.

Example: exiting a program

MOV RAX, 60    ; syscall number for exit
MOV RDI, 0     ; exit code 0
SYSCALL

Summary

  • CMP compares values and sets flags.
  • Conditional jumps (Jcc) make execution dependent on flags.
  • CALL and RET handle reusable functions.
  • SYSCALL invokes the operating system.

Together, these instructions enable structured, logical program execution at the CPU level.