Untitled
Alignment Restrictions
- Importance: Word and halfword store and load instructions must be properly aligned for effective data access.
- Alignment Requirements:
- Word accesses must occur at addresses that are multiples of 4.
- Halfword accesses must occur at addresses that are multiples of 2.
Overview of Arrays
Definition: An array is a sequence of data items that are contiguous in memory.
Example of Byte Array:
- Declaring an array of bytes:
.data Primes: .byte 2, 3, 5, 7- Memory mapping:
- Addresses 1001 0000 to 1001 0003 hold values 02 to 07.
Example of Word Array:
- Declaring an array of words:
.data Primes: .word 2, 3, 5, 7- Memory mapping:
- Each word spans 4 bytes (e.g., Addresses 1001 0000 to 1001 0003 holds 2; 1001 0004 to 1001 0007 holds 3; etc.).
Loading Values from Arrays
- Loading the First Element:
- Code to load first element:
lw $t0, Primes- This translates to
$t0 = Primes[0] = 2.
- Loading All Elements:
- Use offsets to access all elements:
lw $t0, Primes+0lw $t1, Primes+4lw $t2, Primes+8lw $t3, Primes+12- Indexed as:
t1 = Primes[1],t3 = Primes[3].
Understanding Pointers
- Definition: A pointer is a variable or register that holds a memory address.
- Setting a Pointer:
- Example of setting a pointer to an array:
la $a0, Primes- Now,
$a0contains the address of the Primes array (e.g., 1001 0000).
- Loading Values via Pointers:
- To load first element using pointer:
lw a0)- Translates to
$s0 = a0[0] = 2. - Load all elements with offsets:
lw a0)lw a0)lw a0)lw a0).
Performing Operations with Arrays
- Example Operation:
- Let x be in
s2, address of Z in$s3and add Z[5] to y: lw s3)// Load Z[5]add $s1, $s2, $s1// Calculate x = y + Z[5]
- Let x be in
Array of Halfwords Exercise
- Task: Add three halfwords from an array pointed to by
$a1:- Code:
lhu a1)// Load first halfwordlhu a1)// Load second halfwordadd $v0, $v0, $t0// Add first and second valueslhu a1)// Load third halfwordadd $v0, $v0, v0.
Address Calculation Example
- Example with Halfword Array B:
- Let
jbe ins1: mul $t0, $s0, 2// Calculate offset for B[j]add $t1, $s1, $t0// Obtain address of B[j]lw t1)// Load value from B[j].
- Let
Assigning Array Values
- Example of Array Assignment:
- If
A[n] = A[m], code example: mul $t0, $a1, 4// Calculate offset for A[m]add $t0, $a0, $t0// Address of A[m]lw t0)// Load A[m]mul $t0, $a2, 4// Calculate offset for A[n]add $t0, $a0, $t0// Address of A[n]sw t0)// Store value in A[n].
- If
Instruction Summary
- Instructions Used:
- Load/Store:
li,move,la,lw,sw,lhu,sh,lbu,sb - Arithmetic:
add,sub,mul,div,neg
- Load/Store:
Recommended Reading
- Text: "Computer Organization and Design: The Hardware/Software Interface" (5th Edition) by David A. Patterson & John L. Hennessy