Skip to content

Branch miscompiled as if it were comptime known #9749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
adlerd opened this issue Sep 12, 2021 · 1 comment
Closed

Branch miscompiled as if it were comptime known #9749

adlerd opened this issue Sep 12, 2021 · 1 comment
Milestone

Comments

@adlerd
Copy link

adlerd commented Sep 12, 2021

I tried running this program

const std = @import("std");
pub fn main() anyerror!void{
    var args = std.process.args();
    _ = args.skip();
    const flag = args.skip();
    return std.fmt.format(std.io.getStdOut().writer(), "{any}\n{s}\n", .{
        flag,
        if (flag) @as([]const u8, "YES") else "NO",
    });
}

zig version: 0.9.0-dev.874+4334dbb9a

When running the program with no arguments, the expected output is:

false
NO

The observed output is:

false
YES

This example was minimized from another example; the general problem seems to be format arguments initialized by a branch between two constant strings, when the branch is not comptime known.

@adlerd adlerd changed the title Incorrect constant string printed by std.fmt.format Branch miscompiled as if it were comptime known Sep 16, 2021
@rohlem
Copy link
Contributor

rohlem commented Sep 16, 2021

Probably a manifestation/duplicate of the nasty #3882 / #4491 / #5230 / #7097 .
The stage1 compiler is alarmingly buggy with conditional control flow filling tuples.
The current workaround is to write the values to variables first, and use those in the tuple.

const answer = if (flag) @as([]const u8, "YES") else "NO";
return std.fmt.format(std.io.getStdOut().writer(), "{any}\n{s}\n", .{
    flag,
    answer,
});

Not great. Would probably be better for stage1 to hard-error if we could reliably detect these scenarios.

@Vexu Vexu closed this as completed Sep 16, 2021
@andrewrk andrewrk added this to the 0.9.0 milestone Nov 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants