diff --git a/bench/pp_bench.zig b/bench/pp_bench.zig new file mode 100644 index 0000000..bce586e --- /dev/null +++ b/bench/pp_bench.zig @@ -0,0 +1,112 @@ +//! Preprocessor benchmark: lexes / preprocesses a set of files in-process +//! and reports the best-of-N wall time and throughput. +//! +//! Usage: pp_bench [-mode lex|pp|print] [-iters N] +//! The file list has one path per line. File contents are read once and +//! served from memory, so disk I/O is excluded from the timings. + +const std = @import("std"); +const Io = std.Io; +const zdxc = @import("zdxc"); +const front = zdxc.front; + +const Mode = enum { lex, pp, print }; + +/// Serves each path from memory after the first read. +const CachedFs = struct { + io: Io, + gpa: std.mem.Allocator, + files: std.StringHashMapUnmanaged(?[]const u8) = .empty, + + fn fileSystem(c: *CachedFs) front.source.FileSystem { + return .{ .ctx = c, .readFn = readImpl }; + } + + fn readImpl(ctx: *anyopaque, _: std.mem.Allocator, path: []const u8) ?[]const u8 { + const c: *CachedFs = @ptrCast(@alignCast(ctx)); + const gop = c.files.getOrPut(c.gpa, path) catch return null; + if (!gop.found_existing) { + gop.key_ptr.* = c.gpa.dupe(u8, path) catch return null; + gop.value_ptr.* = Io.Dir.cwd().readFileAlloc(c.io, path, c.gpa, .limited(256 << 20)) catch null; + } + return gop.value_ptr.*; + } +}; + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + + var mode: Mode = .pp; + var iters: usize = 5; + var list_path: ?[]const u8 = null; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "-mode")) { + i += 1; + mode = std.meta.stringToEnum(Mode, args[i]) orelse return error.BadMode; + } else if (std.mem.eql(u8, args[i], "-iters")) { + i += 1; + iters = try std.fmt.parseInt(usize, args[i], 10); + } else list_path = args[i]; + } + + const list = try Io.Dir.cwd().readFileAlloc(io, list_path orelse return error.MissingFileList, arena, .limited(64 << 20)); + var paths: std.ArrayList([]const u8) = .empty; + var it = std.mem.tokenizeScalar(u8, list, '\n'); + while (it.next()) |p| try paths.append(arena, p); + + var cfs: CachedFs = .{ .io = io, .gpa = gpa }; + var total_bytes: usize = 0; + for (paths.items) |p| { + if (CachedFs.readImpl(&cfs, gpa, p)) |text| total_bytes += text.len; + } + + var best: u64 = std.math.maxInt(u64); + var checksum: u64 = 0; + for (0..iters) |_| { + const start = Io.Timestamp.now(io, .awake); + checksum = 0; + for (paths.items) |p| checksum +%= try runOne(gpa, &cfs, p, mode); + const ns: u64 = @intCast(start.durationTo(Io.Timestamp.now(io, .awake)).nanoseconds); + best = @min(best, ns); + } + + var buf: [256]u8 = undefined; + var w = Io.File.Writer.init(.stdout(), io, &buf); + const mb = @as(f64, @floatFromInt(total_bytes)) / (1024.0 * 1024.0); + const secs = @as(f64, @floatFromInt(best)) / 1e9; + try w.interface.print("{s}: {d} files, {d:.1} MB, best {d:.2} ms, {d:.0} MB/s (checksum {d})\n", .{ + @tagName(mode), paths.items.len, mb, secs * 1000.0, mb / secs, checksum, + }); + try w.interface.flush(); +} + +fn runOne(gpa: std.mem.Allocator, cfs: *CachedFs, path: []const u8, mode: Mode) !u64 { + var arena_state: std.heap.ArenaAllocator = .init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + + if (mode == .lex) { + const text = CachedFs.readImpl(cfs, gpa, path) orelse return 0; + var lx = front.lexer.Lexer.init(text, 0); + var n: u64 = 0; + while (lx.next().kind != .eof) n += 1; + return n; + } + + var sm = front.source.SourceManager.init(arena, cfs.fileSystem()); + var diags = zdxc.Diagnostics.init(arena); + var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{}); + if (!try pp.enterMainFile(path)) return 0; + if (mode == .print) { + var out: Io.Writer.Allocating = .init(arena); + try front.pp_print.print(&pp, &out.writer); + return out.written().len; + } + var n: u64 = 0; + while ((try pp.next()).kind != .eof) n += 1; + return n; +} diff --git a/build.zig b/build.zig index fbd2a95..be46034 100644 --- a/build.zig +++ b/build.zig @@ -47,6 +47,19 @@ pub fn build(b: *std.Build) void { oracle.has_side_effects = true; oracle_step.dependOn(&oracle.step); + // Benchmarks always build optimized so numbers are comparable. + const bench = b.addExecutable(.{ + .name = "pp_bench", + .root_module = b.createModule(.{ + .root_source_file = b.path("bench/pp_bench.zig"), + .target = target, + .optimize = .ReleaseFast, + .imports = &.{.{ .name = "zdxc", .module = mod }}, + }), + }); + const bench_step = b.step("bench", "Build the preprocessor benchmark (zig-out/bin/pp_bench)"); + bench_step.dependOn(&b.addInstallArtifact(bench, .{}).step); + const oracle_pp_step = b.step("oracle-pp", "Compare zdxc -P with dxc -P over the DXC test corpus"); const oracle_pp = b.addSystemCommand(&.{ "sh", "test/oracle/pp.sh" }); oracle_pp.addArtifactArg(exe); diff --git a/src/front/lexer.zig b/src/front/lexer.zig index 95777fa..9243a47 100644 --- a/src/front/lexer.zig +++ b/src/front/lexer.zig @@ -3,6 +3,7 @@ const std = @import("std"); const source = @import("source.zig"); +const scan = @import("scan.zig"); pub const Kind = enum(u8) { eof, @@ -133,21 +134,14 @@ pub const Lexer = struct { '/' => { const n = l.peekAt(l.pos + 1); if (n == '/') { - while (l.pos < l.text.len and l.text[l.pos] != '\n') l.pos += 1; + l.pos = @intCast(scan.findNewline(l.text, l.pos + 2)); space = true; } else if (n == '*') { - l.pos += 2; // A newline inside a block comment does not start a // new line for directive purposes (the comment is one - // space after translation phase 3). - while (l.pos < l.text.len) : (l.pos += 1) { - if (l.text[l.pos] == '*' and l.peekAt(l.pos + 1) == '/') { - l.pos += 2; - break; - } - } else { - // Unterminated block comment: consume to EOF. - } + // space after translation phase 3). An unterminated + // comment runs to EOF. + l.pos = @intCast(scan.skipBlockComment(l.text, l.pos + 2)); space = true; } else break; }, @@ -235,7 +229,7 @@ pub const Lexer = struct { l.pos += 1; switch (c) { 'a'...'z', 'A'...'Z', '_' => { - while (l.pos < l.text.len and isIdentChar(l.text[l.pos])) l.pos += 1; + l.pos = @intCast(scan.skipIdent(l.text, l.pos)); return .identifier; }, '0'...'9' => { diff --git a/src/front/pp_print.zig b/src/front/pp_print.zig index 8f02827..f1dab20 100644 --- a/src/front/pp_print.zig +++ b/src/front/pp_print.zig @@ -11,11 +11,13 @@ pub fn print(pp: *Preprocessor, w: *std.Io.Writer) !void { var cur_line: u32 = 0; var prev: ?Token = null; var line_has_tokens = false; + var cursor: Preprocessor.LineCursor = .{}; while (true) { const t = try pp.next(); if (t.kind == .eof) break; - const p = pp.presumedLoc(t.loc); - const same_file = cur_file != null and std.mem.eql(u8, cur_file.?, p.file); + const p = pp.presumedLocCursor(t.loc, &cursor); + // Paths usually share storage, so compare pointers before bytes. + const same_file = if (cur_file) |cf| (cf.ptr == p.file.ptr and cf.len == p.file.len) or std.mem.eql(u8, cf, p.file) else false; if (!same_file) { if (line_has_tokens) try w.writeByte('\n'); try w.print("#line {d} \"", .{p.line}); diff --git a/src/front/preproc.zig b/src/front/preproc.zig index aa0a43e..c515ed1 100644 --- a/src/front/preproc.zig +++ b/src/front/preproc.zig @@ -72,6 +72,29 @@ const Macro = struct { } }; +const MacroFilter = struct { + bits: [filter_words]u64 = @splat(0), + + const filter_words = 16; // 1024 bits + + fn slot(name: []const u8) u10 { + const first: u32 = name[0]; + const last: u32 = name[name.len - 1]; + const len: u32 = @truncate(name.len); + return @truncate(first *% 31 +% last *% 7 +% len *% 131); + } + + fn add(f: *MacroFilter, name: []const u8) void { + const s = slot(name); + f.bits[s >> 6] |= @as(u64, 1) << @as(u6, @truncate(s)); + } + + fn mayContain(f: *const MacroFilter, name: []const u8) bool { + const s = slot(name); + return f.bits[s >> 6] & (@as(u64, 1) << @as(u6, @truncate(s))) != 0; + } +}; + const Context = struct { tokens: []const Token, pos: usize = 0, @@ -121,6 +144,9 @@ pub const Preprocessor = struct { diags: *Diagnostics, opts: Options, macros: std.StringHashMapUnmanaged(*Macro) = .empty, + /// Conservative filter over defined macro names (bits are never + /// cleared), letting most identifiers skip the hash lookup. + macro_filter: MacroFilter = .{}, contexts: std.ArrayList(Context) = .empty, includes: std.ArrayList(IncludeFrame) = .empty, conds: std.ArrayList(Cond) = .empty, @@ -182,10 +208,11 @@ pub const Preprocessor = struct { .{ "__has_attribute", .has_nothing }, .{ "__has_cpp_attribute", .has_nothing }, .{ "__has_declspec_attribute", .has_nothing }, }; + try pp.macros.ensureTotalCapacity(pp.arena, 64); for (builtins) |b| { const m = try pp.arena.create(Macro); m.* = .{ .name = b[0], .builtin = b[1] }; - try pp.macros.put(pp.arena, b[0], m); + try pp.defineMacro(b[0], m); } var text: std.Io.Writer.Allocating = .init(pp.arena); @@ -223,6 +250,16 @@ pub const Preprocessor = struct { try pp.enterFileId(id); } + fn defineMacro(pp: *Preprocessor, name: []const u8, m: *Macro) Error!void { + pp.macro_filter.add(name); + try pp.macros.put(pp.arena, name, m); + } + + fn lookupMacro(pp: *const Preprocessor, name: []const u8) ?*Macro { + if (!pp.macro_filter.mayContain(name)) return null; + return pp.macros.get(name); + } + // --------------------------------------------------------------------- // Raw token sources @@ -283,7 +320,7 @@ pub const Preprocessor = struct { if (try pp.pragmaOperator(t)) |pragma| return pragma; continue; } - const m = pp.macros.get(t.text) orelse return t; + const m = pp.lookupMacro(t.text) orelse return t; if (m.disabled) { var painted = t; painted.flags.no_expand = true; @@ -411,7 +448,7 @@ pub const Preprocessor = struct { } // Identifiers naming a currently disabled macro stay painted. if (t.kind == .identifier and !t.flags.no_expand) { - if (pp.macros.get(t.text)) |am| { + if (pp.lookupMacro(t.text)) |am| { if (am.disabled) t.flags.no_expand = true; } } @@ -608,9 +645,33 @@ pub const Preprocessor = struct { pub fn presumedLoc(pp: *const Preprocessor, loc: Loc) PresumedLoc { if (loc.isNone()) return .{ .file = "", .line = 0 }; - const phys = pp.sm.lineCol(loc).line; - var result: PresumedLoc = .{ .file = pp.sm.file(loc.file).path, .line = phys }; - if (pp.line_overrides.get(loc.file)) |list| { + return pp.applyLineOverrides(loc.file, pp.sm.lineCol(loc).line); + } + + /// Tracks the physical line of the previous lookup so that a stream of + /// increasing locations (as when printing) costs O(1) per token instead + /// of a binary search. + pub const LineCursor = struct { + file: source.FileId = Loc.none.file, + /// 0-based index into line_starts of the current line. + line_index: u32 = 0, + }; + + pub fn presumedLocCursor(pp: *const Preprocessor, loc: Loc, cursor: *LineCursor) PresumedLoc { + if (loc.isNone()) return .{ .file = "", .line = 0 }; + const starts = pp.sm.file(loc.file).line_starts; + if (cursor.file != loc.file or starts[cursor.line_index] > loc.offset) { + cursor.* = .{ .file = loc.file, .line_index = pp.sm.lineCol(loc).line - 1 }; + } else { + while (cursor.line_index + 1 < starts.len and starts[cursor.line_index + 1] <= loc.offset) cursor.line_index += 1; + } + return pp.applyLineOverrides(loc.file, cursor.line_index + 1); + } + + fn applyLineOverrides(pp: *const Preprocessor, file: source.FileId, phys: u32) PresumedLoc { + var result: PresumedLoc = .{ .file = pp.sm.file(file).path, .line = phys }; + if (pp.line_overrides.count() == 0) return result; + if (pp.line_overrides.get(file)) |list| { for (list.items) |ov| { if (ov.phys_line >= phys) break; result.line = ov.line + (phys - ov.phys_line - 1); @@ -884,7 +945,7 @@ pub const Preprocessor = struct { pp.diags.warn(name.loc, "'{s}' macro redefined", .{name.text}); } } - try pp.macros.put(pp.arena, name.text, m); + try pp.defineMacro(name.text, m); } fn handleInclude(pp: *Preprocessor, directive: Token) Error!void { diff --git a/src/front/scan.zig b/src/front/scan.zig new file mode 100644 index 0000000..5e9ebc6 --- /dev/null +++ b/src/front/scan.zig @@ -0,0 +1,126 @@ +//! Byte-scanning primitives for the lexer and source manager, written with +//! portable `@Vector`s (the vector length comes from +//! std.simd.suggestVectorLength; no per-platform code). + +const std = @import("std"); + +const vec_len = std.simd.suggestVectorLength(u8) orelse 16; +const V = @Vector(vec_len, u8); +const Mask = @Int(.unsigned, vec_len); + +inline fn load(text: []const u8, i: usize) V { + return text[i..][0..vec_len].*; +} + +inline fn bits(m: @Vector(vec_len, bool)) Mask { + return @bitCast(m); +} + +/// Index of the first byte at or after `start` that is not ' ' or '\t', +/// or text.len. +pub fn skipBlanks(text: []const u8, start: usize) usize { + var i = start; + while (i + vec_len <= text.len) : (i += vec_len) { + const b = load(text, i); + const blank = bits(b == @as(V, @splat(' '))) | bits(b == @as(V, @splat('\t'))); + if (blank != std.math.maxInt(Mask)) return i + @ctz(~blank); + } + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + return i; +} + +/// Index of the first '\n' at or after `start`, or text.len. +pub fn findNewline(text: []const u8, start: usize) usize { + return std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len; +} + +/// Index just past the `*/` closing a block comment whose body starts at +/// `start`, or text.len if it is unterminated. +pub fn skipBlockComment(text: []const u8, start: usize) usize { + var i = start; + while (std.mem.indexOfScalarPos(u8, text, i, '*')) |star| { + if (star + 1 < text.len and text[star + 1] == '/') return star + 2; + i = star + 1; + } + return text.len; +} + +/// Append the offset of the byte after every '\n' in `text`. +pub fn appendLineStarts(gpa: std.mem.Allocator, list: *std.ArrayList(u32), text: []const u8) !void { + var i: usize = 0; + while (i + vec_len <= text.len) : (i += vec_len) { + var m = bits(load(text, i) == @as(V, @splat('\n'))); + if (m == 0) continue; + try list.ensureUnusedCapacity(gpa, @popCount(m)); + while (m != 0) : (m &= m - 1) { + list.appendAssumeCapacity(@intCast(i + @ctz(m) + 1)); + } + } + while (i < text.len) : (i += 1) { + if (text[i] == '\n') try list.append(gpa, @intCast(i + 1)); + } +} + +/// Number of '\n' bytes in `text`. +pub fn countNewlines(text: []const u8) usize { + var n: usize = 0; + var i: usize = 0; + while (i + vec_len <= text.len) : (i += vec_len) { + n += @popCount(bits(load(text, i) == @as(V, @splat('\n')))); + } + while (i < text.len) : (i += 1) n += @intFromBool(text[i] == '\n'); + return n; +} + +/// Character classes for the scalar lexer paths (identifiers are usually +/// shorter than a vector, so a table lookup beats SIMD there). +pub const ident_char: [256]bool = blk: { + var t: [256]bool = @splat(false); + for ('a'..'z' + 1) |c| t[c] = true; + for ('A'..'Z' + 1) |c| t[c] = true; + for ('0'..'9' + 1) |c| t[c] = true; + t['_'] = true; + break :blk t; +}; + +/// Index of the first non-identifier byte at or after `start`. +pub fn skipIdent(text: []const u8, start: usize) usize { + var i = start; + while (i < text.len and ident_char[text[i]]) i += 1; + return i; +} + +fn refLineStarts(gpa: std.mem.Allocator, text: []const u8) ![]u32 { + var l: std.ArrayList(u32) = .empty; + for (text, 0..) |c, i| if (c == '\n') try l.append(gpa, @intCast(i + 1)); + return l.toOwnedSlice(gpa); +} + +test "vector scans agree with scalar references" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(0x5eed); + const r = prng.random(); + const alphabet = " \t\n/*ab_9\"\\"; + for (0..300) |_| { + const len = r.uintLessThan(usize, 200); + const text = try gpa.alloc(u8, len); + defer gpa.free(text); + for (text) |*c| c.* = alphabet[r.uintLessThan(usize, alphabet.len)]; + const start = if (len == 0) 0 else r.uintLessThan(usize, len); + + var blanks = start; + while (blanks < len and (text[blanks] == ' ' or text[blanks] == '\t')) blanks += 1; + try std.testing.expectEqual(blanks, skipBlanks(text, start)); + + const ref_end = if (std.mem.indexOfPos(u8, text, start, "*/")) |e| e + 2 else len; + try std.testing.expectEqual(ref_end, skipBlockComment(text, start)); + + const ref = try refLineStarts(gpa, text); + defer gpa.free(ref); + var got: std.ArrayList(u32) = .empty; + defer got.deinit(gpa); + try appendLineStarts(gpa, &got, text); + try std.testing.expectEqualSlices(u32, ref, got.items); + try std.testing.expectEqual(ref.len, countNewlines(text)); + } +} diff --git a/src/front/source.zig b/src/front/source.zig index 202eb38..41d1abe 100644 --- a/src/front/source.zig +++ b/src/front/source.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; +const scan = @import("scan.zig"); pub const FileId = u32; @@ -147,10 +148,9 @@ pub const SourceManager = struct { const no_bom = if (std.mem.startsWith(u8, raw, "\xEF\xBB\xBF")) raw[3..] else raw; const text = try spliceLines(a, no_bom); var starts: std.ArrayList(u32) = .empty; - try starts.append(a, 0); - for (text, 0..) |c, i| { - if (c == '\n') try starts.append(a, @intCast(i + 1)); - } + try starts.ensureTotalCapacity(a, text.len / 32 + 16); + starts.appendAssumeCapacity(0); + try scan.appendLineStarts(a, &starts, text); const content = try a.create(Content); content.* = .{ .text = text, .line_starts = try starts.toOwnedSlice(a) }; return content; diff --git a/src/root.zig b/src/root.zig index 2934b18..2cf20f6 100644 --- a/src/root.zig +++ b/src/root.zig @@ -5,6 +5,7 @@ pub const Diagnostics = @import("diag.zig").Diagnostics; pub const front = struct { pub const source = @import("front/source.zig"); pub const lexer = @import("front/lexer.zig"); + pub const scan = @import("front/scan.zig"); pub const preproc = @import("front/preproc.zig"); pub const pp_print = @import("front/pp_print.zig"); };