[英]Converting C code snippet to MIPS Assembly
as part of a homework assignment we're required to convert the following code snippet from C to MIPS Assembly:作为家庭作业的一部分,我们需要将以下代码片段从 C 转换为 MIPS 程序集:
for (i=0; i<A; i++) {
for (j=0; j<B; j++) {
C[4 * j] = i + j;
}
}
I believe I have the logic down and most of the code is correct.我相信我的逻辑是错误的,并且大部分代码都是正确的。 I'm just stuck at the line: D[4 * j] = i + j;
我只是卡在这条线上: D[4 * j] = i + j;
. . I know how to get the sum of i
and j
, but I'm not sure how to actually put it into a multiple of its j address.我知道如何获得i
和j
的总和,但我不确定如何将其实际放入其 j 地址的倍数中。 Could someone please tell me what I'm missing in loop2?有人可以告诉我我在loop2中缺少什么吗? Thanks谢谢
.data
A: .word 2
B: .word 5
D: .word 0 : 100
size: .word 100
.text
.globl main
main:
lw, $s0, A #$s0 = A
addi $s0, $s0, -1 #Allows for loop to properly run
lw $s1, B #$s1 = B
addi $s1, $s1, -1 #Allows for loop to properly run
la $s5, C # load address of array
li $t0, 0 #i = 0
li $t1, 0 #j = 0
loop1:
blt $s0, $t0, Exit #for(i = 0; i < A; i++)
addi $t0, $t0, 1 #i++
li $t1, 0 #Sets j to 0 before calling loop2
j loop2 #Calls loop2
loop2:
blt $s0, $t0, loop1 #for(j = 0; j < B; j++)
addi $t2, $t0, -1 #Allows to properly perform loop
{Where I'm confused what to do}
{Last two steps of loop2}
addi $t1, $t1, 1 #j++
j loop2
Exit:
# The program is finished. Exit.
li $v0, 10 # system call for exit
syscall # Exit!
Your assembly code barely resembles the C equivalent you're showing.您的汇编代码几乎与您展示的 C 等效代码相似。 For example, there is no -1
in the C code, yet used multiple times in the assembly code!例如,C 代码中没有-1
,但在汇编代码中多次使用!
Thus, you have gone down the classic error-prone approach of hyper-optimizing your code during translation from C to assembly .因此,在从 C 转换到 assembly 期间,您已经采用了经典的容易出错的超优化代码的方法。 This is a very error prone process, and also unnecessary!!这是一个非常容易出错的过程,也是不必要的!!
The best way to do this pointer and loop optimization is to do it all in C first, We can express many, many optimizations such as these and others in C directly!进行这种指针和循环优化的最佳方法是首先在 C 中完成所有这些,我们可以直接在 C 中表达诸如此类和其他许多优化! Then test it in C to make sure it works, only then take to assembly knowing that at least the algorithm works!然后在 C 中对其进行测试以确保它可以正常工作,然后才知道至少该算法可以工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.