1

I have a short snippet of RISC-V assembly that I'm having trouble understanding. I'm not sure if I'm interpreting the instructions wrong, from my interpretation it seems as if the branch (BNE) will be taken but it is given that it should not be.

Given commented code:

000001b8 <test_4>:
lui  sp,0xfffff     # -> load [sp]  = 0xfffff000
addi sp,sp,-96      # -> add -96 to [sp], resulting in [sp]  = 0xffffefa0 
sb   sp,2(ra)       # -> store 0xffffffff (sign extend [23:16] of [sp]) to memory
lh   a4,2(ra)       # -> load halfword from data memory to [a4]  = 0xffffffff 
lui  t2,0xfffff
addi t2,t2,-96      # -> [t2]  = 0xffffefa0 
li   gp,4 
bne  a4,t2,56c <fail> # -> guaranteed fail since 0xffffffff != 0xffffefa0? 

Any help would be greatly appreciated!

jhe4x
  • 13
  • 1
  • 4
  • 1
    Sorry, I felt that the comments I added provided an adequate explanation of what I expected each instruction to do. RISC-V is relatively new, but it does share quite a significant portion of its instruction set with MIPS, which is fairly commonplace and taught in many college courses. I believe the LUI, ADDI, SB, BNE, and SH instructions are all included in the MIPS ISA. I was wondering if specifically I interpreted the SB (store byte) and LH (load halfword) instructions correctly; or if those two instructions do load the value 0xffffffff into memory. I hope this is better! – jhe4x Jul 21 '21 at 07:09
  • Specifically, I was hoping someone could look at the comments for each instruction and see if the interpretation of the instructions is incorrect. This snippet of code was assembled for the RV32i base integer ISA if that helps. If there's any additional information I can provide just let me know – jhe4x Jul 21 '21 at 07:23
  • Why do you say "it is given that it should not be"? My reading is that following the branch is considered to be a fail, and it will always fail. – Simon B Aug 05 '21 at 21:15

1 Answers1

3

You seem to misunderstand SB:

sb   sp,2(ra)       # -> store 0xffffffff (sign extend [23:16] of [sp]) to memory

This comment is not correct. This stores 0xa0 (lower 8 bits of sp) to memory. The address is ra+2.

a4 will have the value of 0xSSSSXXa0 where XX is whatever value happens to be in the next byte and SSSS is the sign extension of it. If that byte was 0xef then a4 can indeed have the value 0xffffefa0.

user253751
  • 11,998
  • 2
  • 21
  • 37