authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-02 07:21:51-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-07 22:43:52-07:00
log756a2dbf1a5f8af7fe153960e332eaad2ab3bcd8
tree15f74e430673e16884aec01aa8374eb35e214ac6
parent941bc3719382a4f6245ad42175d911964f1bc9a4

compiler: upgrade various std.io API usage


11 files changed, 398 insertions(+), 403 deletions(-)

lib/std/io/tty.zig+4-7
......@@ -71,12 +71,9 @@ pub const Config = union(enum) {
7171 reset_attributes: u16,
7272 };
7373
74 pub fn setColor(
75 conf: Config,
76 writer: anytype,
77 color: Color,
78 ) (@typeInfo(@TypeOf(writer.writeAll(""))).error_union.error_set ||
79 windows.SetConsoleTextAttributeError)!void {
74 pub const SetColorError = std.os.windows.SetConsoleTextAttributeError || std.io.Writer.Error;
75
76 pub fn setColor(conf: Config, w: *std.io.Writer, color: Color) SetColorError!void {
8077 nosuspend switch (conf) {
8178 .no_color => return,
8279 .escape_codes => {
......@@ -101,7 +98,7 @@ pub const Config = union(enum) {
10198 .dim => "\x1b[2m",
10299 .reset => "\x1b[0m",
103100 };
104 try writer.writeAll(color_string);
101 try w.writeAll(color_string);
105102 },
106103 .windows_api => |ctx| if (native_os == .windows) {
107104 const attributes = switch (color) {
src/Air/print.zig+102-96
......@@ -1,6 +1,5 @@
11const std = @import("std");
22const Allocator = std.mem.Allocator;
3const fmtIntSizeBin = std.fmt.fmtIntSizeBin;
43
54const build_options = @import("build_options");
65const Zcu = @import("../Zcu.zig");
......@@ -9,7 +8,7 @@ const Type = @import("../Type.zig");
98const Air = @import("../Air.zig");
109const InternPool = @import("../InternPool.zig");
1110
12pub fn write(air: Air, stream: anytype, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
11pub fn write(air: Air, stream: *std.io.Writer, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
1312 comptime std.debug.assert(build_options.enable_debug_extensions);
1413 const instruction_bytes = air.instructions.len *
1514 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
......@@ -25,20 +24,20 @@ pub fn write(air: Air, stream: anytype, pt: Zcu.PerThread, liveness: ?Air.Livene
2524
2625 // zig fmt: off
2726 stream.print(
28 \\# Total AIR+Liveness bytes: {}
29 \\# AIR Instructions: {d} ({})
30 \\# AIR Extra Data: {d} ({})
31 \\# Liveness tomb_bits: {}
32 \\# Liveness Extra Data: {d} ({})
33 \\# Liveness special table: {d} ({})
27 \\# Total AIR+Liveness bytes: {Bi}
28 \\# AIR Instructions: {d} ({Bi})
29 \\# AIR Extra Data: {d} ({Bi})
30 \\# Liveness tomb_bits: {Bi}
31 \\# Liveness Extra Data: {d} ({Bi})
32 \\# Liveness special table: {d} ({Bi})
3433 \\
3534 , .{
36 fmtIntSizeBin(total_bytes),
37 air.instructions.len, fmtIntSizeBin(instruction_bytes),
38 air.extra.items.len, fmtIntSizeBin(extra_bytes),
39 fmtIntSizeBin(tomb_bytes),
40 if (liveness) |l| l.extra.len else 0, fmtIntSizeBin(liveness_extra_bytes),
41 if (liveness) |l| l.special.count() else 0, fmtIntSizeBin(liveness_special_bytes),
35 total_bytes,
36 air.instructions.len, instruction_bytes,
37 air.extra.items.len, extra_bytes,
38 tomb_bytes,
39 if (liveness) |l| l.extra.len else 0, liveness_extra_bytes,
40 if (liveness) |l| l.special.count() else 0, liveness_special_bytes,
4241 }) catch return;
4342 // zig fmt: on
4443
......@@ -55,7 +54,7 @@ pub fn write(air: Air, stream: anytype, pt: Zcu.PerThread, liveness: ?Air.Livene
5554
5655pub fn writeInst(
5756 air: Air,
58 stream: anytype,
57 stream: *std.io.Writer,
5958 inst: Air.Inst.Index,
6059 pt: Zcu.PerThread,
6160 liveness: ?Air.Liveness,
......@@ -73,11 +72,15 @@ pub fn writeInst(
7372}
7473
7574pub fn dump(air: Air, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
76 air.write(std.fs.File.stderr().deprecatedWriter(), pt, liveness);
75 const stderr_bw = std.debug.lockStderrWriter(&.{});
76 defer std.debug.unlockStderrWriter();
77 air.write(stderr_bw, pt, liveness);
7778}
7879
7980pub fn dumpInst(air: Air, inst: Air.Inst.Index, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
80 air.writeInst(std.fs.File.stderr().deprecatedWriter(), inst, pt, liveness);
81 const stderr_bw = std.debug.lockStderrWriter(&.{});
82 defer std.debug.unlockStderrWriter();
83 air.writeInst(stderr_bw, inst, pt, liveness);
8184}
8285
8386const Writer = struct {
......@@ -88,17 +91,19 @@ const Writer = struct {
8891 indent: usize,
8992 skip_body: bool,
9093
91 fn writeBody(w: *Writer, s: anytype, body: []const Air.Inst.Index) @TypeOf(s).Error!void {
94 const Error = std.io.Writer.Error;
95
96 fn writeBody(w: *Writer, s: *std.io.Writer, body: []const Air.Inst.Index) Error!void {
9297 for (body) |inst| {
9398 try w.writeInst(s, inst);
9499 try s.writeByte('\n');
95100 }
96101 }
97102
98 fn writeInst(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
103 fn writeInst(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
99104 const tag = w.air.instructions.items(.tag)[@intFromEnum(inst)];
100 try s.writeByteNTimes(' ', w.indent);
101 try s.print("{}{c}= {s}(", .{
105 try s.splatByteAll(' ', w.indent);
106 try s.print("{f}{c}= {s}(", .{
102107 inst,
103108 @as(u8, if (if (w.liveness) |liveness| liveness.isUnused(inst) else false) '!' else ' '),
104109 @tagName(tag),
......@@ -335,47 +340,48 @@ const Writer = struct {
335340 try s.writeByte(')');
336341 }
337342
338 fn writeBinOp(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
343 fn writeBinOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
339344 const bin_op = w.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
340345 try w.writeOperand(s, inst, 0, bin_op.lhs);
341346 try s.writeAll(", ");
342347 try w.writeOperand(s, inst, 1, bin_op.rhs);
343348 }
344349
345 fn writeUnOp(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
350 fn writeUnOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
346351 const un_op = w.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
347352 try w.writeOperand(s, inst, 0, un_op);
348353 }
349354
350 fn writeNoOp(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
355 fn writeNoOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
351356 _ = w;
357 _ = s;
352358 _ = inst;
353359 // no-op, no argument to write
354360 }
355361
356 fn writeType(w: *Writer, s: anytype, ty: Type) !void {
362 fn writeType(w: *Writer, s: *std.io.Writer, ty: Type) !void {
357363 return ty.print(s, w.pt);
358364 }
359365
360 fn writeTy(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
366 fn writeTy(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
361367 const ty = w.air.instructions.items(.data)[@intFromEnum(inst)].ty;
362368 try w.writeType(s, ty);
363369 }
364370
365 fn writeArg(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
371 fn writeArg(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
366372 const arg = w.air.instructions.items(.data)[@intFromEnum(inst)].arg;
367373 try w.writeType(s, arg.ty.toType());
368374 try s.print(", {d}", .{arg.zir_param_index});
369375 }
370376
371 fn writeTyOp(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
377 fn writeTyOp(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
372378 const ty_op = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
373379 try w.writeType(s, ty_op.ty.toType());
374380 try s.writeAll(", ");
375381 try w.writeOperand(s, inst, 0, ty_op.operand);
376382 }
377383
378 fn writeBlock(w: *Writer, s: anytype, tag: Air.Inst.Tag, inst: Air.Inst.Index) @TypeOf(s).Error!void {
384 fn writeBlock(w: *Writer, s: *std.io.Writer, tag: Air.Inst.Tag, inst: Air.Inst.Index) Error!void {
379385 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
380386 try w.writeType(s, ty_pl.ty.toType());
381387 const body: []const Air.Inst.Index = @ptrCast(switch (tag) {
......@@ -408,15 +414,15 @@ const Writer = struct {
408414 w.indent += 2;
409415 try w.writeBody(s, body);
410416 w.indent = old_indent;
411 try s.writeByteNTimes(' ', w.indent);
417 try s.splatByteAll(' ', w.indent);
412418 try s.writeAll("}");
413419
414420 for (liveness_block.deaths) |operand| {
415 try s.print(" {}!", .{operand});
421 try s.print(" {f}!", .{operand});
416422 }
417423 }
418424
419 fn writeLoop(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
425 fn writeLoop(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
420426 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
421427 const extra = w.air.extraData(Air.Block, ty_pl.payload);
422428 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
......@@ -428,11 +434,11 @@ const Writer = struct {
428434 w.indent += 2;
429435 try w.writeBody(s, body);
430436 w.indent = old_indent;
431 try s.writeByteNTimes(' ', w.indent);
437 try s.splatByteAll(' ', w.indent);
432438 try s.writeAll("}");
433439 }
434440
435 fn writeAggregateInit(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
441 fn writeAggregateInit(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
436442 const zcu = w.pt.zcu;
437443 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
438444 const vector_ty = ty_pl.ty.toType();
......@@ -448,7 +454,7 @@ const Writer = struct {
448454 try s.writeAll("]");
449455 }
450456
451 fn writeUnionInit(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
457 fn writeUnionInit(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
452458 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
453459 const extra = w.air.extraData(Air.UnionInit, ty_pl.payload).data;
454460
......@@ -456,7 +462,7 @@ const Writer = struct {
456462 try w.writeOperand(s, inst, 0, extra.init);
457463 }
458464
459 fn writeStructField(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
465 fn writeStructField(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
460466 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
461467 const extra = w.air.extraData(Air.StructField, ty_pl.payload).data;
462468
......@@ -464,7 +470,7 @@ const Writer = struct {
464470 try s.print(", {d}", .{extra.field_index});
465471 }
466472
467 fn writeTyPlBin(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
473 fn writeTyPlBin(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
468474 const data = w.air.instructions.items(.data);
469475 const ty_pl = data[@intFromEnum(inst)].ty_pl;
470476 const extra = w.air.extraData(Air.Bin, ty_pl.payload).data;
......@@ -477,7 +483,7 @@ const Writer = struct {
477483 try w.writeOperand(s, inst, 1, extra.rhs);
478484 }
479485
480 fn writeCmpxchg(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
486 fn writeCmpxchg(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
481487 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
482488 const extra = w.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
483489
......@@ -491,7 +497,7 @@ const Writer = struct {
491497 });
492498 }
493499
494 fn writeMulAdd(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
500 fn writeMulAdd(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
495501 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
496502 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
497503
......@@ -502,7 +508,7 @@ const Writer = struct {
502508 try w.writeOperand(s, inst, 2, pl_op.operand);
503509 }
504510
505 fn writeShuffleOne(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
511 fn writeShuffleOne(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
506512 const unwrapped = w.air.unwrapShuffleOne(w.pt.zcu, inst);
507513 try w.writeType(s, unwrapped.result_ty);
508514 try s.writeAll(", ");
......@@ -518,7 +524,7 @@ const Writer = struct {
518524 try s.writeByte(']');
519525 }
520526
521 fn writeShuffleTwo(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
527 fn writeShuffleTwo(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
522528 const unwrapped = w.air.unwrapShuffleTwo(w.pt.zcu, inst);
523529 try w.writeType(s, unwrapped.result_ty);
524530 try s.writeAll(", ");
......@@ -537,7 +543,7 @@ const Writer = struct {
537543 try s.writeByte(']');
538544 }
539545
540 fn writeSelect(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
546 fn writeSelect(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
541547 const zcu = w.pt.zcu;
542548 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
543549 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
......@@ -552,14 +558,14 @@ const Writer = struct {
552558 try w.writeOperand(s, inst, 2, extra.rhs);
553559 }
554560
555 fn writeReduce(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
561 fn writeReduce(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
556562 const reduce = w.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
557563
558564 try w.writeOperand(s, inst, 0, reduce.operand);
559565 try s.print(", {s}", .{@tagName(reduce.operation)});
560566 }
561567
562 fn writeCmpVector(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
568 fn writeCmpVector(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
563569 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
564570 const extra = w.air.extraData(Air.VectorCmp, ty_pl.payload).data;
565571
......@@ -569,7 +575,7 @@ const Writer = struct {
569575 try w.writeOperand(s, inst, 1, extra.rhs);
570576 }
571577
572 fn writeVectorStoreElem(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
578 fn writeVectorStoreElem(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
573579 const data = w.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
574580 const extra = w.air.extraData(Air.VectorCmp, data.payload).data;
575581
......@@ -580,21 +586,21 @@ const Writer = struct {
580586 try w.writeOperand(s, inst, 2, extra.rhs);
581587 }
582588
583 fn writeRuntimeNavPtr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
589 fn writeRuntimeNavPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
584590 const ip = &w.pt.zcu.intern_pool;
585591 const ty_nav = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_nav;
586592 try w.writeType(s, .fromInterned(ty_nav.ty));
587593 try s.print(", '{}'", .{ip.getNav(ty_nav.nav).fqn.fmt(ip)});
588594 }
589595
590 fn writeAtomicLoad(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
596 fn writeAtomicLoad(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
591597 const atomic_load = w.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
592598
593599 try w.writeOperand(s, inst, 0, atomic_load.ptr);
594600 try s.print(", {s}", .{@tagName(atomic_load.order)});
595601 }
596602
597 fn writePrefetch(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
603 fn writePrefetch(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
598604 const prefetch = w.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
599605
600606 try w.writeOperand(s, inst, 0, prefetch.ptr);
......@@ -605,10 +611,10 @@ const Writer = struct {
605611
606612 fn writeAtomicStore(
607613 w: *Writer,
608 s: anytype,
614 s: *std.io.Writer,
609615 inst: Air.Inst.Index,
610616 order: std.builtin.AtomicOrder,
611 ) @TypeOf(s).Error!void {
617 ) Error!void {
612618 const bin_op = w.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
613619 try w.writeOperand(s, inst, 0, bin_op.lhs);
614620 try s.writeAll(", ");
......@@ -616,7 +622,7 @@ const Writer = struct {
616622 try s.print(", {s}", .{@tagName(order)});
617623 }
618624
619 fn writeAtomicRmw(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
625 fn writeAtomicRmw(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
620626 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
621627 const extra = w.air.extraData(Air.AtomicRmw, pl_op.payload).data;
622628
......@@ -626,7 +632,7 @@ const Writer = struct {
626632 try s.print(", {s}, {s}", .{ @tagName(extra.op()), @tagName(extra.ordering()) });
627633 }
628634
629 fn writeFieldParentPtr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
635 fn writeFieldParentPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
630636 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
631637 const extra = w.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
632638
......@@ -634,7 +640,7 @@ const Writer = struct {
634640 try s.print(", {d}", .{extra.field_index});
635641 }
636642
637 fn writeAssembly(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
643 fn writeAssembly(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
638644 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
639645 const extra = w.air.extraData(Air.Asm, ty_pl.payload);
640646 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;
......@@ -704,22 +710,22 @@ const Writer = struct {
704710 }
705711 }
706712 const asm_source = std.mem.sliceAsBytes(w.air.extra.items[extra_i..])[0..extra.data.source_len];
707 try s.print(", \"{f}\"", .{std.zig.fmtString(asm_source)});
713 try s.print(", \"{f}\"", .{std.zig.fmtEscapes(asm_source)});
708714 }
709715
710 fn writeDbgStmt(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
716 fn writeDbgStmt(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
711717 const dbg_stmt = w.air.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
712718 try s.print("{d}:{d}", .{ dbg_stmt.line + 1, dbg_stmt.column + 1 });
713719 }
714720
715 fn writeDbgVar(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
721 fn writeDbgVar(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
716722 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
717723 try w.writeOperand(s, inst, 0, pl_op.operand);
718724 const name: Air.NullTerminatedString = @enumFromInt(pl_op.payload);
719 try s.print(", \"{f}\"", .{std.zig.fmtString(name.toSlice(w.air))});
725 try s.print(", \"{f}\"", .{std.zig.fmtEscapes(name.toSlice(w.air))});
720726 }
721727
722 fn writeCall(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
728 fn writeCall(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
723729 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
724730 const extra = w.air.extraData(Air.Call, pl_op.payload);
725731 const args = @as([]const Air.Inst.Ref, @ptrCast(w.air.extra.items[extra.end..][0..extra.data.args_len]));
......@@ -732,19 +738,19 @@ const Writer = struct {
732738 try s.writeAll("]");
733739 }
734740
735 fn writeBr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
741 fn writeBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
736742 const br = w.air.instructions.items(.data)[@intFromEnum(inst)].br;
737743 try w.writeInstIndex(s, br.block_inst, false);
738744 try s.writeAll(", ");
739745 try w.writeOperand(s, inst, 0, br.operand);
740746 }
741747
742 fn writeRepeat(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
748 fn writeRepeat(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
743749 const repeat = w.air.instructions.items(.data)[@intFromEnum(inst)].repeat;
744750 try w.writeInstIndex(s, repeat.loop_inst, false);
745751 }
746752
747 fn writeTry(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
753 fn writeTry(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
748754 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
749755 const extra = w.air.extraData(Air.Try, pl_op.payload);
750756 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
......@@ -760,25 +766,25 @@ const Writer = struct {
760766 w.indent += 2;
761767
762768 if (liveness_condbr.else_deaths.len != 0) {
763 try s.writeByteNTimes(' ', w.indent);
769 try s.splatByteAll(' ', w.indent);
764770 for (liveness_condbr.else_deaths, 0..) |operand, i| {
765771 if (i != 0) try s.writeAll(" ");
766 try s.print("{}!", .{operand});
772 try s.print("{f}!", .{operand});
767773 }
768774 try s.writeAll("\n");
769775 }
770776 try w.writeBody(s, body);
771777
772778 w.indent = old_indent;
773 try s.writeByteNTimes(' ', w.indent);
779 try s.splatByteAll(' ', w.indent);
774780 try s.writeAll("}");
775781
776782 for (liveness_condbr.then_deaths) |operand| {
777 try s.print(" {}!", .{operand});
783 try s.print(" {f}!", .{operand});
778784 }
779785 }
780786
781 fn writeTryPtr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
787 fn writeTryPtr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
782788 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
783789 const extra = w.air.extraData(Air.TryPtr, ty_pl.payload);
784790 const body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.body_len]);
......@@ -797,25 +803,25 @@ const Writer = struct {
797803 w.indent += 2;
798804
799805 if (liveness_condbr.else_deaths.len != 0) {
800 try s.writeByteNTimes(' ', w.indent);
806 try s.splatByteAll(' ', w.indent);
801807 for (liveness_condbr.else_deaths, 0..) |operand, i| {
802808 if (i != 0) try s.writeAll(" ");
803 try s.print("{}!", .{operand});
809 try s.print("{f}!", .{operand});
804810 }
805811 try s.writeAll("\n");
806812 }
807813 try w.writeBody(s, body);
808814
809815 w.indent = old_indent;
810 try s.writeByteNTimes(' ', w.indent);
816 try s.splatByteAll(' ', w.indent);
811817 try s.writeAll("}");
812818
813819 for (liveness_condbr.then_deaths) |operand| {
814 try s.print(" {}!", .{operand});
820 try s.print(" {f}!", .{operand});
815821 }
816822 }
817823
818 fn writeCondBr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
824 fn writeCondBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
819825 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
820826 const extra = w.air.extraData(Air.CondBr, pl_op.payload);
821827 const then_body: []const Air.Inst.Index = @ptrCast(w.air.extra.items[extra.end..][0..extra.data.then_body_len]);
......@@ -839,16 +845,16 @@ const Writer = struct {
839845 w.indent += 2;
840846
841847 if (liveness_condbr.then_deaths.len != 0) {
842 try s.writeByteNTimes(' ', w.indent);
848 try s.splatByteAll(' ', w.indent);
843849 for (liveness_condbr.then_deaths, 0..) |operand, i| {
844850 if (i != 0) try s.writeAll(" ");
845 try s.print("{}!", .{operand});
851 try s.print("{f}!", .{operand});
846852 }
847853 try s.writeAll("\n");
848854 }
849855
850856 try w.writeBody(s, then_body);
851 try s.writeByteNTimes(' ', old_indent);
857 try s.splatByteAll(' ', old_indent);
852858 try s.writeAll("},");
853859 if (extra.data.branch_hints.false != .none) {
854860 try s.print(" {s}", .{@tagName(extra.data.branch_hints.false)});
......@@ -859,10 +865,10 @@ const Writer = struct {
859865 try s.writeAll(" {\n");
860866
861867 if (liveness_condbr.else_deaths.len != 0) {
862 try s.writeByteNTimes(' ', w.indent);
868 try s.splatByteAll(' ', w.indent);
863869 for (liveness_condbr.else_deaths, 0..) |operand, i| {
864870 if (i != 0) try s.writeAll(" ");
865 try s.print("{}!", .{operand});
871 try s.print("{f}!", .{operand});
866872 }
867873 try s.writeAll("\n");
868874 }
......@@ -870,11 +876,11 @@ const Writer = struct {
870876 try w.writeBody(s, else_body);
871877 w.indent = old_indent;
872878
873 try s.writeByteNTimes(' ', old_indent);
879 try s.splatByteAll(' ', old_indent);
874880 try s.writeAll("}");
875881 }
876882
877 fn writeSwitchBr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
883 fn writeSwitchBr(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
878884 const switch_br = w.air.unwrapSwitch(inst);
879885
880886 const liveness: Air.Liveness.SwitchBrTable = if (w.liveness) |liveness|
......@@ -916,17 +922,17 @@ const Writer = struct {
916922
917923 const deaths = liveness.deaths[case.idx];
918924 if (deaths.len != 0) {
919 try s.writeByteNTimes(' ', w.indent);
925 try s.splatByteAll(' ', w.indent);
920926 for (deaths, 0..) |operand, i| {
921927 if (i != 0) try s.writeAll(" ");
922 try s.print("{}!", .{operand});
928 try s.print("{f}!", .{operand});
923929 }
924930 try s.writeAll("\n");
925931 }
926932
927933 try w.writeBody(s, case.body);
928934 w.indent -= 2;
929 try s.writeByteNTimes(' ', w.indent);
935 try s.splatByteAll(' ', w.indent);
930936 try s.writeAll("}");
931937 }
932938
......@@ -942,47 +948,47 @@ const Writer = struct {
942948
943949 const deaths = liveness.deaths[liveness.deaths.len - 1];
944950 if (deaths.len != 0) {
945 try s.writeByteNTimes(' ', w.indent);
951 try s.splatByteAll(' ', w.indent);
946952 for (deaths, 0..) |operand, i| {
947953 if (i != 0) try s.writeAll(" ");
948 try s.print("{}!", .{operand});
954 try s.print("{f}!", .{operand});
949955 }
950956 try s.writeAll("\n");
951957 }
952958
953959 try w.writeBody(s, else_body);
954960 w.indent -= 2;
955 try s.writeByteNTimes(' ', w.indent);
961 try s.splatByteAll(' ', w.indent);
956962 try s.writeAll("}");
957963 }
958964
959965 try s.writeAll("\n");
960 try s.writeByteNTimes(' ', old_indent);
966 try s.splatByteAll(' ', old_indent);
961967 }
962968
963 fn writeWasmMemorySize(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
969 fn writeWasmMemorySize(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
964970 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
965971 try s.print("{d}", .{pl_op.payload});
966972 }
967973
968 fn writeWasmMemoryGrow(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
974 fn writeWasmMemoryGrow(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
969975 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
970976 try s.print("{d}, ", .{pl_op.payload});
971977 try w.writeOperand(s, inst, 0, pl_op.operand);
972978 }
973979
974 fn writeWorkDimension(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
980 fn writeWorkDimension(w: *Writer, s: *std.io.Writer, inst: Air.Inst.Index) Error!void {
975981 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
976982 try s.print("{d}", .{pl_op.payload});
977983 }
978984
979985 fn writeOperand(
980986 w: *Writer,
981 s: anytype,
987 s: *std.io.Writer,
982988 inst: Air.Inst.Index,
983989 op_index: usize,
984990 operand: Air.Inst.Ref,
985 ) @TypeOf(s).Error!void {
991 ) Error!void {
986992 const small_tomb_bits = Air.Liveness.bpi - 1;
987993 const dies = if (w.liveness) |liveness| blk: {
988994 if (op_index < small_tomb_bits)
......@@ -1004,16 +1010,16 @@ const Writer = struct {
10041010
10051011 fn writeInstRef(
10061012 w: *Writer,
1007 s: anytype,
1013 s: *std.io.Writer,
10081014 operand: Air.Inst.Ref,
10091015 dies: bool,
1010 ) @TypeOf(s).Error!void {
1016 ) Error!void {
10111017 if (@intFromEnum(operand) < InternPool.static_len) {
10121018 return s.print("@{}", .{operand});
10131019 } else if (operand.toInterned()) |ip_index| {
10141020 const pt = w.pt;
10151021 const ty = Type.fromInterned(pt.zcu.intern_pool.indexToKey(ip_index).typeOf());
1016 try s.print("<{}, {}>", .{
1022 try s.print("<{f}, {f}>", .{
10171023 ty.fmt(pt),
10181024 Value.fromInterned(ip_index).fmtValue(pt),
10191025 });
......@@ -1024,12 +1030,12 @@ const Writer = struct {
10241030
10251031 fn writeInstIndex(
10261032 w: *Writer,
1027 s: anytype,
1033 s: *std.io.Writer,
10281034 inst: Air.Inst.Index,
10291035 dies: bool,
1030 ) @TypeOf(s).Error!void {
1036 ) Error!void {
10311037 _ = w;
1032 try s.print("{}", .{inst});
1038 try s.print("{f}", .{inst});
10331039 if (dies) try s.writeByte('!');
10341040 }
10351041
src/Compilation.zig+2-2
......@@ -5852,7 +5852,7 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_obj_prog_node: std.Pr
58525852
58535853 try child.spawn();
58545854
5855 const stderr = try child.stderr.?.reader().readAllAlloc(arena, std.math.maxInt(usize));
5855 const stderr = try child.stderr.?.deprecatedReader().readAllAlloc(arena, std.math.maxInt(usize));
58565856
58575857 const term = child.wait() catch |err| {
58585858 return comp.failCObj(c_object, "failed to spawn zig clang {s}: {s}", .{ argv.items[0], @errorName(err) });
......@@ -6249,7 +6249,7 @@ fn spawnZigRc(
62496249 }
62506250
62516251 // Just in case there's a failure that didn't send an ErrorBundle (e.g. an error return trace)
6252 const stderr_reader = child.stderr.?.reader();
6252 const stderr_reader = child.stderr.?.deprecatedReader();
62536253 const stderr = try stderr_reader.readAllAlloc(arena, 10 * 1024 * 1024);
62546254
62556255 const term = child.wait() catch |err| {
src/Sema.zig+5-5
......@@ -3026,8 +3026,8 @@ pub fn createTypeName(
30263026
30273027 var aw: std.io.Writer.Allocating = .init(gpa);
30283028 defer aw.deinit();
3029 const bw = &aw.writer;
3030 bw.print("{f}(", .{block.type_name_ctx.fmt(ip)}) catch return error.OutOfMemory;
3029 const w = &aw.writer;
3030 w.print("{f}(", .{block.type_name_ctx.fmt(ip)}) catch return error.OutOfMemory;
30313031
30323032 var arg_i: usize = 0;
30333033 for (fn_info.param_body) |zir_inst| switch (zir_tags[@intFromEnum(zir_inst)]) {
......@@ -3040,13 +3040,13 @@ pub fn createTypeName(
30403040 // result in a compile error.
30413041 const arg_val = try sema.resolveValue(arg) orelse break :func_strat; // fall through to anon strat
30423042
3043 if (arg_i != 0) bw.writeByte(',') catch return error.OutOfMemory;
3043 if (arg_i != 0) w.writeByte(',') catch return error.OutOfMemory;
30443044
30453045 // Limiting the depth here helps avoid type names getting too long, which
30463046 // in turn helps to avoid unreasonably long symbol names for namespaced
30473047 // symbols. Such names should ideally be human-readable, and additionally,
30483048 // some tooling may not support very long symbol names.
3049 bw.print("{f}", .{Value.fmtValueSemaFull(.{
3049 w.print("{f}", .{Value.fmtValueSemaFull(.{
30503050 .val = arg_val,
30513051 .pt = pt,
30523052 .opt_sema = sema,
......@@ -3059,7 +3059,7 @@ pub fn createTypeName(
30593059 else => continue,
30603060 };
30613061
3062 try bw.writeByte(')');
3062 w.writeByte(')') catch return error.OutOfMemory;
30633063 return .{
30643064 .name = try ip.getOrPutString(gpa, pt.tid, aw.getWritten(), .no_embedded_nulls),
30653065 .nav = .none,
src/arch/x86_64/CodeGen.zig+2-7
......@@ -1135,15 +1135,10 @@ fn formatWipMir(data: FormatWipMirData, w: *Writer) Writer.Error!void {
11351135 try w.writeAll(lower.err_msg.?.msg);
11361136 return;
11371137 },
1138 error.OutOfMemory, error.InvalidInstruction, error.CannotEncode => |e| {
1139 try w.writeAll(switch (e) {
1140 error.OutOfMemory => "Out of memory",
1141 error.InvalidInstruction => "CodeGen failed to find a viable instruction.",
1142 error.CannotEncode => "CodeGen failed to encode the instruction.",
1143 });
1138 else => |e| {
1139 try w.writeAll(@errorName(e));
11441140 return;
11451141 },
1146 else => |e| return e,
11471142 }).insts) |lowered_inst| {
11481143 if (!first) try w.writeAll("\ndebug(wip_mir): ");
11491144 try w.print(" | {f}", .{lowered_inst});
src/arch/x86_64/encoder.zig+110-136
......@@ -3,6 +3,7 @@ const assert = std.debug.assert;
33const log = std.log.scoped(.x86_64_encoder);
44const math = std.math;
55const testing = std.testing;
6const Writer = std.io.Writer;
67
78const bits = @import("bits.zig");
89const Encoding = @import("Encoding.zig");
......@@ -226,101 +227,81 @@ pub const Instruction = struct {
226227 };
227228 }
228229
229 fn format(
230 op: Operand,
231 comptime unused_format_string: []const u8,
232 options: std.fmt.FormatOptions,
233 writer: anytype,
234 ) !void {
235 _ = op;
236 _ = unused_format_string;
237 _ = options;
238 _ = writer;
239 @compileError("do not format Operand directly; use fmt() instead");
240 }
241
242 const FormatContext = struct {
230 const Format = struct {
243231 op: Operand,
244232 enc_op: Encoding.Op,
245 };
246233
247 fn fmtContext(
248 ctx: FormatContext,
249 comptime unused_format_string: []const u8,
250 options: std.fmt.FormatOptions,
251 writer: anytype,
252 ) @TypeOf(writer).Error!void {
253 _ = unused_format_string;
254 _ = options;
255 const op = ctx.op;
256 const enc_op = ctx.enc_op;
257 switch (op) {
258 .none => {},
259 .reg => |reg| try writer.writeAll(@tagName(reg)),
260 .mem => |mem| switch (mem) {
261 .rip => |rip| {
262 try writer.print("{} [rip", .{rip.ptr_size});
263 if (rip.disp != 0) try writer.print(" {c} 0x{x}", .{
264 @as(u8, if (rip.disp < 0) '-' else '+'),
265 @abs(rip.disp),
266 });
267 try writer.writeByte(']');
268 },
269 .sib => |sib| {
270 try writer.print("{} ", .{sib.ptr_size});
234 fn default(f: Format, w: *Writer) Writer.Error!void {
235 const op = f.op;
236 const enc_op = f.enc_op;
237 switch (op) {
238 .none => {},
239 .reg => |reg| try w.writeAll(@tagName(reg)),
240 .mem => |mem| switch (mem) {
241 .rip => |rip| {
242 try w.print("{f} [rip", .{rip.ptr_size});
243 if (rip.disp != 0) try w.print(" {c} 0x{x}", .{
244 @as(u8, if (rip.disp < 0) '-' else '+'),
245 @abs(rip.disp),
246 });
247 try w.writeByte(']');
248 },
249 .sib => |sib| {
250 try w.print("{f} ", .{sib.ptr_size});
271251
272 if (mem.isSegmentRegister()) {
273 return writer.print("{s}:0x{x}", .{ @tagName(sib.base.reg), sib.disp });
274 }
252 if (mem.isSegmentRegister()) {
253 return w.print("{s}:0x{x}", .{ @tagName(sib.base.reg), sib.disp });
254 }
275255
276 try writer.writeByte('[');
277
278 var any = true;
279 switch (sib.base) {
280 .none => any = false,
281 .reg => |reg| try writer.print("{s}", .{@tagName(reg)}),
282 .frame => |frame_index| try writer.print("{}", .{frame_index}),
283 .table => try writer.print("Table", .{}),
284 .rip_inst => |inst_index| try writer.print("RipInst({d})", .{inst_index}),
285 .nav => |nav| try writer.print("Nav({d})", .{@intFromEnum(nav)}),
286 .uav => |uav| try writer.print("Uav({d})", .{@intFromEnum(uav.val)}),
287 .lazy_sym => |lazy_sym| try writer.print("LazySym({s}, {d})", .{
288 @tagName(lazy_sym.kind),
289 @intFromEnum(lazy_sym.ty),
290 }),
291 .extern_func => |extern_func| try writer.print("ExternFunc({d})", .{@intFromEnum(extern_func)}),
292 }
293 if (mem.scaleIndex()) |si| {
294 if (any) try writer.writeAll(" + ");
295 try writer.print("{s} * {d}", .{ @tagName(si.index), si.scale });
296 any = true;
297 }
298 if (sib.disp != 0 or !any) {
299 if (any)
300 try writer.print(" {c} ", .{@as(u8, if (sib.disp < 0) '-' else '+')})
301 else if (sib.disp < 0)
302 try writer.writeByte('-');
303 try writer.print("0x{x}", .{@abs(sib.disp)});
304 any = true;
305 }
256 try w.writeByte('[');
257
258 var any = true;
259 switch (sib.base) {
260 .none => any = false,
261 .reg => |reg| try w.print("{s}", .{@tagName(reg)}),
262 .frame => |frame_index| try w.print("{}", .{frame_index}),
263 .table => try w.print("Table", .{}),
264 .rip_inst => |inst_index| try w.print("RipInst({d})", .{inst_index}),
265 .nav => |nav| try w.print("Nav({d})", .{@intFromEnum(nav)}),
266 .uav => |uav| try w.print("Uav({d})", .{@intFromEnum(uav.val)}),
267 .lazy_sym => |lazy_sym| try w.print("LazySym({s}, {d})", .{
268 @tagName(lazy_sym.kind),
269 @intFromEnum(lazy_sym.ty),
270 }),
271 .extern_func => |extern_func| try w.print("ExternFunc({d})", .{@intFromEnum(extern_func)}),
272 }
273 if (mem.scaleIndex()) |si| {
274 if (any) try w.writeAll(" + ");
275 try w.print("{s} * {d}", .{ @tagName(si.index), si.scale });
276 any = true;
277 }
278 if (sib.disp != 0 or !any) {
279 if (any)
280 try w.print(" {c} ", .{@as(u8, if (sib.disp < 0) '-' else '+')})
281 else if (sib.disp < 0)
282 try w.writeByte('-');
283 try w.print("0x{x}", .{@abs(sib.disp)});
284 any = true;
285 }
306286
307 try writer.writeByte(']');
287 try w.writeByte(']');
288 },
289 .moffs => |moffs| try w.print("{s}:0x{x}", .{
290 @tagName(moffs.seg),
291 moffs.offset,
292 }),
308293 },
309 .moffs => |moffs| try writer.print("{s}:0x{x}", .{
310 @tagName(moffs.seg),
311 moffs.offset,
312 }),
313 },
314 .imm => |imm| if (enc_op.isSigned()) {
315 const imms = imm.asSigned(enc_op.immBitSize());
316 if (imms < 0) try writer.writeByte('-');
317 try writer.print("0x{x}", .{@abs(imms)});
318 } else try writer.print("0x{x}", .{imm.asUnsigned(enc_op.immBitSize())}),
319 .bytes => unreachable,
294 .imm => |imm| if (enc_op.isSigned()) {
295 const imms = imm.asSigned(enc_op.immBitSize());
296 if (imms < 0) try w.writeByte('-');
297 try w.print("0x{x}", .{@abs(imms)});
298 } else try w.print("0x{x}", .{imm.asUnsigned(enc_op.immBitSize())}),
299 .bytes => unreachable,
300 }
320301 }
321 }
302 };
322303
323 pub fn fmt(op: Operand, enc_op: Encoding.Op) std.fmt.Formatter(fmtContext) {
304 pub fn fmt(op: Operand, enc_op: Encoding.Op) std.fmt.Formatter(Format, Format.default) {
324305 return .{ .data = .{ .op = op, .enc_op = enc_op } };
325306 }
326307 };
......@@ -361,7 +342,7 @@ pub const Instruction = struct {
361342 },
362343 },
363344 };
364 log.debug("selected encoding: {}", .{encoding});
345 log.debug("selected encoding: {f}", .{encoding});
365346
366347 var inst: Instruction = .{
367348 .prefix = prefix,
......@@ -372,30 +353,23 @@ pub const Instruction = struct {
372353 return inst;
373354 }
374355
375 pub fn format(
376 inst: Instruction,
377 comptime unused_format_string: []const u8,
378 options: std.fmt.FormatOptions,
379 writer: anytype,
380 ) @TypeOf(writer).Error!void {
381 _ = unused_format_string;
382 _ = options;
356 pub fn format(inst: Instruction, w: *Writer, comptime unused_format_string: []const u8) Writer.Error!void {
357 comptime assert(unused_format_string.len == 0);
383358 switch (inst.prefix) {
384359 .none, .directive => {},
385 else => try writer.print("{s} ", .{@tagName(inst.prefix)}),
360 else => try w.print("{s} ", .{@tagName(inst.prefix)}),
386361 }
387 try writer.print("{s}", .{@tagName(inst.encoding.mnemonic)});
362 try w.print("{s}", .{@tagName(inst.encoding.mnemonic)});
388363 for (inst.ops, inst.encoding.data.ops, 0..) |op, enc, i| {
389364 if (op == .none) break;
390 if (i > 0) try writer.writeByte(',');
391 try writer.writeByte(' ');
392 try writer.print("{}", .{op.fmt(enc)});
365 if (i > 0) try w.writeByte(',');
366 try w.print(" {f}", .{op.fmt(enc)});
393367 }
394368 }
395369
396 pub fn encode(inst: Instruction, writer: anytype, comptime opts: Options) !void {
370 pub fn encode(inst: Instruction, w: *Writer, comptime opts: Options) !void {
397371 assert(inst.prefix != .directive);
398 const encoder = Encoder(@TypeOf(writer), opts){ .writer = writer };
372 const encoder: Encoder(opts) = .{ .w = w };
399373 const enc = inst.encoding;
400374 const data = enc.data;
401375
......@@ -801,9 +775,9 @@ pub const LegacyPrefixes = packed struct {
801775
802776pub const Options = struct { allow_frame_locs: bool = false, allow_symbols: bool = false };
803777
804fn Encoder(comptime T: type, comptime opts: Options) type {
778fn Encoder(comptime opts: Options) type {
805779 return struct {
806 writer: T,
780 w: *Writer,
807781
808782 const Self = @This();
809783 pub const options = opts;
......@@ -818,31 +792,31 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
818792 // Hopefully this path isn't taken very often, so we'll do it the slow way for now
819793
820794 // LOCK
821 if (prefixes.prefix_f0) try self.writer.writeByte(0xf0);
795 if (prefixes.prefix_f0) try self.w.writeByte(0xf0);
822796 // REPNZ, REPNE, REP, Scalar Double-precision
823 if (prefixes.prefix_f2) try self.writer.writeByte(0xf2);
797 if (prefixes.prefix_f2) try self.w.writeByte(0xf2);
824798 // REPZ, REPE, REP, Scalar Single-precision
825 if (prefixes.prefix_f3) try self.writer.writeByte(0xf3);
799 if (prefixes.prefix_f3) try self.w.writeByte(0xf3);
826800
827801 // CS segment override or Branch not taken
828 if (prefixes.prefix_2e) try self.writer.writeByte(0x2e);
802 if (prefixes.prefix_2e) try self.w.writeByte(0x2e);
829803 // DS segment override
830 if (prefixes.prefix_36) try self.writer.writeByte(0x36);
804 if (prefixes.prefix_36) try self.w.writeByte(0x36);
831805 // ES segment override
832 if (prefixes.prefix_26) try self.writer.writeByte(0x26);
806 if (prefixes.prefix_26) try self.w.writeByte(0x26);
833807 // FS segment override
834 if (prefixes.prefix_64) try self.writer.writeByte(0x64);
808 if (prefixes.prefix_64) try self.w.writeByte(0x64);
835809 // GS segment override
836 if (prefixes.prefix_65) try self.writer.writeByte(0x65);
810 if (prefixes.prefix_65) try self.w.writeByte(0x65);
837811
838812 // Branch taken
839 if (prefixes.prefix_3e) try self.writer.writeByte(0x3e);
813 if (prefixes.prefix_3e) try self.w.writeByte(0x3e);
840814
841815 // Operand size override
842 if (prefixes.prefix_66) try self.writer.writeByte(0x66);
816 if (prefixes.prefix_66) try self.w.writeByte(0x66);
843817
844818 // Address size override
845 if (prefixes.prefix_67) try self.writer.writeByte(0x67);
819 if (prefixes.prefix_67) try self.w.writeByte(0x67);
846820 }
847821 }
848822
......@@ -850,7 +824,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
850824 ///
851825 /// Note that this flag is overridden by REX.W, if both are present.
852826 pub fn prefix16BitMode(self: Self) !void {
853 try self.writer.writeByte(0x66);
827 try self.w.writeByte(0x66);
854828 }
855829
856830 /// Encodes a REX prefix byte given all the fields
......@@ -869,7 +843,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
869843 if (fields.x) byte |= 0b0010;
870844 if (fields.b) byte |= 0b0001;
871845
872 try self.writer.writeByte(byte);
846 try self.w.writeByte(byte);
873847 }
874848
875849 /// Encodes a VEX prefix given all the fields
......@@ -877,24 +851,24 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
877851 /// See struct `Vex` for a description of each field.
878852 pub fn vex(self: Self, fields: Vex) !void {
879853 if (fields.is3Byte()) {
880 try self.writer.writeByte(0b1100_0100);
854 try self.w.writeByte(0b1100_0100);
881855
882 try self.writer.writeByte(
856 try self.w.writeByte(
883857 @as(u8, ~@intFromBool(fields.r)) << 7 |
884858 @as(u8, ~@intFromBool(fields.x)) << 6 |
885859 @as(u8, ~@intFromBool(fields.b)) << 5 |
886860 @as(u8, @intFromEnum(fields.m)) << 0,
887861 );
888862
889 try self.writer.writeByte(
863 try self.w.writeByte(
890864 @as(u8, @intFromBool(fields.w)) << 7 |
891865 @as(u8, ~@as(u4, @intCast(fields.v.enc()))) << 3 |
892866 @as(u8, @intFromBool(fields.l)) << 2 |
893867 @as(u8, @intFromEnum(fields.p)) << 0,
894868 );
895869 } else {
896 try self.writer.writeByte(0b1100_0101);
897 try self.writer.writeByte(
870 try self.w.writeByte(0b1100_0101);
871 try self.w.writeByte(
898872 @as(u8, ~@intFromBool(fields.r)) << 7 |
899873 @as(u8, ~@as(u4, @intCast(fields.v.enc()))) << 3 |
900874 @as(u8, @intFromBool(fields.l)) << 2 |
......@@ -909,7 +883,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
909883
910884 /// Encodes a 1 byte opcode
911885 pub fn opcode_1byte(self: Self, opcode: u8) !void {
912 try self.writer.writeByte(opcode);
886 try self.w.writeByte(opcode);
913887 }
914888
915889 /// Encodes a 2 byte opcode
......@@ -918,7 +892,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
918892 ///
919893 /// encoder.opcode_2byte(0x0f, 0xaf);
920894 pub fn opcode_2byte(self: Self, prefix: u8, opcode: u8) !void {
921 try self.writer.writeAll(&.{ prefix, opcode });
895 try self.w.writeAll(&.{ prefix, opcode });
922896 }
923897
924898 /// Encodes a 3 byte opcode
......@@ -927,7 +901,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
927901 ///
928902 /// encoder.opcode_3byte(0xf2, 0x0f, 0x10);
929903 pub fn opcode_3byte(self: Self, prefix_1: u8, prefix_2: u8, opcode: u8) !void {
930 try self.writer.writeAll(&.{ prefix_1, prefix_2, opcode });
904 try self.w.writeAll(&.{ prefix_1, prefix_2, opcode });
931905 }
932906
933907 /// Encodes a 1 byte opcode with a reg field
......@@ -935,7 +909,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
935909 /// Remember to add a REX prefix byte if reg is extended!
936910 pub fn opcode_withReg(self: Self, opcode: u8, reg: u3) !void {
937911 assert(opcode & 0b111 == 0);
938 try self.writer.writeByte(opcode | reg);
912 try self.w.writeByte(opcode | reg);
939913 }
940914
941915 // ------
......@@ -946,7 +920,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
946920 ///
947921 /// Remember to add a REX prefix byte if reg or rm are extended!
948922 pub fn modRm(self: Self, mod: u2, reg_or_opx: u3, rm: u3) !void {
949 try self.writer.writeByte(@as(u8, mod) << 6 | @as(u8, reg_or_opx) << 3 | rm);
923 try self.w.writeByte(@as(u8, mod) << 6 | @as(u8, reg_or_opx) << 3 | rm);
950924 }
951925
952926 /// Construct a ModR/M byte using direct r/m addressing
......@@ -1032,7 +1006,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
10321006 ///
10331007 /// Remember to add a REX prefix byte if index or base are extended!
10341008 pub fn sib(self: Self, scale: u2, index: u3, base: u3) !void {
1035 try self.writer.writeByte(@as(u8, scale) << 6 | @as(u8, index) << 3 | base);
1009 try self.w.writeByte(@as(u8, scale) << 6 | @as(u8, index) << 3 | base);
10361010 }
10371011
10381012 /// Construct a SIB byte with scale * index + base, no frills.
......@@ -1124,42 +1098,42 @@ fn Encoder(comptime T: type, comptime opts: Options) type {
11241098 ///
11251099 /// It is sign-extended to 64 bits by the cpu.
11261100 pub fn disp8(self: Self, disp: i8) !void {
1127 try self.writer.writeByte(@as(u8, @bitCast(disp)));
1101 try self.w.writeByte(@as(u8, @bitCast(disp)));
11281102 }
11291103
11301104 /// Encode an 32 bit displacement
11311105 ///
11321106 /// It is sign-extended to 64 bits by the cpu.
11331107 pub fn disp32(self: Self, disp: i32) !void {
1134 try self.writer.writeInt(i32, disp, .little);
1108 try self.w.writeInt(i32, disp, .little);
11351109 }
11361110
11371111 /// Encode an 8 bit immediate
11381112 ///
11391113 /// It is sign-extended to 64 bits by the cpu.
11401114 pub fn imm8(self: Self, imm: u8) !void {
1141 try self.writer.writeByte(imm);
1115 try self.w.writeByte(imm);
11421116 }
11431117
11441118 /// Encode an 16 bit immediate
11451119 ///
11461120 /// It is sign-extended to 64 bits by the cpu.
11471121 pub fn imm16(self: Self, imm: u16) !void {
1148 try self.writer.writeInt(u16, imm, .little);
1122 try self.w.writeInt(u16, imm, .little);
11491123 }
11501124
11511125 /// Encode an 32 bit immediate
11521126 ///
11531127 /// It is sign-extended to 64 bits by the cpu.
11541128 pub fn imm32(self: Self, imm: u32) !void {
1155 try self.writer.writeInt(u32, imm, .little);
1129 try self.w.writeInt(u32, imm, .little);
11561130 }
11571131
11581132 /// Encode an 64 bit immediate
11591133 ///
11601134 /// It is sign-extended to 64 bits by the cpu.
11611135 pub fn imm64(self: Self, imm: u64) !void {
1162 try self.writer.writeInt(u64, imm, .little);
1136 try self.w.writeInt(u64, imm, .little);
11631137 }
11641138 };
11651139}
......@@ -2217,10 +2191,10 @@ const Assembler = struct {
22172191 };
22182192 }
22192193
2220 pub fn assemble(as: *Assembler, writer: anytype) !void {
2194 pub fn assemble(as: *Assembler, w: *Writer) !void {
22212195 while (try as.next()) |parsed_inst| {
22222196 const inst: Instruction = try .new(.none, parsed_inst.mnemonic, &parsed_inst.ops);
2223 try inst.encode(writer, .{});
2197 try inst.encode(w, .{});
22242198 }
22252199 }
22262200
src/codegen/c.zig+117-107
......@@ -604,8 +604,12 @@ pub const Function = struct {
604604 return f.object.dg.renderIntCast(w, dest_ty, .{ .c_value = .{ .f = f, .value = src, .v = v } }, src_ty, location);
605605 }
606606
607 fn fmtIntLiteral(f: *Function, val: Value) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
608 return f.object.dg.fmtIntLiteral(val, .Other);
607 fn fmtIntLiteralDec(f: *Function, val: Value) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
608 return f.object.dg.fmtIntLiteralDec(val, .Other);
609 }
610
611 fn fmtIntLiteralHex(f: *Function, val: Value) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
612 return f.object.dg.fmtIntLiteralHex(val, .Other);
609613 }
610614
611615 fn getLazyFnName(f: *Function, key: LazyFnKey) ![]const u8 {
......@@ -629,7 +633,7 @@ pub const Function = struct {
629633 }),
630634 .never_tail,
631635 .never_inline,
632 => |owner_nav| try ctype_pool.fmt(gpa, "zig_{s}_{}__{d}", .{
636 => |owner_nav| try ctype_pool.fmt(gpa, "zig_{s}_{f}__{d}", .{
633637 @tagName(key),
634638 fmtIdentUnsolo(ip.getNav(owner_nav).name.toSlice(ip)),
635639 @intFromEnum(owner_nav),
......@@ -880,7 +884,7 @@ pub const DeclGen = struct {
880884 const addr_val = try pt.intValue(.usize, int.addr);
881885 try writer.writeByte('(');
882886 try dg.renderCType(writer, ptr_ctype);
883 try writer.print("){x}", .{try dg.fmtIntLiteral(addr_val, .Other)});
887 try writer.print("){f}", .{try dg.fmtIntLiteralHex(addr_val, .Other)});
884888 },
885889
886890 .nav_ptr => |nav| try dg.renderNav(writer, nav, location),
......@@ -920,7 +924,7 @@ pub const DeclGen = struct {
920924 const offset_val = try pt.intValue(.usize, byte_offset);
921925 try writer.writeAll("((char *)");
922926 try dg.renderPointer(writer, field.parent.*, location);
923 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
927 try writer.print(" + {f})", .{try dg.fmtIntLiteralDec(offset_val, .Other)});
924928 },
925929 }
926930 },
......@@ -942,7 +946,7 @@ pub const DeclGen = struct {
942946 // The pointer already has an appropriate type - just do the arithmetic.
943947 try writer.writeByte('(');
944948 try dg.renderPointer(writer, elem.parent.*, location);
945 try writer.print(" + {})", .{try dg.fmtIntLiteral(index_val, .Other)});
949 try writer.print(" + {f})", .{try dg.fmtIntLiteralDec(index_val, .Other)});
946950 } else {
947951 // We probably have an array pointer `T (*)[n]`. Cast to an element pointer,
948952 // and *then* apply the index.
......@@ -950,7 +954,7 @@ pub const DeclGen = struct {
950954 try dg.renderCType(writer, result_ctype);
951955 try writer.writeByte(')');
952956 try dg.renderPointer(writer, elem.parent.*, location);
953 try writer.print(" + {})", .{try dg.fmtIntLiteral(index_val, .Other)});
957 try writer.print(" + {f})", .{try dg.fmtIntLiteralDec(index_val, .Other)});
954958 }
955959 },
956960
......@@ -965,7 +969,7 @@ pub const DeclGen = struct {
965969 const offset_val = try pt.intValue(.usize, oac.byte_offset);
966970 try writer.writeAll("((char *)");
967971 try dg.renderPointer(writer, oac.parent.*, location);
968 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
972 try writer.print(" + {f})", .{try dg.fmtIntLiteralDec(offset_val, .Other)});
969973 }
970974 },
971975 }
......@@ -1037,11 +1041,11 @@ pub const DeclGen = struct {
10371041 .empty_enum_value,
10381042 => unreachable, // non-runtime values
10391043 .int => |int| switch (int.storage) {
1040 .u64, .i64, .big_int => try writer.print("{}", .{try dg.fmtIntLiteral(val, location)}),
1044 .u64, .i64, .big_int => try writer.print("{f}", .{try dg.fmtIntLiteralDec(val, location)}),
10411045 .lazy_align, .lazy_size => {
10421046 try writer.writeAll("((");
10431047 try dg.renderCType(writer, ctype);
1044 try writer.print("){x})", .{try dg.fmtIntLiteral(
1048 try writer.print("){f})", .{try dg.fmtIntLiteralHex(
10451049 try pt.intValue(.usize, val.toUnsignedInt(zcu)),
10461050 .Other,
10471051 )});
......@@ -1170,7 +1174,7 @@ pub const DeclGen = struct {
11701174 try writer.writeAll(", ");
11711175 empty = false;
11721176 }
1173 try writer.print("{x}", .{try dg.fmtIntLiteral(
1177 try writer.print("{f}", .{try dg.fmtIntLiteralHex(
11741178 try pt.intValue_big(repr_ty, repr_val_big.toConst()),
11751179 location,
11761180 )});
......@@ -1642,15 +1646,15 @@ pub const DeclGen = struct {
16421646 .enum_type,
16431647 .error_set_type,
16441648 .inferred_error_set_type,
1645 => return writer.print("{x}", .{
1646 try dg.fmtIntLiteral(try pt.undefValue(ty), location),
1649 => return writer.print("{f}", .{
1650 try dg.fmtIntLiteralHex(try pt.undefValue(ty), location),
16471651 }),
16481652 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
16491653 .one, .many, .c => {
16501654 try writer.writeAll("((");
16511655 try dg.renderCType(writer, ctype);
1652 return writer.print("){x})", .{
1653 try dg.fmtIntLiteral(.undef_usize, .Other),
1656 return writer.print("){f})", .{
1657 try dg.fmtIntLiteralHex(.undef_usize, .Other),
16541658 });
16551659 },
16561660 .slice => {
......@@ -1663,8 +1667,8 @@ pub const DeclGen = struct {
16631667 try writer.writeAll("{(");
16641668 const ptr_ty = ty.slicePtrFieldType(zcu);
16651669 try dg.renderType(writer, ptr_ty);
1666 return writer.print("){x}, {0x}}}", .{
1667 try dg.fmtIntLiteral(.undef_usize, .Other),
1670 return writer.print("){f}, {0x}}}", .{
1671 try dg.fmtIntLiteralHex(.undef_usize, .Other),
16681672 });
16691673 },
16701674 },
......@@ -1727,8 +1731,8 @@ pub const DeclGen = struct {
17271731 }
17281732 return writer.writeByte('}');
17291733 },
1730 .@"packed" => return writer.print("{x}", .{
1731 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
1734 .@"packed" => return writer.print("{f}", .{
1735 try dg.fmtIntLiteralHex(try pt.undefValue(ty), .Other),
17321736 }),
17331737 }
17341738 },
......@@ -1797,8 +1801,8 @@ pub const DeclGen = struct {
17971801 }
17981802 if (has_tag) try writer.writeByte('}');
17991803 },
1800 .@"packed" => return writer.print("{x}", .{
1801 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
1804 .@"packed" => return writer.print("{f}", .{
1805 try dg.fmtIntLiteralHex(try pt.undefValue(ty), .Other),
18021806 }),
18031807 }
18041808 },
......@@ -1940,8 +1944,8 @@ pub const DeclGen = struct {
19401944 try w.print("{}", .{trailing});
19411945 switch (name) {
19421946 .nav => |nav| try dg.renderNavName(w, nav),
1943 .fmt_ctype_pool_string => |fmt| try w.print("{ }", .{fmt}),
1944 .@"export" => |@"export"| try w.print("{ }", .{fmtIdentSolo(@"export".extern_name.toSlice(ip))}),
1947 .fmt_ctype_pool_string => |fmt| try w.print("{f}", .{fmt}),
1948 .@"export" => |@"export"| try w.print("{f}", .{fmtIdentSolo(@"export".extern_name.toSlice(ip))}),
19451949 }
19461950
19471951 try renderTypeSuffix(
......@@ -2126,7 +2130,7 @@ pub const DeclGen = struct {
21262130 } else if (dest_bits > 64 and src_bits <= 64) {
21272131 try w.writeAll("zig_make_");
21282132 try dg.renderTypeForBuiltinFnName(w, dest_ty);
2129 try w.writeAll("(0, "); // TODO: Should the 0 go through fmtIntLiteral?
2133 try w.writeAll("(0, ");
21302134 if (src_is_ptr) {
21312135 try w.writeByte('(');
21322136 try dg.renderType(w, src_eff_ty);
......@@ -2398,7 +2402,7 @@ pub const DeclGen = struct {
23982402 };
23992403
24002404 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});
2401 try writer.print(", {}", .{try dg.fmtIntLiteral(
2405 try writer.print(", {f}", .{try dg.fmtIntLiteralDec(
24022406 try pt.intValue(if (is_big) .u16 else .u8, int_info.bits),
24032407 .FunctionArgument,
24042408 )});
......@@ -2408,18 +2412,38 @@ pub const DeclGen = struct {
24082412 dg: *DeclGen,
24092413 val: Value,
24102414 loc: ValueRenderLocation,
2411 ) !std.fmt.Formatter(formatIntLiteral) {
2415 base: u8,
2416 case: std.fmt.Case,
2417 ) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
24122418 const zcu = dg.pt.zcu;
24132419 const kind = loc.toCTypeKind();
24142420 const ty = val.typeOf(zcu);
2415 return std.fmt.Formatter(formatIntLiteral){ .data = .{
2421 return .{ .data = .{
24162422 .dg = dg,
24172423 .int_info = ty.intInfo(zcu),
24182424 .kind = kind,
24192425 .ctype = try dg.ctypeFromType(ty, kind),
24202426 .val = val,
2427 .base = base,
2428 .case = case,
24212429 } };
24222430 }
2431
2432 fn fmtIntLiteralDec(
2433 dg: *DeclGen,
2434 val: Value,
2435 loc: ValueRenderLocation,
2436 ) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
2437 return fmtIntLiteral(dg, val, loc, 10, .lower);
2438 }
2439
2440 fn fmtIntLiteralHex(
2441 dg: *DeclGen,
2442 val: Value,
2443 loc: ValueRenderLocation,
2444 ) !std.fmt.Formatter(FormatIntLiteralContext, formatIntLiteral) {
2445 return fmtIntLiteral(dg, val, loc, 16, .lower);
2446 }
24232447};
24242448
24252449const CTypeFix = enum { prefix, suffix };
......@@ -2848,9 +2872,9 @@ pub fn genErrDecls(o: *Object) !void {
28482872 for (names, 1..) |name_nts, val| {
28492873 const name = name_nts.toSlice(ip);
28502874 if (val > 1) try writer.writeAll(", ");
2851 try writer.print("{{" ++ name_prefix ++ "{}, {}}}", .{
2875 try writer.print("{{" ++ name_prefix ++ "{f}, {f}}}", .{
28522876 fmtIdentUnsolo(name),
2853 try o.dg.fmtIntLiteral(try pt.intValue(.usize, name.len), .StaticInitializer),
2877 try o.dg.fmtIntLiteralDec(try pt.intValue(.usize, name.len), .StaticInitializer),
28542878 });
28552879 }
28562880 try writer.writeAll("};\n");
......@@ -2890,17 +2914,17 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
28902914 .storage = .{ .bytes = tag_name.toString() },
28912915 } });
28922916
2893 try w.print(" case {}: {{\n static ", .{
2894 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, pt), .Other),
2917 try w.print(" case {f}: {{\n static ", .{
2918 try o.dg.fmtIntLiteralDec(try tag_val.intFromEnum(enum_ty, pt), .Other),
28952919 });
28962920 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);
28972921 try w.writeAll(" = ");
28982922 try o.dg.renderValue(w, Value.fromInterned(name_val), .StaticInitializer);
28992923 try w.writeAll(";\n return (");
29002924 try o.dg.renderType(w, name_slice_ty);
2901 try w.print("){{{}, {}}};\n", .{
2925 try w.print("){{{f}, {f}}};\n", .{
29022926 fmtIdentUnsolo("name"),
2903 try o.dg.fmtIntLiteral(try pt.intValue(.usize, tag_name_len), .Other),
2927 try o.dg.fmtIntLiteralDec(try pt.intValue(.usize, tag_name_len), .Other),
29042928 });
29052929
29062930 try w.writeAll(" }\n");
......@@ -2915,7 +2939,7 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
29152939 const fn_val = zcu.navValue(fn_nav_index);
29162940 const fn_ctype = try o.dg.ctypeFromType(fn_val.typeOf(zcu), .complete);
29172941 const fn_info = fn_ctype.info(ctype_pool).function;
2918 const fn_name = fmtCTypePoolString(val.fn_name, lazy_ctype_pool);
2942 const fn_name = fmtCTypePoolString(val.fn_name, lazy_ctype_pool, true);
29192943
29202944 const fwd = o.dg.fwdDeclWriter();
29212945 try fwd.print("static zig_{s} ", .{@tagName(key)});
......@@ -3954,7 +3978,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
39543978 try writer.writeByte('(');
39553979 try f.writeCValueDeref(writer, operand);
39563980 try v.elem(f, writer);
3957 try writer.print(", {})", .{try f.fmtIntLiteral(bit_offset_val)});
3981 try writer.print(", {f})", .{try f.fmtIntLiteralDec(bit_offset_val)});
39583982 if (cant_cast) try writer.writeByte(')');
39593983 try f.object.dg.renderBuiltinInfo(writer, field_ty, .bits);
39603984 try writer.writeByte(')');
......@@ -4102,8 +4126,8 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
41024126 try writer.writeByte('(');
41034127 try f.writeCValue(writer, operand, .FunctionArgument);
41044128 try v.elem(f, writer);
4105 try writer.print(", {x})", .{
4106 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(pt, scalar_ty)),
4129 try writer.print(", {f})", .{
4130 try f.fmtIntLiteralHex(try inst_scalar_ty.maxIntScalar(pt, scalar_ty)),
41074131 });
41084132 },
41094133 .signed => {
......@@ -4127,9 +4151,9 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
41274151 try f.writeCValue(writer, operand, .FunctionArgument);
41284152 try v.elem(f, writer);
41294153 if (c_bits == 128) try writer.writeByte(')');
4130 try writer.print(", {})", .{try f.fmtIntLiteral(shift_val)});
4154 try writer.print(", {f})", .{try f.fmtIntLiteralDec(shift_val)});
41314155 if (c_bits == 128) try writer.writeByte(')');
4132 try writer.print(", {})", .{try f.fmtIntLiteral(shift_val)});
4156 try writer.print(", {f})", .{try f.fmtIntLiteralDec(shift_val)});
41334157 },
41344158 }
41354159 if (need_lo) try writer.writeByte(')');
......@@ -4244,7 +4268,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
42444268 try writer.writeByte('(');
42454269 try f.writeCValueDeref(writer, ptr_val);
42464270 try v.elem(f, writer);
4247 try writer.print(", {x}), zig_shl_", .{try f.fmtIntLiteral(mask_val)});
4271 try writer.print(", {f}), zig_shl_", .{try f.fmtIntLiteralHex(mask_val)});
42484272 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
42494273 try writer.writeByte('(');
42504274 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
......@@ -4267,7 +4291,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
42674291 try f.writeCValue(writer, src_val, .Other);
42684292 try v.elem(f, writer);
42694293 if (cant_cast) try writer.writeByte(')');
4270 try writer.print(", {}))", .{try f.fmtIntLiteral(bit_offset_val)});
4294 try writer.print(", {f}))", .{try f.fmtIntLiteralDec(bit_offset_val)});
42714295 try a.end(f, writer);
42724296 try v.end(f, inst, writer);
42734297 } else {
......@@ -5348,7 +5372,7 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index, is_dispatch_loop: bool) !void
53485372 write_val: {
53495373 if (condition_ty.isPtrAtRuntime(zcu)) {
53505374 if (item_value.?.getUnsignedInt(zcu)) |item_int| {
5351 try writer.print("{}", .{try f.fmtIntLiteral(try pt.intValue(lowered_condition_ty, item_int))});
5375 try writer.print("{f}", .{try f.fmtIntLiteralDec(try pt.intValue(lowered_condition_ty, item_int))});
53525376 break :write_val;
53535377 }
53545378 }
......@@ -6004,8 +6028,8 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
60046028 try f.renderType(writer, u8_ptr_ty);
60056029 try writer.writeByte(')');
60066030 try f.writeCValue(writer, field_ptr_val, .Other);
6007 try writer.print(" - {})", .{
6008 try f.fmtIntLiteral(try pt.intValue(.usize, byte_offset)),
6031 try writer.print(" - {f})", .{
6032 try f.fmtIntLiteralDec(try pt.intValue(.usize, byte_offset)),
60096033 });
60106034 },
60116035 }
......@@ -6049,8 +6073,8 @@ fn fieldPtr(
60496073 try f.renderType(writer, u8_ptr_ty);
60506074 try writer.writeByte(')');
60516075 try f.writeCValue(writer, container_ptr_val, .Other);
6052 try writer.print(" + {})", .{
6053 try f.fmtIntLiteral(try pt.intValue(.usize, byte_offset)),
6076 try writer.print(" + {f})", .{
6077 try f.fmtIntLiteralDec(try pt.intValue(.usize, byte_offset)),
60546078 });
60556079 },
60566080 }
......@@ -6121,8 +6145,8 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
61216145 try writer.writeByte('(');
61226146 }
61236147 try f.writeCValue(writer, struct_byval, .Other);
6124 if (bit_offset > 0) try writer.print(", {})", .{
6125 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
6148 if (bit_offset > 0) try writer.print(", {f})", .{
6149 try f.fmtIntLiteralDec(try pt.intValue(bit_offset_ty, bit_offset)),
61266150 });
61276151 if (cant_cast) try writer.writeByte(')');
61286152 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);
......@@ -6227,8 +6251,8 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
62276251 if (!payload_ty.hasRuntimeBits(zcu))
62286252 try f.writeCValue(writer, operand, .Other)
62296253 else if (error_ty.errorSetIsEmpty(zcu))
6230 try writer.print("{}", .{
6231 try f.fmtIntLiteral(try pt.intValue(try pt.errorIntType(), 0)),
6254 try writer.print("{f}", .{
6255 try f.fmtIntLiteralDec(try pt.intValue(try pt.errorIntType(), 0)),
62326256 })
62336257 else if (operand_is_ptr)
62346258 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
......@@ -6374,7 +6398,7 @@ fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
63746398 const a = try Assignment.start(f, writer, try f.ctypeFromType(operand_ty, .complete));
63756399 try f.writeCValueDeref(writer, operand);
63766400 try a.assign(f, writer);
6377 try writer.print("{}", .{try f.fmtIntLiteral(no_err)});
6401 try writer.print("{f}", .{try f.fmtIntLiteralDec(no_err)});
63786402 try a.end(f, writer);
63796403 return .none;
63806404 }
......@@ -6382,7 +6406,7 @@ fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
63826406 const a = try Assignment.start(f, writer, try f.ctypeFromType(err_int_ty, .complete));
63836407 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" });
63846408 try a.assign(f, writer);
6385 try writer.print("{}", .{try f.fmtIntLiteral(no_err)});
6409 try writer.print("{f}", .{try f.fmtIntLiteralDec(no_err)});
63866410 try a.end(f, writer);
63876411 }
63886412
......@@ -6520,7 +6544,7 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
65206544 if (operand_child_ctype.info(ctype_pool) == .array) {
65216545 try writer.writeByte('&');
65226546 try f.writeCValueDeref(writer, operand);
6523 try writer.print("[{}]", .{try f.fmtIntLiteral(.zero_usize)});
6547 try writer.print("[{f}]", .{try f.fmtIntLiteralDec(.zero_usize)});
65246548 } else try f.writeCValue(writer, operand, .Other);
65256549 }
65266550 try a.end(f, writer);
......@@ -6529,8 +6553,8 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
65296553 const a = try Assignment.start(f, writer, .usize);
65306554 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
65316555 try a.assign(f, writer);
6532 try writer.print("{}", .{
6533 try f.fmtIntLiteral(try pt.intValue(.usize, array_ty.arrayLen(zcu))),
6556 try writer.print("{f}", .{
6557 try f.fmtIntLiteralDec(try pt.intValue(.usize, array_ty.arrayLen(zcu))),
65346558 });
65356559 try a.end(f, writer);
65366560 }
......@@ -6736,9 +6760,9 @@ fn airCmpBuiltinCall(
67366760 try v.elem(f, writer);
67376761 try f.object.dg.renderBuiltinInfo(writer, scalar_ty, info);
67386762 try writer.writeByte(')');
6739 if (!ref_ret) try writer.print("{s}{}", .{
6763 if (!ref_ret) try writer.print("{s}{f}", .{
67406764 compareOperatorC(operator),
6741 try f.fmtIntLiteral(try pt.intValue(.i32, 0)),
6765 try f.fmtIntLiteralDec(try pt.intValue(.i32, 0)),
67426766 });
67436767 try writer.writeAll(";\n");
67446768 try v.end(f, inst, writer);
......@@ -7148,8 +7172,8 @@ fn writeArrayLen(f: *Function, writer: ArrayListWriter, dest_ptr: CValue, dest_t
71487172 const pt = f.object.dg.pt;
71497173 const zcu = pt.zcu;
71507174 switch (dest_ty.ptrSize(zcu)) {
7151 .one => try writer.print("{}", .{
7152 try f.fmtIntLiteral(try pt.intValue(.usize, dest_ty.childType(zcu).arrayLen(zcu))),
7175 .one => try writer.print("{f}", .{
7176 try f.fmtIntLiteralDec(try pt.intValue(.usize, dest_ty.childType(zcu).arrayLen(zcu))),
71537177 }),
71547178 .many, .c => unreachable,
71557179 .slice => try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" }),
......@@ -7635,8 +7659,8 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
76357659 try writer.writeByte(')');
76367660 }
76377661
7638 try writer.print(", {}", .{
7639 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
7662 try writer.print(", {f}", .{
7663 try f.fmtIntLiteralDec(try pt.intValue(bit_offset_ty, bit_offset)),
76407664 });
76417665 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);
76427666 try writer.writeByte(')');
......@@ -7693,7 +7717,7 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
76937717 const a = try Assignment.start(f, writer, try f.ctypeFromType(tag_ty, .complete));
76947718 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });
76957719 try a.assign(f, writer);
7696 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, pt))});
7720 try writer.print("{f}", .{try f.fmtIntLiteralDec(try tag_val.intFromEnum(tag_ty, pt))});
76977721 try a.end(f, writer);
76987722 }
76997723 break :field .{ .payload_identifier = field_name.toSlice(ip) };
......@@ -8207,14 +8231,12 @@ fn stringLiteral(
82078231 };
82088232}
82098233
8210const FormatStringContext = struct { str: []const u8, sentinel: ?u8 };
8211fn formatStringLiteral(
8212 data: FormatStringContext,
8213 writer: *std.io.Writer,
8214 comptime fmt: []const u8, // TODO move this state to FormatStringContext
8215) std.io.Writer.Error!void {
8216 if (fmt.len != 1 or fmt[0] != 's') @compileError("Invalid fmt: " ++ fmt);
8234const FormatStringContext = struct {
8235 str: []const u8,
8236 sentinel: ?u8,
8237};
82178238
8239fn formatStringLiteral(data: FormatStringContext, writer: *std.io.Writer) std.io.Writer.Error!void {
82188240 var literal = stringLiteral(writer, data.str.len + @intFromBool(data.sentinel != null));
82198241 try literal.start();
82208242 for (data.str) |c| try literal.writeChar(c);
......@@ -8238,12 +8260,10 @@ const FormatIntLiteralContext = struct {
82388260 kind: CType.Kind,
82398261 ctype: CType,
82408262 val: Value,
8263 base: u8,
8264 case: std.fmt.Case,
82418265};
8242fn formatIntLiteral(
8243 data: FormatIntLiteralContext,
8244 writer: *std.io.Writer,
8245 comptime fmt: []const u8, // TODO move this state to FormatIntLiteralContext
8246) std.io.Writer.Error!void {
8266fn formatIntLiteral(data: FormatIntLiteralContext, writer: *std.io.Writer) std.io.Writer.Error!void {
82478267 const pt = data.dg.pt;
82488268 const zcu = pt.zcu;
82498269 const target = &data.dg.mod.resolved_target.result;
......@@ -8268,7 +8288,7 @@ fn formatIntLiteral(
82688288
82698289 var int_buf: Value.BigIntSpace = undefined;
82708290 const int = if (data.val.isUndefDeep(zcu)) blk: {
8271 undef_limbs = try allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(data.int_info.bits));
8291 undef_limbs = try oom(allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(data.int_info.bits)));
82728292 @memset(undef_limbs, undefPattern(BigIntLimb));
82738293
82748294 var undef_int = BigInt.Mutable{
......@@ -8286,7 +8306,7 @@ fn formatIntLiteral(
82868306 const one = BigInt.Mutable.init(&one_limbs, 1).toConst();
82878307
82888308 var wrap = BigInt.Mutable{
8289 .limbs = try allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(c_bits)),
8309 .limbs = try oom(allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(c_bits))),
82908310 .len = undefined,
82918311 .positive = undefined,
82928312 };
......@@ -8333,32 +8353,14 @@ fn formatIntLiteral(
83338353 if (!int.positive) try writer.writeByte('-');
83348354 try data.ctype.renderLiteralPrefix(writer, data.kind, ctype_pool);
83358355
8336 const style: struct { base: u8, case: std.fmt.Case = undefined } = switch (fmt.len) {
8337 0 => .{ .base = 10 },
8338 1 => switch (fmt[0]) {
8339 'b' => style: {
8340 try writer.writeAll("0b");
8341 break :style .{ .base = 2 };
8342 },
8343 'o' => style: {
8344 try writer.writeByte('0');
8345 break :style .{ .base = 8 };
8346 },
8347 'd' => .{ .base = 10 },
8348 'x', 'X' => |base| style: {
8349 try writer.writeAll("0x");
8350 break :style .{ .base = 16, .case = switch (base) {
8351 'x' => .lower,
8352 'X' => .upper,
8353 else => unreachable,
8354 } };
8355 },
8356 else => @compileError("Invalid fmt: " ++ fmt),
8357 },
8358 else => @compileError("Invalid fmt: " ++ fmt),
8359 };
8360
8361 const string = try int.abs().toStringAlloc(allocator, style.base, style.case);
8356 switch (data.base) {
8357 2 => try writer.writeAll("0b"),
8358 8 => try writer.writeByte('0'),
8359 10 => {},
8360 16 => try writer.writeAll("0x"),
8361 else => unreachable,
8362 }
8363 const string = try oom(int.abs().toStringAlloc(allocator, data.base, data.case));
83628364 defer allocator.free(string);
83638365 try writer.writeAll(string);
83648366 } else {
......@@ -8411,8 +8413,10 @@ fn formatIntLiteral(
84118413 .int_info = c_limb_int_info,
84128414 .kind = data.kind,
84138415 .ctype = c_limb_ctype,
8414 .val = try pt.intValue_big(.comptime_int, c_limb_mut.toConst()),
8415 }, fmt, writer);
8416 .val = try oom(pt.intValue_big(.comptime_int, c_limb_mut.toConst())),
8417 .base = data.base,
8418 .case = data.case,
8419 }, writer);
84168420 }
84178421 }
84188422 try data.ctype.renderLiteralSuffix(writer, ctype_pool);
......@@ -8492,11 +8496,11 @@ const Vectorize = struct {
84928496
84938497 try writer.writeAll("for (");
84948498 try f.writeCValue(writer, local, .Other);
8495 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(.zero_usize)});
8499 try writer.print(" = {f}; ", .{try f.fmtIntLiteralDec(.zero_usize)});
84968500 try f.writeCValue(writer, local, .Other);
8497 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try pt.intValue(.usize, ty.vectorLen(zcu)))});
8501 try writer.print(" < {f}; ", .{try f.fmtIntLiteralDec(try pt.intValue(.usize, ty.vectorLen(zcu)))});
84988502 try f.writeCValue(writer, local, .Other);
8499 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(.one_usize)});
8503 try writer.print(" += {f}) {{\n", .{try f.fmtIntLiteralDec(.one_usize)});
85008504 f.object.indent_writer.pushIndent();
85018505
85028506 break :index .{ .index = local };
......@@ -8622,3 +8626,9 @@ fn deinitFreeLocalsMap(gpa: Allocator, map: *LocalsMap) void {
86228626 }
86238627 map.deinit(gpa);
86248628}
8629
8630fn oom(x: anytype) error{WriteFailed}!@typeInfo(@TypeOf(x)).error_union.payload {
8631 return x catch |err| switch (err) {
8632 error.OutOfMemory => error.WriteFailed,
8633 };
8634}
src/codegen/c/Type.zig+20-18
......@@ -209,7 +209,7 @@ pub fn getStandardDefineAbbrev(ctype: CType) ?[]const u8 {
209209 };
210210}
211211
212pub fn renderLiteralPrefix(ctype: CType, writer: anytype, kind: Kind, pool: *const Pool) @TypeOf(writer).Error!void {
212pub fn renderLiteralPrefix(ctype: CType, w: *Writer, kind: Kind, pool: *const Pool) Writer.Error!void {
213213 switch (ctype.info(pool)) {
214214 .basic => |basic_info| switch (basic_info) {
215215 .void => unreachable,
......@@ -224,7 +224,7 @@ pub fn renderLiteralPrefix(ctype: CType, writer: anytype, kind: Kind, pool: *con
224224 .uintptr_t,
225225 .intptr_t,
226226 => switch (kind) {
227 else => try writer.print("({s})", .{@tagName(basic_info)}),
227 else => try w.print("({s})", .{@tagName(basic_info)}),
228228 .global => {},
229229 },
230230 .int,
......@@ -246,7 +246,7 @@ pub fn renderLiteralPrefix(ctype: CType, writer: anytype, kind: Kind, pool: *con
246246 .int32_t,
247247 .uint64_t,
248248 .int64_t,
249 => try writer.print("{s}_C(", .{ctype.getStandardDefineAbbrev().?}),
249 => try w.print("{s}_C(", .{ctype.getStandardDefineAbbrev().?}),
250250 .zig_u128,
251251 .zig_i128,
252252 .zig_f16,
......@@ -255,7 +255,7 @@ pub fn renderLiteralPrefix(ctype: CType, writer: anytype, kind: Kind, pool: *con
255255 .zig_f80,
256256 .zig_f128,
257257 .zig_c_longdouble,
258 => try writer.print("zig_{s}_{s}(", .{
258 => try w.print("zig_{s}_{s}(", .{
259259 switch (kind) {
260260 else => "make",
261261 .global => "init",
......@@ -265,12 +265,12 @@ pub fn renderLiteralPrefix(ctype: CType, writer: anytype, kind: Kind, pool: *con
265265 .va_list => unreachable,
266266 _ => unreachable,
267267 },
268 .array, .vector => try writer.writeByte('{'),
268 .array, .vector => try w.writeByte('{'),
269269 else => unreachable,
270270 }
271271}
272272
273pub fn renderLiteralSuffix(ctype: CType, writer: anytype, pool: *const Pool) @TypeOf(writer).Error!void {
273pub fn renderLiteralSuffix(ctype: CType, w: *Writer, pool: *const Pool) Writer.Error!void {
274274 switch (ctype.info(pool)) {
275275 .basic => |basic_info| switch (basic_info) {
276276 .void => unreachable,
......@@ -280,20 +280,20 @@ pub fn renderLiteralSuffix(ctype: CType, writer: anytype, pool: *const Pool) @Ty
280280 .short,
281281 .int,
282282 => {},
283 .long => try writer.writeByte('l'),
284 .@"long long" => try writer.writeAll("ll"),
283 .long => try w.writeByte('l'),
284 .@"long long" => try w.writeAll("ll"),
285285 .@"unsigned char",
286286 .@"unsigned short",
287287 .@"unsigned int",
288 => try writer.writeByte('u'),
288 => try w.writeByte('u'),
289289 .@"unsigned long",
290290 .size_t,
291291 .uintptr_t,
292 => try writer.writeAll("ul"),
293 .@"unsigned long long" => try writer.writeAll("ull"),
294 .float => try writer.writeByte('f'),
292 => try w.writeAll("ul"),
293 .@"unsigned long long" => try w.writeAll("ull"),
294 .float => try w.writeByte('f'),
295295 .double => {},
296 .@"long double" => try writer.writeByte('l'),
296 .@"long double" => try w.writeByte('l'),
297297 .bool,
298298 .ptrdiff_t,
299299 .intptr_t,
......@@ -314,11 +314,11 @@ pub fn renderLiteralSuffix(ctype: CType, writer: anytype, pool: *const Pool) @Ty
314314 .zig_f80,
315315 .zig_f128,
316316 .zig_c_longdouble,
317 => try writer.writeByte(')'),
317 => try w.writeByte(')'),
318318 .va_list => unreachable,
319319 _ => unreachable,
320320 },
321 .array, .vector => try writer.writeByte('}'),
321 .array, .vector => try w.writeByte('}'),
322322 else => unreachable,
323323 }
324324}
......@@ -938,7 +938,7 @@ pub const Pool = struct {
938938 index: String.Index,
939939
940940 const FormatData = struct { string: String, pool: *const Pool };
941 fn format(data: FormatData, writer: *std.io.Writer) std.io.Writer.Error!void {
941 fn format(data: FormatData, writer: *Writer) Writer.Error!void {
942942 if (data.string.toSlice(data.pool)) |slice|
943943 try writer.writeAll(slice)
944944 else
......@@ -2884,7 +2884,7 @@ pub const Pool = struct {
28842884 comptime fmt_str: []const u8,
28852885 fmt_args: anytype,
28862886 ) !String {
2887 try pool.string_bytes.writer(allocator).print(fmt_str, fmt_args);
2887 try pool.string_bytes.print(allocator, fmt_str, fmt_args);
28882888 return pool.trailingString(allocator);
28892889 }
28902890
......@@ -3275,10 +3275,12 @@ pub const AlignAs = packed struct {
32753275 }
32763276};
32773277
3278const std = @import("std");
32783279const assert = std.debug.assert;
3280const Writer = std.io.Writer;
3281
32793282const CType = @This();
32803283const InternPool = @import("../../InternPool.zig");
32813284const Module = @import("../../Package/Module.zig");
3282const std = @import("std");
32833285const Type = @import("../../Type.zig");
32843286const Zcu = @import("../../Zcu.zig");
src/codegen/llvm.zig+28-18
......@@ -239,12 +239,12 @@ pub fn targetTriple(allocator: Allocator, target: *const std.Target) ![]const u8
239239 .none,
240240 .windows,
241241 => {},
242 .semver => |ver| try llvm_triple.writer().print("{d}.{d}.{d}", .{
242 .semver => |ver| try llvm_triple.print("{d}.{d}.{d}", .{
243243 ver.min.major,
244244 ver.min.minor,
245245 ver.min.patch,
246246 }),
247 inline .linux, .hurd => |ver| try llvm_triple.writer().print("{d}.{d}.{d}", .{
247 inline .linux, .hurd => |ver| try llvm_triple.print("{d}.{d}.{d}", .{
248248 ver.range.min.major,
249249 ver.range.min.minor,
250250 ver.range.min.patch,
......@@ -295,13 +295,13 @@ pub fn targetTriple(allocator: Allocator, target: *const std.Target) ![]const u8
295295 .windows,
296296 => {},
297297 inline .hurd, .linux => |ver| if (target.abi.isGnu()) {
298 try llvm_triple.writer().print("{d}.{d}.{d}", .{
298 try llvm_triple.print("{d}.{d}.{d}", .{
299299 ver.glibc.major,
300300 ver.glibc.minor,
301301 ver.glibc.patch,
302302 });
303303 } else if (@TypeOf(ver) == std.Target.Os.LinuxVersionRange and target.abi.isAndroid()) {
304 try llvm_triple.writer().print("{d}", .{ver.android});
304 try llvm_triple.print("{d}", .{ver.android});
305305 },
306306 }
307307
......@@ -746,12 +746,18 @@ pub const Object = struct {
746746 try wip.finish();
747747 }
748748
749 fn genModuleLevelAssembly(object: *Object) !void {
750 const writer = object.builder.setModuleAsm();
749 fn genModuleLevelAssembly(object: *Object) Allocator.Error!void {
750 const b = &object.builder;
751 const gpa = b.gpa;
752 b.module_asm.clearRetainingCapacity();
751753 for (object.pt.zcu.global_assembly.values()) |assembly| {
752 try writer.print("{s}\n", .{assembly});
754 try b.module_asm.ensureUnusedCapacity(gpa, assembly.len + 1);
755 b.module_asm.appendSliceAssumeCapacity(assembly);
756 b.module_asm.appendAssumeCapacity('\n');
757 }
758 if (b.module_asm.getLastOrNull()) |last| {
759 if (last != '\n') try b.module_asm.append(gpa, '\n');
753760 }
754 try object.builder.finishModuleAsm();
755761 }
756762
757763 pub const EmitOptions = struct {
......@@ -939,7 +945,9 @@ pub const Object = struct {
939945 if (std.mem.eql(u8, path, "-")) {
940946 o.builder.dump();
941947 } else {
942 _ = try o.builder.printToFile(path);
948 o.builder.printToFilePath(std.fs.cwd(), path) catch |err| {
949 log.err("failed printing LLVM module to \"{s}\": {s}", .{ path, @errorName(err) });
950 };
943951 }
944952 }
945953
......@@ -2680,10 +2688,12 @@ pub const Object = struct {
26802688 }
26812689
26822690 fn allocTypeName(o: *Object, ty: Type) Allocator.Error![:0]const u8 {
2683 var buffer = std.ArrayList(u8).init(o.gpa);
2684 errdefer buffer.deinit();
2685 try ty.print(buffer.writer(), o.pt);
2686 return buffer.toOwnedSliceSentinel(0);
2691 var aw: std.io.Writer.Allocating = .init(o.gpa);
2692 defer aw.deinit();
2693 ty.print(&aw.writer, o.pt) catch |err| switch (err) {
2694 error.WriteFailed => return error.OutOfMemory,
2695 };
2696 return aw.toOwnedSliceSentinel(0);
26872697 }
26882698
26892699 /// If the llvm function does not exist, create it.
......@@ -4482,7 +4492,7 @@ pub const Object = struct {
44824492 const target = &zcu.root_mod.resolved_target.result;
44834493 const function_index = try o.builder.addFunction(
44844494 try o.builder.fnType(ret_ty, &.{try o.lowerType(Type.fromInterned(enum_type.tag_ty))}, .normal),
4485 try o.builder.strtabStringFmt("__zig_tag_name_{}", .{enum_type.name.fmt(ip)}),
4495 try o.builder.strtabStringFmt("__zig_tag_name_{f}", .{enum_type.name.fmt(ip)}),
44864496 toLlvmAddressSpace(.generic, target),
44874497 );
44884498
......@@ -4633,7 +4643,7 @@ pub const NavGen = struct {
46334643 if (zcu.getTarget().cpu.arch.isWasm() and ty.zigTypeTag(zcu) == .@"fn") {
46344644 if (lib_name.toSlice(ip)) |lib_name_slice| {
46354645 if (!std.mem.eql(u8, lib_name_slice, "c")) {
4636 break :decl_name try o.builder.strtabStringFmt("{}|{s}", .{ nav.name.fmt(ip), lib_name_slice });
4646 break :decl_name try o.builder.strtabStringFmt("{f}|{s}", .{ nav.name.fmt(ip), lib_name_slice });
46374647 }
46384648 }
46394649 }
......@@ -7472,7 +7482,7 @@ pub const FuncGen = struct {
74727482 llvm_param_types[llvm_param_i] = llvm_elem_ty;
74737483 }
74747484
7475 try llvm_constraints.writer(self.gpa).print(",{d}", .{output_index});
7485 try llvm_constraints.print(self.gpa, ",{d}", .{output_index});
74767486
74777487 // In the case of indirect inputs, LLVM requires the callsite to have
74787488 // an elementtype(<ty>) attribute.
......@@ -7573,7 +7583,7 @@ pub const FuncGen = struct {
75737583 // we should validate the assembly in Sema; by now it is too late
75747584 return self.todo("unknown input or output name: '{s}'", .{name});
75757585 };
7576 try rendered_template.writer().print("{d}", .{index});
7586 try rendered_template.print("{d}", .{index});
75777587 if (byte == ':') {
75787588 try rendered_template.append(':');
75797589 modifier_start = i + 1;
......@@ -10370,7 +10380,7 @@ pub const FuncGen = struct {
1037010380 const target = &zcu.root_mod.resolved_target.result;
1037110381 const function_index = try o.builder.addFunction(
1037210382 try o.builder.fnType(.i1, &.{try o.lowerType(Type.fromInterned(enum_type.tag_ty))}, .normal),
10373 try o.builder.strtabStringFmt("__zig_is_named_enum_value_{}", .{enum_type.name.fmt(ip)}),
10383 try o.builder.strtabStringFmt("__zig_is_named_enum_value_{f}", .{enum_type.name.fmt(ip)}),
1037410384 toLlvmAddressSpace(.generic, target),
1037510385 );
1037610386
src/codegen/spirv.zig+6-4
......@@ -1260,10 +1260,12 @@ const NavGen = struct {
12601260
12611261 // Turn a Zig type's name into a cache reference.
12621262 fn resolveTypeName(self: *NavGen, ty: Type) ![]const u8 {
1263 var name = std.ArrayList(u8).init(self.gpa);
1264 defer name.deinit();
1265 try ty.print(name.writer(), self.pt);
1266 return try name.toOwnedSlice();
1263 var aw: std.io.Writer.Allocating = .init(self.gpa);
1264 defer aw.deinit();
1265 ty.print(&aw.writer, self.pt) catch |err| switch (err) {
1266 error.WriteFailed => return error.OutOfMemory,
1267 };
1268 return try aw.toOwnedSlice();
12671269 }
12681270
12691271 /// Create an integer type suitable for storing at least 'bits' bits.
src/link/MachO/Atom.zig+2-3
......@@ -938,10 +938,9 @@ const x86_64 = struct {
938938 }
939939
940940 fn encode(insts: []const Instruction, code: []u8) !void {
941 var stream = std.io.fixedBufferStream(code);
942 const writer = stream.writer();
941 var stream: std.io.Writer = .fixed(code);
943942 for (insts) |inst| {
944 try inst.encode(writer, .{});
943 try inst.encode(&stream, .{});
945944 }
946945 }
947946