MIPS結構體傳參

本文講解了C語言運行在MIPS體系中結構體傳參的情況

硬件平臺:Loongson 3A3000

系統:uos

在《see MIPS run》中11.2.5中描述到,會將結構體成員壓縮到各個arg寄存器中進行傳遞
“we have to pack the register with data to mimic the arrangement of data in memory.”

  1. C語言代碼:
    構造一個函數,參數爲結構體,在main函數中調用函數,並傳入結構體
	#include <stdio.h>
#include <stdint.h>

struct shape{
        uint32_t a;
        uint16_t b
};

void test(struct shape sp){

    uint32_t c = sp.a + sp.b;
    printf("%d \n", c); 
}

void main()
{
    struct shape sp; 
    sp.a = 12; 
    sp.b = 32; 
    test(sp);
}

  1. 彙編代碼

0000000000000b00 <test>:
 b00:   67bdffc0    daddiu  sp,sp,-64
 b04:   ffbf0038    sd  ra,56(sp)
 b08:   ffbe0030    sd  s8,48(sp)
 b0c:   ffbc0028    sd  gp,40(sp)
 b10:   03a0f025    move    s8,sp
 b14:   3c1c0002    lui gp,0x2
 b18:   0399e02d    daddu   gp,gp,t9
 b1c:   679c8320    daddiu  gp,gp,-31968
 b20:   ffc40010    sd  a0,16(s8)
 b24:   8fc30010    lw  v1,16(s8)
 b28:   97c20014    lhu v0,20(s8)
 b2c:   00621021    addu    v0,v1,v0



0000000000000b74 <main>:
 b74:   67bdffd0    daddiu  sp,sp,-48
 b78:   ffbf0028    sd  ra,40(sp)
 b7c:   ffbe0020    sd  s8,32(sp)
 b80:   ffbc0018    sd  gp,24(sp)
 b84:   03a0f025    move    s8,sp
 b88:   3c1c0002    lui gp,0x2
 b8c:   0399e02d    daddu   gp,gp,t9
 b90:   679c82ac    daddiu  gp,gp,-32084
 b94:   2402000c    li  v0,12		//加載立即數到V0
 b98:   afc20000    sw  v0,0(s8)		//保存到棧中
 b9c:   24020020    li  v0,32		//加載立即數到V0
 ba0:   a7c20004    sh  v0,4(s8)	//保存到棧中
 ba4:   dfc40000    ld  a0,0(s8)
 ba8:   df828058    ld  v0,-32680(gp)
 bac:   0040c825    move    t9,v0
 bb0:   0411ffd3    bal b00 <test>

  • 在ba0代碼執行完畢後棧內數據情況如下
    在這裏插入圖片描述
  • ba4 ld a0,0(s8); 把棧中8個字節加載到了a0寄存器,即圖中0~8中的數據,即結構體中的a、b
  • b20 sd a0,16(s8); 把a0,放到棧中16offset
  • b24 lw v1,16(s8); 從棧中16offset讀取前4個字節
  • b28 lhu v0,20(s8);從棧中20offset讀取剩下兩個字節
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章