简体   繁体   English

C到MIPS的组装混乱

[英]C to MIPS assembly confusion

I am new to assembly coding and I came across a problem that says to transfer the following C code to MIPS assembly. 我是汇编编码的新手,遇到一个问题,该问题说将以下C代码转移到MIPS汇编中。

b[8] = b[i-j] + x ;

and variables i,j,x are in registers 7,4 and 15 and base address of array b is in 2,870,220 decimal. 变量i,j,x位于寄存器7,4和15中,而数组b的基址则位于十进制2,870,220中。

I came up with the following solution 我想出了以下解决方案

 lui $2, 0x002B
 ori $2, $2, 0xCBCC
 sub $3, $7, $4
 add $3, $2, $3
 lw $12, 0($3)
 addu $12, $12, $15
 sw $12, 32($2) 

but when I checked the answer, there was one additional line of 但是当我检查答案时,又有一行

sll $3, $3, 2 

after the subtract instruction. 在减法指令之后。

Could someone please explain why do we need to multiply the content of register $3 by 4 ? 有人可以解释一下为什么我们需要将寄存器$ 3的内容乘以4吗?

I'll give an illustration. 我会举例说明。

Let's say we have these 5 bytes stored in memory locations 0x00000000 to 0x00000004 (as an example, I'm disregarding memory maps): 假设我们将这5个字节存储在内存位置0x00000000至0x00000004中(例如,我不考虑内存映射):

| | 0x27 | 0x27 | 0x82 | 0x82 | 0x97 | 0x97 | 0x42 | 0x42 | 0x11 | 0x11 |

When loading a word at memory address 0x00000000, it would give you the 32-bit word 0x27829742 because it concatates the next 4 bytes from the base address. 在存储器地址0x00000000加载一个字时,它将为您提供32位字0x27829742,因为它会连接基地址中的下一个4个字节。

At memory address 0x00000001, however, you get 0x82974211. 但是,在内存地址0x00000001处,您将获得0x82974211。


I'm thinking that this misunderstanding is coming from how operator[] is implemented in arrays, so I'll try to expand on that. 我认为这种误解来自于如何在数组中实现operator [],因此我将尝试对此进行扩展。 Consider the following C code: 考虑以下C代码:

int arr[3] = { 1, 3, 5 };
printf("%d\n", arr[2]); // print third element

When accessing arr[2], it has to take into account the size of the elements of the array. 访问arr [2]时,必须考虑数组元素的大小 Assuming that the int standard is 32bit (4byte), you would get the following code during compile time: 假设int标准为32位(4字节),则在编译时将获得以下代码:

int arr[3] = { 1, 3, 5 };
printf("%d\n", *(arr + (2 * sizeof(int)))); // print third element

In this case, it offsets the base pointer of the array by an integer's worth of bytes multiplied by the index being accessed, and then deferenced to get the specified element. 在这种情况下,它将数组的基本指针偏移一个整数字节的值再乘以要访问的索引,然后进行引用以获取指定的元素。

In conclusion: 结论:

Memory blocks are aligned in 8bit bytes, not 32bit words. 内存块以8位字节而不是32位字对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM