diff --git a/src/compiler/sema_expr.c b/src/compiler/sema_expr.c index b2d279304..a50da2421 100644 --- a/src/compiler/sema_expr.c +++ b/src/compiler/sema_expr.c @@ -4792,8 +4792,9 @@ static bool sema_expr_analyse_bit(Context *context, Expr *expr, Expr *left, Expr // 3. Do constant folding if both sides are constant. if (expr_both_const(left, right)) { + BinaryOp op = expr->binary_expr.operator; expr_replace(expr, left); - switch (expr->binary_expr.operator) + switch (op) { case BINARYOP_BIT_AND: expr->const_expr.ixx = int_and(left->const_expr.ixx, right->const_expr.ixx); @@ -4857,8 +4858,9 @@ static bool sema_expr_analyse_shift(Context *context, Expr *expr, Expr *left, Ex // 5. Fold constant expressions. if (IS_CONST(left)) { + bool shr = expr->binary_expr.operator == BINARYOP_SHR; expr_replace(expr, left); - if (expr->binary_expr.operator == BINARYOP_SHR) + if (shr) { expr->const_expr.ixx = int_shr64(left->const_expr.ixx, right->const_expr.ixx.i.low); } diff --git a/test/test_suite/compile_time/compile_time_bitops.c3t b/test/test_suite/compile_time/compile_time_bitops.c3t new file mode 100644 index 000000000..eb3cb79be --- /dev/null +++ b/test/test_suite/compile_time/compile_time_bitops.c3t @@ -0,0 +1,18 @@ +// #target: x64-darwin +module foo; + +int x1 = 2 ^ 4; +int x2 = 2 | 4; +int x3 = 2 & 4; +int y1 = 4 << 2; +int y2 = 4 >> 2; +int y3 = ~4; + +/* #expect: foo.ll + +@foo.x1 = global i32 6, align 4 +@foo.x2 = global i32 6, align 4 +@foo.x3 = global i32 0, align 4 +@foo.y1 = global i32 16, align 4 +@foo.y2 = global i32 1, align 4 +@foo.y3 = global i32 -5, align 4 \ No newline at end of file