Addressing Modes: Direct, Indirect, Base+Index, Offsets

From MediaWiki
Jump to navigation Jump to search

Addressing Modes: Direct, Indirect, Base+Index, Offsets

This page explains how different addressing modes work in x86-64 assembly and how they apply beyond the mov instruction.

Overview

Addressing modes define how operands are interpreted by the CPU:

  • **Immediate** – The value is part of the instruction itself.
  • **Register** – The operand is stored in a CPU register.
  • **Memory** – The operand is located in RAM, referenced by an address.

Understanding addressing modes is essential for efficient data access and struct or array manipulation.

Immediate addressing

The constant value is embedded directly into the instruction.

Example:

mov rax, 42     ; load 42 directly into rax

Useful for initializing values or setting counters.

Direct memory addressing

The instruction refers to a fixed memory address.

Example:

mov rax, [100]  ; load from memory at address 100

Used for accessing global or static data at a known location.

Register indirect addressing

A register holds the memory address to read from or write to.

Example:

mov [rbx], rax  ; write the value of rax to the address stored in rbx

Commonly used for pointer-like behavior.

Direct offset addressing

Adds a fixed offset to a base register to access a specific location in a structure.

Example:

mov [rbx+8], rax  ; write to the field at offset 8 from base address in rbx

Useful when working with data structures or objects.

Base + index addressing

Uses one register as a base address and another as an index.

Example:

mov rax, [rbx + rdi]  ; read an array element

If each element has a size larger than one byte, a scaling factor can be used:

mov rax, [rbx + rdi*8]  ; access 8-byte (64-bit) elements

Addressing with other instructions

Many instructions other than mov can access memory operands directly.

Example:

add [rax], 10  ; add 10 to the value stored at memory address in rax

This single instruction: 1. Loads the value from memory at [rax]. 2. Adds 10 to it. 3. Stores the result back to [rax].

CISC vs. RISC note

x86-64 is a Complex Instruction Set Computer (CISC). It allows instructions that perform multiple steps (like load + operate + store). Internally, however, modern x86 CPUs translate these into smaller RISC-like operations for efficiency.

Understanding addressing modes helps predict performance and design efficient code.