将结构从 c 翻译成 mips

Translate struct from c to mips

如何将此 C 代码转换为 Mips? 我有一个 List 结构,List 由一个数组组成,数组中的每个索引包含一个字符和一个整数,我如何在 .data 中翻译 Mips 中的列表以及如何访问类型条目数组的优先级和数据在主要?

#include <stdio.h>
#include <stdlib.h>
#define MAX 20

typedef struct{
   int priority;
   char data;
}entry;

typedef struct{
  entry arr[MAX];
  int Size;
}List;

int main()
{
   List l1;
   entry array[5];
   int priority=array[0].priority;
   char ch=array[0].data;
}

entry 一个大小和对齐方式,通过给它的每个字段一个偏移量和大小以及一个对齐方式。我将在开头添加一个额外的 char 字段,以便您可以更好地了解这是如何完成的。

field type size align pad start last next comment
extra char 1 1 0 0 0 1 first field
priority int 4 4 3 4 7 8 second field: padding of 3 for int so that the start offset is rounded up to a multiple of align=4 (from next=1 as left by the preceding field)
data char 1 1 0 8 8 9 third field
final padding 0 4 3 9 11 12 alignment=max of the preceding
totals entry 12 4 0 0 11 12 summary of whole struct

每个字段都有一个类型,并且该类型有大小和对齐要求。对于原始类型,对齐要求通常与字段的大小相同,对于结构,对齐是其所有字段的最大值。

第一个字段偏移量为 0,不需要填充。

对于第一个字段之后的每个字段,在字段的起始偏移量前面放置足够的填充,以便其起始偏移量与其数据类型正确对齐。

还有final padding,除了它的padding,我们可以(或不)认为是一个零长度的隐藏最后字段。最后一个字段和整个结构的对齐要求是所有其他字段对齐要求的最大值。

现在我们知道 entry 的大小,所以我们可以为下一个结构添加到 table(或单独的 table)。由于第一个字段是 20 的数组,我们将其大小乘以 20。

field type size align pad start last next comment
arr entry 240=12*20 4 0 0 239 240 first field
size int 4 4 0 240 243 244 second field
final padding 0 4 0 none required
totals List 244 4 0 0 243 244 summary of whole struct

好的,现在我们知道 List 的大小为 244,对齐要求为 4。

如果您将 List l1 作为全局变量(推荐),则:

    .data
    ...
    .align 2  # asking for 2^2=4 byte alignment
l1: .space 244
    ...

    .text
    ...
    la $a0, l1         # $a0 = & l1;
    lw $t0, 36($a0)    # $t0 = l1.arr[3].priority
    ...

您的 C 代码将 List l1 作为局部变量(而不是 .data 部分中的全局变量)。大小和对齐的计算对于局部变量是相同的,但是这个变量将存在于堆栈中,这意味着您必须为其分配堆栈 space 并计算其相对于堆栈指针的初始偏移量。

    .text
    ...
main:
    addiu $sp, $sp, -244 # allocate space for List l1 as local variable
    ...
    addiu $a0, $sp, 0    # $a0 = & l1; List l1 is lives at sp+0 .. sp+243
    lw $t0, 36($a0)      # $t0 = l1.arr[3].priority
    ...
    addiu $sp, $sp, 244  # release stack space
    ...

堆栈指针可以假定为至少 4 字节对齐,在某些系统(例如 64 位)上可能为 8 字节。