In: Computer Science
Write an arm assembly program that will multiply two arrays (index by index) and store the result in a third array.
Declare an array:
.data
Arr1: .quad 10 #index 0
.quad 4 #index 1
…..
Arr2: .quad 2,5,6….
Arr3: .quad 0,0,0….
To load array pointer address:
Movq $Arr1, %rdx #stores address of Arr1 index 0 in rdx
To move to the next index of an array:
Addq $8,%rdx
To retrieve data:
Movq (%rdx), %rcx # will have data at address in rdx
We can also use LEA instruction.
Xorq %rbx,%rbx
LEAQ (%rdx, %rbx,8), %<reg> #address if index 0 in reg
Movq(%<reg>) , %<reg> #data at index 0
Inc %rbx
To store data:
Movq %<reg>, (%<reg that has address>)
.global main
.text
main:
movq $arr, %rcx #load address of index 0
movq (%rcx), %rax #retrieve data at index 0
addq $8, %rcx #go to next index 8 bytes over
movq (%rcx), %rax #get data at index 1
#or
xorq %rcx,%rcx
movq $arr, %rbx
leaq (%rbx,%rcx,8), %rax #ADDRESS OF INDEX 0
movq (%rax),%rax #content at index 0
incq %rcx
leaq (%rbx,%rcx,8), %rax #address of index 1
# or
xorq %rcx, %rcx
movq arr(,%rcx,8), %rax #move content at index 0 to rax
#or
xorq %rcx,%rcx
movq $arr,%rbx
movq (%rbx,%rcx,8), %rdx #move content at index 0
# exiting
movq $60, %rax # sys_exit syscall number: 60
xorq %Rdi, %Rdi # set exit status to 0
syscall
.data
arr: .quad 10,11,12
.data
x: .word 4,5,2
y: .word 1,8,3
z: .space 12
main:
.text
la $a0 x #loads contents into $a0
la $a1 y
la $a2 z
jal addArray #function call
li $v0, 4
syscall
addArray:
addi $sp, $sp, -4 # make room for 1 saved register
[b] sw $s0, 0($sp) # save $s0 onto frame stack[/b]
add $s0, $zero, $zero # initialize i=0
add $s1, $zero, 12 #for the loop condition
L1:
add $t1, $s0, $a0 # compute x[i] as $a0[$s0]
add $t2, $s0, $a1
lbu $t3, 0($t1) # load byte at x[i] (x+i) into $t3
lbu $t4, 0($t2) # load byte at y[i] (y+i) into $t3
add $t5, $t3, $t4 #adding elements x+y and putting it in $t5
add $t6, $s0, $a2
sb $t5, 0($t6) #adds to the third array
beq $s0, $s1, L2 # $s0 >=$s1
addi $s0, $s0, 4 # increment array
j L1 # jump unconditionally to L1 (beginning of loop)
L2:
lw $s0, 0($sp) # restore $sp
addi $sp, $sp, 1 # pop 1 word off the stack
jr $ra # return to sender