所以我在火星匯編中有一個小程式,它得到最大公約數:
.text
addiu $4,$zero,49
addiu $5,$zero,42
add $2,$zero,$5
beq $4,$zero,label10
loop:
beq $5,$zero,label9
slt $9,$5,$4
bne $9,$zero,if
slt $10,$4,$5
bne $10,$zero,else
beq $10,$zero,else##if $4 and $5 are equal.
if:
sub $4,$4,$5
j endif
else:
sub $5,$5,$4
j endif
endif:
j loop
label9:
add $2,$0,$4
label10:
結果將保存在暫存器 2 中。現在我的第二個任務是,我應該更改我的程式,以便我的演算法是一些“函式”(子程式),您可以在其中設定暫存器 4 和 5 的引數以及暫存器 2 中的回傳值.我現在的問題是,我不知道該怎么做。
uj5u.com熱心網友回復:
為了將代碼片段轉換為函式,需要執行以下操作:
- 在開頭給它一個標簽,例如
MyFunc。 jr $ra最后加上一個return:。- 制作一個呼叫您的函式的測驗主程式并將其放在該
.text部分的開頭-您希望此測驗主程式成為模擬器首先運行的,因此它將呼叫您的函式-您不希望首先使用您的函式,因為它不再是一個片段,而是一個函式,它應該被正確呼叫:通過傳遞引數和回傳地址。主程式還必須正確終止程式,否則它將運行邊緣并再次運行該函式,但這次是意外。
.text
# test main: call MyFunc
#
# call function, pass some parameters
li $a0, 20 # load first arg register
li $a1, 15 # load second arg register
jal MyFunc # the actual invocation
# this jumps to the function,
# while also passing the return address in $ra
# here's where come back to when the function is done:
move $a0, $v0 # move return value into $a0, so we can print it
li $v0, 1 # and print
syscall
li $v0, 10 # and stop the program
syscall
#
#
#
MyFunc: # start of MyFunc
# ... # code of function goes here
jr $ra # jump back to the caller by using the return address register
建議使用友好的暫存器名稱而不是簡單的數字名稱。(而且我們不應該在同一個程式中將友好名稱與簡單的數字名稱混合在一起。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488488.html
上一篇:6502代碼中的高效多重間接尋址
