-
Notifications
You must be signed in to change notification settings - Fork 0
/
power.s
71 lines (58 loc) · 2.24 KB
/
power.s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#PURPOSE: Program to illustrate how functions work.
# This program will compute the value of 2^3 + 5^2
#
#Everything in the main progmra is stored in registers, so the data section doesn't have anything.
.section .data
.section .text
.globl _start
_start:
pushl $3 #push the second argument on to the stack
pushl $2 #push the first argument on to the stack
call power #call the function
addl $8, %esp #move the stack pointer back. We add 8 to %esp because we passed two arguments (2*4)
pushl %eax #save the first answer before calling the next function
pushl $2 #push the second arg
pushl $5 #push the first arg
call power #call the function
addl $8, %esp #move the stack pointer back
popl %ebx #the second answer is already in %eax. We saved the first answer onto the stack, so now
#we cab just pop it out into %ebx
addl %eax, %ebx #add them together. the result is in %ebx
movl $1, %eax #exit
int $0x80
#PURPOSE: This function is sued to compute the value of a number raised to a power.
#
#INPUT: First argument -the base number
# Second argument - the power to raise is to
#OUTPUT: Will give the result as a return value
#
#NOTES: The power must be 1 or greater
#
#VARIABLES:
# %ebx - holds the base number
# %ecx - holds the power
# -4(%ebp) - holds the current result
#
# %eax is used for temporary storage
#
.type power, @function
power:
pushl %ebp #save old base pointer
movl %esp, %ebp #make stack pointer the base pointer
subl $4, %esp #get room for our local storage
movl 8(%ebp), %ebx #put the first argument in %ebx
movl 12(%ebp), %ecx #put the second argument in %ecx
movl %ebx, -4(%ebp) #store current result
power_loop_start:
cmpl $1, %ecx #if the power is 1, we are done
je end_power
movl -4(%ebp), %eax #move the current result into %eax
imull %ebx, %eax #multiply the current result by the base number
movl %eax, -4(%ebp) #store the current result
decl %ecx #decrease the power
jmp power_loop_start #run for the next power
end_power:
movl -4(%ebp), %eax #return value goes in %eax
movl %ebp, %esp #restore the stack pointer
popl %ebp #restore the base pointer
ret