使用循环增量(MARS)

时间:2014-02-07 17:19:26

标签: loops assembly mips mars-simulator

所以我在MIPS中有一个我目前坚持的任务。我的任务也是:

1)编写一个从数组的第一个元素开始的循环 2)然后依次为每个元素添加1并将结果存储回数组中 3)如果遇到零,退出程序

这是我已经拥有的:

.data  #by default, the "data segment" starts at address 0x10010000
.word 1
.word 2
.word 3
.word 4
.word 5
.word 6
.word 7
.word 8
.word 9
.word 0

.text #instructions start below
lui $s0, 0x1001     # $s0 holds base address of the array
addi $s1, $zero, 0  # $s1 holds the index of the array
jal increment       # call loop procedure

increment:
beq $s0, $zero, Exit    # if $s0 value is zero, branch and go to else
addi $s0, $s0, 1    # adds 1 to each element
addi $s1, $s1, 1    # i = i + 1

j increment     # jump back to loop

Exit:
infinite: j infinite 

我运行它时遇到的问题是它一直在运行。我知道第10个单词(.word0)包含值0.

我的代码中哪些比赛我错了?

非常感谢


@Robert B,这就是我现在所拥有的:

main: #instructions start below
la $s0, myData      # $s0 holds base address of the array
addi $s1, $zero, 0  # $s1 holds the index of the array

loop:
beq $s0, $zero, else    # if $s0 value is zero, branch and go to else
addi $s0, $s0, 2    # adds 2 to each element
addi $s1, $s1, 1    # i = i + 1

j loop      # call loop procedure

else:
addi $v0, $zero, 10     # terminate execution
syscall 

2 个答案:

答案 0 :(得分:0)

无限跳跃至少是问题的一部分。

答案 1 :(得分:0)

我看到了一些潜在的问题。

.text #instructions start below

虽然可执行指令确实在.text之后开始,但在那里定义一个名为main:的标签是个好主意。模拟器看到了这一点并且明确地知道从哪里开始(至少,我认为这是默认配置的方式。)

lui $s0, 0x1001     # $s0 holds base address of the array
addi $s1, $zero, 0  # $s1 holds the index of the array

你在这里做了一个与实现相关的重大假设。最好添加一个指向第一个数据项的标签:

.data  # Maybe the "data segment" starts at address 0x10010000, maybe it doesn't
myData:
.word 1
.word 2
...

现在,您可以将标签的地址加载到$ s1中。下面的代码实际上是一个伪操作码,编译器将其扩展为luiaddi

la $s0, myData

编译器可能会提出你开始使用的确切代码,指向地址0x10010000 ......但你最好让编译器做出决定。

最后,问题是为什么你在这里做jal

jal increment       # call loop procedure
increment:

除非您为了清晰起见省略了一些代码,否则您将跳转并链接到下一个地址。这没有多大意义。您只需要在调用子例程时使用jal。通过执行jal,子例程将返回j $ra之后的行。

哦,是的,你的教授希望你使用无限循环。那太奇怪了。 syscall 10有什么问题?

li  $v0, 10 # terminate execution
syscall