如何在assembly riscv中使用short int求和堆栈的元素



Aready有一个使用数组的代码,但我想使用短int。如何使用短int?

sum:
lw x1, 0x0(x10)
lw x2, 0x4(x10)
add x3, x0, x0
loop:
lw x4, 0x0(x1)
add x3, x3, x4
addi x1, x1, 4
addi x2, x2, -1
bnex x2, loop

sw x3, 0x8(x10)

Risc-V没有任何类型。因此编译器可以使用短int编译相同的代码。

但是,由于短int在大多数情况下都是16位长,也称为半字,因此可以使用lh(加载半字(和sh(存储半字(而不是lw和sw重写代码。

此外,您还需要注意正在使用的寄存器,否则代码将无法正确运行。还有你正在加载的内容。在您的示例中,您使用x10(a0-参数寄存器1(作为指向数组指针的指针,同时也是指向大小的指针。这通常是不可能的,也不可能用C来描述(可能用structs(。

回到寄存器。您使用的是x1(ra-返回地址(、x2(sp-堆栈指针(、x3(gp-全局指针(和x4(tp-线程指针(。所有这些都是你不想为了基本的通用操作而触摸的寄存器。通常用于此类操作的寄存器是x5-x7和x28-x31临时寄存器。但为了便于阅读,最好使用t0-t6。

这是短整型的正确版本:

sum:                 # C-style: short int sum(short int* array, short int size)
# a0 holds the array pointer and a1 holds the size
addi t0, zero, 0 # t0 will hold the result of the summation
loop:
lh t1, 0(a0)     # load the first element of the array
add t0, t0, t1   # sum the array element to t0
addi a1, a1, -1  # decrement the size to not overflow the array
addi a0, a0, 2   # increment the array address to point to the next array element
# its 2 because of short ints (16 bits -> 2 bytes)
bnez a1, loop    # check if the summation is done
add a0, t0, zero # move the result to a0 (also return value register)
ret              # return using the ra register (so don't overwrite the ra register)

我希望这会有所帮助。

为了获得进一步的帮助,我强烈建议阅读";Risc-V用户规范";。它还描述了寄存器的使用以及如何很好地映射函数。

最新更新