210 likes | 436 Views
Assembly language: arrays and loops. Ellen Spertus MCS 111 September 27, 2001. The big picture. Addition of immediates. addi $s1, $s2, immediate Meaning: $s1 = $s2 + immediate Exactly three operands First two operands are registers Last operand is an immediate (constant)
E N D
Assembly language:arrays and loops Ellen Spertus MCS 111 September 27, 2001
Addition of immediates addi $s1, $s2, immediate • Meaning: $s1 = $s2 +immediate • Exactly three operands • First two operands are registers • Last operand is an immediate (constant) Why do we call them immediates?
Storage • Registers • 32-bit wide D flip-flops • Hold data • Can be directly operated on by assembly instructions, e.g., add $r1, $r2, $r3 • Main memory (aka RAM) • An array of bytes(8 bits wide) • Hold data and instructions • Can only be accessed through the load (lw, lb) and store (sw, sb) instructions
Where do we keep variables? • Their permanent home is main memory • Why? • They may temporarily be stored in registers • Why?
Example (bytes) sum = sum + count; addi $a0, $zero, 200 lb $t0, 0($a0) lb $t1, 1($a0) add $t0, $t0, $t1 sb $t0, 0($a0)
Example (words) sum = sum + count; addi $a0, $zero, 200 lw $t0, 0($a0) lw $t1, 4($a0) add $t0, $t0, $t1 sw $t0, 0($a0) sum count
Scalars vs. arrays • Scalar variable • Single item, e.g., count • Takes up one word of memory • Array • Many items, e.g., a[0]…a[7] • Each element takes up one word of memory
Arrays: example 1 count[1] = count[1] +count[0]; addi $a0, $zero, 200 lw $t0, 0($a0) addi $a0, $zero, 204 lw $t1, 0($a0) add $t1, $t1, $t0 sw $t1, 0($a0)
Arrays: example 2 count[1] = count[1] +count[0]; addi $a0, $zero, 200 lw $t0, __($a0) addi $a0, $zero, 204 lw $t1, __($a0) add $t1, $t1, $t0 sw $t1, __($a0)
Rules for accessing arrays • The array is stored somewhere in memory. Put the address of the base(beginning) of the array into a register. • Assuming each element of the array is one word (4 bytes) long, the offset(distance from base) of element n is 4*n.
Arrays: example 3 count[2] = count[2] +count[5]; addi $a0, $zero, 200 lw $t0, __($a0) lw $t1, __($a0) add $t1, $t1, $t0 sw $t1, __($a0)
Arrays: practice c[0]=c[0]- c[1] + c[2]; addi $a0, $zero, 200
Arrays: example 4 count[i] =0; Assume base of array is in $a0 Assumeiis in$t0
Arrays: example 5 for (i=0; i < 100; i++)count[i] = 0; Assume base of array is in $a0 add $t0, $zero, $zero addi $t1, $zero, 100 addi $t0, $t0, 1 bne $t0, ____, ____
Arrays: Practice for (int i = 0; i <= 100; i++)a[i] = b[i] + c;