Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. .globl read_matrix
  2.  
  3. .text
  4. # ==============================================================================
  5. # FUNCTION: Allocates memory and reads in a binary file as a matrix of integers
  6. # If any file operation fails or doesn't read the proper number of bytes,
  7. # exit the program with exit code 1.
  8. # FILE FORMAT:
  9. # The first 8 bytes are two 4 byte ints representing the # of rows and columns
  10. # in the matrix. Every 4 bytes afterwards is an element of the matrix in
  11. # row-major order.
  12. # Arguments:
  13. # a0 is the pointer to string representing the filename
  14. # a1 is a pointer to an integer, we will set it to the number of rows
  15. # a2 is a pointer to an integer, we will set it to the number of columns
  16. # Returns:
  17. # a0 is the pointer to the matrix in memory
  18. # ==============================================================================
  19. read_matrix:
  20.  
  21. # Prologue
  22. addi sp sp -28
  23.  
  24. sw ra 0(sp)
  25. sw s0 4(sp)
  26. sw s1 8(sp)
  27. sw s2 12(sp)
  28. sw s3 16(sp)
  29. sw s4 20(sp)
  30. sw s5 24(sp)
  31.  
  32. # save the args
  33. mv s0 a0
  34. mv s1 a1 # s1 is the pointer to the number of rows
  35. mv s2 a2 # s2 is the pointer ot the number of cols
  36.  
  37. # open the file
  38. mv a1 a0
  39. li a2 0
  40. jal ra fopen
  41.  
  42. li t1, -1
  43. beq a0 t1 eof_or_error
  44. mv s3 a0 # s3 is the descriptor
  45.  
  46. # read the row num and col num
  47. mv a1 s3
  48. mv a2 s1
  49. li a3 4
  50. jal ra fread
  51. li t1, 4
  52. bne a0 t1 eof_or_error
  53.  
  54. mv a1 s3
  55. mv a2 s2
  56. li a3 4
  57. jal ra fread
  58. li t1, 4
  59. bne a0 t1 eof_or_error
  60.  
  61. # malloc for the matrix
  62. li t0 1
  63. lw t1 0(s1)
  64. blt t1 t0 eof_or_error
  65. lw t2 0(s2)
  66. blt t2 t0 eof_or_error
  67. mul t3 t1 t2
  68. slli s4 t3 2
  69.  
  70. mv a0 s4
  71. jal ra malloc
  72. mv s5 a0
  73.  
  74.  
  75. # read the matrix
  76. mv a1 s3
  77. mv a2 s5
  78. mv a3 s4
  79. jal ra fread
  80. bne a0 s4 eof_or_error
  81.  
  82. # close the file
  83. mv a1 s3
  84. jal ra fclose
  85. li t1 -1
  86. beq a0 t1 eof_or_error
  87.  
  88. # put the resulting matrix into r0
  89. mv a0 s5
  90.  
  91. # Epilogue
  92. lw ra 0(sp)
  93. lw s0 4(sp)
  94. lw s1 8(sp)
  95. lw s2 12(sp)
  96. lw s3 16(sp)
  97. lw s4 20(sp)
  98. lw s5 24(sp)
  99. addi sp sp 28
  100. jr ra
  101.  
  102. ret
  103.  
  104. eof_or_error:
  105. li a1 1
  106. jal exit2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement