summary refs log tree commit diff
path: root/src/main.zig
blob: 993c0a144e8e519733deae7b2520635ec0a1ae1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
//! Parse command-line arguments and call the compiler.
const Allocator = std.mem.Allocator;
const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
const arch = builtin.target.cpu.arch;
const argsWithAllocator = std.process.argsWithAllocator;
const assert = std.debug.assert;
const builtin = @import("builtin");
const c = @import("cimport.zig");
const cWriter = std.io.cWriter;
const eql = std.mem.eql;
const exit = std.os.exit;
const fclose = std.c.fclose;
const fopen = std.c.fopen;
const getStdErr = std.io.getStdErr;
const getStdOut = std.io.getStdOut;
const isAlphabetic = std.ascii.isAlphabetic;
const span = std.mem.span;
const std = @import("std");
const toUpper = std.ascii.toUpper;

/// Native target.
const default_target = switch (builtin.target.os.tag) {
    .macos => switch (arch) {
        .aarch64 => &c.T_arm64_apple,
        .x86_64 => &c.T_amd64_apple,
        else => unreachable,
    },
    else => switch (arch) {
        .aarch64 => &c.T_arm64,
        .riscv64 => &c.T_rv64,
        .x86_64 => &c.T_amd64_sysv,
        else => unreachable,
    },
};

/// Print the help message and exit with the given status.
/// The usage is printed to stderr on an error status, to stdout otherwise.
fn printUsage(prog: [:0]const u8, status: u8) !noreturn {
    const stream = (if (status == 0) getStdOut() else getStdErr()).writer();
    try stream.print(
        \\{s} [OPTIONS] {{file.ssa, -}}
        \\	-h          prints this help
        \\	-o file     output to file
        \\	-t <target> generate for a target among:
        \\	            
    , .{ prog });
    for (c.targets, 0..) |target, i| {
        if (i > 0)
            try stream.writeAll(", ");
        const name: [*:0]const u8 = @ptrCast(&target.name);
        try stream.print("{s}", .{ span(name) });
        if (target == default_target)
            try stream.writeAll(" (default)");
    }
    try stream.writeAll(
        \\
        \\	-d <flags>  dump debug information:
        \\	            P (parsing),
        \\	            M (memory optimization),
        \\	            N (SSA construction),
        \\	            C (copy elimination),
        \\	            F (constant folding),
        \\	            A (ABI lowering),
        \\	            I (instruction selection),
        \\	            L (liveness),
        \\	            S (spilling),
        \\	            R (register allocation)
        \\
    );
    exit(status);
}

/// Print the given message and exit.  The message is printed
/// to stderr on an error status, to stdout otherwise.
fn die(comptime format: []const u8, args: anytype, status: u8) !noreturn {
    const stream = if (status == 0) getStdOut() else getStdErr();
    try stream.writer().print(format, args);
    exit(status);
}

/// Function emitter.
const Fun = struct {
    /// Postprocess the parsed function.
    fn process(fun: *c.Fn) void {
        c.T.abi0(fun);
        c.fillrpo(fun);
        c.fillpreds(fun);
        c.filluse(fun);
        c.promote(fun);
        c.filluse(fun);
        c.ssa(fun);
        c.filluse(fun);
        c.ssacheck(fun);
        c.fillalias(fun);
        c.loadopt(fun);
        c.filluse(fun);
        c.fillalias(fun);
        c.coalesce(fun);
        c.filluse(fun);
        c.ssacheck(fun);
        c.copy(fun);
        c.filluse(fun);
        c.fold(fun);
        c.T.abi1(fun);
        c.simpl(fun);
        c.fillpreds(fun);
        c.filluse(fun);
        c.T.isel(fun);
        c.fillrpo(fun);
        c.filllive(fun);
        c.fillloop(fun);
        c.fillcost(fun);
        c.spill(fun);
        c.rega(fun);
        c.fillrpo(fun);
        c.simpljmp(fun);
        c.fillpreds(fun);
        c.fillrpo(fun);
        assert(fun.rpo[0] == fun.start);
        var n: c_uint = 0;
        while (n + 1 < fun.nblk) : (n += 1)
            fun.rpo[n].?.link = fun.rpo[n + 1]
        else
            fun.rpo[n].?.link = null;
    }

    /// Log debugging information about the given function.
    fn debug(fun: *c.Fn, out: *c.FILE) callconv(.C) void {
        const writer = cWriter(@ptrCast(out));
        const name: [*:0]const u8 = @ptrCast(&fun.name);
        writer.print("**** Function {s} ****", .{ span(name) })
            catch unreachable;
        if (c.debug['P']) {
            writer.writeAll("\n> After parsing:\n") catch unreachable;
            c.printfn(fun, out);
        }
        process(fun);
        writer.writeAll("\n") catch unreachable;
        c.freeall();
    }

    /// Emit the given function.
    fn emit(fun: *c.Fn, out: *c.FILE) callconv(.C) void {
        process(fun);
        c.T.emitfn(fun, out);
        const writer = cWriter(@ptrCast(out));
        const name: [*:0]const u8 = @ptrCast(&fun.name);
        writer.print("/* end function {s} */\n\n", .{ span(name) })
            catch unreachable;
        c.freeall();
    }
};

/// Parser of a compilation unit.
const Parser = struct {
    dbg: bool,
    out: *c.FILE,

    /// Initialize parser from command-line options.
    pub fn init(allocator: Allocator) !Parser {
        c.T = default_target.*;
        var args = try argsWithAllocator(allocator);
        var dbg = false;
        var out = fopen("/dev/stdout", "w").?;
        errdefer _ = fclose(out);

        const prog = args.next().?;
        while (args.next()) |arg| {
            if (arg.len < 2 or arg[0] != '-')
                continue;
            const value = if (arg[1] == 'h')
                try printUsage(prog, 0)
            else if (arg.len == 2)
                args.next() orelse try printUsage(prog, 1)
            else
                arg[2..];

            switch (arg[1]) {
                'd' => for (value) |flag| {
                    if (isAlphabetic(flag)) {
                        c.debug[toUpper(flag)] = true;
                        dbg = true;
                    }
                },
                'o' => {
                    _ = fclose(out);
                    out = fopen(value, "w") // TODO: explicit OpenError
                        orelse try die("cannot open '{s}'\n", .{ value }, 1);
                },
                't' => {
                    if (eql(u8, value, "?")) {
                        const name: [*:0]const u8 = @ptrCast(&c.T.name);
                        try die("{s}\n", .{ span(name) }, 0);
                    }
                    c.T = for (c.targets) |target| {
                        const name: [*:0]const u8 = @ptrCast(&target.name);
                        if (eql(u8, value, span(name)))
                            break target.*;
                    } else try die("unknown target '{s}'\n", .{ value }, 1);
                },
                else => try printUsage(prog, 1),
            }
        }

        if (dbg) {
            _ = fclose(out);
            out = fopen("/dev/stdout", "w").?;
        }
        return .{ .dbg = dbg, .out = out };
    }

    /// Finish writing to output file.
    pub fn deinit(self: Parser) void {
        if (!self.dbg)
            c.T.emitfin(self.out);
        _ = fclose(self.out);
    }

    /// Skip emitting data in debug mode.
    fn noop_dat(_: *c.Dat, _: *c.FILE) callconv(.C) void {}

    /// Parse the given file.
    pub fn parse(self: Parser, file: *c.FILE, path: [*:0]const u8) void {
        c.parse(file, path, self.out,
            if (self.dbg) noop_dat else c.emitdat,
            if (self.dbg) Fun.debug else Fun.emit);
    }
};

pub fn main() !void {
    var gpa = GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.detectLeaks();

    const parser = try Parser.init(allocator);
    defer parser.deinit();
    var read_stdin = true;
    var args = try argsWithAllocator(allocator);
    _ = args.next().?;
    const stdin = fopen("/dev/stdin", "r").?;
    while (args.next()) |arg| {
        if (arg[0] == '-' and arg.len > 1) {
            // must be -d, -o or -t
            if (arg.len == 2)
                _ = args.next().?;
            continue;
        }
        read_stdin = false;
        const in_file = if (eql(u8, arg, "-")) stdin else fopen(arg, "r")
            orelse try die("cannot open '{s}'\n", .{ arg }, 1);
        defer _ = fclose(in_file);
        parser.parse(in_file, arg.ptr);
    }
    if (read_stdin)
        parser.parse(stdin, "-");
}