-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite_matrix.s
More file actions
98 lines (88 loc) · 2.15 KB
/
write_matrix.s
File metadata and controls
98 lines (88 loc) · 2.15 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
.globl write_matrix
.text
# ==============================================================================
# FUNCTION: Writes a matrix of integers into a binary file
# If any file operation fails or doesn't write the proper number of bytes,
# exit the program with exit code 1.
# FILE FORMAT:
# The first 8 bytes of the file will be two 4 byte ints representing the
# numbers of rows and columns respectively. Every 4 bytes thereafter is an
# element of the matrix in row-major order.
# Arguments:
# a0 is the pointer to string representing the filename
# a1 is the pointer to the start of the matrix in memory
# a2 is the number of rows in the matrix
# a3 is the number of columns in the matrix
# Returns:
# None
# ==============================================================================
write_matrix:
# Prologue
addi sp, sp, -28
sw s0, 0(sp)
sw s1, 4(sp)
sw s2, 8(sp)
sw s3, 12(sp)
sw s4, 16(sp)
sw s5, 20(sp)
sw ra, 24(sp)
mv s0, a0 #filename
mv s1, a1 #ptr to start of matrix in memory
mv s2, a2 #number of rows
mv s3, a3 #number of columns
#open file w/ write only permission
mv a1, s0
li a2, 1
jal ra, fopen
#error if file fails to open
li t0, -1
beq a0, t0, eof_or_error
#save fopen return value
mv s4, a0 #s3= file descriptor
#put number of rows into stack
addi sp, sp, -4
sw s2, 0(sp)
#write number of rows into file
mv a1, s4
mv a2, sp
li a3, 1
li a4, 4
jal ra, fwrite
li t0, 1
bne t0, a0, eof_or_error
#write number of columns into file
sw s3, 0(sp)
mv a1, s4
mv a2, sp
li a3, 1
li a4, 4
jal ra, fwrite
li t0, 1
bne t0, a0, eof_or_error
addi sp, sp, 4
#store number of items in matrix
mul s5, s2, s3
#write matrix to file
mv a1, s4
mv a2, s1
mv a3, s5
li a4, 4
jal ra, fwrite
bne a0, s5, eof_or_error
#close file
mv a1, s4
jal ra, fclose
bne a0, x0, eof_or_error
# Epilogue
lw s0, 0(sp)
lw s1, 4(sp)
lw s2, 8(sp)
lw s3, 12(sp)
lw s4, 16(sp)
lw s5, 20(sp)
lw ra, 24(sp)
addi sp, sp, 28
ret
eof_or_error:
li a1 1
jal exit2