Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions src/parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* shecc is freely redistributable under the BSD 2 clause license. See the
* file "LICENSE" for information on usage and redistribution of this file.
*/
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Expand Down Expand Up @@ -3512,16 +3513,29 @@ int eval_expression_imm(opcode_t op, int op1, int op2)
res = op1 * op2;
break;
case OP_div:
if (!op2)
error_at("Division by zero in constant expression",
cur_token_loc());
res = op1 / op2;
break;
case OP_mod:
if (!op2)
error_at("Modulo by zero in constant expression", cur_token_loc());
/* Use bitwise AND for modulo optimization when divisor is power of 2 */
if (tmp == INT_MIN) {
res = op1 % op2;
break;
}
tmp = tmp < 0 ? -tmp : tmp;
Comment thread
tobiichi3227 marked this conversation as resolved.
tmp &= (tmp - 1);
if ((op2 != 0) && (tmp == 0)) {
res = op1;
res &= (op2 - 1);
} else
if (tmp != 0) {
res = op1 % op2;
break;
}
op2 = op2 < 0 ? -op2 : op2;
res = op1 & (op2 - 1);
if (op1 < 0 && res != 0)
res -= op2;
break;
case OP_lshift:
res = op1 << op2;
Expand Down
21 changes: 21 additions & 0 deletions tests/driver.sh
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,27 @@ declare -a arithmetic_tests=(
run_expr_tests arithmetic_tests
expr 6 "111 % 7"

try_output 0 "1 1 -1 -1" << EOF
int v1 = 5 % 4;
int v2 = 5 % -4;
int v3 = -5 % 4;
int v4 = -5 % -4;
int main() {
printf("%d %d %d %d", v1, v2, v3, v4);
return 0;
}
EOF

try_compile_error << EOF
int value = 1 / 0;
int main() { return value; }
EOF

try_compile_error << EOF
int value = 1 % 0;
int main() { return value; }
EOF

# Category: Overflow Behavior
begin_category "Overflow Behavior" "Testing integer overflow handling"

Expand Down
Loading