authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-08 21:03:28-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-08 21:03:28-07:00
loga489ea0b2f38c67025c2b2424749a9a7320cdd5a
treeb27dffca9c3c26ef8cb33776dfbdf1941e7f6e55
parent0e1c7209e8632ebf398e60de9053e2e0fe8b5661
parentbf56cdd9edffd5b97d2084b46cda6e6a89a391c1

Merge branch 'register-allocation'


14 files changed, 1395 insertions(+), 438 deletions(-)

lib/std/array_list.zig+60
......@@ -257,6 +257,24 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
257257 return &self.items[self.items.len - 1];
258258 }
259259
260 /// Resize the array, adding `n` new elements, which have `undefined` values.
261 /// The return value is an array pointing to the newly allocated elements.
262 pub fn addManyAsArray(self: *Self, comptime n: usize) !*[n]T {
263 const prev_len = self.items.len;
264 try self.resize(self.items.len + n);
265 return self.items[prev_len..][0..n];
266 }
267
268 /// Resize the array, adding `n` new elements, which have `undefined` values.
269 /// The return value is an array pointing to the newly allocated elements.
270 /// Asserts that there is already space for the new item without allocating more.
271 pub fn addManyAsArrayAssumeCapacity(self: *Self, comptime n: usize) *[n]T {
272 assert(self.items.len + n <= self.capacity);
273 const prev_len = self.items.len;
274 self.items.len += n;
275 return self.items[prev_len..][0..n];
276 }
277
260278 /// Remove and return the last element from the list.
261279 /// Asserts the list has at least one item.
262280 pub fn pop(self: *Self) T {
......@@ -488,6 +506,24 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
488506 return &self.items[self.items.len - 1];
489507 }
490508
509 /// Resize the array, adding `n` new elements, which have `undefined` values.
510 /// The return value is an array pointing to the newly allocated elements.
511 pub fn addManyAsArray(self: *Self, allocator: *Allocator, comptime n: usize) !*[n]T {
512 const prev_len = self.items.len;
513 try self.resize(allocator, self.items.len + n);
514 return self.items[prev_len..][0..n];
515 }
516
517 /// Resize the array, adding `n` new elements, which have `undefined` values.
518 /// The return value is an array pointing to the newly allocated elements.
519 /// Asserts that there is already space for the new item without allocating more.
520 pub fn addManyAsArrayAssumeCapacity(self: *Self, comptime n: usize) *[n]T {
521 assert(self.items.len + n <= self.capacity);
522 const prev_len = self.items.len;
523 self.items.len += n;
524 return self.items[prev_len..][0..n];
525 }
526
491527 /// Remove and return the last element from the list.
492528 /// Asserts the list has at least one item.
493529 /// This operation does not invalidate any element pointers.
......@@ -727,3 +763,27 @@ test "std.ArrayList.writer" {
727763 try writer.writeAll("efg");
728764 testing.expectEqualSlices(u8, list.items, "abcdefg");
729765}
766
767test "addManyAsArray" {
768 const a = std.testing.allocator;
769 {
770 var list = ArrayList(u8).init(a);
771 defer list.deinit();
772
773 (try list.addManyAsArray(4)).* = "aoeu".*;
774 try list.ensureCapacity(8);
775 list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
776
777 testing.expectEqualSlices(u8, list.items, "aoeuasdf");
778 }
779 {
780 var list = ArrayListUnmanaged(u8){};
781 defer list.deinit(a);
782
783 (try list.addManyAsArray(a, 4)).* = "aoeu".*;
784 try list.ensureCapacity(a, 8);
785 list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
786
787 testing.expectEqualSlices(u8, list.items, "aoeuasdf");
788 }
789}
lib/std/hash_map.zig+4
......@@ -15,6 +15,10 @@ pub fn AutoHashMap(comptime K: type, comptime V: type) type {
1515 return HashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), autoEqlIsCheap(K));
1616}
1717
18pub fn AutoHashMapUnmanaged(comptime K: type, comptime V: type) type {
19 return HashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), autoEqlIsCheap(K));
20}
21
1822/// Builtin hashmap for strings as keys.
1923pub fn StringHashMap(comptime V: type) type {
2024 return HashMap([]const u8, V, hashString, eqlString, true);
lib/std/math.zig-5
......@@ -1047,19 +1047,14 @@ pub fn order(a: var, b: var) Order {
10471047pub const CompareOperator = enum {
10481048 /// Less than (`<`)
10491049 lt,
1050
10511050 /// Less than or equal (`<=`)
10521051 lte,
1053
10541052 /// Equal (`==`)
10551053 eq,
1056
10571054 /// Greater than or equal (`>=`)
10581055 gte,
1059
10601056 /// Greater than (`>`)
10611057 gt,
1062
10631058 /// Not equal (`!=`)
10641059 neq,
10651060};
lib/std/special/test_runner.zig+12
......@@ -21,6 +21,7 @@ pub fn main() anyerror!void {
2121
2222 for (test_fn_list) |test_fn, i| {
2323 std.testing.base_allocator_instance.reset();
24 std.testing.log_level = .warn;
2425
2526 var test_node = root_node.start(test_fn.name, null);
2627 test_node.activate();
......@@ -73,3 +74,14 @@ pub fn main() anyerror!void {
7374 std.debug.warn("{} passed; {} skipped.\n", .{ ok_count, skip_count });
7475 }
7576}
77
78pub fn log(
79 comptime message_level: std.log.Level,
80 comptime scope: @Type(.EnumLiteral),
81 comptime format: []const u8,
82 args: var,
83) void {
84 if (@enumToInt(message_level) <= @enumToInt(std.testing.log_level)) {
85 std.debug.print("[{}] ({}): " ++ format, .{@tagName(scope), @tagName(message_level)} ++ args);
86 }
87}
lib/std/std.zig+5-3
......@@ -3,14 +3,16 @@ pub const ArrayListAligned = @import("array_list.zig").ArrayListAligned;
33pub const ArrayListAlignedUnmanaged = @import("array_list.zig").ArrayListAlignedUnmanaged;
44pub const ArrayListSentineled = @import("array_list_sentineled.zig").ArrayListSentineled;
55pub const ArrayListUnmanaged = @import("array_list.zig").ArrayListUnmanaged;
6pub const AutoHashMap = @import("hash_map.zig").AutoHashMap;
6pub const AutoHashMap = hash_map.AutoHashMap;
7pub const AutoHashMapUnmanaged = hash_map.AutoHashMapUnmanaged;
78pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;
89pub const BufMap = @import("buf_map.zig").BufMap;
910pub const BufSet = @import("buf_set.zig").BufSet;
1011pub const ChildProcess = @import("child_process.zig").ChildProcess;
1112pub const ComptimeStringMap = @import("comptime_string_map.zig").ComptimeStringMap;
1213pub const DynLib = @import("dynamic_library.zig").DynLib;
13pub const HashMap = @import("hash_map.zig").HashMap;
14pub const HashMap = hash_map.HashMap;
15pub const HashMapUnmanaged = hash_map.HashMapUnmanaged;
1416pub const Mutex = @import("mutex.zig").Mutex;
1517pub const PackedIntArray = @import("packed_int_array.zig").PackedIntArray;
1618pub const PackedIntArrayEndian = @import("packed_int_array.zig").PackedIntArrayEndian;
......@@ -22,7 +24,7 @@ pub const ResetEvent = @import("reset_event.zig").ResetEvent;
2224pub const SegmentedList = @import("segmented_list.zig").SegmentedList;
2325pub const SinglyLinkedList = @import("linked_list.zig").SinglyLinkedList;
2426pub const SpinLock = @import("spinlock.zig").SpinLock;
25pub const StringHashMap = @import("hash_map.zig").StringHashMap;
27pub const StringHashMap = hash_map.StringHashMap;
2628pub const TailQueue = @import("linked_list.zig").TailQueue;
2729pub const Target = @import("target.zig").Target;
2830pub const Thread = @import("thread.zig").Thread;
lib/std/testing.zig+3
......@@ -14,6 +14,9 @@ pub var failing_allocator_instance = FailingAllocator.init(&base_allocator_insta
1414pub var base_allocator_instance = std.mem.validationWrap(std.heap.ThreadSafeFixedBufferAllocator.init(allocator_mem[0..]));
1515var allocator_mem: [2 * 1024 * 1024]u8 = undefined;
1616
17/// TODO https://github.com/ziglang/zig/issues/5738
18pub var log_level = std.log.Level.warn;
19
1720/// This function is intended to be used only in tests. It prints diagnostics to stderr
1821/// and then aborts when actual_error_union is not expected_error.
1922pub fn expectError(expected_error: anyerror, actual_error_union: var) void {
lib/std/zig/ast.zig+2
......@@ -959,6 +959,8 @@ pub const Node = struct {
959959 };
960960
961961 /// The params are directly after the FnProto in memory.
962 /// TODO have a flags field for the optional nodes, and have them appended
963 /// before or after the parameters in memory.
962964 pub const FnProto = struct {
963965 base: Node = Node{ .id = .FnProto },
964966 doc_comments: ?*DocComment,
src-self-hosted/Module.zig+388-267
......@@ -18,9 +18,10 @@ const Inst = ir.Inst;
1818const Body = ir.Body;
1919const ast = std.zig.ast;
2020const trace = @import("tracy.zig").trace;
21const liveness = @import("liveness.zig");
2122
22/// General-purpose allocator.
23allocator: *Allocator,
23/// General-purpose allocator. Used for both temporary and long-term storage.
24gpa: *Allocator,
2425/// Pointer to externally managed resource.
2526root_pkg: *Package,
2627/// Module owns this resource.
......@@ -32,7 +33,7 @@ bin_file_path: []const u8,
3233/// It's rare for a decl to be exported, so we save memory by having a sparse map of
3334/// Decl pointers to details about them being exported.
3435/// The Export memory is owned by the `export_owners` table; the slice itself is owned by this table.
35decl_exports: std.AutoHashMap(*Decl, []*Export),
36decl_exports: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
3637/// We track which export is associated with the given symbol name for quick
3738/// detection of symbol collisions.
3839symbol_exports: std.StringHashMap(*Export),
......@@ -40,9 +41,9 @@ symbol_exports: std.StringHashMap(*Export),
4041/// is modified. Note that the key of this table is not the Decl being exported, but the Decl that
4142/// is performing the export of another Decl.
4243/// This table owns the Export memory.
43export_owners: std.AutoHashMap(*Decl, []*Export),
44export_owners: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
4445/// Maps fully qualified namespaced names to the Decl struct for them.
45decl_table: DeclTable,
46decl_table: std.HashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
4647
4748optimize_mode: std.builtin.Mode,
4849link_error_flags: link.File.ErrorFlags = .{},
......@@ -54,13 +55,13 @@ work_queue: std.fifo.LinearFifo(WorkItem, .Dynamic),
5455/// The ErrorMsg memory is owned by the decl, using Module's allocator.
5556/// Note that a Decl can succeed but the Fn it represents can fail. In this case,
5657/// a Decl can have a failed_decls entry but have analysis status of success.
57failed_decls: std.AutoHashMap(*Decl, *ErrorMsg),
58failed_decls: std.AutoHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
5859/// Using a map here for consistency with the other fields here.
5960/// The ErrorMsg memory is owned by the `Scope`, using Module's allocator.
60failed_files: std.AutoHashMap(*Scope, *ErrorMsg),
61failed_files: std.AutoHashMapUnmanaged(*Scope, *ErrorMsg) = .{},
6162/// Using a map here for consistency with the other fields here.
6263/// The ErrorMsg memory is owned by the `Export`, using Module's allocator.
63failed_exports: std.AutoHashMap(*Export, *ErrorMsg),
64failed_exports: std.AutoHashMapUnmanaged(*Export, *ErrorMsg) = .{},
6465
6566/// Incrementing integer used to compare against the corresponding Decl
6667/// field to determine whether a Decl's status applies to an ongoing update, or a
......@@ -75,8 +76,6 @@ deletion_set: std.ArrayListUnmanaged(*Decl) = .{},
7576
7677keep_source_files_loaded: bool,
7778
78const DeclTable = std.HashMap(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false);
79
8079const WorkItem = union(enum) {
8180 /// Write the machine code for a Decl to the output file.
8281 codegen_decl: *Decl,
......@@ -175,19 +174,23 @@ pub const Decl = struct {
175174
176175 /// The shallow set of other decls whose typed_value could possibly change if this Decl's
177176 /// typed_value is modified.
178 dependants: ArrayListUnmanaged(*Decl) = ArrayListUnmanaged(*Decl){},
177 dependants: DepsTable = .{},
179178 /// The shallow set of other decls whose typed_value changing indicates that this Decl's
180179 /// typed_value may need to be regenerated.
181 dependencies: ArrayListUnmanaged(*Decl) = ArrayListUnmanaged(*Decl){},
180 dependencies: DepsTable = .{},
181
182 /// The reason this is not `std.AutoHashMapUnmanaged` is a workaround for
183 /// stage1 compiler giving me: `error: struct 'Module.Decl' depends on itself`
184 pub const DepsTable = std.HashMapUnmanaged(*Decl, void, std.hash_map.getAutoHashFn(*Decl), std.hash_map.getAutoEqlFn(*Decl), false);
182185
183 pub fn destroy(self: *Decl, allocator: *Allocator) void {
184 allocator.free(mem.spanZ(self.name));
186 pub fn destroy(self: *Decl, gpa: *Allocator) void {
187 gpa.free(mem.spanZ(self.name));
185188 if (self.typedValueManaged()) |tvm| {
186 tvm.deinit(allocator);
189 tvm.deinit(gpa);
187190 }
188 self.dependants.deinit(allocator);
189 self.dependencies.deinit(allocator);
190 allocator.destroy(self);
191 self.dependants.deinit(gpa);
192 self.dependencies.deinit(gpa);
193 gpa.destroy(self);
191194 }
192195
193196 pub fn src(self: Decl) usize {
......@@ -246,23 +249,11 @@ pub const Decl = struct {
246249 }
247250
248251 fn removeDependant(self: *Decl, other: *Decl) void {
249 for (self.dependants.items) |item, i| {
250 if (item == other) {
251 _ = self.dependants.swapRemove(i);
252 return;
253 }
254 }
255 unreachable;
252 self.dependants.removeAssertDiscard(other);
256253 }
257254
258255 fn removeDependency(self: *Decl, other: *Decl) void {
259 for (self.dependencies.items) |item, i| {
260 if (item == other) {
261 _ = self.dependencies.swapRemove(i);
262 return;
263 }
264 }
265 unreachable;
256 self.dependencies.removeAssertDiscard(other);
266257 }
267258};
268259
......@@ -312,14 +303,14 @@ pub const Scope = struct {
312303 switch (self.tag) {
313304 .block => return self.cast(Block).?.arena,
314305 .decl => return &self.cast(DeclAnalysis).?.arena.allocator,
315 .gen_zir => return &self.cast(GenZIR).?.arena.allocator,
306 .gen_zir => return self.cast(GenZIR).?.arena,
316307 .zir_module => return &self.cast(ZIRModule).?.contents.module.arena.allocator,
317308 .file => unreachable,
318309 }
319310 }
320311
321 /// Asserts the scope has a parent which is a DeclAnalysis and
322 /// returns the Decl.
312 /// If the scope has a parent which is a `DeclAnalysis`,
313 /// returns the `Decl`, otherwise returns `null`.
323314 pub fn decl(self: *Scope) ?*Decl {
324315 return switch (self.tag) {
325316 .block => self.cast(Block).?.decl,
......@@ -389,10 +380,10 @@ pub const Scope = struct {
389380 }
390381 }
391382
392 pub fn unload(base: *Scope, allocator: *Allocator) void {
383 pub fn unload(base: *Scope, gpa: *Allocator) void {
393384 switch (base.tag) {
394 .file => return @fieldParentPtr(File, "base", base).unload(allocator),
395 .zir_module => return @fieldParentPtr(ZIRModule, "base", base).unload(allocator),
385 .file => return @fieldParentPtr(File, "base", base).unload(gpa),
386 .zir_module => return @fieldParentPtr(ZIRModule, "base", base).unload(gpa),
396387 .block => unreachable,
397388 .gen_zir => unreachable,
398389 .decl => unreachable,
......@@ -421,17 +412,17 @@ pub const Scope = struct {
421412 }
422413
423414 /// Asserts the scope is a File or ZIRModule and deinitializes it, then deallocates it.
424 pub fn destroy(base: *Scope, allocator: *Allocator) void {
415 pub fn destroy(base: *Scope, gpa: *Allocator) void {
425416 switch (base.tag) {
426417 .file => {
427418 const scope_file = @fieldParentPtr(File, "base", base);
428 scope_file.deinit(allocator);
429 allocator.destroy(scope_file);
419 scope_file.deinit(gpa);
420 gpa.destroy(scope_file);
430421 },
431422 .zir_module => {
432423 const scope_zir_module = @fieldParentPtr(ZIRModule, "base", base);
433 scope_zir_module.deinit(allocator);
434 allocator.destroy(scope_zir_module);
424 scope_zir_module.deinit(gpa);
425 gpa.destroy(scope_zir_module);
435426 },
436427 .block => unreachable,
437428 .gen_zir => unreachable,
......@@ -482,7 +473,7 @@ pub const Scope = struct {
482473 /// Direct children of the file.
483474 decls: ArrayListUnmanaged(*Decl),
484475
485 pub fn unload(self: *File, allocator: *Allocator) void {
476 pub fn unload(self: *File, gpa: *Allocator) void {
486477 switch (self.status) {
487478 .never_loaded,
488479 .unloaded_parse_failure,
......@@ -496,16 +487,16 @@ pub const Scope = struct {
496487 }
497488 switch (self.source) {
498489 .bytes => |bytes| {
499 allocator.free(bytes);
490 gpa.free(bytes);
500491 self.source = .{ .unloaded = {} };
501492 },
502493 .unloaded => {},
503494 }
504495 }
505496
506 pub fn deinit(self: *File, allocator: *Allocator) void {
507 self.decls.deinit(allocator);
508 self.unload(allocator);
497 pub fn deinit(self: *File, gpa: *Allocator) void {
498 self.decls.deinit(gpa);
499 self.unload(gpa);
509500 self.* = undefined;
510501 }
511502
......@@ -527,7 +518,7 @@ pub const Scope = struct {
527518 switch (self.source) {
528519 .unloaded => {
529520 const source = try module.root_pkg.root_src_dir.readFileAllocOptions(
530 module.allocator,
521 module.gpa,
531522 self.sub_file_path,
532523 std.math.maxInt(u32),
533524 1,
......@@ -575,7 +566,7 @@ pub const Scope = struct {
575566 /// not this one.
576567 decls: ArrayListUnmanaged(*Decl),
577568
578 pub fn unload(self: *ZIRModule, allocator: *Allocator) void {
569 pub fn unload(self: *ZIRModule, gpa: *Allocator) void {
579570 switch (self.status) {
580571 .never_loaded,
581572 .unloaded_parse_failure,
......@@ -584,30 +575,30 @@ pub const Scope = struct {
584575 => {},
585576
586577 .loaded_success => {
587 self.contents.module.deinit(allocator);
588 allocator.destroy(self.contents.module);
578 self.contents.module.deinit(gpa);
579 gpa.destroy(self.contents.module);
589580 self.contents = .{ .not_available = {} };
590581 self.status = .unloaded_success;
591582 },
592583 .loaded_sema_failure => {
593 self.contents.module.deinit(allocator);
594 allocator.destroy(self.contents.module);
584 self.contents.module.deinit(gpa);
585 gpa.destroy(self.contents.module);
595586 self.contents = .{ .not_available = {} };
596587 self.status = .unloaded_sema_failure;
597588 },
598589 }
599590 switch (self.source) {
600591 .bytes => |bytes| {
601 allocator.free(bytes);
592 gpa.free(bytes);
602593 self.source = .{ .unloaded = {} };
603594 },
604595 .unloaded => {},
605596 }
606597 }
607598
608 pub fn deinit(self: *ZIRModule, allocator: *Allocator) void {
609 self.decls.deinit(allocator);
610 self.unload(allocator);
599 pub fn deinit(self: *ZIRModule, gpa: *Allocator) void {
600 self.decls.deinit(gpa);
601 self.unload(gpa);
611602 self.* = undefined;
612603 }
613604
......@@ -629,7 +620,7 @@ pub const Scope = struct {
629620 switch (self.source) {
630621 .unloaded => {
631622 const source = try module.root_pkg.root_src_dir.readFileAllocOptions(
632 module.allocator,
623 module.gpa,
633624 self.sub_file_path,
634625 std.math.maxInt(u32),
635626 1,
......@@ -662,7 +653,7 @@ pub const Scope = struct {
662653 label: ?Label = null,
663654
664655 pub const Label = struct {
665 name: []const u8,
656 zir_block: *zir.Inst.Block,
666657 results: ArrayListUnmanaged(*Inst),
667658 block_inst: *Inst.Block,
668659 };
......@@ -683,8 +674,8 @@ pub const Scope = struct {
683674 pub const base_tag: Tag = .gen_zir;
684675 base: Scope = Scope{ .tag = base_tag },
685676 decl: *Decl,
686 arena: std.heap.ArenaAllocator,
687 instructions: std.ArrayList(*zir.Inst),
677 arena: *Allocator,
678 instructions: std.ArrayListUnmanaged(*zir.Inst) = .{},
688679 };
689680};
690681
......@@ -700,8 +691,8 @@ pub const AllErrors = struct {
700691 msg: []const u8,
701692 };
702693
703 pub fn deinit(self: *AllErrors, allocator: *Allocator) void {
704 self.arena.promote(allocator).deinit();
694 pub fn deinit(self: *AllErrors, gpa: *Allocator) void {
695 self.arena.promote(gpa).deinit();
705696 }
706697
707698 fn add(
......@@ -773,20 +764,14 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
773764 };
774765
775766 return Module{
776 .allocator = gpa,
767 .gpa = gpa,
777768 .root_pkg = options.root_pkg,
778769 .root_scope = root_scope,
779770 .bin_file_dir = bin_file_dir,
780771 .bin_file_path = options.bin_file_path,
781772 .bin_file = bin_file,
782773 .optimize_mode = options.optimize_mode,
783 .decl_table = DeclTable.init(gpa),
784 .decl_exports = std.AutoHashMap(*Decl, []*Export).init(gpa),
785774 .symbol_exports = std.StringHashMap(*Export).init(gpa),
786 .export_owners = std.AutoHashMap(*Decl, []*Export).init(gpa),
787 .failed_decls = std.AutoHashMap(*Decl, *ErrorMsg).init(gpa),
788 .failed_files = std.AutoHashMap(*Scope, *ErrorMsg).init(gpa),
789 .failed_exports = std.AutoHashMap(*Export, *ErrorMsg).init(gpa),
790775 .work_queue = std.fifo.LinearFifo(WorkItem, .Dynamic).init(gpa),
791776 .keep_source_files_loaded = options.keep_source_files_loaded,
792777 };
......@@ -794,51 +779,51 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
794779
795780pub fn deinit(self: *Module) void {
796781 self.bin_file.destroy();
797 const allocator = self.allocator;
798 self.deletion_set.deinit(allocator);
782 const gpa = self.gpa;
783 self.deletion_set.deinit(gpa);
799784 self.work_queue.deinit();
800785
801786 for (self.decl_table.items()) |entry| {
802 entry.value.destroy(allocator);
787 entry.value.destroy(gpa);
803788 }
804 self.decl_table.deinit();
789 self.decl_table.deinit(gpa);
805790
806791 for (self.failed_decls.items()) |entry| {
807 entry.value.destroy(allocator);
792 entry.value.destroy(gpa);
808793 }
809 self.failed_decls.deinit();
794 self.failed_decls.deinit(gpa);
810795
811796 for (self.failed_files.items()) |entry| {
812 entry.value.destroy(allocator);
797 entry.value.destroy(gpa);
813798 }
814 self.failed_files.deinit();
799 self.failed_files.deinit(gpa);
815800
816801 for (self.failed_exports.items()) |entry| {
817 entry.value.destroy(allocator);
802 entry.value.destroy(gpa);
818803 }
819 self.failed_exports.deinit();
804 self.failed_exports.deinit(gpa);
820805
821806 for (self.decl_exports.items()) |entry| {
822807 const export_list = entry.value;
823 allocator.free(export_list);
808 gpa.free(export_list);
824809 }
825 self.decl_exports.deinit();
810 self.decl_exports.deinit(gpa);
826811
827812 for (self.export_owners.items()) |entry| {
828 freeExportList(allocator, entry.value);
813 freeExportList(gpa, entry.value);
829814 }
830 self.export_owners.deinit();
815 self.export_owners.deinit(gpa);
831816
832817 self.symbol_exports.deinit();
833 self.root_scope.destroy(allocator);
818 self.root_scope.destroy(gpa);
834819 self.* = undefined;
835820}
836821
837fn freeExportList(allocator: *Allocator, export_list: []*Export) void {
822fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
838823 for (export_list) |exp| {
839 allocator.destroy(exp);
824 gpa.destroy(exp);
840825 }
841 allocator.free(export_list);
826 gpa.free(export_list);
842827}
843828
844829pub fn target(self: Module) std.Target {
......@@ -856,7 +841,7 @@ pub fn update(self: *Module) !void {
856841 // Until then we simulate a full cache miss. Source files could have been loaded for any reason;
857842 // to force a refresh we unload now.
858843 if (self.root_scope.cast(Scope.File)) |zig_file| {
859 zig_file.unload(self.allocator);
844 zig_file.unload(self.gpa);
860845 self.analyzeRootSrcFile(zig_file) catch |err| switch (err) {
861846 error.AnalysisFail => {
862847 assert(self.totalErrorCount() != 0);
......@@ -864,7 +849,7 @@ pub fn update(self: *Module) !void {
864849 else => |e| return e,
865850 };
866851 } else if (self.root_scope.cast(Scope.ZIRModule)) |zir_module| {
867 zir_module.unload(self.allocator);
852 zir_module.unload(self.gpa);
868853 self.analyzeRootZIRModule(zir_module) catch |err| switch (err) {
869854 error.AnalysisFail => {
870855 assert(self.totalErrorCount() != 0);
......@@ -877,22 +862,25 @@ pub fn update(self: *Module) !void {
877862
878863 // Process the deletion set.
879864 while (self.deletion_set.popOrNull()) |decl| {
880 if (decl.dependants.items.len != 0) {
865 if (decl.dependants.items().len != 0) {
881866 decl.deletion_flag = false;
882867 continue;
883868 }
884869 try self.deleteDecl(decl);
885870 }
886871
872 if (self.totalErrorCount() == 0) {
873 // This is needed before reading the error flags.
874 try self.bin_file.flush();
875 }
876
887877 self.link_error_flags = self.bin_file.errorFlags();
878 std.log.debug(.module, "link_error_flags: {}\n", .{self.link_error_flags});
888879
889880 // If there are any errors, we anticipate the source files being loaded
890881 // to report error messages. Otherwise we unload all source files to save memory.
891 if (self.totalErrorCount() == 0) {
892 if (!self.keep_source_files_loaded) {
893 self.root_scope.unload(self.allocator);
894 }
895 try self.bin_file.flush();
882 if (self.totalErrorCount() == 0 and !self.keep_source_files_loaded) {
883 self.root_scope.unload(self.gpa);
896884 }
897885}
898886
......@@ -916,10 +904,10 @@ pub fn totalErrorCount(self: *Module) usize {
916904}
917905
918906pub fn getAllErrorsAlloc(self: *Module) !AllErrors {
919 var arena = std.heap.ArenaAllocator.init(self.allocator);
907 var arena = std.heap.ArenaAllocator.init(self.gpa);
920908 errdefer arena.deinit();
921909
922 var errors = std.ArrayList(AllErrors.Message).init(self.allocator);
910 var errors = std.ArrayList(AllErrors.Message).init(self.gpa);
923911 defer errors.deinit();
924912
925913 for (self.failed_files.items()) |entry| {
......@@ -988,6 +976,12 @@ pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void {
988976 .sema_failure, .dependency_failure => continue,
989977 .success => {},
990978 }
979 // Here we tack on additional allocations to the Decl's arena. The allocations are
980 // lifetime annotations in the ZIR.
981 var decl_arena = decl.typed_value.most_recent.arena.?.promote(self.gpa);
982 defer decl.typed_value.most_recent.arena.?.* = decl_arena.state;
983 std.log.debug(.module, "analyze liveness of {}\n", .{decl.name});
984 try liveness.analyze(self.gpa, &decl_arena.allocator, payload.func.analysis.success);
991985 }
992986
993987 assert(decl.typed_value.most_recent.typed_value.ty.hasCodeGenBits());
......@@ -998,9 +992,9 @@ pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void {
998992 decl.analysis = .dependency_failure;
999993 },
1000994 else => {
1001 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
995 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
1002996 self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
1003 self.allocator,
997 self.gpa,
1004998 decl.src(),
1005999 "unable to codegen: {}",
10061000 .{@errorName(err)},
......@@ -1044,16 +1038,17 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10441038 // prior to re-analysis.
10451039 self.deleteDeclExports(decl);
10461040 // Dependencies will be re-discovered, so we remove them here prior to re-analysis.
1047 for (decl.dependencies.items) |dep| {
1041 for (decl.dependencies.items()) |entry| {
1042 const dep = entry.key;
10481043 dep.removeDependant(decl);
1049 if (dep.dependants.items.len == 0 and !dep.deletion_flag) {
1044 if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
10501045 // We don't perform a deletion here, because this Decl or another one
10511046 // may end up referencing it before the update is complete.
10521047 dep.deletion_flag = true;
1053 try self.deletion_set.append(self.allocator, dep);
1048 try self.deletion_set.append(self.gpa, dep);
10541049 }
10551050 }
1056 decl.dependencies.shrink(self.allocator, 0);
1051 decl.dependencies.clearRetainingCapacity();
10571052
10581053 break :blk true;
10591054 },
......@@ -1068,9 +1063,9 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10681063 error.OutOfMemory => return error.OutOfMemory,
10691064 error.AnalysisFail => return error.AnalysisFail,
10701065 else => {
1071 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
1066 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
10721067 self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
1073 self.allocator,
1068 self.gpa,
10741069 decl.src(),
10751070 "unable to analyze: {}",
10761071 .{@errorName(err)},
......@@ -1084,7 +1079,8 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10841079 // We may need to chase the dependants and re-analyze them.
10851080 // However, if the decl is a function, and the type is the same, we do not need to.
10861081 if (type_changed or decl.typed_value.most_recent.typed_value.val.tag() != .function) {
1087 for (decl.dependants.items) |dep| {
1082 for (decl.dependants.items()) |entry| {
1083 const dep = entry.key;
10881084 switch (dep.analysis) {
10891085 .unreferenced => unreachable,
10901086 .in_progress => unreachable,
......@@ -1121,19 +1117,19 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11211117 // This arena allocator's memory is discarded at the end of this function. It is used
11221118 // to determine the type of the function, and hence the type of the decl, which is needed
11231119 // to complete the Decl analysis.
1120 var fn_type_scope_arena = std.heap.ArenaAllocator.init(self.gpa);
1121 defer fn_type_scope_arena.deinit();
11241122 var fn_type_scope: Scope.GenZIR = .{
11251123 .decl = decl,
1126 .arena = std.heap.ArenaAllocator.init(self.allocator),
1127 .instructions = std.ArrayList(*zir.Inst).init(self.allocator),
1124 .arena = &fn_type_scope_arena.allocator,
11281125 };
1129 defer fn_type_scope.arena.deinit();
1130 defer fn_type_scope.instructions.deinit();
1126 defer fn_type_scope.instructions.deinit(self.gpa);
11311127
11321128 const body_node = fn_proto.body_node orelse
11331129 return self.failTok(&fn_type_scope.base, fn_proto.fn_token, "TODO implement extern functions", .{});
11341130
11351131 const param_decls = fn_proto.params();
1136 const param_types = try fn_type_scope.arena.allocator.alloc(*zir.Inst, param_decls.len);
1132 const param_types = try fn_type_scope.arena.alloc(*zir.Inst, param_decls.len);
11371133 for (param_decls) |param_decl, i| {
11381134 const param_type_node = switch (param_decl.param_type) {
11391135 .var_type => |node| return self.failNode(&fn_type_scope.base, node, "TODO implement anytype parameter", .{}),
......@@ -1174,7 +1170,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11741170 _ = try self.addZIRInst(&fn_type_scope.base, fn_src, zir.Inst.Return, .{ .operand = fn_type_inst }, .{});
11751171
11761172 // We need the memory for the Type to go into the arena for the Decl
1177 var decl_arena = std.heap.ArenaAllocator.init(self.allocator);
1173 var decl_arena = std.heap.ArenaAllocator.init(self.gpa);
11781174 errdefer decl_arena.deinit();
11791175 const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
11801176
......@@ -1185,7 +1181,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11851181 .instructions = .{},
11861182 .arena = &decl_arena.allocator,
11871183 };
1188 defer block_scope.instructions.deinit(self.allocator);
1184 defer block_scope.instructions.deinit(self.gpa);
11891185
11901186 const fn_type = try self.analyzeBodyValueAsType(&block_scope, .{
11911187 .instructions = fn_type_scope.instructions.items,
......@@ -1196,24 +1192,24 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11961192 const fn_zir = blk: {
11971193 // This scope's arena memory is discarded after the ZIR generation
11981194 // pass completes, and semantic analysis of it completes.
1195 var gen_scope_arena = std.heap.ArenaAllocator.init(self.gpa);
1196 errdefer gen_scope_arena.deinit();
11991197 var gen_scope: Scope.GenZIR = .{
12001198 .decl = decl,
1201 .arena = std.heap.ArenaAllocator.init(self.allocator),
1202 .instructions = std.ArrayList(*zir.Inst).init(self.allocator),
1199 .arena = &gen_scope_arena.allocator,
12031200 };
1204 errdefer gen_scope.arena.deinit();
1205 defer gen_scope.instructions.deinit();
1201 defer gen_scope.instructions.deinit(self.gpa);
12061202
12071203 const body_block = body_node.cast(ast.Node.Block).?;
12081204
12091205 try self.astGenBlock(&gen_scope.base, body_block);
12101206
1211 const fn_zir = try gen_scope.arena.allocator.create(Fn.ZIR);
1207 const fn_zir = try gen_scope_arena.allocator.create(Fn.ZIR);
12121208 fn_zir.* = .{
12131209 .body = .{
1214 .instructions = try gen_scope.arena.allocator.dupe(*zir.Inst, gen_scope.instructions.items),
1210 .instructions = try gen_scope.arena.dupe(*zir.Inst, gen_scope.instructions.items),
12151211 },
1216 .arena = gen_scope.arena.state,
1212 .arena = gen_scope_arena.state,
12171213 };
12181214 break :blk fn_zir;
12191215 };
......@@ -1231,7 +1227,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
12311227 prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits();
12321228 type_changed = !tvm.typed_value.ty.eql(fn_type);
12331229
1234 tvm.deinit(self.allocator);
1230 tvm.deinit(self.gpa);
12351231 }
12361232
12371233 decl_arena_state.* = decl_arena.state;
......@@ -1315,6 +1311,33 @@ fn astGenInfixOp(self: *Module, scope: *Scope, infix_node: *ast.Node.InfixOp) In
13151311
13161312 return self.addZIRInst(scope, src, zir.Inst.Add, .{ .lhs = lhs, .rhs = rhs }, .{});
13171313 },
1314 .BangEqual,
1315 .EqualEqual,
1316 .GreaterThan,
1317 .GreaterOrEqual,
1318 .LessThan,
1319 .LessOrEqual,
1320 => {
1321 const lhs = try self.astGenExpr(scope, infix_node.lhs);
1322 const rhs = try self.astGenExpr(scope, infix_node.rhs);
1323
1324 const tree = scope.tree();
1325 const src = tree.token_locs[infix_node.op_token].start;
1326
1327 return self.addZIRInst(scope, src, zir.Inst.Cmp, .{
1328 .lhs = lhs,
1329 .op = @as(std.math.CompareOperator, switch (infix_node.op) {
1330 .BangEqual => .neq,
1331 .EqualEqual => .eq,
1332 .GreaterThan => .gt,
1333 .GreaterOrEqual => .gte,
1334 .LessThan => .lt,
1335 .LessOrEqual => .lte,
1336 else => unreachable,
1337 }),
1338 .rhs = rhs,
1339 }, .{});
1340 },
13181341 else => |op| {
13191342 return self.failNode(scope, &infix_node.base, "TODO implement infix operator {}", .{op});
13201343 },
......@@ -1330,9 +1353,70 @@ fn astGenIf(self: *Module, scope: *Scope, if_node: *ast.Node.If) InnerError!*zir
13301353 return self.failNode(scope, payload, "TODO implement astGenIf for error unions", .{});
13311354 }
13321355 }
1333 const cond = try self.astGenExpr(scope, if_node.condition);
1334 const body = try self.astGenExpr(scope, if_node.condition);
1335 return self.failNode(scope, if_node.condition, "TODO implement astGenIf", .{});
1356 var block_scope: Scope.GenZIR = .{
1357 .decl = scope.decl().?,
1358 .arena = scope.arena(),
1359 .instructions = .{},
1360 };
1361 defer block_scope.instructions.deinit(self.gpa);
1362
1363 const cond = try self.astGenExpr(&block_scope.base, if_node.condition);
1364
1365 const tree = scope.tree();
1366 const if_src = tree.token_locs[if_node.if_token].start;
1367 const condbr = try self.addZIRInstSpecial(&block_scope.base, if_src, zir.Inst.CondBr, .{
1368 .condition = cond,
1369 .true_body = undefined, // populated below
1370 .false_body = undefined, // populated below
1371 }, .{});
1372
1373 const block = try self.addZIRInstBlock(scope, if_src, .{
1374 .instructions = try block_scope.arena.dupe(*zir.Inst, block_scope.instructions.items),
1375 });
1376 var then_scope: Scope.GenZIR = .{
1377 .decl = block_scope.decl,
1378 .arena = block_scope.arena,
1379 .instructions = .{},
1380 };
1381 defer then_scope.instructions.deinit(self.gpa);
1382
1383 const then_result = try self.astGenExpr(&then_scope.base, if_node.body);
1384 const then_src = tree.token_locs[if_node.body.lastToken()].start;
1385 _ = try self.addZIRInst(&then_scope.base, then_src, zir.Inst.Break, .{
1386 .block = block,
1387 .operand = then_result,
1388 }, .{});
1389 condbr.positionals.true_body = .{
1390 .instructions = try then_scope.arena.dupe(*zir.Inst, then_scope.instructions.items),
1391 };
1392
1393 var else_scope: Scope.GenZIR = .{
1394 .decl = block_scope.decl,
1395 .arena = block_scope.arena,
1396 .instructions = .{},
1397 };
1398 defer else_scope.instructions.deinit(self.gpa);
1399
1400 if (if_node.@"else") |else_node| {
1401 const else_result = try self.astGenExpr(&else_scope.base, else_node.body);
1402 const else_src = tree.token_locs[else_node.body.lastToken()].start;
1403 _ = try self.addZIRInst(&else_scope.base, else_src, zir.Inst.Break, .{
1404 .block = block,
1405 .operand = else_result,
1406 }, .{});
1407 } else {
1408 // TODO Optimization opportunity: we can avoid an allocation and a memcpy here
1409 // by directly allocating the body for this one instruction.
1410 const else_src = tree.token_locs[if_node.lastToken()].start;
1411 _ = try self.addZIRInst(&else_scope.base, else_src, zir.Inst.BreakVoid, .{
1412 .block = block,
1413 }, .{});
1414 }
1415 condbr.positionals.false_body = .{
1416 .instructions = try else_scope.arena.dupe(*zir.Inst, else_scope.instructions.items),
1417 };
1418
1419 return &block.base;
13361420}
13371421
13381422fn astGenControlFlowExpression(
......@@ -1358,12 +1442,12 @@ fn astGenControlFlowExpression(
13581442fn astGenIdent(self: *Module, scope: *Scope, ident: *ast.Node.Identifier) InnerError!*zir.Inst {
13591443 const tree = scope.tree();
13601444 const ident_name = tree.tokenSlice(ident.token);
1445 const src = tree.token_locs[ident.token].start;
13611446 if (mem.eql(u8, ident_name, "_")) {
13621447 return self.failNode(scope, &ident.base, "TODO implement '_' identifier", .{});
13631448 }
13641449
13651450 if (getSimplePrimitiveValue(ident_name)) |typed_value| {
1366 const src = tree.token_locs[ident.token].start;
13671451 return self.addZIRInstConst(scope, src, typed_value);
13681452 }
13691453
......@@ -1387,7 +1471,6 @@ fn astGenIdent(self: *Module, scope: *Scope, ident: *ast.Node.Identifier) InnerE
13871471 64 => if (is_signed) Value.initTag(.i64_type) else Value.initTag(.u64_type),
13881472 else => return self.failNode(scope, &ident.base, "TODO implement arbitrary integer bitwidth types", .{}),
13891473 };
1390 const src = tree.token_locs[ident.token].start;
13911474 return self.addZIRInstConst(scope, src, .{
13921475 .ty = Type.initTag(.type),
13931476 .val = val,
......@@ -1396,10 +1479,21 @@ fn astGenIdent(self: *Module, scope: *Scope, ident: *ast.Node.Identifier) InnerE
13961479 }
13971480
13981481 if (self.lookupDeclName(scope, ident_name)) |decl| {
1399 const src = tree.token_locs[ident.token].start;
14001482 return try self.addZIRInst(scope, src, zir.Inst.DeclValInModule, .{ .decl = decl }, .{});
14011483 }
14021484
1485 // Function parameter
1486 if (scope.decl()) |decl| {
1487 if (tree.root_node.decls()[decl.src_index].cast(ast.Node.FnProto)) |fn_proto| {
1488 for (fn_proto.params()) |param, i| {
1489 const param_name = tree.tokenSlice(param.name_token.?);
1490 if (mem.eql(u8, param_name, ident_name)) {
1491 return try self.addZIRInst(scope, src, zir.Inst.Arg, .{ .index = i }, .{});
1492 }
1493 }
1494 }
1495 }
1496
14031497 return self.failNode(scope, &ident.base, "TODO implement local variable identifier lookup", .{});
14041498}
14051499
......@@ -1542,7 +1636,7 @@ fn astGenCall(self: *Module, scope: *Scope, call: *ast.Node.Call) InnerError!*zi
15421636 const lhs = try self.astGenExpr(scope, call.lhs);
15431637
15441638 const param_nodes = call.params();
1545 const args = try scope.cast(Scope.GenZIR).?.arena.allocator.alloc(*zir.Inst, param_nodes.len);
1639 const args = try scope.cast(Scope.GenZIR).?.arena.alloc(*zir.Inst, param_nodes.len);
15461640 for (param_nodes) |param_node, i| {
15471641 args[i] = try self.astGenExpr(scope, param_node);
15481642 }
......@@ -1622,40 +1716,31 @@ fn getSimplePrimitiveValue(name: []const u8) ?TypedValue {
16221716}
16231717
16241718fn declareDeclDependency(self: *Module, depender: *Decl, dependee: *Decl) !void {
1625 try depender.dependencies.ensureCapacity(self.allocator, depender.dependencies.items.len + 1);
1626 try dependee.dependants.ensureCapacity(self.allocator, dependee.dependants.items.len + 1);
1719 try depender.dependencies.ensureCapacity(self.gpa, depender.dependencies.items().len + 1);
1720 try dependee.dependants.ensureCapacity(self.gpa, dependee.dependants.items().len + 1);
16271721
1628 for (depender.dependencies.items) |item| {
1629 if (item == dependee) break; // Already in the set.
1630 } else {
1631 depender.dependencies.appendAssumeCapacity(dependee);
1632 }
1633
1634 for (dependee.dependants.items) |item| {
1635 if (item == depender) break; // Already in the set.
1636 } else {
1637 dependee.dependants.appendAssumeCapacity(depender);
1638 }
1722 depender.dependencies.putAssumeCapacity(dependee, {});
1723 dependee.dependants.putAssumeCapacity(depender, {});
16391724}
16401725
16411726fn getSrcModule(self: *Module, root_scope: *Scope.ZIRModule) !*zir.Module {
16421727 switch (root_scope.status) {
16431728 .never_loaded, .unloaded_success => {
1644 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
1729 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
16451730
16461731 const source = try root_scope.getSource(self);
16471732
16481733 var keep_zir_module = false;
1649 const zir_module = try self.allocator.create(zir.Module);
1650 defer if (!keep_zir_module) self.allocator.destroy(zir_module);
1734 const zir_module = try self.gpa.create(zir.Module);
1735 defer if (!keep_zir_module) self.gpa.destroy(zir_module);
16511736
1652 zir_module.* = try zir.parse(self.allocator, source);
1653 defer if (!keep_zir_module) zir_module.deinit(self.allocator);
1737 zir_module.* = try zir.parse(self.gpa, source);
1738 defer if (!keep_zir_module) zir_module.deinit(self.gpa);
16541739
16551740 if (zir_module.error_msg) |src_err_msg| {
16561741 self.failed_files.putAssumeCapacityNoClobber(
16571742 &root_scope.base,
1658 try ErrorMsg.create(self.allocator, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}),
1743 try ErrorMsg.create(self.gpa, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}),
16591744 );
16601745 root_scope.status = .unloaded_parse_failure;
16611746 return error.AnalysisFail;
......@@ -1682,22 +1767,22 @@ fn getAstTree(self: *Module, root_scope: *Scope.File) !*ast.Tree {
16821767
16831768 switch (root_scope.status) {
16841769 .never_loaded, .unloaded_success => {
1685 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
1770 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
16861771
16871772 const source = try root_scope.getSource(self);
16881773
16891774 var keep_tree = false;
1690 const tree = try std.zig.parse(self.allocator, source);
1775 const tree = try std.zig.parse(self.gpa, source);
16911776 defer if (!keep_tree) tree.deinit();
16921777
16931778 if (tree.errors.len != 0) {
16941779 const parse_err = tree.errors[0];
16951780
1696 var msg = std.ArrayList(u8).init(self.allocator);
1781 var msg = std.ArrayList(u8).init(self.gpa);
16971782 defer msg.deinit();
16981783
16991784 try parse_err.render(tree.token_ids, msg.outStream());
1700 const err_msg = try self.allocator.create(ErrorMsg);
1785 const err_msg = try self.gpa.create(ErrorMsg);
17011786 err_msg.* = .{
17021787 .msg = msg.toOwnedSlice(),
17031788 .byte_offset = tree.token_locs[parse_err.loc()].start,
......@@ -1728,11 +1813,11 @@ fn analyzeRootSrcFile(self: *Module, root_scope: *Scope.File) !void {
17281813 const decls = tree.root_node.decls();
17291814
17301815 try self.work_queue.ensureUnusedCapacity(decls.len);
1731 try root_scope.decls.ensureCapacity(self.allocator, decls.len);
1816 try root_scope.decls.ensureCapacity(self.gpa, decls.len);
17321817
17331818 // Keep track of the decls that we expect to see in this file so that
17341819 // we know which ones have been deleted.
1735 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.allocator);
1820 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.gpa);
17361821 defer deleted_decls.deinit();
17371822 try deleted_decls.ensureCapacity(root_scope.decls.items.len);
17381823 for (root_scope.decls.items) |file_decl| {
......@@ -1756,9 +1841,9 @@ fn analyzeRootSrcFile(self: *Module, root_scope: *Scope.File) !void {
17561841 decl.src_index = decl_i;
17571842 if (deleted_decls.remove(decl) == null) {
17581843 decl.analysis = .sema_failure;
1759 const err_msg = try ErrorMsg.create(self.allocator, tree.token_locs[name_tok].start, "redefinition of '{}'", .{decl.name});
1760 errdefer err_msg.destroy(self.allocator);
1761 try self.failed_decls.putNoClobber(decl, err_msg);
1844 const err_msg = try ErrorMsg.create(self.gpa, tree.token_locs[name_tok].start, "redefinition of '{}'", .{decl.name});
1845 errdefer err_msg.destroy(self.gpa);
1846 try self.failed_decls.putNoClobber(self.gpa, decl, err_msg);
17621847 } else {
17631848 if (!srcHashEql(decl.contents_hash, contents_hash)) {
17641849 try self.markOutdatedDecl(decl);
......@@ -1792,14 +1877,14 @@ fn analyzeRootZIRModule(self: *Module, root_scope: *Scope.ZIRModule) !void {
17921877 const src_module = try self.getSrcModule(root_scope);
17931878
17941879 try self.work_queue.ensureUnusedCapacity(src_module.decls.len);
1795 try root_scope.decls.ensureCapacity(self.allocator, src_module.decls.len);
1880 try root_scope.decls.ensureCapacity(self.gpa, src_module.decls.len);
17961881
1797 var exports_to_resolve = std.ArrayList(*zir.Decl).init(self.allocator);
1882 var exports_to_resolve = std.ArrayList(*zir.Decl).init(self.gpa);
17981883 defer exports_to_resolve.deinit();
17991884
18001885 // Keep track of the decls that we expect to see in this file so that
18011886 // we know which ones have been deleted.
1802 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.allocator);
1887 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.gpa);
18031888 defer deleted_decls.deinit();
18041889 try deleted_decls.ensureCapacity(self.decl_table.items().len);
18051890 for (self.decl_table.items()) |entry| {
......@@ -1841,7 +1926,7 @@ fn analyzeRootZIRModule(self: *Module, root_scope: *Scope.ZIRModule) !void {
18411926}
18421927
18431928fn deleteDecl(self: *Module, decl: *Decl) !void {
1844 try self.deletion_set.ensureCapacity(self.allocator, self.deletion_set.items.len + decl.dependencies.items.len);
1929 try self.deletion_set.ensureCapacity(self.gpa, self.deletion_set.items.len + decl.dependencies.items().len);
18451930
18461931 // Remove from the namespace it resides in. In the case of an anonymous Decl it will
18471932 // not be present in the set, and this does nothing.
......@@ -1851,9 +1936,10 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18511936 const name_hash = decl.fullyQualifiedNameHash();
18521937 self.decl_table.removeAssertDiscard(name_hash);
18531938 // Remove itself from its dependencies, because we are about to destroy the decl pointer.
1854 for (decl.dependencies.items) |dep| {
1939 for (decl.dependencies.items()) |entry| {
1940 const dep = entry.key;
18551941 dep.removeDependant(decl);
1856 if (dep.dependants.items.len == 0 and !dep.deletion_flag) {
1942 if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
18571943 // We don't recursively perform a deletion here, because during the update,
18581944 // another reference to it may turn up.
18591945 dep.deletion_flag = true;
......@@ -1861,7 +1947,8 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18611947 }
18621948 }
18631949 // Anything that depends on this deleted decl certainly needs to be re-analyzed.
1864 for (decl.dependants.items) |dep| {
1950 for (decl.dependants.items()) |entry| {
1951 const dep = entry.key;
18651952 dep.removeDependency(decl);
18661953 if (dep.analysis != .outdated) {
18671954 // TODO Move this failure possibility to the top of the function.
......@@ -1869,11 +1956,11 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18691956 }
18701957 }
18711958 if (self.failed_decls.remove(decl)) |entry| {
1872 entry.value.destroy(self.allocator);
1959 entry.value.destroy(self.gpa);
18731960 }
18741961 self.deleteDeclExports(decl);
18751962 self.bin_file.freeDecl(decl);
1876 decl.destroy(self.allocator);
1963 decl.destroy(self.gpa);
18771964}
18781965
18791966/// Delete all the Export objects that are caused by this Decl. Re-analysis of
......@@ -1895,7 +1982,7 @@ fn deleteDeclExports(self: *Module, decl: *Decl) void {
18951982 i += 1;
18961983 }
18971984 }
1898 decl_exports_kv.value = self.allocator.shrink(list, new_len);
1985 decl_exports_kv.value = self.gpa.shrink(list, new_len);
18991986 if (new_len == 0) {
19001987 self.decl_exports.removeAssertDiscard(exp.exported_decl);
19011988 }
......@@ -1904,12 +1991,12 @@ fn deleteDeclExports(self: *Module, decl: *Decl) void {
19041991 elf.deleteExport(exp.link);
19051992 }
19061993 if (self.failed_exports.remove(exp)) |entry| {
1907 entry.value.destroy(self.allocator);
1994 entry.value.destroy(self.gpa);
19081995 }
19091996 _ = self.symbol_exports.remove(exp.options.name);
1910 self.allocator.destroy(exp);
1997 self.gpa.destroy(exp);
19111998 }
1912 self.allocator.free(kv.value);
1999 self.gpa.free(kv.value);
19132000}
19142001
19152002fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
......@@ -1917,7 +2004,7 @@ fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
19172004 defer tracy.end();
19182005
19192006 // Use the Decl's arena for function memory.
1920 var arena = decl.typed_value.most_recent.arena.?.promote(self.allocator);
2007 var arena = decl.typed_value.most_recent.arena.?.promote(self.gpa);
19212008 defer decl.typed_value.most_recent.arena.?.* = arena.state;
19222009 var inner_block: Scope.Block = .{
19232010 .parent = null,
......@@ -1926,10 +2013,10 @@ fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
19262013 .instructions = .{},
19272014 .arena = &arena.allocator,
19282015 };
1929 defer inner_block.instructions.deinit(self.allocator);
2016 defer inner_block.instructions.deinit(self.gpa);
19302017
19312018 const fn_zir = func.analysis.queued;
1932 defer fn_zir.arena.promote(self.allocator).deinit();
2019 defer fn_zir.arena.promote(self.gpa).deinit();
19332020 func.analysis = .{ .in_progress = {} };
19342021 //std.debug.warn("set {} to in_progress\n", .{decl.name});
19352022
......@@ -1944,7 +2031,7 @@ fn markOutdatedDecl(self: *Module, decl: *Decl) !void {
19442031 //std.debug.warn("mark {} outdated\n", .{decl.name});
19452032 try self.work_queue.writeItem(.{ .analyze_decl = decl });
19462033 if (self.failed_decls.remove(decl)) |entry| {
1947 entry.value.destroy(self.allocator);
2034 entry.value.destroy(self.gpa);
19482035 }
19492036 decl.analysis = .outdated;
19502037}
......@@ -1955,7 +2042,7 @@ fn allocateNewDecl(
19552042 src_index: usize,
19562043 contents_hash: std.zig.SrcHash,
19572044) !*Decl {
1958 const new_decl = try self.allocator.create(Decl);
2045 const new_decl = try self.gpa.create(Decl);
19592046 new_decl.* = .{
19602047 .name = "",
19612048 .scope = scope.namespace(),
......@@ -1978,10 +2065,10 @@ fn createNewDecl(
19782065 name_hash: Scope.NameHash,
19792066 contents_hash: std.zig.SrcHash,
19802067) !*Decl {
1981 try self.decl_table.ensureCapacity(self.decl_table.items().len + 1);
2068 try self.decl_table.ensureCapacity(self.gpa, self.decl_table.items().len + 1);
19822069 const new_decl = try self.allocateNewDecl(scope, src_index, contents_hash);
1983 errdefer self.allocator.destroy(new_decl);
1984 new_decl.name = try mem.dupeZ(self.allocator, u8, decl_name);
2070 errdefer self.gpa.destroy(new_decl);
2071 new_decl.name = try mem.dupeZ(self.gpa, u8, decl_name);
19852072 self.decl_table.putAssumeCapacityNoClobber(name_hash, new_decl);
19862073 return new_decl;
19872074}
......@@ -1989,7 +2076,7 @@ fn createNewDecl(
19892076fn analyzeZirDecl(self: *Module, decl: *Decl, src_decl: *zir.Decl) InnerError!bool {
19902077 var decl_scope: Scope.DeclAnalysis = .{
19912078 .decl = decl,
1992 .arena = std.heap.ArenaAllocator.init(self.allocator),
2079 .arena = std.heap.ArenaAllocator.init(self.gpa),
19932080 };
19942081 errdefer decl_scope.arena.deinit();
19952082
......@@ -2005,7 +2092,7 @@ fn analyzeZirDecl(self: *Module, decl: *Decl, src_decl: *zir.Decl) InnerError!bo
20052092 prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits();
20062093 type_changed = !tvm.typed_value.ty.eql(typed_value.ty);
20072094
2008 tvm.deinit(self.allocator);
2095 tvm.deinit(self.gpa);
20092096 }
20102097
20112098 arena_state.* = decl_scope.arena.state;
......@@ -2143,11 +2230,11 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21432230 else => return self.fail(scope, src, "unable to export type '{}'", .{typed_value.ty}),
21442231 }
21452232
2146 try self.decl_exports.ensureCapacity(self.decl_exports.items().len + 1);
2147 try self.export_owners.ensureCapacity(self.export_owners.items().len + 1);
2233 try self.decl_exports.ensureCapacity(self.gpa, self.decl_exports.items().len + 1);
2234 try self.export_owners.ensureCapacity(self.gpa, self.export_owners.items().len + 1);
21482235
2149 const new_export = try self.allocator.create(Export);
2150 errdefer self.allocator.destroy(new_export);
2236 const new_export = try self.gpa.create(Export);
2237 errdefer self.gpa.destroy(new_export);
21512238
21522239 const owner_decl = scope.decl().?;
21532240
......@@ -2161,27 +2248,27 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21612248 };
21622249
21632250 // Add to export_owners table.
2164 const eo_gop = self.export_owners.getOrPut(owner_decl) catch unreachable;
2251 const eo_gop = self.export_owners.getOrPut(self.gpa, owner_decl) catch unreachable;
21652252 if (!eo_gop.found_existing) {
21662253 eo_gop.entry.value = &[0]*Export{};
21672254 }
2168 eo_gop.entry.value = try self.allocator.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
2255 eo_gop.entry.value = try self.gpa.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
21692256 eo_gop.entry.value[eo_gop.entry.value.len - 1] = new_export;
2170 errdefer eo_gop.entry.value = self.allocator.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
2257 errdefer eo_gop.entry.value = self.gpa.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
21712258
21722259 // Add to exported_decl table.
2173 const de_gop = self.decl_exports.getOrPut(exported_decl) catch unreachable;
2260 const de_gop = self.decl_exports.getOrPut(self.gpa, exported_decl) catch unreachable;
21742261 if (!de_gop.found_existing) {
21752262 de_gop.entry.value = &[0]*Export{};
21762263 }
2177 de_gop.entry.value = try self.allocator.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
2264 de_gop.entry.value = try self.gpa.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
21782265 de_gop.entry.value[de_gop.entry.value.len - 1] = new_export;
2179 errdefer de_gop.entry.value = self.allocator.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
2266 errdefer de_gop.entry.value = self.gpa.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
21802267
21812268 if (self.symbol_exports.get(symbol_name)) |_| {
2182 try self.failed_exports.ensureCapacity(self.failed_exports.items().len + 1);
2269 try self.failed_exports.ensureCapacity(self.gpa, self.failed_exports.items().len + 1);
21832270 self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create(
2184 self.allocator,
2271 self.gpa,
21852272 src,
21862273 "exported symbol collision: {}",
21872274 .{symbol_name},
......@@ -2192,21 +2279,19 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21922279 }
21932280
21942281 try self.symbol_exports.putNoClobber(symbol_name, new_export);
2195 if (self.bin_file.cast(link.File.Elf)) |elf| {
2196 elf.updateDeclExports(self, exported_decl, de_gop.entry.value) catch |err| switch (err) {
2197 error.OutOfMemory => return error.OutOfMemory,
2198 else => {
2199 try self.failed_exports.ensureCapacity(self.failed_exports.items().len + 1);
2200 self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create(
2201 self.allocator,
2202 src,
2203 "unable to export: {}",
2204 .{@errorName(err)},
2205 ));
2206 new_export.status = .failed_retryable;
2207 },
2208 };
2209 }
2282 self.bin_file.updateDeclExports(self, exported_decl, de_gop.entry.value) catch |err| switch (err) {
2283 error.OutOfMemory => return error.OutOfMemory,
2284 else => {
2285 try self.failed_exports.ensureCapacity(self.gpa, self.failed_exports.items().len + 1);
2286 self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create(
2287 self.gpa,
2288 src,
2289 "unable to export: {}",
2290 .{@errorName(err)},
2291 ));
2292 new_export.status = .failed_retryable;
2293 },
2294 };
22102295}
22112296
22122297fn addNewInstArgs(
......@@ -2223,13 +2308,13 @@ fn addNewInstArgs(
22232308}
22242309
22252310fn newZIRInst(
2226 allocator: *Allocator,
2311 gpa: *Allocator,
22272312 src: usize,
22282313 comptime T: type,
22292314 positionals: std.meta.fieldInfo(T, "positionals").field_type,
22302315 kw_args: std.meta.fieldInfo(T, "kw_args").field_type,
2231) !*zir.Inst {
2232 const inst = try allocator.create(T);
2316) !*T {
2317 const inst = try gpa.create(T);
22332318 inst.* = .{
22342319 .base = .{
22352320 .tag = T.base_tag,
......@@ -2238,30 +2323,48 @@ fn newZIRInst(
22382323 .positionals = positionals,
22392324 .kw_args = kw_args,
22402325 };
2241 return &inst.base;
2326 return inst;
22422327}
22432328
2244fn addZIRInst(
2329fn addZIRInstSpecial(
22452330 self: *Module,
22462331 scope: *Scope,
22472332 src: usize,
22482333 comptime T: type,
22492334 positionals: std.meta.fieldInfo(T, "positionals").field_type,
22502335 kw_args: std.meta.fieldInfo(T, "kw_args").field_type,
2251) !*zir.Inst {
2336) !*T {
22522337 const gen_zir = scope.cast(Scope.GenZIR).?;
2253 try gen_zir.instructions.ensureCapacity(gen_zir.instructions.items.len + 1);
2254 const inst = try newZIRInst(&gen_zir.arena.allocator, src, T, positionals, kw_args);
2255 gen_zir.instructions.appendAssumeCapacity(inst);
2338 try gen_zir.instructions.ensureCapacity(self.gpa, gen_zir.instructions.items.len + 1);
2339 const inst = try newZIRInst(gen_zir.arena, src, T, positionals, kw_args);
2340 gen_zir.instructions.appendAssumeCapacity(&inst.base);
22562341 return inst;
22572342}
22582343
2344fn addZIRInst(
2345 self: *Module,
2346 scope: *Scope,
2347 src: usize,
2348 comptime T: type,
2349 positionals: std.meta.fieldInfo(T, "positionals").field_type,
2350 kw_args: std.meta.fieldInfo(T, "kw_args").field_type,
2351) !*zir.Inst {
2352 const inst_special = try self.addZIRInstSpecial(scope, src, T, positionals, kw_args);
2353 return &inst_special.base;
2354}
2355
22592356/// TODO The existence of this function is a workaround for a bug in stage1.
22602357fn addZIRInstConst(self: *Module, scope: *Scope, src: usize, typed_value: TypedValue) !*zir.Inst {
22612358 const P = std.meta.fieldInfo(zir.Inst.Const, "positionals").field_type;
22622359 return self.addZIRInst(scope, src, zir.Inst.Const, P{ .typed_value = typed_value }, .{});
22632360}
22642361
2362/// TODO The existence of this function is a workaround for a bug in stage1.
2363fn addZIRInstBlock(self: *Module, scope: *Scope, src: usize, body: zir.Module.Body) !*zir.Inst.Block {
2364 const P = std.meta.fieldInfo(zir.Inst.Block, "positionals").field_type;
2365 return self.addZIRInstSpecial(scope, src, zir.Inst.Block, P{ .body = body }, .{});
2366}
2367
22652368fn addNewInst(self: *Module, block: *Scope.Block, src: usize, ty: Type, comptime T: type) !*T {
22662369 const inst = try block.arena.create(T);
22672370 inst.* = .{
......@@ -2272,7 +2375,7 @@ fn addNewInst(self: *Module, block: *Scope.Block, src: usize, ty: Type, comptime
22722375 },
22732376 .args = undefined,
22742377 };
2275 try block.instructions.append(self.allocator, &inst.base);
2378 try block.instructions.append(self.gpa, &inst.base);
22762379 return inst;
22772380}
22782381
......@@ -2392,6 +2495,7 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
23922495 switch (old_inst.tag) {
23932496 .arg => return self.analyzeInstArg(scope, old_inst.cast(zir.Inst.Arg).?),
23942497 .block => return self.analyzeInstBlock(scope, old_inst.cast(zir.Inst.Block).?),
2498 .@"break" => return self.analyzeInstBreak(scope, old_inst.cast(zir.Inst.Break).?),
23952499 .breakpoint => return self.analyzeInstBreakpoint(scope, old_inst.cast(zir.Inst.Breakpoint).?),
23962500 .breakvoid => return self.analyzeInstBreakVoid(scope, old_inst.cast(zir.Inst.BreakVoid).?),
23972501 .call => return self.analyzeInstCall(scope, old_inst.cast(zir.Inst.Call).?),
......@@ -2406,6 +2510,7 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
24062510 const big_int = old_inst.cast(zir.Inst.Int).?.positionals.int;
24072511 return self.constIntBig(scope, old_inst.src, Type.initTag(.comptime_int), big_int);
24082512 },
2513 .inttype => return self.analyzeInstIntType(scope, old_inst.cast(zir.Inst.IntType).?),
24092514 .ptrtoint => return self.analyzeInstPtrToInt(scope, old_inst.cast(zir.Inst.PtrToInt).?),
24102515 .fieldptr => return self.analyzeInstFieldPtr(scope, old_inst.cast(zir.Inst.FieldPtr).?),
24112516 .deref => return self.analyzeInstDeref(scope, old_inst.cast(zir.Inst.Deref).?),
......@@ -2422,6 +2527,7 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
24222527 .bitcast => return self.analyzeInstBitCast(scope, old_inst.cast(zir.Inst.BitCast).?),
24232528 .elemptr => return self.analyzeInstElemPtr(scope, old_inst.cast(zir.Inst.ElemPtr).?),
24242529 .add => return self.analyzeInstAdd(scope, old_inst.cast(zir.Inst.Add).?),
2530 .sub => return self.analyzeInstSub(scope, old_inst.cast(zir.Inst.Sub).?),
24252531 .cmp => return self.analyzeInstCmp(scope, old_inst.cast(zir.Inst.Cmp).?),
24262532 .condbr => return self.analyzeInstCondBr(scope, old_inst.cast(zir.Inst.CondBr).?),
24272533 .isnull => return self.analyzeInstIsNull(scope, old_inst.cast(zir.Inst.IsNull).?),
......@@ -2432,7 +2538,7 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
24322538fn analyzeInstStr(self: *Module, scope: *Scope, str_inst: *zir.Inst.Str) InnerError!*Inst {
24332539 // The bytes references memory inside the ZIR module, which can get deallocated
24342540 // after semantic analysis is complete. We need the memory to be in the new anonymous Decl's arena.
2435 var new_decl_arena = std.heap.ArenaAllocator.init(self.allocator);
2541 var new_decl_arena = std.heap.ArenaAllocator.init(self.gpa);
24362542 const arena_bytes = try new_decl_arena.allocator.dupe(u8, str_inst.positionals.bytes);
24372543
24382544 const ty_payload = try scope.arena().create(Type.Payload.Array_u8_Sentinel0);
......@@ -2456,8 +2562,8 @@ fn createAnonymousDecl(
24562562) !*Decl {
24572563 const name_index = self.getNextAnonNameIndex();
24582564 const scope_decl = scope.decl().?;
2459 const name = try std.fmt.allocPrint(self.allocator, "{}__anon_{}", .{ scope_decl.name, name_index });
2460 defer self.allocator.free(name);
2565 const name = try std.fmt.allocPrint(self.gpa, "{}__anon_{}", .{ scope_decl.name, name_index });
2566 defer self.gpa.free(name);
24612567 const name_hash = scope.namespace().fullyQualifiedNameHash(name);
24622568 const src_hash: std.zig.SrcHash = undefined;
24632569 const new_decl = try self.createNewDecl(scope, name, scope_decl.src_index, name_hash, src_hash);
......@@ -2546,15 +2652,15 @@ fn analyzeInstBlock(self: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerEr
25462652 .arena = parent_block.arena,
25472653 // TODO @as here is working around a miscompilation compiler bug :(
25482654 .label = @as(?Scope.Block.Label, Scope.Block.Label{
2549 .name = inst.positionals.label,
2655 .zir_block = inst,
25502656 .results = .{},
25512657 .block_inst = block_inst,
25522658 }),
25532659 };
25542660 const label = &child_block.label.?;
25552661
2556 defer child_block.instructions.deinit(self.allocator);
2557 defer label.results.deinit(self.allocator);
2662 defer child_block.instructions.deinit(self.gpa);
2663 defer label.results.deinit(self.gpa);
25582664
25592665 try self.analyzeBody(&child_block.base, inst.positionals.body);
25602666
......@@ -2562,21 +2668,9 @@ fn analyzeInstBlock(self: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerEr
25622668 assert(child_block.instructions.items.len != 0);
25632669 assert(child_block.instructions.items[child_block.instructions.items.len - 1].tag.isNoReturn());
25642670
2565 if (label.results.items.len <= 1) {
2566 // No need to add the Block instruction; we can add the instructions to the parent block directly.
2567 // Blocks are terminated with a noreturn instruction which we do not want to include.
2568 const instrs = child_block.instructions.items;
2569 try parent_block.instructions.appendSlice(self.allocator, instrs[0 .. instrs.len - 1]);
2570 if (label.results.items.len == 1) {
2571 return label.results.items[0];
2572 } else {
2573 return self.constNoReturn(scope, inst.base.src);
2574 }
2575 }
2576
25772671 // Need to set the type and emit the Block instruction. This allows machine code generation
25782672 // to emit a jump instruction to after the block when it encounters the break.
2579 try parent_block.instructions.append(self.allocator, &block_inst.base);
2673 try parent_block.instructions.append(self.gpa, &block_inst.base);
25802674 block_inst.base.ty = try self.resolvePeerTypes(scope, label.results.items);
25812675 block_inst.args.body = .{ .instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items) };
25822676 return &block_inst.base;
......@@ -2587,22 +2681,39 @@ fn analyzeInstBreakpoint(self: *Module, scope: *Scope, inst: *zir.Inst.Breakpoin
25872681 return self.addNewInstArgs(b, inst.base.src, Type.initTag(.void), Inst.Breakpoint, {});
25882682}
25892683
2684fn analyzeInstBreak(self: *Module, scope: *Scope, inst: *zir.Inst.Break) InnerError!*Inst {
2685 const operand = try self.resolveInst(scope, inst.positionals.operand);
2686 const block = inst.positionals.block;
2687 return self.analyzeBreak(scope, inst.base.src, block, operand);
2688}
2689
25902690fn analyzeInstBreakVoid(self: *Module, scope: *Scope, inst: *zir.Inst.BreakVoid) InnerError!*Inst {
2591 const label_name = inst.positionals.label;
2691 const block = inst.positionals.block;
25922692 const void_inst = try self.constVoid(scope, inst.base.src);
2693 return self.analyzeBreak(scope, inst.base.src, block, void_inst);
2694}
25932695
2696fn analyzeBreak(
2697 self: *Module,
2698 scope: *Scope,
2699 src: usize,
2700 zir_block: *zir.Inst.Block,
2701 operand: *Inst,
2702) InnerError!*Inst {
25942703 var opt_block = scope.cast(Scope.Block);
25952704 while (opt_block) |block| {
25962705 if (block.label) |*label| {
2597 if (mem.eql(u8, label.name, label_name)) {
2598 try label.results.append(self.allocator, void_inst);
2599 return self.constNoReturn(scope, inst.base.src);
2706 if (label.zir_block == zir_block) {
2707 try label.results.append(self.gpa, operand);
2708 const b = try self.requireRuntimeBlock(scope, src);
2709 return self.addNewInstArgs(b, src, Type.initTag(.noreturn), Inst.Br, .{
2710 .block = label.block_inst,
2711 .operand = operand,
2712 });
26002713 }
26012714 }
26022715 opt_block = block.parent;
2603 } else {
2604 return self.fail(scope, inst.base.src, "use of undeclared label '{}'", .{label_name});
2605 }
2716 } else unreachable;
26062717}
26072718
26082719fn analyzeInstDeclRefStr(self: *Module, scope: *Scope, inst: *zir.Inst.DeclRefStr) InnerError!*Inst {
......@@ -2718,8 +2829,8 @@ fn analyzeInstCall(self: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerErro
27182829
27192830 // TODO handle function calls of generic functions
27202831
2721 const fn_param_types = try self.allocator.alloc(Type, fn_params_len);
2722 defer self.allocator.free(fn_param_types);
2832 const fn_param_types = try self.gpa.alloc(Type, fn_params_len);
2833 defer self.gpa.free(fn_param_types);
27232834 func.ty.fnParamTypes(fn_param_types);
27242835
27252836 const casted_args = try scope.arena().alloc(*Inst, fn_params_len);
......@@ -2738,7 +2849,7 @@ fn analyzeInstCall(self: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerErro
27382849fn analyzeInstFn(self: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError!*Inst {
27392850 const fn_type = try self.resolveType(scope, fn_inst.positionals.fn_type);
27402851 const fn_zir = blk: {
2741 var fn_arena = std.heap.ArenaAllocator.init(self.allocator);
2852 var fn_arena = std.heap.ArenaAllocator.init(self.gpa);
27422853 errdefer fn_arena.deinit();
27432854
27442855 const fn_zir = try scope.arena().create(Fn.ZIR);
......@@ -2763,6 +2874,10 @@ fn analyzeInstFn(self: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError
27632874 });
27642875}
27652876
2877fn analyzeInstIntType(self: *Module, scope: *Scope, inttype: *zir.Inst.IntType) InnerError!*Inst {
2878 return self.fail(scope, inttype.base.src, "TODO implement inttype", .{});
2879}
2880
27662881fn analyzeInstFnType(self: *Module, scope: *Scope, fntype: *zir.Inst.FnType) InnerError!*Inst {
27672882 const return_type = try self.resolveType(scope, fntype.positionals.return_type);
27682883
......@@ -2923,6 +3038,10 @@ fn analyzeInstElemPtr(self: *Module, scope: *Scope, inst: *zir.Inst.ElemPtr) Inn
29233038 return self.fail(scope, inst.base.src, "TODO implement more analyze elemptr", .{});
29243039}
29253040
3041fn analyzeInstSub(self: *Module, scope: *Scope, inst: *zir.Inst.Sub) InnerError!*Inst {
3042 return self.fail(scope, inst.base.src, "TODO implement analysis of sub", .{});
3043}
3044
29263045fn analyzeInstAdd(self: *Module, scope: *Scope, inst: *zir.Inst.Add) InnerError!*Inst {
29273046 const tracy = trace(@src());
29283047 defer tracy.end();
......@@ -3119,7 +3238,7 @@ fn analyzeInstCondBr(self: *Module, scope: *Scope, inst: *zir.Inst.CondBr) Inner
31193238 .instructions = .{},
31203239 .arena = parent_block.arena,
31213240 };
3122 defer true_block.instructions.deinit(self.allocator);
3241 defer true_block.instructions.deinit(self.gpa);
31233242 try self.analyzeBody(&true_block.base, inst.positionals.true_body);
31243243
31253244 var false_block: Scope.Block = .{
......@@ -3129,7 +3248,7 @@ fn analyzeInstCondBr(self: *Module, scope: *Scope, inst: *zir.Inst.CondBr) Inner
31293248 .instructions = .{},
31303249 .arena = parent_block.arena,
31313250 };
3132 defer false_block.instructions.deinit(self.allocator);
3251 defer false_block.instructions.deinit(self.gpa);
31333252 try self.analyzeBody(&false_block.base, inst.positionals.false_body);
31343253
31353254 return self.addNewInstArgs(parent_block, inst.base.src, Type.initTag(.void), Inst.CondBr, Inst.Args(Inst.CondBr){
......@@ -3283,7 +3402,7 @@ fn cmpNumeric(
32833402 return self.constUndef(scope, src, Type.initTag(.bool));
32843403 const is_unsigned = if (lhs_is_float) x: {
32853404 var bigint_space: Value.BigIntSpace = undefined;
3286 var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.allocator);
3405 var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.gpa);
32873406 defer bigint.deinit();
32883407 const zcmp = lhs_val.orderAgainstZero();
32893408 if (lhs_val.floatHasFraction()) {
......@@ -3318,7 +3437,7 @@ fn cmpNumeric(
33183437 return self.constUndef(scope, src, Type.initTag(.bool));
33193438 const is_unsigned = if (rhs_is_float) x: {
33203439 var bigint_space: Value.BigIntSpace = undefined;
3321 var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.allocator);
3440 var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.gpa);
33223441 defer bigint.deinit();
33233442 const zcmp = rhs_val.orderAgainstZero();
33243443 if (rhs_val.floatHasFraction()) {
......@@ -3355,7 +3474,7 @@ fn cmpNumeric(
33553474 break :blk try self.makeIntType(scope, dest_int_is_signed, casted_bits);
33563475 };
33573476 const casted_lhs = try self.coerce(scope, dest_type, lhs);
3358 const casted_rhs = try self.coerce(scope, dest_type, lhs);
3477 const casted_rhs = try self.coerce(scope, dest_type, rhs);
33593478
33603479 return self.addNewInstArgs(b, src, Type.initTag(.bool), Inst.Cmp, .{
33613480 .lhs = casted_lhs,
......@@ -3379,6 +3498,8 @@ fn makeIntType(self: *Module, scope: *Scope, signed: bool, bits: u16) !Type {
33793498fn resolvePeerTypes(self: *Module, scope: *Scope, instructions: []*Inst) !Type {
33803499 if (instructions.len == 0)
33813500 return Type.initTag(.noreturn);
3501 if (instructions.len == 1)
3502 return instructions[0].ty;
33823503 return self.fail(scope, instructions[0].src, "TODO peer type resolution", .{});
33833504}
33843505
......@@ -3456,7 +3577,7 @@ fn coerceArrayPtrToSlice(self: *Module, scope: *Scope, dest_type: Type, inst: *I
34563577
34573578fn fail(self: *Module, scope: *Scope, src: usize, comptime format: []const u8, args: var) InnerError {
34583579 @setCold(true);
3459 const err_msg = try ErrorMsg.create(self.allocator, src, format, args);
3580 const err_msg = try ErrorMsg.create(self.gpa, src, format, args);
34603581 return self.failWithOwnedErrorMsg(scope, src, err_msg);
34613582}
34623583
......@@ -3486,9 +3607,9 @@ fn failNode(
34863607
34873608fn failWithOwnedErrorMsg(self: *Module, scope: *Scope, src: usize, err_msg: *ErrorMsg) InnerError {
34883609 {
3489 errdefer err_msg.destroy(self.allocator);
3490 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
3491 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
3610 errdefer err_msg.destroy(self.gpa);
3611 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
3612 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
34923613 }
34933614 switch (scope.tag) {
34943615 .decl => {
......@@ -3541,28 +3662,28 @@ pub const ErrorMsg = struct {
35413662 byte_offset: usize,
35423663 msg: []const u8,
35433664
3544 pub fn create(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !*ErrorMsg {
3545 const self = try allocator.create(ErrorMsg);
3546 errdefer allocator.destroy(self);
3547 self.* = try init(allocator, byte_offset, format, args);
3665 pub fn create(gpa: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !*ErrorMsg {
3666 const self = try gpa.create(ErrorMsg);
3667 errdefer gpa.destroy(self);
3668 self.* = try init(gpa, byte_offset, format, args);
35483669 return self;
35493670 }
35503671
35513672 /// Assumes the ErrorMsg struct and msg were both allocated with allocator.
3552 pub fn destroy(self: *ErrorMsg, allocator: *Allocator) void {
3553 self.deinit(allocator);
3554 allocator.destroy(self);
3673 pub fn destroy(self: *ErrorMsg, gpa: *Allocator) void {
3674 self.deinit(gpa);
3675 gpa.destroy(self);
35553676 }
35563677
3557 pub fn init(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !ErrorMsg {
3678 pub fn init(gpa: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !ErrorMsg {
35583679 return ErrorMsg{
35593680 .byte_offset = byte_offset,
3560 .msg = try std.fmt.allocPrint(allocator, format, args),
3681 .msg = try std.fmt.allocPrint(gpa, format, args),
35613682 };
35623683 }
35633684
3564 pub fn deinit(self: *ErrorMsg, allocator: *Allocator) void {
3565 allocator.free(self.msg);
3685 pub fn deinit(self: *ErrorMsg, gpa: *Allocator) void {
3686 gpa.free(self.msg);
35663687 self.* = undefined;
35673688 }
35683689};
src-self-hosted/codegen.zig+460-83
......@@ -12,6 +12,18 @@ const Target = std.Target;
1212const Allocator = mem.Allocator;
1313const trace = @import("tracy.zig").trace;
1414
15/// The codegen-related data that is stored in `ir.Inst.Block` instructions.
16pub const BlockData = struct {
17 relocs: std.ArrayListUnmanaged(Reloc) = .{},
18};
19
20pub const Reloc = union(enum) {
21 /// The value is an offset into the `Function` `code` from the beginning.
22 /// To perform the reloc, write 32-bit signed little-endian integer
23 /// which is a relative jump, based on the address following the reloc.
24 rel32: usize,
25};
26
1527pub const Result = union(enum) {
1628 /// The `code` parameter passed to `generateSymbol` has the value appended.
1729 appended: void,
......@@ -46,7 +58,14 @@ pub fn generateSymbol(
4658 var mc_args = try std.ArrayList(Function.MCValue).initCapacity(bin_file.allocator, param_types.len);
4759 defer mc_args.deinit();
4860
49 var next_stack_offset: u64 = 0;
61 var branch_stack = std.ArrayList(Function.Branch).init(bin_file.allocator);
62 defer {
63 assert(branch_stack.items.len == 1);
64 branch_stack.items[0].deinit(bin_file.allocator);
65 branch_stack.deinit();
66 }
67 const branch = try branch_stack.addOne();
68 branch.* = .{};
5069
5170 switch (fn_type.fnCallingConvention()) {
5271 .Naked => assert(mc_args.items.len == 0),
......@@ -61,8 +80,8 @@ pub fn generateSymbol(
6180 switch (param_type.zigTypeTag()) {
6281 .Bool, .Int => {
6382 if (next_int_reg >= integer_registers.len) {
64 try mc_args.append(.{ .stack_offset = next_stack_offset });
65 next_stack_offset += param_type.abiSize(bin_file.options.target);
83 try mc_args.append(.{ .stack_offset = branch.next_stack_offset });
84 branch.next_stack_offset += @intCast(u32, param_type.abiSize(bin_file.options.target));
6685 } else {
6786 try mc_args.append(.{ .register = @enumToInt(integer_registers[next_int_reg]) });
6887 next_int_reg += 1;
......@@ -100,16 +119,17 @@ pub fn generateSymbol(
100119 }
101120
102121 var function = Function{
122 .gpa = bin_file.allocator,
103123 .target = &bin_file.options.target,
104124 .bin_file = bin_file,
105125 .mod_fn = module_fn,
106126 .code = code,
107 .inst_table = std.AutoHashMap(*ir.Inst, Function.MCValue).init(bin_file.allocator),
108127 .err_msg = null,
109128 .args = mc_args.items,
129 .branch_stack = &branch_stack,
110130 };
111 defer function.inst_table.deinit();
112131
132 branch.max_end_stack = branch.next_stack_offset;
113133 function.gen() catch |err| switch (err) {
114134 error.CodegenFail => return Result{ .fail = function.err_msg.? },
115135 else => |e| return e,
......@@ -210,18 +230,67 @@ pub fn generateSymbol(
210230 }
211231}
212232
233const InnerError = error {
234 OutOfMemory,
235 CodegenFail,
236};
237
213238const Function = struct {
239 gpa: *Allocator,
214240 bin_file: *link.File.Elf,
215241 target: *const std.Target,
216242 mod_fn: *const Module.Fn,
217243 code: *std.ArrayList(u8),
218 inst_table: std.AutoHashMap(*ir.Inst, MCValue),
219244 err_msg: ?*ErrorMsg,
220245 args: []MCValue,
221246
247 /// Whenever there is a runtime branch, we push a Branch onto this stack,
248 /// and pop it off when the runtime branch joins. This provides an "overlay"
249 /// of the table of mappings from instructions to `MCValue` from within the branch.
250 /// This way we can modify the `MCValue` for an instruction in different ways
251 /// within different branches. Special consideration is needed when a branch
252 /// joins with its parent, to make sure all instructions have the same MCValue
253 /// across each runtime branch upon joining.
254 branch_stack: *std.ArrayList(Branch),
255
256 const Branch = struct {
257 inst_table: std.AutoHashMapUnmanaged(*ir.Inst, MCValue) = .{},
258
259 /// The key is an enum value of an arch-specific register.
260 registers: std.AutoHashMapUnmanaged(usize, RegisterAllocation) = .{},
261
262 /// Maps offset to what is stored there.
263 stack: std.AutoHashMapUnmanaged(usize, StackAllocation) = .{},
264 /// Offset from the stack base, representing the end of the stack frame.
265 max_end_stack: u32 = 0,
266 /// Represents the current end stack offset. If there is no existing slot
267 /// to place a new stack allocation, it goes here, and then bumps `max_end_stack`.
268 next_stack_offset: u32 = 0,
269
270 fn deinit(self: *Branch, gpa: *Allocator) void {
271 self.inst_table.deinit(gpa);
272 self.registers.deinit(gpa);
273 self.stack.deinit(gpa);
274 self.* = undefined;
275 }
276 };
277
278 const RegisterAllocation = struct {
279 inst: *ir.Inst,
280 };
281
282 const StackAllocation = struct {
283 inst: *ir.Inst,
284 size: u32,
285 };
286
222287 const MCValue = union(enum) {
288 /// No runtime bits. `void` types, empty structs, u0, enums with 1 tag, etc.
223289 none,
290 /// Control flow will not allow this value to be observed.
224291 unreach,
292 /// No more references to this value remain.
293 dead,
225294 /// A pointer-sized integer that fits in a register.
226295 immediate: u64,
227296 /// The constant was emitted into the code, at this offset.
......@@ -233,6 +302,45 @@ const Function = struct {
233302 memory: u64,
234303 /// The value is one of the stack variables.
235304 stack_offset: u64,
305 /// The value is in the compare flags assuming an unsigned operation,
306 /// with this operator applied on top of it.
307 compare_flags_unsigned: std.math.CompareOperator,
308 /// The value is in the compare flags assuming a signed operation,
309 /// with this operator applied on top of it.
310 compare_flags_signed: std.math.CompareOperator,
311
312 fn isMemory(mcv: MCValue) bool {
313 return switch (mcv) {
314 .embedded_in_code, .memory, .stack_offset => true,
315 else => false,
316 };
317 }
318
319 fn isImmediate(mcv: MCValue) bool {
320 return switch (mcv) {
321 .immediate => true,
322 else => false,
323 };
324 }
325
326 fn isMutable(mcv: MCValue) bool {
327 return switch (mcv) {
328 .none => unreachable,
329 .unreach => unreachable,
330 .dead => unreachable,
331
332 .immediate,
333 .embedded_in_code,
334 .memory,
335 .compare_flags_unsigned,
336 .compare_flags_signed,
337 => false,
338
339 .register,
340 .stack_offset,
341 => true,
342 };
343 }
236344 };
237345
238346 fn gen(self: *Function) !void {
......@@ -292,9 +400,14 @@ const Function = struct {
292400 }
293401
294402 fn genArch(self: *Function, comptime arch: std.Target.Cpu.Arch) !void {
295 for (self.mod_fn.analysis.success.instructions) |inst| {
403 return self.genBody(self.mod_fn.analysis.success, arch);
404 }
405
406 fn genBody(self: *Function, body: ir.Body, comptime arch: std.Target.Cpu.Arch) InnerError!void {
407 const inst_table = &self.branch_stack.items[0].inst_table;
408 for (body.instructions) |inst| {
296409 const new_inst = try self.genFuncInst(inst, arch);
297 try self.inst_table.putNoClobber(inst, new_inst);
410 try inst_table.putNoClobber(self.gpa, inst, new_inst);
298411 }
299412 }
300413
......@@ -302,39 +415,166 @@ const Function = struct {
302415 switch (inst.tag) {
303416 .add => return self.genAdd(inst.cast(ir.Inst.Add).?, arch),
304417 .arg => return self.genArg(inst.cast(ir.Inst.Arg).?),
418 .assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?, arch),
419 .bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?),
305420 .block => return self.genBlock(inst.cast(ir.Inst.Block).?, arch),
421 .br => return self.genBr(inst.cast(ir.Inst.Br).?, arch),
306422 .breakpoint => return self.genBreakpoint(inst.src, arch),
423 .brvoid => return self.genBrVoid(inst.cast(ir.Inst.BrVoid).?, arch),
307424 .call => return self.genCall(inst.cast(ir.Inst.Call).?, arch),
308 .unreach => return MCValue{ .unreach = {} },
425 .cmp => return self.genCmp(inst.cast(ir.Inst.Cmp).?, arch),
426 .condbr => return self.genCondBr(inst.cast(ir.Inst.CondBr).?, arch),
309427 .constant => unreachable, // excluded from function bodies
310 .assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?, arch),
428 .isnonnull => return self.genIsNonNull(inst.cast(ir.Inst.IsNonNull).?, arch),
429 .isnull => return self.genIsNull(inst.cast(ir.Inst.IsNull).?, arch),
311430 .ptrtoint => return self.genPtrToInt(inst.cast(ir.Inst.PtrToInt).?),
312 .bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?),
313431 .ret => return self.genRet(inst.cast(ir.Inst.Ret).?, arch),
314432 .retvoid => return self.genRetVoid(inst.cast(ir.Inst.RetVoid).?, arch),
315 .cmp => return self.genCmp(inst.cast(ir.Inst.Cmp).?, arch),
316 .condbr => return self.genCondBr(inst.cast(ir.Inst.CondBr).?, arch),
317 .isnull => return self.genIsNull(inst.cast(ir.Inst.IsNull).?, arch),
318 .isnonnull => return self.genIsNonNull(inst.cast(ir.Inst.IsNonNull).?, arch),
433 .sub => return self.genSub(inst.cast(ir.Inst.Sub).?, arch),
434 .unreach => return MCValue{ .unreach = {} },
319435 }
320436 }
321437
322438 fn genAdd(self: *Function, inst: *ir.Inst.Add, comptime arch: std.Target.Cpu.Arch) !MCValue {
323 const lhs = try self.resolveInst(inst.args.lhs);
324 const rhs = try self.resolveInst(inst.args.rhs);
439 // No side effects, so if it's unreferenced, do nothing.
440 if (inst.base.isUnused())
441 return MCValue.dead;
325442 switch (arch) {
326 .i386, .x86_64 => {
327 // const lhs_reg = try self.instAsReg(lhs);
328 // const rhs_reg = try self.instAsReg(rhs);
329 // const result = try self.allocateReg();
443 .x86_64 => {
444 return try self.genX8664BinMath(&inst.base, inst.args.lhs, inst.args.rhs, 0, 0x00);
445 },
446 else => return self.fail(inst.base.src, "TODO implement add for {}", .{self.target.cpu.arch}),
447 }
448 }
330449
331 // try self.code.append(??);
450 fn genSub(self: *Function, inst: *ir.Inst.Sub, comptime arch: std.Target.Cpu.Arch) !MCValue {
451 // No side effects, so if it's unreferenced, do nothing.
452 if (inst.base.isUnused())
453 return MCValue.dead;
454 switch (arch) {
455 .x86_64 => {
456 return try self.genX8664BinMath(&inst.base, inst.args.lhs, inst.args.rhs, 5, 0x28);
457 },
458 else => return self.fail(inst.base.src, "TODO implement sub for {}", .{self.target.cpu.arch}),
459 }
460 }
461
462 /// ADD, SUB
463 fn genX8664BinMath(self: *Function, inst: *ir.Inst, op_lhs: *ir.Inst, op_rhs: *ir.Inst, opx: u8, mr: u8) !MCValue {
464 try self.code.ensureCapacity(self.code.items.len + 8);
465
466 const lhs = try self.resolveInst(op_lhs);
467 const rhs = try self.resolveInst(op_rhs);
332468
333 // lhs_reg.release();
334 // rhs_reg.release();
335 return self.fail(inst.base.src, "TODO implement register allocation", .{});
469 // There are 2 operands, destination and source.
470 // Either one, but not both, can be a memory operand.
471 // Source operand can be an immediate, 8 bits or 32 bits.
472 // So, if either one of the operands dies with this instruction, we can use it
473 // as the result MCValue.
474 var dst_mcv: MCValue = undefined;
475 var src_mcv: MCValue = undefined;
476 var src_inst: *ir.Inst = undefined;
477 if (inst.operandDies(0) and lhs.isMutable()) {
478 // LHS dies; use it as the destination.
479 // Both operands cannot be memory.
480 src_inst = op_rhs;
481 if (lhs.isMemory() and rhs.isMemory()) {
482 dst_mcv = try self.copyToNewRegister(op_lhs);
483 src_mcv = rhs;
484 } else {
485 dst_mcv = lhs;
486 src_mcv = rhs;
487 }
488 } else if (inst.operandDies(1) and rhs.isMutable()) {
489 // RHS dies; use it as the destination.
490 // Both operands cannot be memory.
491 src_inst = op_lhs;
492 if (lhs.isMemory() and rhs.isMemory()) {
493 dst_mcv = try self.copyToNewRegister(op_rhs);
494 src_mcv = lhs;
495 } else {
496 dst_mcv = rhs;
497 src_mcv = lhs;
498 }
499 } else {
500 if (lhs.isMemory()) {
501 dst_mcv = try self.copyToNewRegister(op_lhs);
502 src_mcv = rhs;
503 src_inst = op_rhs;
504 } else {
505 dst_mcv = try self.copyToNewRegister(op_rhs);
506 src_mcv = lhs;
507 src_inst = op_lhs;
508 }
509 }
510 // This instruction supports only signed 32-bit immediates at most. If the immediate
511 // value is larger than this, we put it in a register.
512 // A potential opportunity for future optimization here would be keeping track
513 // of the fact that the instruction is available both as an immediate
514 // and as a register.
515 switch (src_mcv) {
516 .immediate => |imm| {
517 if (imm > std.math.maxInt(u31)) {
518 src_mcv = try self.copyToNewRegister(src_inst);
519 }
520 },
521 else => {},
522 }
523
524 try self.genX8664BinMathCode(inst.src, dst_mcv, src_mcv, opx, mr);
525
526 return dst_mcv;
527 }
528
529 fn genX8664BinMathCode(self: *Function, src: usize, dst_mcv: MCValue, src_mcv: MCValue, opx: u8, mr: u8) !void {
530 switch (dst_mcv) {
531 .none => unreachable,
532 .dead, .unreach, .immediate => unreachable,
533 .compare_flags_unsigned => unreachable,
534 .compare_flags_signed => unreachable,
535 .register => |dst_reg_usize| {
536 const dst_reg = @intToEnum(Reg(.x86_64), @intCast(u8, dst_reg_usize));
537 switch (src_mcv) {
538 .none => unreachable,
539 .dead, .unreach => unreachable,
540 .register => |src_reg_usize| {
541 const src_reg = @intToEnum(Reg(.x86_64), @intCast(u8, src_reg_usize));
542 self.rex(.{ .b = dst_reg.isExtended(), .r = src_reg.isExtended(), .w = dst_reg.size() == 64 });
543 self.code.appendSliceAssumeCapacity(&[_]u8{ mr + 0x1, 0xC0 | (@as(u8, src_reg.id() & 0b111) << 3) | @as(u8, dst_reg.id() & 0b111) });
544 },
545 .immediate => |imm| {
546 const imm32 = @intCast(u31, imm); // This case must be handled before calling genX8664BinMathCode.
547 // 81 /opx id
548 if (imm32 <= std.math.maxInt(u7)) {
549 self.rex(.{ .b = dst_reg.isExtended(), .w = dst_reg.size() == 64 });
550 self.code.appendSliceAssumeCapacity(&[_]u8{
551 0x83,
552 0xC0 | (opx << 3) | @truncate(u3, dst_reg.id()),
553 @intCast(u8, imm32),
554 });
555 } else {
556 self.rex(.{ .r = dst_reg.isExtended(), .w = dst_reg.size() == 64 });
557 self.code.appendSliceAssumeCapacity(&[_]u8{
558 0x81,
559 0xC0 | (opx << 3) | @truncate(u3, dst_reg.id()),
560 });
561 std.mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), imm32);
562 }
563 },
564 .embedded_in_code, .memory, .stack_offset => {
565 return self.fail(src, "TODO implement x86 ADD/SUB/CMP source memory", .{});
566 },
567 .compare_flags_unsigned => {
568 return self.fail(src, "TODO implement x86 ADD/SUB/CMP source compare flag (unsigned)", .{});
569 },
570 .compare_flags_signed => {
571 return self.fail(src, "TODO implement x86 ADD/SUB/CMP source compare flag (signed)", .{});
572 },
573 }
574 },
575 .embedded_in_code, .memory, .stack_offset => {
576 return self.fail(src, "TODO implement x86 ADD/SUB/CMP destination memory", .{});
336577 },
337 else => return self.fail(inst.base.src, "TODO implement add for {}", .{self.target.cpu.arch}),
338578 }
339579 }
340580
......@@ -410,17 +650,86 @@ const Function = struct {
410650 }
411651
412652 fn genCmp(self: *Function, inst: *ir.Inst.Cmp, comptime arch: std.Target.Cpu.Arch) !MCValue {
653 // No side effects, so if it's unreferenced, do nothing.
654 if (inst.base.isUnused())
655 return MCValue.dead;
413656 switch (arch) {
657 .x86_64 => {
658 try self.code.ensureCapacity(self.code.items.len + 8);
659
660 const lhs = try self.resolveInst(inst.args.lhs);
661 const rhs = try self.resolveInst(inst.args.rhs);
662
663 // There are 2 operands, destination and source.
664 // Either one, but not both, can be a memory operand.
665 // Source operand can be an immediate, 8 bits or 32 bits.
666 const dst_mcv = if (lhs.isImmediate() or (lhs.isMemory() and rhs.isMemory()))
667 try self.copyToNewRegister(inst.args.lhs)
668 else
669 lhs;
670 // This instruction supports only signed 32-bit immediates at most.
671 const src_mcv = try self.limitImmediateType(inst.args.rhs, i32);
672
673 try self.genX8664BinMathCode(inst.base.src, dst_mcv, src_mcv, 7, 0x38);
674 const info = inst.args.lhs.ty.intInfo(self.target.*);
675 if (info.signed) {
676 return MCValue{.compare_flags_signed = inst.args.op};
677 } else {
678 return MCValue{.compare_flags_unsigned = inst.args.op};
679 }
680 },
414681 else => return self.fail(inst.base.src, "TODO implement cmp for {}", .{self.target.cpu.arch}),
415682 }
416683 }
417684
418685 fn genCondBr(self: *Function, inst: *ir.Inst.CondBr, comptime arch: std.Target.Cpu.Arch) !MCValue {
419686 switch (arch) {
687 .i386, .x86_64 => {
688 try self.code.ensureCapacity(self.code.items.len + 6);
689
690 const cond = try self.resolveInst(inst.args.condition);
691 switch (cond) {
692 .compare_flags_signed => |cmp_op| {
693 // Here we map to the opposite opcode because the jump is to the false branch.
694 const opcode: u8 = switch (cmp_op) {
695 .gte => 0x8c,
696 .gt => 0x8e,
697 .neq => 0x84,
698 .lt => 0x8d,
699 .lte => 0x8f,
700 .eq => 0x85,
701 };
702 return self.genX86CondBr(inst, opcode, arch);
703 },
704 .compare_flags_unsigned => |cmp_op| {
705 // Here we map to the opposite opcode because the jump is to the false branch.
706 const opcode: u8 = switch (cmp_op) {
707 .gte => 0x82,
708 .gt => 0x86,
709 .neq => 0x84,
710 .lt => 0x83,
711 .lte => 0x87,
712 .eq => 0x85,
713 };
714 return self.genX86CondBr(inst, opcode, arch);
715 },
716 else => return self.fail(inst.base.src, "TODO implement condbr {} when condition not already in the compare flags", .{self.target.cpu.arch}),
717 }
718 },
420719 else => return self.fail(inst.base.src, "TODO implement condbr for {}", .{self.target.cpu.arch}),
421720 }
422721 }
423722
723 fn genX86CondBr(self: *Function, inst: *ir.Inst.CondBr, opcode: u8, comptime arch: std.Target.Cpu.Arch) !MCValue {
724 self.code.appendSliceAssumeCapacity(&[_]u8{0x0f, opcode});
725 const reloc = Reloc{ .rel32 = self.code.items.len };
726 self.code.items.len += 4;
727 try self.genBody(inst.args.true_body, arch);
728 try self.performReloc(inst.base.src, reloc);
729 try self.genBody(inst.args.false_body, arch);
730 return MCValue.unreach;
731 }
732
424733 fn genIsNull(self: *Function, inst: *ir.Inst.IsNull, comptime arch: std.Target.Cpu.Arch) !MCValue {
425734 switch (arch) {
426735 else => return self.fail(inst.base.src, "TODO implement isnull for {}", .{self.target.cpu.arch}),
......@@ -435,29 +744,52 @@ const Function = struct {
435744 }
436745 }
437746
438 fn genRelativeFwdJump(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch, amount: u32) !void {
439 switch (arch) {
440 .i386, .x86_64 => {
441 // TODO x86 treats the operands as signed
442 if (amount <= std.math.maxInt(u8)) {
443 try self.code.resize(self.code.items.len + 2);
444 self.code.items[self.code.items.len - 2] = 0xeb;
445 self.code.items[self.code.items.len - 1] = @intCast(u8, amount);
446 } else {
447 try self.code.resize(self.code.items.len + 5);
448 self.code.items[self.code.items.len - 5] = 0xe9; // jmp rel32
449 const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
450 mem.writeIntLittle(u32, imm_ptr, amount);
451 }
747 fn genBlock(self: *Function, inst: *ir.Inst.Block, comptime arch: std.Target.Cpu.Arch) !MCValue {
748 if (inst.base.ty.hasCodeGenBits()) {
749 return self.fail(inst.base.src, "TODO codegen Block with non-void type", .{});
750 }
751 // A block is nothing but a setup to be able to jump to the end.
752 defer inst.codegen.relocs.deinit(self.gpa);
753 try self.genBody(inst.args.body, arch);
754
755 for (inst.codegen.relocs.items) |reloc| try self.performReloc(inst.base.src, reloc);
756
757 return MCValue.none;
758 }
759
760 fn performReloc(self: *Function, src: usize, reloc: Reloc) !void {
761 switch (reloc) {
762 .rel32 => |pos| {
763 const amt = self.code.items.len - (pos + 4);
764 const s32_amt = std.math.cast(i32, amt) catch
765 return self.fail(src, "unable to perform relocation: jump too far", .{});
766 mem.writeIntLittle(i32, self.code.items[pos..][0..4], s32_amt);
452767 },
453 else => return self.fail(src, "TODO implement relative forward jump for {}", .{self.target.cpu.arch}),
454768 }
455769 }
456770
457 fn genBlock(self: *Function, inst: *ir.Inst.Block, comptime arch: std.Target.Cpu.Arch) !MCValue {
771 fn genBr(self: *Function, inst: *ir.Inst.Br, comptime arch: std.Target.Cpu.Arch) !MCValue {
458772 switch (arch) {
459 else => return self.fail(inst.base.src, "TODO implement codegen Block for {}", .{self.target.cpu.arch}),
773 else => return self.fail(inst.base.src, "TODO implement br for {}", .{self.target.cpu.arch}),
774 }
775 }
776
777 fn genBrVoid(self: *Function, inst: *ir.Inst.BrVoid, comptime arch: std.Target.Cpu.Arch) !MCValue {
778 // Emit a jump with a relocation. It will be patched up after the block ends.
779 try inst.args.block.codegen.relocs.ensureCapacity(self.gpa, inst.args.block.codegen.relocs.items.len + 1);
780
781 switch (arch) {
782 .i386, .x86_64 => {
783 // TODO optimization opportunity: figure out when we can emit this as a 2 byte instruction
784 // which is available if the jump is 127 bytes or less forward.
785 try self.code.resize(self.code.items.len + 5);
786 self.code.items[self.code.items.len - 5] = 0xe9; // jmp rel32
787 // Leave the jump offset undefined
788 inst.args.block.codegen.relocs.appendAssumeCapacity(.{ .rel32 = self.code.items.len - 4 });
789 },
790 else => return self.fail(inst.base.src, "TODO implement brvoid for {}", .{self.target.cpu.arch}),
460791 }
792 return .none;
461793 }
462794
463795 fn genAsm(self: *Function, inst: *ir.Inst.Assembly, comptime arch: Target.Cpu.Arch) !MCValue {
......@@ -502,30 +834,38 @@ const Function = struct {
502834 /// resulting REX is meaningful, but will remain the same if it is not.
503835 /// * Deliberately inserting a "meaningless REX" requires explicit usage of
504836 /// 0x40, and cannot be done via this function.
505 fn REX(self: *Function, arg: struct { B: bool = false, W: bool = false, X: bool = false, R: bool = false }) !void {
837 fn rex(self: *Function, arg: struct { b: bool = false, w: bool = false, x: bool = false, r: bool = false }) void {
506838 // From section 2.2.1.2 of the manual, REX is encoded as b0100WRXB.
507839 var value: u8 = 0x40;
508 if (arg.B) {
840 if (arg.b) {
509841 value |= 0x1;
510842 }
511 if (arg.X) {
843 if (arg.x) {
512844 value |= 0x2;
513845 }
514 if (arg.R) {
846 if (arg.r) {
515847 value |= 0x4;
516848 }
517 if (arg.W) {
849 if (arg.w) {
518850 value |= 0x8;
519851 }
520852 if (value != 0x40) {
521 try self.code.append(value);
853 self.code.appendAssumeCapacity(value);
522854 }
523855 }
524856
525857 fn genSetReg(self: *Function, src: usize, comptime arch: Target.Cpu.Arch, reg: Reg(arch), mcv: MCValue) error{ CodegenFail, OutOfMemory }!void {
526858 switch (arch) {
527859 .x86_64 => switch (mcv) {
528 .none, .unreach => unreachable,
860 .dead => unreachable,
861 .none => unreachable,
862 .unreach => unreachable,
863 .compare_flags_unsigned => |op| {
864 return self.fail(src, "TODO set register with compare flags value (unsigned)", .{});
865 },
866 .compare_flags_signed => |op| {
867 return self.fail(src, "TODO set register with compare flags value (signed)", .{});
868 },
529869 .immediate => |x| {
530870 if (reg.size() != 64) {
531871 return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
......@@ -544,11 +884,11 @@ const Function = struct {
544884 // If we're accessing e.g. r8d, we need to use a REX prefix before the actual operation. Since
545885 // this is a 32-bit operation, the W flag is set to zero. X is also zero, as we're not using a SIB.
546886 // Both R and B are set, as we're extending, in effect, the register bits *and* the operand.
547 try self.REX(.{ .R = reg.isExtended(), .B = reg.isExtended() });
887 try self.code.ensureCapacity(self.code.items.len + 3);
888 self.rex(.{ .r = reg.isExtended(), .b = reg.isExtended() });
548889 const id = @as(u8, reg.id() & 0b111);
549 return self.code.appendSlice(&[_]u8{
550 0x31, 0xC0 | id << 3 | id,
551 });
890 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x31, 0xC0 | id << 3 | id });
891 return;
552892 }
553893 if (x <= std.math.maxInt(u32)) {
554894 // Next best case: if we set the lower four bytes, the upper four will be zeroed.
......@@ -581,9 +921,9 @@ const Function = struct {
581921 // Since we always need a REX here, let's just check if we also need to set REX.B.
582922 //
583923 // In this case, the encoding of the REX byte is 0b0100100B
584
585 try self.REX(.{ .W = true, .B = reg.isExtended() });
586 try self.code.resize(self.code.items.len + 9);
924 try self.code.ensureCapacity(self.code.items.len + 10);
925 self.rex(.{ .w = true, .b = reg.isExtended() });
926 self.code.items.len += 9;
587927 self.code.items[self.code.items.len - 9] = 0xB8 | @as(u8, reg.id() & 0b111);
588928 const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8];
589929 mem.writeIntLittle(u64, imm_ptr, x);
......@@ -594,13 +934,13 @@ const Function = struct {
594934 }
595935 // We need the offset from RIP in a signed i32 twos complement.
596936 // The instruction is 7 bytes long and RIP points to the next instruction.
597 //
937 try self.code.ensureCapacity(self.code.items.len + 7);
598938 // 64-bit LEA is encoded as REX.W 8D /r. If the register is extended, the REX byte is modified,
599939 // but the operation size is unchanged. Since we're using a disp32, we want mode 0 and lower three
600940 // bits as five.
601941 // REX 0x8D 0b00RRR101, where RRR is the lower three bits of the id.
602 try self.REX(.{ .W = true, .B = reg.isExtended() });
603 try self.code.resize(self.code.items.len + 6);
942 self.rex(.{ .w = true, .b = reg.isExtended() });
943 self.code.items.len += 6;
604944 const rip = self.code.items.len;
605945 const big_offset = @intCast(i64, code_offset) - @intCast(i64, rip);
606946 const offset = @intCast(i32, big_offset);
......@@ -620,9 +960,10 @@ const Function = struct {
620960 // If the *source* is extended, the B field must be 1.
621961 // Since the register is being accessed directly, the R/M mode is three. The reg field (the middle
622962 // three bits) contain the destination, and the R/M field (the lower three bits) contain the source.
623 try self.REX(.{ .W = true, .R = reg.isExtended(), .B = src_reg.isExtended() });
963 try self.code.ensureCapacity(self.code.items.len + 3);
964 self.rex(.{ .w = true, .r = reg.isExtended(), .b = src_reg.isExtended() });
624965 const R = 0xC0 | (@as(u8, reg.id() & 0b111) << 3) | @as(u8, src_reg.id() & 0b111);
625 try self.code.appendSlice(&[_]u8{ 0x8B, R });
966 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, R });
626967 },
627968 .memory => |x| {
628969 if (reg.size() != 64) {
......@@ -636,14 +977,14 @@ const Function = struct {
636977 // The SIB must be 0x25, to indicate a disp32 with no scaled index.
637978 // 0b00RRR100, where RRR is the lower three bits of the register ID.
638979 // The instruction is thus eight bytes; REX 0x8B 0b00RRR100 0x25 followed by a four-byte disp32.
639 try self.REX(.{ .W = true, .B = reg.isExtended() });
640 try self.code.resize(self.code.items.len + 7);
641 const r = 0x04 | (@as(u8, reg.id() & 0b111) << 3);
642 self.code.items[self.code.items.len - 7] = 0x8B;
643 self.code.items[self.code.items.len - 6] = r;
644 self.code.items[self.code.items.len - 5] = 0x25;
645 const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
646 mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x));
980 try self.code.ensureCapacity(self.code.items.len + 8);
981 self.rex(.{ .w = true, .b = reg.isExtended() });
982 self.code.appendSliceAssumeCapacity(&[_]u8{
983 0x8B,
984 0x04 | (@as(u8, reg.id() & 0b111) << 3), // R
985 0x25,
986 });
987 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), @intCast(u32, x));
647988 } else {
648989 // If this is RAX, we can use a direct load; otherwise, we need to load the address, then indirectly load
649990 // the value.
......@@ -674,15 +1015,15 @@ const Function = struct {
6741015 // Currently, we're only allowing 64-bit registers, so we need the `REX.W 8B /r` variant.
6751016 // TODO: determine whether to allow other sized registers, and if so, handle them properly.
6761017 // This operation requires three bytes: REX 0x8B R/M
677 //
1018 try self.code.ensureCapacity(self.code.items.len + 3);
6781019 // For this operation, we want R/M mode *zero* (use register indirectly), and the two register
6791020 // values must match. Thus, it's 00ABCABC where ABC is the lower three bits of the register ID.
6801021 //
6811022 // Furthermore, if this is an extended register, both B and R must be set in the REX byte, as *both*
6821023 // register operands need to be marked as extended.
683 try self.REX(.{ .W = true, .B = reg.isExtended(), .R = reg.isExtended() });
1024 self.rex(.{ .w = true, .b = reg.isExtended(), .r = reg.isExtended() });
6841025 const RM = (@as(u8, reg.id() & 0b111) << 3) | @truncate(u3, reg.id());
685 try self.code.appendSlice(&[_]u8{ 0x8B, RM });
1026 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, RM });
6861027 }
6871028 }
6881029 },
......@@ -705,22 +1046,58 @@ const Function = struct {
7051046 }
7061047
7071048 fn resolveInst(self: *Function, inst: *ir.Inst) !MCValue {
708 if (self.inst_table.get(inst)) |mcv| {
709 return mcv;
710 }
1049 // Constants have static lifetimes, so they are always memoized in the outer most table.
7111050 if (inst.cast(ir.Inst.Constant)) |const_inst| {
712 const mcvalue = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
713 try self.inst_table.putNoClobber(inst, mcvalue);
714 return mcvalue;
715 } else {
716 return self.inst_table.get(inst).?;
1051 const branch = &self.branch_stack.items[0];
1052 const gop = try branch.inst_table.getOrPut(self.gpa, inst);
1053 if (!gop.found_existing) {
1054 gop.entry.value = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
1055 }
1056 return gop.entry.value;
1057 }
1058
1059 // Treat each stack item as a "layer" on top of the previous one.
1060 var i: usize = self.branch_stack.items.len;
1061 while (true) {
1062 i -= 1;
1063 if (self.branch_stack.items[i].inst_table.get(inst)) |mcv| {
1064 return mcv;
1065 }
7171066 }
7181067 }
7191068
1069 fn copyToNewRegister(self: *Function, inst: *ir.Inst) !MCValue {
1070 return self.fail(inst.src, "TODO implement copyToNewRegister", .{});
1071 }
1072
1073 /// If the MCValue is an immediate, and it does not fit within this type,
1074 /// we put it in a register.
1075 /// A potential opportunity for future optimization here would be keeping track
1076 /// of the fact that the instruction is available both as an immediate
1077 /// and as a register.
1078 fn limitImmediateType(self: *Function, inst: *ir.Inst, comptime T: type) !MCValue {
1079 const mcv = try self.resolveInst(inst);
1080 const ti = @typeInfo(T).Int;
1081 switch (mcv) {
1082 .immediate => |imm| {
1083 // This immediate is unsigned.
1084 const U = @Type(.{ .Int = .{
1085 .bits = ti.bits - @boolToInt(ti.is_signed),
1086 .is_signed = false,
1087 }});
1088 if (imm >= std.math.maxInt(U)) {
1089 return self.copyToNewRegister(inst);
1090 }
1091 },
1092 else => {},
1093 }
1094 return mcv;
1095 }
1096
1097
7201098 fn genTypedValue(self: *Function, src: usize, typed_value: TypedValue) !MCValue {
7211099 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
7221100 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
723 const allocator = self.code.allocator;
7241101 switch (typed_value.ty.zigTypeTag()) {
7251102 .Pointer => {
7261103 if (typed_value.val.cast(Value.Payload.DeclRef)) |payload| {
......@@ -747,7 +1124,7 @@ const Function = struct {
7471124 fn fail(self: *Function, src: usize, comptime format: []const u8, args: var) error{ CodegenFail, OutOfMemory } {
7481125 @setCold(true);
7491126 assert(self.err_msg == null);
750 self.err_msg = try ErrorMsg.create(self.code.allocator, src, format, args);
1127 self.err_msg = try ErrorMsg.create(self.bin_file.allocator, src, format, args);
7511128 return error.CodegenFail;
7521129 }
7531130};
src-self-hosted/ir.zig+68-1
......@@ -2,6 +2,8 @@ const std = @import("std");
22const Value = @import("value.zig").Value;
33const Type = @import("type.zig").Type;
44const Module = @import("Module.zig");
5const assert = std.debug.assert;
6const codegen = @import("codegen.zig");
57
68/// These are in-memory, analyzed instructions. See `zir.Inst` for the representation
79/// of instructions that correspond to the ZIR text format.
......@@ -10,17 +12,43 @@ const Module = @import("Module.zig");
1012/// a memory location for the value to survive after a const instruction.
1113pub const Inst = struct {
1214 tag: Tag,
15 /// Each bit represents the index of an `Inst` parameter in the `args` field.
16 /// If a bit is set, it marks the end of the lifetime of the corresponding
17 /// instruction parameter. For example, 0b000_00101 means that the first and
18 /// third `Inst` parameters' lifetimes end after this instruction, and will
19 /// not have any more following references.
20 /// The most significant bit being set means that the instruction itself is
21 /// never referenced, in other words its lifetime ends as soon as it finishes.
22 /// If bit 7 (0b1xxx_xxxx) is set, it means this instruction itself is unreferenced.
23 /// If bit 6 (0bx1xx_xxxx) is set, it means this is a special case and the
24 /// lifetimes of operands are encoded elsewhere.
25 deaths: u8 = undefined,
1326 ty: Type,
1427 /// Byte offset into the source.
1528 src: usize,
1629
30 pub fn isUnused(self: Inst) bool {
31 return (self.deaths & 0b1000_0000) != 0;
32 }
33
34 pub fn operandDies(self: Inst, index: u3) bool {
35 assert(index < 6);
36 return @truncate(u1, self.deaths << index) != 0;
37 }
38
39 pub fn specialOperandDeaths(self: Inst) bool {
40 return (self.deaths & 0b1000_0000) != 0;
41 }
42
1743 pub const Tag = enum {
1844 add,
1945 arg,
2046 assembly,
2147 bitcast,
2248 block,
49 br,
2350 breakpoint,
51 brvoid,
2452 call,
2553 cmp,
2654 condbr,
......@@ -30,6 +58,7 @@ pub const Inst = struct {
3058 ptrtoint,
3159 ret,
3260 retvoid,
61 sub,
3362 unreach,
3463
3564 /// Returns whether the instruction is one of the control flow "noreturn" types.
......@@ -43,14 +72,17 @@ pub const Inst = struct {
4372 .bitcast,
4473 .block,
4574 .breakpoint,
75 .call,
4676 .cmp,
4777 .constant,
4878 .isnonnull,
4979 .isnull,
5080 .ptrtoint,
51 .call,
81 .sub,
5282 => false,
5383
84 .br,
85 .brvoid,
5486 .condbr,
5587 .ret,
5688 .retvoid,
......@@ -128,6 +160,17 @@ pub const Inst = struct {
128160 args: struct {
129161 body: Body,
130162 },
163 /// This memory is reserved for codegen code to do whatever it needs to here.
164 codegen: codegen.BlockData = .{},
165 };
166
167 pub const Br = struct {
168 pub const base_tag = Tag.br;
169 base: Inst,
170 args: struct {
171 block: *Block,
172 operand: *Inst,
173 },
131174 };
132175
133176 pub const Breakpoint = struct {
......@@ -136,6 +179,14 @@ pub const Inst = struct {
136179 args: void,
137180 };
138181
182 pub const BrVoid = struct {
183 pub const base_tag = Tag.brvoid;
184 base: Inst,
185 args: struct {
186 block: *Block,
187 },
188 };
189
139190 pub const Call = struct {
140191 pub const base_tag = Tag.call;
141192 base: Inst,
......@@ -165,6 +216,12 @@ pub const Inst = struct {
165216 true_body: Body,
166217 false_body: Body,
167218 },
219 /// Set of instructions whose lifetimes end at the start of one of the branches.
220 /// The `true` branch is first: `deaths[0..true_death_count]`.
221 /// The `false` branch is next: `(deaths + true_death_count)[..false_death_count]`.
222 deaths: [*]*Inst = undefined,
223 true_death_count: u32 = 0,
224 false_death_count: u32 = 0,
168225 };
169226
170227 pub const Constant = struct {
......@@ -215,6 +272,16 @@ pub const Inst = struct {
215272 args: void,
216273 };
217274
275 pub const Sub = struct {
276 pub const base_tag = Tag.sub;
277 base: Inst,
278
279 args: struct {
280 lhs: *Inst,
281 rhs: *Inst,
282 },
283 };
284
218285 pub const Unreach = struct {
219286 pub const base_tag = Tag.unreach;
220287 base: Inst,
src-self-hosted/link.zig+29-15
......@@ -206,6 +206,19 @@ pub const File = struct {
206206 };
207207 }
208208
209 /// Must be called only after a successful call to `updateDecl`.
210 pub fn updateDeclExports(
211 base: *File,
212 module: *Module,
213 decl: *const Module.Decl,
214 exports: []const *Module.Export,
215 ) !void {
216 switch (base.tag) {
217 .Elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
218 .C => return {},
219 }
220 }
221
209222 pub const Tag = enum {
210223 Elf,
211224 C,
......@@ -248,7 +261,7 @@ pub const File = struct {
248261 pub fn updateDecl(self: *File.C, module: *Module, decl: *Module.Decl) !void {
249262 cgen.generate(self, decl) catch |err| {
250263 if (err == error.CGenFailure) {
251 try module.failed_decls.put(decl, self.error_msg);
264 try module.failed_decls.put(module.gpa, decl, self.error_msg);
252265 }
253266 return err;
254267 };
......@@ -566,7 +579,7 @@ pub const File = struct {
566579 const file_size = self.options.program_code_size_hint;
567580 const p_align = 0x1000;
568581 const off = self.findFreeSpace(file_size, p_align);
569 //std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
582 std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
570583 try self.program_headers.append(self.allocator, .{
571584 .p_type = elf.PT_LOAD,
572585 .p_offset = off,
......@@ -587,7 +600,7 @@ pub const File = struct {
587600 // page align.
588601 const p_align = 0x1000;
589602 const off = self.findFreeSpace(file_size, p_align);
590 //std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
603 std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
591604 // TODO instead of hard coding the vaddr, make a function to find a vaddr to put things at.
592605 // we'll need to re-use that function anyway, in case the GOT grows and overlaps something
593606 // else in virtual memory.
......@@ -609,7 +622,7 @@ pub const File = struct {
609622 assert(self.shstrtab.items.len == 0);
610623 try self.shstrtab.append(self.allocator, 0); // need a 0 at position 0
611624 const off = self.findFreeSpace(self.shstrtab.items.len, 1);
612 //std.log.debug(.link, "found shstrtab free space 0x{x} to 0x{x}\n", .{ off, off + self.shstrtab.items.len });
625 std.log.debug(.link, "found shstrtab free space 0x{x} to 0x{x}\n", .{ off, off + self.shstrtab.items.len });
613626 try self.sections.append(self.allocator, .{
614627 .sh_name = try self.makeString(".shstrtab"),
615628 .sh_type = elf.SHT_STRTAB,
......@@ -667,7 +680,7 @@ pub const File = struct {
667680 const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym);
668681 const file_size = self.options.symbol_count_hint * each_size;
669682 const off = self.findFreeSpace(file_size, min_align);
670 //std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
683 std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
671684
672685 try self.sections.append(self.allocator, .{
673686 .sh_name = try self.makeString(".symtab"),
......@@ -783,7 +796,7 @@ pub const File = struct {
783796 shstrtab_sect.sh_offset = self.findFreeSpace(needed_size, 1);
784797 }
785798 shstrtab_sect.sh_size = needed_size;
786 //std.log.debug(.link, "shstrtab start=0x{x} end=0x{x}\n", .{ shstrtab_sect.sh_offset, shstrtab_sect.sh_offset + needed_size });
799 std.log.debug(.link, "shstrtab start=0x{x} end=0x{x}\n", .{ shstrtab_sect.sh_offset, shstrtab_sect.sh_offset + needed_size });
787800
788801 try self.file.?.pwriteAll(self.shstrtab.items, shstrtab_sect.sh_offset);
789802 if (!self.shdr_table_dirty) {
......@@ -829,7 +842,7 @@ pub const File = struct {
829842
830843 for (buf) |*shdr, i| {
831844 shdr.* = self.sections.items[i];
832 //std.log.debug(.link, "writing section {}\n", .{shdr.*});
845 std.log.debug(.link, "writing section {}\n", .{shdr.*});
833846 if (foreign_endian) {
834847 bswapAllFields(elf.Elf64_Shdr, shdr);
835848 }
......@@ -840,6 +853,7 @@ pub const File = struct {
840853 self.shdr_table_dirty = false;
841854 }
842855 if (self.entry_addr == null and self.options.output_mode == .Exe) {
856 std.log.debug(.link, "no_entry_point_found = true\n", .{});
843857 self.error_flags.no_entry_point_found = true;
844858 } else {
845859 self.error_flags.no_entry_point_found = false;
......@@ -1153,10 +1167,10 @@ pub const File = struct {
11531167 try self.offset_table_free_list.ensureCapacity(self.allocator, self.local_symbols.items.len);
11541168
11551169 if (self.local_symbol_free_list.popOrNull()) |i| {
1156 //std.log.debug(.link, "reusing symbol index {} for {}\n", .{i, decl.name});
1170 std.log.debug(.link, "reusing symbol index {} for {}\n", .{i, decl.name});
11571171 decl.link.local_sym_index = i;
11581172 } else {
1159 //std.log.debug(.link, "allocating symbol index {} for {}\n", .{self.local_symbols.items.len, decl.name});
1173 std.log.debug(.link, "allocating symbol index {} for {}\n", .{self.local_symbols.items.len, decl.name});
11601174 decl.link.local_sym_index = @intCast(u32, self.local_symbols.items.len);
11611175 _ = self.local_symbols.addOneAssumeCapacity();
11621176 }
......@@ -1204,7 +1218,7 @@ pub const File = struct {
12041218 .appended => code_buffer.items,
12051219 .fail => |em| {
12061220 decl.analysis = .codegen_failure;
1207 try module.failed_decls.put(decl, em);
1221 try module.failed_decls.put(module.gpa, decl, em);
12081222 return;
12091223 },
12101224 };
......@@ -1224,11 +1238,11 @@ pub const File = struct {
12241238 !mem.isAlignedGeneric(u64, local_sym.st_value, required_alignment);
12251239 if (need_realloc) {
12261240 const vaddr = try self.growTextBlock(&decl.link, code.len, required_alignment);
1227 //std.log.debug(.link, "growing {} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr });
1241 std.log.debug(.link, "growing {} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr });
12281242 if (vaddr != local_sym.st_value) {
12291243 local_sym.st_value = vaddr;
12301244
1231 //std.log.debug(.link, " (writing new offset table entry)\n", .{});
1245 std.log.debug(.link, " (writing new offset table entry)\n", .{});
12321246 self.offset_table.items[decl.link.offset_table_index] = vaddr;
12331247 try self.writeOffsetTableEntry(decl.link.offset_table_index);
12341248 }
......@@ -1246,7 +1260,7 @@ pub const File = struct {
12461260 const decl_name = mem.spanZ(decl.name);
12471261 const name_str_index = try self.makeString(decl_name);
12481262 const vaddr = try self.allocateTextBlock(&decl.link, code.len, required_alignment);
1249 //std.log.debug(.link, "allocated text block for {} at 0x{x}\n", .{ decl_name, vaddr });
1263 std.log.debug(.link, "allocated text block for {} at 0x{x}\n", .{ decl_name, vaddr });
12501264 errdefer self.freeTextBlock(&decl.link);
12511265
12521266 local_sym.* = .{
......@@ -1290,7 +1304,7 @@ pub const File = struct {
12901304 for (exports) |exp| {
12911305 if (exp.options.section) |section_name| {
12921306 if (!mem.eql(u8, section_name, ".text")) {
1293 try module.failed_exports.ensureCapacity(module.failed_exports.items().len + 1);
1307 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
12941308 module.failed_exports.putAssumeCapacityNoClobber(
12951309 exp,
12961310 try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: ExportOptions.section", .{}),
......@@ -1308,7 +1322,7 @@ pub const File = struct {
13081322 },
13091323 .Weak => elf.STB_WEAK,
13101324 .LinkOnce => {
1311 try module.failed_exports.ensureCapacity(module.failed_exports.items().len + 1);
1325 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
13121326 module.failed_exports.putAssumeCapacityNoClobber(
13131327 exp,
13141328 try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: GlobalLinkage.LinkOnce", .{}),
src-self-hosted/liveness.zig created+139
......@@ -0,0 +1,139 @@
1const std = @import("std");
2const ir = @import("ir.zig");
3const trace = @import("tracy.zig").trace;
4
5/// Perform Liveness Analysis over the `Body`. Each `Inst` will have its `deaths` field populated.
6pub fn analyze(
7 /// Used for temporary storage during the analysis.
8 gpa: *std.mem.Allocator,
9 /// Used to tack on extra allocations in the same lifetime as the existing instructions.
10 arena: *std.mem.Allocator,
11 body: ir.Body,
12) error{OutOfMemory}!void {
13 const tracy = trace(@src());
14 defer tracy.end();
15
16 var table = std.AutoHashMap(*ir.Inst, void).init(gpa);
17 defer table.deinit();
18 try table.ensureCapacity(body.instructions.len);
19 try analyzeWithTable(arena, &table, body);
20}
21
22fn analyzeWithTable(arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void), body: ir.Body) error{OutOfMemory}!void {
23 var i: usize = body.instructions.len;
24
25 while (i != 0) {
26 i -= 1;
27 const base = body.instructions[i];
28 try analyzeInstGeneric(arena, table, base);
29 }
30}
31
32fn analyzeInstGeneric(arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void), base: *ir.Inst) error{OutOfMemory}!void {
33 // Obtain the corresponding instruction type based on the tag type.
34 inline for (std.meta.declarations(ir.Inst)) |decl| {
35 switch (decl.data) {
36 .Type => |T| {
37 if (@hasDecl(T, "base_tag")) {
38 if (T.base_tag == base.tag) {
39 return analyzeInst(arena, table, T, @fieldParentPtr(T, "base", base));
40 }
41 }
42 },
43 else => {},
44 }
45 }
46 unreachable;
47}
48
49fn analyzeInst(arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void), comptime T: type, inst: *T) error{OutOfMemory}!void {
50 inst.base.deaths = 0;
51
52 switch (T) {
53 ir.Inst.Constant => return,
54 ir.Inst.Block => {
55 try analyzeWithTable(arena, table, inst.args.body);
56 // We let this continue so that it can possibly mark the block as
57 // unreferenced below.
58 },
59 ir.Inst.CondBr => {
60 var true_table = std.AutoHashMap(*ir.Inst, void).init(table.allocator);
61 defer true_table.deinit();
62 try true_table.ensureCapacity(inst.args.true_body.instructions.len);
63 try analyzeWithTable(arena, &true_table, inst.args.true_body);
64
65 var false_table = std.AutoHashMap(*ir.Inst, void).init(table.allocator);
66 defer false_table.deinit();
67 try false_table.ensureCapacity(inst.args.false_body.instructions.len);
68 try analyzeWithTable(arena, &false_table, inst.args.false_body);
69
70 // Each death that occurs inside one branch, but not the other, needs
71 // to be added as a death immediately upon entering the other branch.
72 // During the iteration of the table, we additionally propagate the
73 // deaths to the parent table.
74 var true_entry_deaths = std.ArrayList(*ir.Inst).init(table.allocator);
75 defer true_entry_deaths.deinit();
76 var false_entry_deaths = std.ArrayList(*ir.Inst).init(table.allocator);
77 defer false_entry_deaths.deinit();
78 {
79 var it = false_table.iterator();
80 while (it.next()) |entry| {
81 const false_death = entry.key;
82 if (!true_table.contains(false_death)) {
83 try true_entry_deaths.append(false_death);
84 // Here we are only adding to the parent table if the following iteration
85 // would miss it.
86 try table.putNoClobber(false_death, {});
87 }
88 }
89 }
90 {
91 var it = true_table.iterator();
92 while (it.next()) |entry| {
93 const true_death = entry.key;
94 try table.putNoClobber(true_death, {});
95 if (!false_table.contains(true_death)) {
96 try false_entry_deaths.append(true_death);
97 }
98 }
99 }
100 inst.true_death_count = std.math.cast(@TypeOf(inst.true_death_count), true_entry_deaths.items.len) catch return error.OutOfMemory;
101 inst.false_death_count = std.math.cast(@TypeOf(inst.false_death_count), false_entry_deaths.items.len) catch return error.OutOfMemory;
102 const allocated_slice = try arena.alloc(*ir.Inst, true_entry_deaths.items.len + false_entry_deaths.items.len);
103 inst.deaths = allocated_slice.ptr;
104
105 // Continue on with the instruction analysis. The following code will find the condition
106 // instruction, and the deaths flag for the CondBr instruction will indicate whether the
107 // condition's lifetime ends immediately before entering any branch.
108 },
109 else => {},
110 }
111
112 if (!table.contains(&inst.base)) {
113 // No tombstone for this instruction means it is never referenced,
114 // and its birth marks its own death. Very metal 🤘
115 inst.base.deaths |= 1 << 7;
116 }
117
118 const Args = ir.Inst.Args(T);
119 if (Args == void) {
120 return;
121 }
122
123 comptime var arg_index: usize = 0;
124 inline for (std.meta.fields(Args)) |field| {
125 if (field.field_type == *ir.Inst) {
126 if (arg_index >= 6) {
127 @compileError("out of bits to mark deaths of operands");
128 }
129 const prev = try table.fetchPut(@field(inst.args, field.name), {});
130 if (prev == null) {
131 // Death.
132 inst.base.deaths |= 1 << arg_index;
133 }
134 arg_index += 1;
135 }
136 }
137
138 std.log.debug(.liveness, "analyze {}: 0b{b}\n", .{inst.base.tag, inst.base.deaths});
139}
src-self-hosted/main.zig+5-2
......@@ -50,7 +50,10 @@ pub fn log(
5050 const scope_prefix = "(" ++ switch (scope) {
5151 // Uncomment to hide logs
5252 //.compiler,
53 .link => return,
53 .module,
54 .liveness,
55 .link,
56 => return,
5457
5558 else => @tagName(scope),
5659 } ++ "): ";
......@@ -510,7 +513,7 @@ fn updateModule(gpa: *Allocator, module: *Module, zir_out_path: ?[]const u8) !vo
510513 const update_nanos = timer.read();
511514
512515 var errors = try module.getAllErrorsAlloc();
513 defer errors.deinit(module.allocator);
516 defer errors.deinit(module.gpa);
514517
515518 if (errors.list.len != 0) {
516519 for (errors.list) |full_err_msg| {
src-self-hosted/zir.zig+220-62
......@@ -38,6 +38,8 @@ pub const Inst = struct {
3838 arg,
3939 /// A labeled block of code, which can return a value.
4040 block,
41 /// Return a value from a `Block`.
42 @"break",
4143 breakpoint,
4244 /// Same as `break` but without an operand; the operand is assumed to be the void value.
4345 breakvoid,
......@@ -57,6 +59,7 @@ pub const Inst = struct {
5759 /// String Literal. Makes an anonymous Decl and then takes a pointer to it.
5860 str,
5961 int,
62 inttype,
6063 ptrtoint,
6164 fieldptr,
6265 deref,
......@@ -73,6 +76,7 @@ pub const Inst = struct {
7376 bitcast,
7477 elemptr,
7578 add,
79 sub,
7680 cmp,
7781 condbr,
7882 isnull,
......@@ -83,6 +87,7 @@ pub const Inst = struct {
8387 return switch (tag) {
8488 .arg => Arg,
8589 .block => Block,
90 .@"break" => Break,
8691 .breakpoint => Breakpoint,
8792 .breakvoid => BreakVoid,
8893 .call => Call,
......@@ -94,6 +99,7 @@ pub const Inst = struct {
9499 .@"const" => Const,
95100 .str => Str,
96101 .int => Int,
102 .inttype => IntType,
97103 .ptrtoint => PtrToInt,
98104 .fieldptr => FieldPtr,
99105 .deref => Deref,
......@@ -110,6 +116,7 @@ pub const Inst = struct {
110116 .bitcast => BitCast,
111117 .elemptr => ElemPtr,
112118 .add => Add,
119 .sub => Sub,
113120 .cmp => Cmp,
114121 .condbr => CondBr,
115122 .isnull => IsNull,
......@@ -139,12 +146,22 @@ pub const Inst = struct {
139146 base: Inst,
140147
141148 positionals: struct {
142 label: []const u8,
143149 body: Module.Body,
144150 },
145151 kw_args: struct {},
146152 };
147153
154 pub const Break = struct {
155 pub const base_tag = Tag.@"break";
156 base: Inst,
157
158 positionals: struct {
159 block: *Block,
160 operand: *Inst,
161 },
162 kw_args: struct {},
163 };
164
148165 pub const Breakpoint = struct {
149166 pub const base_tag = Tag.breakpoint;
150167 base: Inst,
......@@ -158,7 +175,7 @@ pub const Inst = struct {
158175 base: Inst,
159176
160177 positionals: struct {
161 label: []const u8,
178 block: *Block,
162179 },
163180 kw_args: struct {},
164181 };
......@@ -367,6 +384,17 @@ pub const Inst = struct {
367384 },
368385 };
369386
387 pub const IntType = struct {
388 pub const base_tag = Tag.inttype;
389 base: Inst,
390
391 positionals: struct {
392 signed: *Inst,
393 bits: *Inst,
394 },
395 kw_args: struct {},
396 };
397
370398 pub const Export = struct {
371399 pub const base_tag = Tag.@"export";
372400 base: Inst,
......@@ -512,6 +540,19 @@ pub const Inst = struct {
512540 kw_args: struct {},
513541 };
514542
543 pub const Sub = struct {
544 pub const base_tag = Tag.sub;
545 base: Inst,
546
547 positionals: struct {
548 lhs: *Inst,
549 rhs: *Inst,
550 },
551 kw_args: struct {},
552 };
553
554 /// TODO get rid of the op positional arg and make that data part of
555 /// the base Inst tag.
515556 pub const Cmp = struct {
516557 pub const base_tag = Tag.cmp;
517558 base: Inst,
......@@ -582,8 +623,6 @@ pub const Module = struct {
582623 self.writeToStream(std.heap.page_allocator, std.io.getStdErr().outStream()) catch {};
583624 }
584625
585 const InstPtrTable = std.AutoHashMap(*Inst, struct { inst: *Inst, index: ?usize, name: []const u8 });
586
587626 const DeclAndIndex = struct {
588627 decl: *Decl,
589628 index: usize,
......@@ -617,80 +656,100 @@ pub const Module = struct {
617656 /// The allocator is used for temporary storage, but this function always returns
618657 /// with no resources allocated.
619658 pub fn writeToStream(self: Module, allocator: *Allocator, stream: var) !void {
620 // First, build a map of *Inst to @ or % indexes
621 var inst_table = InstPtrTable.init(allocator);
622 defer inst_table.deinit();
659 var write = Writer{
660 .module = &self,
661 .inst_table = InstPtrTable.init(allocator),
662 .block_table = std.AutoHashMap(*Inst.Block, []const u8).init(allocator),
663 .arena = std.heap.ArenaAllocator.init(allocator),
664 .indent = 2,
665 };
666 defer write.arena.deinit();
667 defer write.inst_table.deinit();
668 defer write.block_table.deinit();
623669
624 try inst_table.ensureCapacity(self.decls.len);
670 // First, build a map of *Inst to @ or % indexes
671 try write.inst_table.ensureCapacity(self.decls.len);
625672
626673 for (self.decls) |decl, decl_i| {
627 try inst_table.putNoClobber(decl.inst, .{ .inst = decl.inst, .index = null, .name = decl.name });
674 try write.inst_table.putNoClobber(decl.inst, .{ .inst = decl.inst, .index = null, .name = decl.name });
628675
629676 if (decl.inst.cast(Inst.Fn)) |fn_inst| {
630677 for (fn_inst.positionals.body.instructions) |inst, inst_i| {
631 try inst_table.putNoClobber(inst, .{ .inst = inst, .index = inst_i, .name = undefined });
678 try write.inst_table.putNoClobber(inst, .{ .inst = inst, .index = inst_i, .name = undefined });
632679 }
633680 }
634681 }
635682
636683 for (self.decls) |decl, i| {
637684 try stream.print("@{} ", .{decl.name});
638 try self.writeInstToStream(stream, decl.inst, &inst_table);
685 try write.writeInstToStream(stream, decl.inst);
639686 try stream.writeByte('\n');
640687 }
641688 }
642689
690};
691
692const InstPtrTable = std.AutoHashMap(*Inst, struct { inst: *Inst, index: ?usize, name: []const u8 });
693
694const Writer = struct {
695 module: *const Module,
696 inst_table: InstPtrTable,
697 block_table: std.AutoHashMap(*Inst.Block, []const u8),
698 arena: std.heap.ArenaAllocator,
699 indent: usize,
700
643701 fn writeInstToStream(
644 self: Module,
702 self: *Writer,
645703 stream: var,
646704 inst: *Inst,
647 inst_table: *const InstPtrTable,
648 ) @TypeOf(stream).Error!void {
705 ) (@TypeOf(stream).Error || error{OutOfMemory})!void {
649706 // TODO I tried implementing this with an inline for loop and hit a compiler bug
650707 switch (inst.tag) {
651 .arg => return self.writeInstToStreamGeneric(stream, .arg, inst, inst_table),
652 .block => return self.writeInstToStreamGeneric(stream, .block, inst, inst_table),
653 .breakpoint => return self.writeInstToStreamGeneric(stream, .breakpoint, inst, inst_table),
654 .breakvoid => return self.writeInstToStreamGeneric(stream, .breakvoid, inst, inst_table),
655 .call => return self.writeInstToStreamGeneric(stream, .call, inst, inst_table),
656 .declref => return self.writeInstToStreamGeneric(stream, .declref, inst, inst_table),
657 .declref_str => return self.writeInstToStreamGeneric(stream, .declref_str, inst, inst_table),
658 .declval => return self.writeInstToStreamGeneric(stream, .declval, inst, inst_table),
659 .declval_in_module => return self.writeInstToStreamGeneric(stream, .declval_in_module, inst, inst_table),
660 .compileerror => return self.writeInstToStreamGeneric(stream, .compileerror, inst, inst_table),
661 .@"const" => return self.writeInstToStreamGeneric(stream, .@"const", inst, inst_table),
662 .str => return self.writeInstToStreamGeneric(stream, .str, inst, inst_table),
663 .int => return self.writeInstToStreamGeneric(stream, .int, inst, inst_table),
664 .ptrtoint => return self.writeInstToStreamGeneric(stream, .ptrtoint, inst, inst_table),
665 .fieldptr => return self.writeInstToStreamGeneric(stream, .fieldptr, inst, inst_table),
666 .deref => return self.writeInstToStreamGeneric(stream, .deref, inst, inst_table),
667 .as => return self.writeInstToStreamGeneric(stream, .as, inst, inst_table),
668 .@"asm" => return self.writeInstToStreamGeneric(stream, .@"asm", inst, inst_table),
669 .@"unreachable" => return self.writeInstToStreamGeneric(stream, .@"unreachable", inst, inst_table),
670 .@"return" => return self.writeInstToStreamGeneric(stream, .@"return", inst, inst_table),
671 .returnvoid => return self.writeInstToStreamGeneric(stream, .returnvoid, inst, inst_table),
672 .@"fn" => return self.writeInstToStreamGeneric(stream, .@"fn", inst, inst_table),
673 .@"export" => return self.writeInstToStreamGeneric(stream, .@"export", inst, inst_table),
674 .primitive => return self.writeInstToStreamGeneric(stream, .primitive, inst, inst_table),
675 .fntype => return self.writeInstToStreamGeneric(stream, .fntype, inst, inst_table),
676 .intcast => return self.writeInstToStreamGeneric(stream, .intcast, inst, inst_table),
677 .bitcast => return self.writeInstToStreamGeneric(stream, .bitcast, inst, inst_table),
678 .elemptr => return self.writeInstToStreamGeneric(stream, .elemptr, inst, inst_table),
679 .add => return self.writeInstToStreamGeneric(stream, .add, inst, inst_table),
680 .cmp => return self.writeInstToStreamGeneric(stream, .cmp, inst, inst_table),
681 .condbr => return self.writeInstToStreamGeneric(stream, .condbr, inst, inst_table),
682 .isnull => return self.writeInstToStreamGeneric(stream, .isnull, inst, inst_table),
683 .isnonnull => return self.writeInstToStreamGeneric(stream, .isnonnull, inst, inst_table),
708 .arg => return self.writeInstToStreamGeneric(stream, .arg, inst),
709 .block => return self.writeInstToStreamGeneric(stream, .block, inst),
710 .@"break" => return self.writeInstToStreamGeneric(stream, .@"break", inst),
711 .breakpoint => return self.writeInstToStreamGeneric(stream, .breakpoint, inst),
712 .breakvoid => return self.writeInstToStreamGeneric(stream, .breakvoid, inst),
713 .call => return self.writeInstToStreamGeneric(stream, .call, inst),
714 .declref => return self.writeInstToStreamGeneric(stream, .declref, inst),
715 .declref_str => return self.writeInstToStreamGeneric(stream, .declref_str, inst),
716 .declval => return self.writeInstToStreamGeneric(stream, .declval, inst),
717 .declval_in_module => return self.writeInstToStreamGeneric(stream, .declval_in_module, inst),
718 .compileerror => return self.writeInstToStreamGeneric(stream, .compileerror, inst),
719 .@"const" => return self.writeInstToStreamGeneric(stream, .@"const", inst),
720 .str => return self.writeInstToStreamGeneric(stream, .str, inst),
721 .int => return self.writeInstToStreamGeneric(stream, .int, inst),
722 .inttype => return self.writeInstToStreamGeneric(stream, .inttype, inst),
723 .ptrtoint => return self.writeInstToStreamGeneric(stream, .ptrtoint, inst),
724 .fieldptr => return self.writeInstToStreamGeneric(stream, .fieldptr, inst),
725 .deref => return self.writeInstToStreamGeneric(stream, .deref, inst),
726 .as => return self.writeInstToStreamGeneric(stream, .as, inst),
727 .@"asm" => return self.writeInstToStreamGeneric(stream, .@"asm", inst),
728 .@"unreachable" => return self.writeInstToStreamGeneric(stream, .@"unreachable", inst),
729 .@"return" => return self.writeInstToStreamGeneric(stream, .@"return", inst),
730 .returnvoid => return self.writeInstToStreamGeneric(stream, .returnvoid, inst),
731 .@"fn" => return self.writeInstToStreamGeneric(stream, .@"fn", inst),
732 .@"export" => return self.writeInstToStreamGeneric(stream, .@"export", inst),
733 .primitive => return self.writeInstToStreamGeneric(stream, .primitive, inst),
734 .fntype => return self.writeInstToStreamGeneric(stream, .fntype, inst),
735 .intcast => return self.writeInstToStreamGeneric(stream, .intcast, inst),
736 .bitcast => return self.writeInstToStreamGeneric(stream, .bitcast, inst),
737 .elemptr => return self.writeInstToStreamGeneric(stream, .elemptr, inst),
738 .add => return self.writeInstToStreamGeneric(stream, .add, inst),
739 .sub => return self.writeInstToStreamGeneric(stream, .sub, inst),
740 .cmp => return self.writeInstToStreamGeneric(stream, .cmp, inst),
741 .condbr => return self.writeInstToStreamGeneric(stream, .condbr, inst),
742 .isnull => return self.writeInstToStreamGeneric(stream, .isnull, inst),
743 .isnonnull => return self.writeInstToStreamGeneric(stream, .isnonnull, inst),
684744 }
685745 }
686746
687747 fn writeInstToStreamGeneric(
688 self: Module,
748 self: *Writer,
689749 stream: var,
690750 comptime inst_tag: Inst.Tag,
691751 base: *Inst,
692 inst_table: *const InstPtrTable,
693 ) !void {
752 ) (@TypeOf(stream).Error || error{OutOfMemory})!void {
694753 const SpecificInst = Inst.TagToType(inst_tag);
695754 const inst = @fieldParentPtr(SpecificInst, "base", base);
696755 const Positionals = @TypeOf(inst.positionals);
......@@ -700,7 +759,7 @@ pub const Module = struct {
700759 if (i != 0) {
701760 try stream.writeAll(", ");
702761 }
703 try self.writeParamToStream(stream, @field(inst.positionals, arg_field.name), inst_table);
762 try self.writeParamToStream(stream, @field(inst.positionals, arg_field.name));
704763 }
705764
706765 comptime var need_comma = pos_fields.len != 0;
......@@ -710,13 +769,13 @@ pub const Module = struct {
710769 if (@field(inst.kw_args, arg_field.name)) |non_optional| {
711770 if (need_comma) try stream.writeAll(", ");
712771 try stream.print("{}=", .{arg_field.name});
713 try self.writeParamToStream(stream, non_optional, inst_table);
772 try self.writeParamToStream(stream, non_optional);
714773 need_comma = true;
715774 }
716775 } else {
717776 if (need_comma) try stream.writeAll(", ");
718777 try stream.print("{}=", .{arg_field.name});
719 try self.writeParamToStream(stream, @field(inst.kw_args, arg_field.name), inst_table);
778 try self.writeParamToStream(stream, @field(inst.kw_args, arg_field.name));
720779 need_comma = true;
721780 }
722781 }
......@@ -724,29 +783,37 @@ pub const Module = struct {
724783 try stream.writeByte(')');
725784 }
726785
727 fn writeParamToStream(self: Module, stream: var, param: var, inst_table: *const InstPtrTable) !void {
786 fn writeParamToStream(self: *Writer, stream: var, param: var) !void {
728787 if (@typeInfo(@TypeOf(param)) == .Enum) {
729788 return stream.writeAll(@tagName(param));
730789 }
731790 switch (@TypeOf(param)) {
732 *Inst => return self.writeInstParamToStream(stream, param, inst_table),
791 *Inst => return self.writeInstParamToStream(stream, param),
733792 []*Inst => {
734793 try stream.writeByte('[');
735794 for (param) |inst, i| {
736795 if (i != 0) {
737796 try stream.writeAll(", ");
738797 }
739 try self.writeInstParamToStream(stream, inst, inst_table);
798 try self.writeInstParamToStream(stream, inst);
740799 }
741800 try stream.writeByte(']');
742801 },
743802 Module.Body => {
744803 try stream.writeAll("{\n");
745804 for (param.instructions) |inst, i| {
746 try stream.print(" %{} ", .{i});
747 try self.writeInstToStream(stream, inst, inst_table);
805 try stream.writeByteNTimes(' ', self.indent);
806 try stream.print("%{} ", .{i});
807 if (inst.cast(Inst.Block)) |block| {
808 const name = try std.fmt.allocPrint(&self.arena.allocator, "label_{}", .{i});
809 try self.block_table.put(block, name);
810 }
811 self.indent += 2;
812 try self.writeInstToStream(stream, inst);
813 self.indent -= 2;
748814 try stream.writeByte('\n');
749815 }
816 try stream.writeByteNTimes(' ', self.indent - 2);
750817 try stream.writeByte('}');
751818 },
752819 bool => return stream.writeByte("01"[@boolToInt(param)]),
......@@ -754,12 +821,16 @@ pub const Module = struct {
754821 BigIntConst, usize => return stream.print("{}", .{param}),
755822 TypedValue => unreachable, // this is a special case
756823 *IrModule.Decl => unreachable, // this is a special case
824 *Inst.Block => {
825 const name = self.block_table.get(param).?;
826 return std.zig.renderStringLiteral(name, stream);
827 },
757828 else => |T| @compileError("unimplemented: rendering parameter of type " ++ @typeName(T)),
758829 }
759830 }
760831
761 fn writeInstParamToStream(self: Module, stream: var, inst: *Inst, inst_table: *const InstPtrTable) !void {
762 if (inst_table.get(inst)) |info| {
832 fn writeInstParamToStream(self: *Writer, stream: var, inst: *Inst) !void {
833 if (self.inst_table.get(inst)) |info| {
763834 if (info.index) |i| {
764835 try stream.print("%{}", .{info.index});
765836 } else {
......@@ -789,7 +860,9 @@ pub fn parse(allocator: *Allocator, source: [:0]const u8) Allocator.Error!Module
789860 .global_name_map = &global_name_map,
790861 .decls = .{},
791862 .unnamed_index = 0,
863 .block_table = std.StringHashMap(*Inst.Block).init(allocator),
792864 };
865 defer parser.block_table.deinit();
793866 errdefer parser.arena.deinit();
794867
795868 parser.parseRoot() catch |err| switch (err) {
......@@ -815,6 +888,7 @@ const Parser = struct {
815888 global_name_map: *std.StringHashMap(*Inst),
816889 error_msg: ?ErrorMsg = null,
817890 unnamed_index: usize,
891 block_table: std.StringHashMap(*Inst.Block),
818892
819893 const Body = struct {
820894 instructions: std.ArrayList(*Inst),
......@@ -1023,6 +1097,10 @@ const Parser = struct {
10231097 .tag = InstType.base_tag,
10241098 };
10251099
1100 if (InstType == Inst.Block) {
1101 try self.block_table.put(inst_name, inst_specific);
1102 }
1103
10261104 if (@hasField(InstType, "ty")) {
10271105 inst_specific.ty = opt_type orelse {
10281106 return self.fail("instruction '" ++ fn_name ++ "' requires type", .{});
......@@ -1128,6 +1206,10 @@ const Parser = struct {
11281206 },
11291207 TypedValue => return self.fail("'const' is a special instruction; not legal in ZIR text", .{}),
11301208 *IrModule.Decl => return self.fail("'declval_in_module' is a special instruction; not legal in ZIR text", .{}),
1209 *Inst.Block => {
1210 const name = try self.parseStringLiteral();
1211 return self.block_table.get(name).?;
1212 },
11311213 else => @compileError("Unimplemented: ir parseParameterGeneric for type " ++ @typeName(T)),
11321214 }
11331215 return self.fail("TODO parse parameter {}", .{@typeName(T)});
......@@ -1191,7 +1273,10 @@ pub fn emit(allocator: *Allocator, old_module: IrModule) !Module {
11911273 .next_auto_name = 0,
11921274 .names = std.StringHashMap(void).init(allocator),
11931275 .primitive_table = std.AutoHashMap(Inst.Primitive.Builtin, *Decl).init(allocator),
1276 .indent = 0,
1277 .block_table = std.AutoHashMap(*ir.Inst.Block, *Inst.Block).init(allocator),
11941278 };
1279 defer ctx.block_table.deinit();
11951280 defer ctx.decls.deinit(allocator);
11961281 defer ctx.names.deinit();
11971282 defer ctx.primitive_table.deinit();
......@@ -1213,6 +1298,8 @@ const EmitZIR = struct {
12131298 names: std.StringHashMap(void),
12141299 next_auto_name: usize,
12151300 primitive_table: std.AutoHashMap(Inst.Primitive.Builtin, *Decl),
1301 indent: usize,
1302 block_table: std.AutoHashMap(*ir.Inst.Block, *Inst.Block),
12161303
12171304 fn emit(self: *EmitZIR) !void {
12181305 // Put all the Decls in a list and sort them by name to avoid nondeterminism introduced
......@@ -1542,6 +1629,22 @@ const EmitZIR = struct {
15421629 };
15431630 break :blk &new_inst.base;
15441631 },
1632 .sub => blk: {
1633 const old_inst = inst.cast(ir.Inst.Sub).?;
1634 const new_inst = try self.arena.allocator.create(Inst.Sub);
1635 new_inst.* = .{
1636 .base = .{
1637 .src = inst.src,
1638 .tag = Inst.Sub.base_tag,
1639 },
1640 .positionals = .{
1641 .lhs = try self.resolveInst(new_body, old_inst.args.lhs),
1642 .rhs = try self.resolveInst(new_body, old_inst.args.rhs),
1643 },
1644 .kw_args = .{},
1645 };
1646 break :blk &new_inst.base;
1647 },
15451648 .arg => blk: {
15461649 const old_inst = inst.cast(ir.Inst.Arg).?;
15471650 const new_inst = try self.arena.allocator.create(Inst.Arg);
......@@ -1559,6 +1662,8 @@ const EmitZIR = struct {
15591662 const old_inst = inst.cast(ir.Inst.Block).?;
15601663 const new_inst = try self.arena.allocator.create(Inst.Block);
15611664
1665 try self.block_table.put(old_inst, new_inst);
1666
15621667 var block_body = std.ArrayList(*Inst).init(self.allocator);
15631668 defer block_body.deinit();
15641669
......@@ -1570,14 +1675,47 @@ const EmitZIR = struct {
15701675 .tag = Inst.Block.base_tag,
15711676 },
15721677 .positionals = .{
1573 .label = try self.autoName(),
15741678 .body = .{ .instructions = block_body.toOwnedSlice() },
15751679 },
15761680 .kw_args = .{},
15771681 };
1682
1683 break :blk &new_inst.base;
1684 },
1685 .br => blk: {
1686 const old_inst = inst.cast(ir.Inst.Br).?;
1687 const new_block = self.block_table.get(old_inst.args.block).?;
1688 const new_inst = try self.arena.allocator.create(Inst.Break);
1689 new_inst.* = .{
1690 .base = .{
1691 .src = inst.src,
1692 .tag = Inst.Break.base_tag,
1693 },
1694 .positionals = .{
1695 .block = new_block,
1696 .operand = try self.resolveInst(new_body, old_inst.args.operand),
1697 },
1698 .kw_args = .{},
1699 };
15781700 break :blk &new_inst.base;
15791701 },
15801702 .breakpoint => try self.emitTrivial(inst.src, Inst.Breakpoint),
1703 .brvoid => blk: {
1704 const old_inst = inst.cast(ir.Inst.BrVoid).?;
1705 const new_block = self.block_table.get(old_inst.args.block).?;
1706 const new_inst = try self.arena.allocator.create(Inst.BreakVoid);
1707 new_inst.* = .{
1708 .base = .{
1709 .src = inst.src,
1710 .tag = Inst.BreakVoid.base_tag,
1711 },
1712 .positionals = .{
1713 .block = new_block,
1714 },
1715 .kw_args = .{},
1716 };
1717 break :blk &new_inst.base;
1718 },
15811719 .call => blk: {
15821720 const old_inst = inst.cast(ir.Inst.Call).?;
15831721 const new_inst = try self.arena.allocator.create(Inst.Call);
......@@ -1765,7 +1903,7 @@ const EmitZIR = struct {
17651903 },
17661904 };
17671905 try instructions.append(new_inst);
1768 try inst_table.putNoClobber(inst, new_inst);
1906 try inst_table.put(inst, new_inst);
17691907 }
17701908 }
17711909
......@@ -1829,6 +1967,26 @@ const EmitZIR = struct {
18291967 };
18301968 return self.emitUnnamedDecl(&fntype_inst.base);
18311969 },
1970 .Int => {
1971 const info = ty.intInfo(self.old_module.target());
1972 const signed = try self.emitPrimitive(src, if (info.signed) .@"true" else .@"false");
1973 const bits_payload = try self.arena.allocator.create(Value.Payload.Int_u64);
1974 bits_payload.* = .{ .int = info.bits };
1975 const bits = try self.emitComptimeIntVal(src, Value.initPayload(&bits_payload.base));
1976 const inttype_inst = try self.arena.allocator.create(Inst.IntType);
1977 inttype_inst.* = .{
1978 .base = .{
1979 .src = src,
1980 .tag = Inst.IntType.base_tag,
1981 },
1982 .positionals = .{
1983 .signed = signed.inst,
1984 .bits = bits.inst,
1985 },
1986 .kw_args = .{},
1987 };
1988 return self.emitUnnamedDecl(&inttype_inst.base);
1989 },
18321990 else => std.debug.panic("TODO implement emitType for {}", .{ty}),
18331991 },
18341992 }