Skip to content

Commit

Permalink
Sema: return comptime_int if all args to @min/@max are comptime_int
Browse files Browse the repository at this point in the history
Resolves: #15776
  • Loading branch information
mlugg authored and andrewrk committed May 29, 2023
1 parent 46e724a commit e2837fd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Sema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21940,10 +21940,18 @@ fn analyzeMinMax(
}
}

const opt_runtime_idx = runtime_known.findFirstSet();

const comptime_refined_ty: ?Type = if (cur_minmax) |ct_minmax_ref| refined: {
// Refine the comptime-known result type based on the operation
const val = (try sema.resolveMaybeUndefVal(ct_minmax_ref)).?;
const orig_ty = sema.typeOf(ct_minmax_ref);

if (opt_runtime_idx == null and orig_ty.eql(Type.comptime_int, mod)) {
// If all arguments were `comptime_int`, and there are no runtime args, we'll preserve that type
break :refined orig_ty;
}

const refined_ty = if (orig_ty.zigTypeTag() == .Vector) blk: {
const elem_ty = orig_ty.childType();
const len = orig_ty.vectorLen();
Expand Down Expand Up @@ -21982,7 +21990,7 @@ fn analyzeMinMax(
break :refined refined_ty;
} else null;

const runtime_idx = runtime_known.findFirstSet() orelse return cur_minmax.?;
const runtime_idx = opt_runtime_idx orelse return cur_minmax.?;
const runtime_src = operand_srcs[runtime_idx];
try sema.requireRuntimeBlock(block, src, runtime_src);

Expand Down
17 changes: 17 additions & 0 deletions test/behavior/maximum_minimum.zig
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,20 @@ test "@min/@max notices vector bounds" {
try expectEqual(@Vector(2, u32){ 140, 300 }, max);
try expectEqual(@Vector(2, u32), @TypeOf(max));
}

test "@min/@max on comptime_int" {
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest; // TODO

const min = @min(1, 2, -2, -1);
const max = @max(1, 2, -2, -1);

try expectEqual(comptime_int, @TypeOf(min));
try expectEqual(comptime_int, @TypeOf(max));
try expectEqual(-2, min);
try expectEqual(2, max);
}

0 comments on commit e2837fd

Please sign in to comment.