Write an x86-64 procedure/function called sum that does the following: a. It is
ID: 3909977 • Letter: W
Question
Write an x86-64 procedure/function called sum that does the following:
a. It is passed two parameters, array and size, by the procedure/function that calls it. The first parameter is a pointer to the beginning of an array of shorts (2-byte values), and the second parameter is the number of elements in the array. sum returns a short value. AC language prototype for the function would be:
short sum(short *array, short size);
b. sum() computes the sum of the elements in the array, calls printf to print the value (Assume that an appropriate format string has been placed in read-only memory with a label .LCO), and also returns the sum result to sum()’s caller in register %ax. Make sure that your sum() function does both!
c. Be sure to do the proper stack set up work at the beginning and end of the procedure/function, and be sure to save and restore the values of any callee save registers that you modify. Also be sure to leave the stackin the appropriate state for the return instruction. You can assume that there is no overflow on any operation.
Explanation / Answer
int sum(int * array, int size)
{
int sum = 0 ;
int i =0;
for(i=0; i<size; i++)
sum += array[i];
return sum;
}
**//
.section .rodata
.LC0:
.string "sum - %d "
.text
.globl sum
.type sum, @function
sum:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $32, %rsp
movq %rdi, -24(%rbp)
movl %esi, -28(%rbp)
movl $0, -8(%rbp)
movl $0, -4(%rbp)
movl $0, -4(%rbp)
jmp .L2
.L3:
movl -4(%rbp), %eax
cltq
leaq 0(,%rax,4), %rdx
movq -24(%rbp), %rax
addq %rdx, %rax
movl (%rax), %eax
addl %eax, -8(%rbp)
addl $1, -4(%rbp)
.L2:
movl -4(%rbp), %eax
cmpl -28(%rbp), %eax
jl .L3
movl -8(%rbp), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movl -8(%rbp), %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size sum, .-sum
.ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609"
.section .note.GNU-stack,"",@progbits
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.