Skip to content

Commit 2a58885

Browse files
committed
Fix signed integer overflow in RV32I
The implementation of add, sub, and addi instructions incorrectly used int32_t for arithmetic operations, leading to signed integer overflow. Address the issue by maintaining the uint32_t type for arithmetic operations, ensuring compliance with the laws of arithmetic modulo 2^n. This approach prevents undefined behavior resulting from signed integer overflow.
1 parent 4975222 commit 2a58885

File tree

2 files changed

+5
-11
lines changed

2 files changed

+5
-11
lines changed

src/rv32_constopt.c

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,8 +233,7 @@ CONSTOPT(srai, {
233233
CONSTOPT(add, {
234234
if (info->is_constant[ir->rs1] && info->is_constant[ir->rs2]) {
235235
info->is_constant[ir->rd] = true;
236-
ir->imm = (int32_t) info->const_val[ir->rs1] +
237-
(int32_t) info->const_val[ir->rs2];
236+
ir->imm = info->const_val[ir->rs1] + info->const_val[ir->rs2];
238237
info->const_val[ir->rd] = ir->imm;
239238
ir->opcode = rv_insn_lui;
240239
ir->impl = dispatch_table[ir->opcode];
@@ -246,8 +245,7 @@ CONSTOPT(add, {
246245
CONSTOPT(sub, {
247246
if (info->is_constant[ir->rs1] && info->is_constant[ir->rs2]) {
248247
info->is_constant[ir->rd] = true;
249-
ir->imm = (int32_t) info->const_val[ir->rs1] -
250-
(int32_t) info->const_val[ir->rs2];
248+
ir->imm = info->const_val[ir->rs1] - info->const_val[ir->rs2];
251249
info->const_val[ir->rd] = ir->imm;
252250
ir->opcode = rv_insn_lui;
253251
ir->impl = dispatch_table[ir->opcode];

src/rv32_template.c

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,7 @@ RVOP(
603603
*/
604604
RVOP(
605605
addi,
606-
{ rv->X[ir->rd] = (int32_t) (rv->X[ir->rs1]) + ir->imm; },
606+
{ rv->X[ir->rd] = rv->X[ir->rs1] + ir->imm; },
607607
GEN({
608608
ld, S32, TMP0, X, rs1;
609609
alu32_imm, 32, 0x81, 0, TMP0, imm;
@@ -732,9 +732,7 @@ RVOP(
732732
/* ADD */
733733
RVOP(
734734
add,
735-
{
736-
rv->X[ir->rd] = (int32_t) (rv->X[ir->rs1]) + (int32_t) (rv->X[ir->rs2]);
737-
},
735+
{ rv->X[ir->rd] = rv->X[ir->rs1] + rv->X[ir->rs2]; },
738736
GEN({
739737
ld, S32, TMP0, X, rs1;
740738
ld, S32, TMP1, X, rs2;
@@ -745,9 +743,7 @@ RVOP(
745743
/* SUB: Substract */
746744
RVOP(
747745
sub,
748-
{
749-
rv->X[ir->rd] = (int32_t) (rv->X[ir->rs1]) - (int32_t) (rv->X[ir->rs2]);
750-
},
746+
{ rv->X[ir->rd] = rv->X[ir->rs1] - rv->X[ir->rs2]; },
751747
GEN({
752748
ld, S32, TMP0, X, rs1;
753749
ld, S32, TMP1, X, rs2;

0 commit comments

Comments
 (0)