You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QtSPIM中MIPS汇编报错:addi x10,x0,0语法错误求助

QtSPIM下MIPS汇编语法错误排查与修正

需求场景

要把这段C代码转成MIPS汇编:

a=0
for(i=0;i<10;i++){
a=a+arr[i]
}

在QtSPIM中运行时报错:spim:syntax error on line 9 addi x10, x0, 0,编写的汇编代码如下:

# data section
   .data
   
   .text
# define main program
   .globl main

main:   
addi x10, x0, 0       # a = 0
addi x11, x0, 0       # i = 0
addi x12, x0, 0x10010000 # arr base address
loop:
    addi x16, x0, 10      # x16 = 10
    bge x11, x16, end_loop # if i >= 10, jump to end_loop
    slli x13, x11, 2      # x13 = i * 4
    add x14, x12, x13     # x14 = arr + i * 4
    lw x15, 0(x14)        # x15 = arr[i]
    add x10, x10, x15     # a = a + arr[i]
    addi x11, x11, 1      # i++
    j loop                # jump to loop
end_loop:

错误原因分析

  1. 寄存器命名不兼容:QtSPIM仅支持MIPS 32位架构的寄存器命名规则(如$0/$zero、$t0、$t1等),你使用的x0、x10是RISC-V架构的寄存器命名,这是触发语法错误的核心原因。
  2. 缺失数组定义:代码直接硬编码数组基地址0x10010000,但未在.data段定义arr数组,运行时会触发内存访问错误。
  3. 主程序无退出逻辑:end_loop后没有退出程序的系统调用,QtSPIM会继续执行后续无效指令导致异常。

修正后的汇编代码

# data section
   .data
arr:    .word   1,2,3,4,5,6,7,8,9,10  # 定义测试用arr数组,包含10个元素
   .text
# define main program
   .globl main

main:   
addi $t0, $zero, 0       # $t0 = a = 0
addi $t1, $zero, 0       # $t1 = i = 0
la   $t2, arr            # 加载arr的基地址(替代硬编码,更规范)
loop:
    addi $t5, $zero, 10      # $t5 = 10
    bge  $t1, $t5, end_loop  # if i >= 10, jump to end_loop
    slli $t3, $t1, 2         # $t3 = i * 4(每个int占4字节)
    add  $t4, $t2, $t3       # $t4 = arr + i*4,即arr[i]的地址
    lw   $t6, 0($t4)         # $t6 = arr[i]
    add  $t0, $t0, $t6       # a = a + arr[i]
    addi $t1, $t1, 1         # i++
    j    loop                # 跳回循环开头
end_loop:
    # 退出程序的系统调用
    li   $v0, 10
    syscall

关键修改说明

  • 将所有xXX格式的寄存器替换为MIPS 32标准命名:$zero(对应x0)、$t0-$t9(临时寄存器,适合存储a、i这类变量)
  • 在.data段添加arr数组定义,用.word声明10个测试元素
  • 用la指令加载数组基地址,替代硬编码内存地址,提升代码可移植性
  • 在end_loop后添加退出程序的系统调用(li $v0,10 + syscall),保证程序正常结束

内容的提问来源于stack exchange,提问作者unit5016

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:18:12