当MIPS转换为C时,无法理解代码顺序

时间:2015-10-16 21:08:15

标签: c mips translate

我试图将MIPS代码转换为C.我得到了问题的答案,但我猜到的答案与答案略有不同。所以我想问你。这是问题和建议的答案:

问题:

sll $t0, $s0, 2 

add $t0, $s6, $t0 

sll $t1, $s1, 2 

add $t1, $s7, $t1 

lw $s0, 0($t0) 

addi $t2, $t0, 4 

lw $t0, 0($t2) 

add $t0, $t0, $s0 

sw $t0, 0($t1)

答案:

B[g] = A[f + 1] + A[f];
f = A[f];

我认为答案恰恰相反,因为f = A [f]首先按从上到下的顺序计算。所以这是我的答案:

 f = A[f];
 B[g] = A[f + 1] + A[f];

我知道答案正确,但为什么?我只是卡在那里。

谢谢你,

1 个答案:

答案 0 :(得分:1)

您的分析是正确的,但您的解释不是:

;These 2 compute the address of A[f], using pointer arithmetic
; s0 is f and s6 is A
sll  $t0, $s0, 2     ; t0 = s0 << 2
add  $t0, $s6, $t0   ; t0 = s6 + t0  -- t0 is now the address of A[f]

;These 2 compute the address of B[g], using pointer arithmetic
; s1 is g and s7 is B
sll  $t1, $s1, 2     ; t1 = s1 << 2
add  $t1, $s7, $t1   ; t1 = s7 + t1  -- t1 is now the address of B[g]

; load A[f] into s0. s0 used to be f so we can read this as f = A[f]
lw   $s0, 0($t0)     ; s0 = A[f]

; Compute address of A[f+1]
addi $t2, $t0, 4     ; t2 = t0 + 4 -- t2 is now the address of A[f+1]

; Load A[f+1]
lw   $t0, 0($t2)     ; t0 = Mem[t2] -- which is t0 = A[f+1]

; Add A[f] + A[f+1]
add  $t0, $t0, $s0   ; t0 = t0 + ts -- which is A[f] + A[f+1]
; Store  A[f] + A[f+1] into B[g]
sw  $t0, 0($t1)      ; Mem[t1] = t0 -- which is B[g] = A[f] + A[f+1]

如果你想用高级语言表达同样的话,那确实是:

B[g] = A[f + 1] + A[f];
f = A[f];

您的顺序执行结果不正确,使用简单替换来检查执行时的含义 顺序

f = A[f];
B[g] = A[f + 1] + A[f];

相同
B[g] = A[A[f] + 1] + A[A[f]];
f = A[f];

这不是代码的作用。